Debian Codegraph @

texk/web2c/pdftexdir/pdftex.web

raw
1 % Copyright 1996-2026 Han Th\^e\llap{\raise 0.5ex\hbox{\'{}}} Th\`anh,
2 % <thanh@@pdftex.org>
3
4 % This file is part of pdfTeX.
5
6 % pdfTeX is free software; you can redistribute it and/or modify it under the
7 % terms of the GNU General Public License as published by the Free Software
8 % Foundation; either version 2 of the License, or (at your option) any later
9 % version.
10
11 % pdfTeX is distributed in the hope that it will be useful, but WITHOUT ANY
12 % WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
13 % A PARTICULAR PURPOSE. See the GNU General Public License for more details.
14
15 % You should have received a copy of the GNU General Public License along with
16 % this program. If not, see <http://www.gnu.org/licenses/>.
17
18 % e-TeX is copyright (C) 1999-2015 by P. Breitenlohner (1994,98 by the NTS
19 % team); all rights are reserved. Copying of this file is authorized only if
20 % (1) you are P. Breitenlohner, or if (2) you make absolutely no changes to
21 % your copy. (Programs such as TIE allow the application of several change
22 % files to tex.web; the master files tex.web and etex.ch should stay intact.)
23
24 % See etex_gen.tex for hints on how to install this program.
25 % And see etripman.tex for details about how to validate it.
26
27 % This program is directly derived from Donald E. Knuth's TeX;
28 % the change history which follows and the reward offered for finders of
29 % bugs refer specifically to TeX; they should not be taken as referring
30 % to e-TeX, although the change history is relevant in that it
31 % demonstrates the evolutionary path followed. This program is not TeX;
32 % that name is reserved strictly for the program which is the creation
33 % and sole responsibility of Professor Knuth.
34
35 % Version 0 was released in September 1982 after it passed a variety of tests.
36 % Version 1 was released in November 1983 after thorough testing.
37 % Version 1.1 fixed ``disappearing font identifiers'' et alia (July 1984).
38 % Version 1.2 allowed `0' in response to an error, et alia (October 1984).
39 % Version 1.3 made memory allocation more flexible and local (November 1984).
40 % Version 1.4 fixed accents right after line breaks, et alia (April 1985).
41 % Version 1.5 fixed \the\toks after other expansion in \edefs (August 1985).
42 % Version 2.0 (almost identical to 1.5) corresponds to "Volume B" (April 1986).
43 % Version 2.1 corrected anomalies in discretionary breaks (January 1987).
44 % Version 2.2 corrected "(Please type...)" with null \endlinechar (April 1987).
45 % Version 2.3 avoided incomplete page in premature termination (August 1987).
46 % Version 2.4 fixed \noaligned rules in indented displays (August 1987).
47 % Version 2.5 saved cur_order when expanding tokens (September 1987).
48 % Version 2.6 added 10sp slop when shipping leaders (November 1987).
49 % Version 2.7 improved rounding of negative-width characters (November 1987).
50 % Version 2.8 fixed weird bug if no \patterns are used (December 1987).
51 % Version 2.9 made \csname\endcsname's "relax" local (December 1987).
52 % Version 2.91 fixed \outer\def\a0{}\a\a bug (April 1988).
53 % Version 2.92 fixed \patterns, also file names with complex macros (May 1988).
54 % Version 2.93 fixed negative halving in allocator when mem_min<0 (June 1988).
55 % Version 2.94 kept open_log_file from calling fatal_error (November 1988).
56 % Version 2.95 solved that problem a better way (December 1988).
57 % Version 2.96 corrected bug in "Infinite shrinkage" recovery (January 1989).
58 % Version 2.97 corrected blunder in creating 2.95 (February 1989).
59 % Version 2.98 omitted save_for_after at outer level (March 1989).
60 % Version 2.99 caught $$\begingroup\halign..$$ (June 1989).
61 % Version 2.991 caught .5\ifdim.6... (June 1989).
62 % Version 2.992 introduced major changes for 8-bit extensions (September 1989).
63 % Version 2.993 fixed a save_stack synchronization bug et alia (December 1989).
64 % Version 3.0 fixed unusual displays; was more \output robust (March 1990).
65 % Version 3.1 fixed nullfont, disabled \write{\the\prevgraf} (September 1990).
66 % Version 3.14 fixed unprintable font names and corrected typos (March 1991).
67 % Version 3.141 more of same; reconstituted ligatures better (March 1992).
68 % Version 3.1415 preserved nonexplicit kerns, tidied up (February 1993).
69 % Version 3.14159 allowed fontmemsize to change; bulletproofing (March 1995).
70 % Version 3.141592 fixed \xleaders, glueset, weird alignments (December 2002).
71 % Version 3.1415926 was a general cleanup with minor fixes (February 2008).
72 % Version 3.14159265 was similar (January 2014).
73 % Version 3.141592653 was similar but more extensive (January 2021).
74
75 % A preliminary version of TeX--XeT was released in April 1992.
76 % TeX--XeT version 1.0 was released in June 1992,
77 % version 1.1 prevented arith overflow in glue computation (Oct 1992).
78 % A preliminary e-TeX version 0.95 was operational in March 1994.
79 % Version 1.0beta was released in May 1995.
80 % Version 1.01beta fixed bugs in just_copy and every_eof (December 1995).
81 % Version 1.02beta allowed 256 mark classes (March 1996).
82 % Version 1.1 changed \group{type,level} -> \currentgroup{type,level},
83 % first public release (October 1996).
84 % Version 2.0 development was started in March 1997;
85 % fixed a ligature-\beginR bug in January 1998;
86 % was released in March 1998.
87 % Version 2.1 fixed a \marks bug (when min_halfword<>0) (January 1999).
88 % Version 2.2 development was started in Feb 2003; released in Oct 2004.
89 % fixed a bug in sparse array handling (0=>null), Jun 2002;
90 % fixed a bug in \lastnodetype (cur_val=>cur_val_level)
91 % reported by Hartmut Henkel <hartmut_henkel@@gmx.de>,
92 % fix by Fabrice Popineau <Fabrice.Popineau@@supelec.fr>,
93 % Jan 2004;
94 % another bug in sparse array handling (cur_ptr=>cur_chr)
95 % reported by Taco Hoekwater <taco@@elvenkind.com>, Jul 2004;
96 % fixed a sparse array reference count bug (\let,\futurelet),
97 % fix by Bernd Raichle <berd@@dante.de>, Aug 2004;
98 % reorganized handling of banner, additional token list and
99 % integer parameters, and similar in order to reduce the
100 % interference between eTeX, pdfTeX, and web2c change files.
101 % adapted to tex.web 3.141592, revised glue rounding for mixed
102 % direction typesetting;
103 % fixed a bug in the revised glue rounding code, detected by
104 % Tigran Aivazian <tigran@@aivazian.fsnet.co.uk>, Oct 2004.
105 % Version 2.3 development was started in Feb 2008; released in Apr 2011.
106 % fixed a bug in hyph_code handling (\savinghyphcodes)
107 % reported by Vladimir Volovich <vvv@@vsu.ru>, Feb 2008.
108 % fixed the error messages for improper use of \protected,
109 % reported by Heiko Oberdiek
110 % <heiko.oberdiek@@googlemail.com>, May 2010.
111 % some rearrangements to reduce interferences between
112 % e-TeX and pTeX, in part suggested by Hironori Kitagawa
113 % <h_kitagawa2001@@yahoo.co.jp>, Mar 2011.
114 % Version 2.4 fixed an uninitialized line number bug, released in May 2012.
115 % Version 2.5 development was started in Aug 2012; released in Feb 2013.
116 % better tracing of font definitions, reported by
117 % Bruno Le Floch <blflatex@@gmail.com>, Jul 2012.
118 % Version 2.6 development was started in Mar 2013; released in ??? 201?.
119 % enable hyphenation of text between \beginL and \endL or
120 % between \beginR and \endR, problem reported by
121 % Vafa Khalighi <vafalgk@@gmail.com>, Nov 2013.
122 % better handling of right-to-left text -- to be done.
123
124 % Although considerable effort has been expended to make the e-TeX program
125 % correct and reliable, no warranty is implied; the author disclaims any
126 % obligation or liability for damages, including but not limited to
127 % special, indirect, or consequential damages arising out of or in
128 % connection with the use or performance of this software. This work has
129 % been a ``labor of love'' and the author hopes that users enjoy it.
130
131 % Here is TeX material that gets inserted after \input webmac
132 \def\hang{\hangindent 3em\noindent\ignorespaces}
133 \def\hangg#1 {\hang\hbox{#1 }}
134 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
135 \font\ninerm=cmr9
136 \let\mc=\ninerm % medium caps for names like SAIL
137 \def\eTeX{$\varepsilon$-\TeX}
138 \font\revrm=xbmc10 % for right-to-left text
139 % to generate xbmc10 (i.e., reflected cmbx10) use a file
140 % xbmc10.mf containing:
141 %+++++++++++++++++++++++++++++++++++++++++++++++++
142 % if unknown cmbase: input cmbase fi
143 % extra_endchar := extra_endchar &
144 % "currentpicture:=currentpicture " &
145 % "reflectedabout((.5[l,r],0),(.5[l,r],1));";
146 % input cmbx10
147 %+++++++++++++++++++++++++++++++++++++++++++++++++
148 \ifx\beginL\undefined % this is TeX
149 \def\XeT{X\kern-.125em\lower.5ex\hbox{E}\kern-.1667emT}
150 \def\TeXeT{\TeX-\hbox{\revrm \XeT}} % for TeX-XeT
151 \def\TeXXeT{\TeX-\hbox{\revrm -\XeT}} % for TeX--XeT
152 \else
153 \ifx\eTeXversion\undefined % this is \TeXeT
154 \def\TeXeT{\TeX-{\revrm\beginR\TeX\endR}} % for TeX-XeT
155 \def\TeXXeT{\TeX-{\revrm\beginR\TeX-\endR}} % for TeX--XeT
156 \else % this is \eTeX
157 \def\TeXeT{\TeX-{\TeXXeTstate=1\revrm\beginR\TeX\endR}} % for TeX-XeT
158 \def\TeXXeT{\TeX-{\TeXXeTstate=1\revrm\beginR\TeX-\endR}} % for TeX--XeT
159 \fi
160 \fi
161 \def\PASCAL{Pascal}
162 \def\pdfTeX{pdf\TeX}
163 \def\pdfeTeX{pdf\eTeX}
164 \def\PDF{PDF}
165 \def\ph{\hbox{Pascal-H}}
166 \def\pct!{{\char`\%}} % percent sign in ordinary text
167 \def\grp{\.{\char'173...\char'175}}
168 \font\logo=logo10 % font used for the METAFONT logo
169 \def\MF{{\logo META}\-{\logo FONT}}
170 \def\<#1>{$\langle#1\rangle$}
171 \def\section{\mathhexbox278}
172
173 \def\(#1){} % this is used to make section names sort themselves better
174 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
175
176 \outer\def\N#1. \[#2]#3.{\MN#1.\vfil\eject % begin starred section
177 \def\rhead{PART #2:\uppercase{#3}} % define running headline
178 \message{*\modno} % progress report
179 \edef\next{\write\cont{\Z{\?#2]#3}{\modno}{\the\pageno}}}\next
180 \ifon\startsection{\bf\ignorespaces#3.\quad}\ignorespaces}
181 \let\?=\relax % we want to be able to \write a \?
182
183 \def\title{\pdfTeX}
184 % system dependent redefinitions of \title should come later
185 % and should use:
186 % \toks0=\expandafter{\title}
187 % \edef\title{...\the\toks0...}
188 \let\maybe=\iftrue % print only changed modules
189 \def\topofcontents{\hsize 5.5in
190 \vglue 0pt plus 1fil minus 1.5in
191 \def\?##1]{\hbox to 1in{\hfil##1.\ }}
192 }
193 \def\botofcontents{\vskip 0pt plus 1fil minus 1.5in}
194 \pageno=3
195 \def\glob{13} % this should be the section number of "<Global...>"
196 \def\gglob{20, 26} % this should be the next two sections of "<Global...>"
197
198 @* \[1] Introduction.
199 This is \eTeX, a program derived from and extending the capabilities of
200 \TeX, a document compiler intended to produce typesetting of high
201 quality.
202 The \PASCAL\ program that follows is the definition of \TeX82, a standard
203 @:PASCAL}{\PASCAL@>
204 @!@:TeX82}{\TeX82@>
205 version of \TeX\ that is designed to be highly portable so that identical output
206 will be obtainable on a great variety of computers.
207
208 The main purpose of the following program is to explain the algorithms of \TeX\
209 as clearly as possible. As a result, the program will not necessarily be very
210 efficient when a particular \PASCAL\ compiler has translated it into a
211 particular machine language. However, the program has been written so that it
212 can be tuned to run efficiently in a wide variety of operating environments
213 by making comparatively few changes. Such flexibility is possible because
214 the documentation that follows is written in the \.{WEB} language, which is
215 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
216 to \PASCAL\ is able to introduce most of the necessary refinements.
217 Semi-automatic translation to other languages is also feasible, because the
218 program below does not make extensive use of features that are peculiar to
219 \PASCAL.
220
221 A large piece of software like \TeX\ has inherent complexity that cannot
222 be reduced below a certain level of difficulty, although each individual
223 part is fairly simple by itself. The \.{WEB} language is intended to make
224 the algorithms as readable as possible, by reflecting the way the
225 individual program pieces fit together and by providing the
226 cross-references that connect different parts. Detailed comments about
227 what is going on, and about why things were done in certain ways, have
228 been liberally sprinkled throughout the program. These comments explain
229 features of the implementation, but they rarely attempt to explain the
230 \TeX\ language itself, since the reader is supposed to be familiar with
231 {\sl The \TeX book}.
232 @.WEB@>
233 @:TeXbook}{\sl The \TeX book@>
234
235 @ The present implementation has a long ancestry, beginning in the summer
236 of~1977, when Michael~F. Plass and Frank~M. Liang designed and coded
237 a prototype
238 @^Plass, Michael Frederick@>
239 @^Liang, Franklin Mark@>
240 @^Knuth, Donald Ervin@>
241 based on some specifications that the author had made in May of that year.
242 This original proto\TeX\ included macro definitions and elementary
243 manipulations on boxes and glue, but it did not have line-breaking,
244 page-breaking, mathematical formulas, alignment routines, error recovery,
245 or the present semantic nest; furthermore,
246 it used character lists instead of token lists, so that a control sequence
247 like \.{\\halign} was represented by a list of seven characters. A
248 complete version of \TeX\ was designed and coded by the author in late
249 1977 and early 1978; that program, like its prototype, was written in the
250 {\mc SAIL} language, for which an excellent debugging system was
251 available. Preliminary plans to convert the {\mc SAIL} code into a form
252 somewhat like the present ``web'' were developed by Luis Trabb~Pardo and
253 @^Trabb Pardo, Luis Isidoro@>
254 the author at the beginning of 1979, and a complete implementation was
255 created by Ignacio~A. Zabala in 1979 and 1980. The \TeX82 program, which
256 @^Zabala Salelles, Ignacio Andr\'es@>
257 was written by the author during the latter part of 1981 and the early
258 part of 1982, also incorporates ideas from the 1979 implementation of
259 @^Guibas, Leonidas Ioannis@>
260 @^Sedgewick, Robert@>
261 @^Wyatt, Douglas Kirk@>
262 \TeX\ in {\mc MESA} that was written by Leonidas Guibas, Robert Sedgewick,
263 and Douglas Wyatt at the Xerox Palo Alto Research Center. Several hundred
264 refinements were introduced into \TeX82 based on the experiences gained with
265 the original implementations, so that essentially every part of the system
266 has been substantially improved. After the appearance of ``Version 0'' in
267 September 1982, this program benefited greatly from the comments of
268 many other people, notably David~R. Fuchs and Howard~W. Trickey.
269 A final revision in September 1989 extended the input character set to
270 eight-bit codes and introduced the ability to hyphenate words from
271 different languages, based on some ideas of Michael~J. Ferguson.
272 @^Fuchs, David Raymond@>
273 @^Trickey, Howard Wellington@>
274 @^Ferguson, Michael John@>
275
276 No doubt there still is plenty of room for improvement, but the author
277 is firmly committed to keeping \TeX82 ``frozen'' from now on; stability
278 and reliability are to be its main virtues.
279
280 On the other hand, the \.{WEB} description can be extended without changing
281 the core of \TeX82 itself, and the program has been designed so that such
282 extensions are not extremely difficult to make.
283 The |banner| string defined here should be changed whenever \TeX\
284 undergoes any modifications, so that it will be clear which version of
285 \TeX\ might be the guilty party when a problem arises.
286 @^extensions to \TeX@>
287 @^system dependencies@>
288
289 This program contains code for various features extending \TeX,
290 therefore this program is called `\eTeX' and not
291 `\TeX'; the official name `\TeX' by itself is reserved
292 for software systems that are fully compatible with each other.
293 A special test suite called the ``\.{TRIP} test'' is available for
294 helping to determine whether a particular implementation deserves to be
295 known as `\TeX' [cf.~Stanford Computer Science report CS1027,
296 November 1984].
297
298 A similar test suite called the ``\.{e-TRIP} test'' is available for
299 helping to determine whether a particular implementation deserves to be
300 known as `\eTeX'.
301
302 @d eTeX_version=2 { \.{\\eTeXversion} }
303 @d eTeX_revision==".6" { \.{\\eTeXrevision} }
304 @d eTeX_version_string=='-2.6' {current \eTeX\ version}
305 @#
306 @d eTeX_banner=='This is e-TeX, Version 3.141592653',eTeX_version_string
307 {printed when \eTeX\ starts}
308 @#
309 @d pdftex_version==140 { \.{\\pdftexversion} }
310 @d pdftex_revision=="29" { \.{\\pdftexrevision} }
311 @d pdftex_version_string=='-1.40.29' {current \pdfTeX\ version}
312 @#
313 @d pdfTeX_banner=='This is pdfTeX, Version 3.141592653',eTeX_version_string,pdftex_version_string
314 {printed when \pdfTeX\ starts}
315 @#
316 @d TeX_banner=='This is TeX, Version 3.141592653' {printed when \TeX\ starts}
317 @#
318 @d banner==pdfTeX_banner
319 @#
320 @d TEX==PDFTEX {change program name into |PDFTEX|}
321 @#
322 @d TeXXeT_code=0 {the \TeXXeT\ feature is optional}
323 @#
324 @d eTeX_states=1 {number of \eTeX\ state variables in |eqtb|}
325
326 @ Different \PASCAL s have slightly different conventions, and the present
327 @!@:PASCAL H}{\ph@>
328 program expresses \TeX\ in terms of the \PASCAL\ that was
329 available to the author in 1982. Constructions that apply to
330 this particular compiler, which we shall call \ph, should help the
331 reader see how to make an appropriate interface for other systems
332 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
333 @^Hedrick, Charles Locke@>
334 for the DECsystem-10 that was originally developed at the University of
335 Hamburg; cf.\ {\sl Software---Practice and Experience \bf6} (1976),
336 29--42. The \TeX\ program below is intended to be adaptable, without
337 extensive changes, to most other versions of \PASCAL, so it does not fully
338 use the admirable features of \ph. Indeed, a conscious effort has been
339 made here to avoid using several idiosyncratic features of standard
340 \PASCAL\ itself, so that most of the code can be translated mechanically
341 into other high-level languages. For example, the `\&{with}' and `\\{new}'
342 features are not used, nor are pointer types, set types, or enumerated
343 scalar types; there are no `\&{var}' parameters, except in the case of files
344 --- \eTeX, however, does use `\&{var}' parameters for the |reverse| function;
345 there are no tag fields on variant records; there are no assignments
346 |real:=integer|; no procedures are declared local to other procedures.)
347
348 The portions of this program that involve system-dependent code, where
349 changes might be necessary because of differences between \PASCAL\ compilers
350 and/or differences between
351 operating systems, can be identified by looking at the sections whose
352 numbers are listed under `system dependencies' in the index. Furthermore,
353 the index entries for `dirty \PASCAL' list all places where the restrictions
354 of \PASCAL\ have not been followed perfectly, for one reason or another.
355 @!@^system dependencies@>
356 @!@^dirty \PASCAL@>
357
358 Incidentally, \PASCAL's standard |round| function can be problematical,
359 because it disagrees with the IEEE floating-point standard.
360 Many implementors have
361 therefore chosen to substitute their own home-grown rounding procedure.
362
363 @ The program begins with a normal \PASCAL\ program heading, whose
364 components will be filled in later, using the conventions of \.{WEB}.
365 @.WEB@>
366 For example, the portion of the program called `\X\glob:Global
367 variables\X' below will be replaced by a sequence of variable declarations
368 that starts in $\section\glob$ of this documentation. In this way, we are able
369 to define each individual global variable when we are prepared to
370 understand what it means; we do not have to define all of the globals at
371 once. Cross references in $\section\glob$, where it says ``See also
372 sections \gglob, \dots,'' also make it possible to look at the set of
373 all global variables, if desired. Similar remarks apply to the other
374 portions of the program heading.
375
376 Actually the heading shown here is not quite normal: The |program| line
377 does not mention any |output| file, because \ph\ would ask the \TeX\ user
378 to specify a file name if |output| were specified here.
379 @:PASCAL H}{\ph@>
380 @^system dependencies@>
381
382 @d mtype==t@&y@&p@&e {this is a \.{WEB} coding trick:}
383 @f mtype==type {`\&{mtype}' will be equivalent to `\&{type}'}
384 @f type==true {but `|type|' will not be treated as a reserved word}
385
386 @p @t\4@>@<Compiler directives@>@/
387 program TEX; {all file names are defined dynamically}
388 label @<Labels in the outer block@>@/
389 const @<Constants in the outer block@>@/
390 mtype @<Types in the outer block@>@/
391 var @<Global variables@>@/
392 @#
393 procedure initialize; {this procedure gets things started properly}
394 var @<Local variables for initialization@>@/
395 begin @<Initialize whatever \TeX\ might access@>@;
396 end;@#
397 @t\4@>@<Basic printing procedures@>@/
398 @t\4@>@<Error handling procedures@>@/
399
400 @ The overall \TeX\ program begins with the heading just shown, after which
401 comes a bunch of procedure declarations and function declarations.
402 Finally we will get to the main program, which begins with the
403 comment `|start_here|'. If you want to skip down to the
404 main program now, you can look up `|start_here|' in the index.
405 But the author suggests that the best way to understand this program
406 is to follow pretty much the order of \TeX's components as they appear in the
407 \.{WEB} description you are now reading, since the present ordering is
408 intended to combine the advantages of the ``bottom up'' and ``top down''
409 approaches to the problem of understanding a somewhat complicated system.
410
411 @ Three labels must be declared in the main program, so we give them
412 symbolic names.
413
414 @d start_of_TEX=1 {go here when \TeX's variables are initialized}
415 @d end_of_TEX=9998 {go here to close files and terminate gracefully}
416 @d final_end=9999 {this label marks the ending of the program}
417
418 @<Labels in the out...@>=
419 start_of_TEX@t\hskip-2pt@>, end_of_TEX@t\hskip-2pt@>,@,final_end;
420 {key control points}
421
422 @ Some of the code below is intended to be used only when diagnosing the
423 strange behavior that sometimes occurs when \TeX\ is being installed or
424 when system wizards are fooling around with \TeX\ without quite knowing
425 what they are doing. Such code will not normally be compiled; it is
426 delimited by the codewords `$|debug|\ldots|gubed|$', with apologies
427 to people who wish to preserve the purity of English.
428
429 Similarly, there is some conditional code delimited by
430 `$|stat|\ldots|tats|$' that is intended for use when statistics are to be
431 kept about \TeX's memory usage. The |stat| $\ldots$ |tats| code also
432 implements diagnostic information for \.{\\tracingparagraphs},
433 \.{\\tracingpages}, and \.{\\tracingrestores}.
434 @^debugging@>
435
436 @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
437 @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
438 @f debug==begin
439 @f gubed==end
440 @#
441 @d stat==@{ {change this to `$\\{stat}\equiv\null$' when gathering
442 usage statistics}
443 @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$' when gathering
444 usage statistics}
445 @f stat==begin
446 @f tats==end
447
448 @ This program has two important variations: (1) There is a long and slow
449 version called \.{INITEX}, which does the extra calculations needed to
450 @.INITEX@>
451 initialize \TeX's internal tables; and (2)~there is a shorter and faster
452 production version, which cuts the initialization to a bare minimum.
453 Parts of the program that are needed in (1) but not in (2) are delimited by
454 the codewords `$|init|\ldots|tini|$'.
455
456 @d init== {change this to `$\\{init}\equiv\.{@@\{}$' in the production version}
457 @d tini== {change this to `$\\{tini}\equiv\.{@@\}}$' in the production version}
458 @f init==begin
459 @f tini==end
460
461 @<Initialize whatever...@>=
462 @<Set initial values of key variables@>@/
463 @!init @<Initialize table entries (done by \.{INITEX} only)@>@;@+tini
464
465 @ If the first character of a \PASCAL\ comment is a dollar sign,
466 \ph\ treats the comment as a list of ``compiler directives'' that will
467 affect the translation of this program into machine language. The
468 directives shown below specify full checking and inclusion of the \PASCAL\
469 debugger when \TeX\ is being debugged, but they cause range checking and other
470 redundant code to be eliminated when the production system is being generated.
471 Arithmetic overflow will be detected in all cases.
472 @:PASCAL H}{\ph@>
473 @^system dependencies@>
474 @^overflow in arithmetic@>
475
476 @<Compiler directives@>=
477 @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
478 @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
479
480 @ This \TeX\ implementation conforms to the rules of the {\sl Pascal User
481 @:PASCAL}{\PASCAL@>
482 @^system dependencies@>
483 Manual} published by Jensen and Wirth in 1975, except where system-dependent
484 @^Wirth, Niklaus@>
485 @^Jensen, Kathleen@>
486 code is necessary to make a useful system program, and except in another
487 respect where such conformity would unnecessarily obscure the meaning
488 and clutter up the code: We assume that |case| statements may include a
489 default case that applies if no matching label is found. Thus, we shall use
490 constructions like
491 $$\vbox{\halign{\ignorespaces#\hfil\cr
492 |case x of|\cr
493 1: $\langle\,$code for $x=1\,\rangle$;\cr
494 3: $\langle\,$code for $x=3\,\rangle$;\cr
495 |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
496 |endcases|\cr}}$$
497 since most \PASCAL\ compilers have plugged this hole in the language by
498 incorporating some sort of default mechanism. For example, the \ph\
499 compiler allows `|others|:' as a default label, and other \PASCAL s allow
500 syntaxes like `\&{else}' or `\&{otherwise}' or `\\{otherwise}:', etc. The
501 definitions of |othercases| and |endcases| should be changed to agree with
502 local conventions. Note that no semicolon appears before |endcases| in
503 this program, so the definition of |endcases| should include a semicolon
504 if the compiler wants one. (Of course, if no default mechanism is
505 available, the |case| statements of \TeX\ will have to be laboriously
506 extended by listing all remaining cases. People who are stuck with such
507 \PASCAL s have, in fact, done this, successfully but not happily!)
508 @:PASCAL H}{\ph@>
509
510 @d othercases == others: {default for cases not listed explicitly}
511 @d endcases == @+end {follows the default case in an extended |case| statement}
512 @f othercases == else
513 @f endcases == end
514
515 @ The following parameters can be changed at compile time to extend or
516 reduce \TeX's capacity. They may have different values in \.{INITEX} and
517 in production versions of \TeX.
518 @.INITEX@>
519 @^system dependencies@>
520
521 @<Constants...@>=
522 @!mem_max=30000; {greatest index in \TeX's internal |mem| array;
523 must be strictly less than |max_halfword|;
524 must be equal to |mem_top| in \.{INITEX}, otherwise |>=mem_top|}
525 @!mem_min=0; {smallest index in \TeX's internal |mem| array;
526 must be |min_halfword| or more;
527 must be equal to |mem_bot| in \.{INITEX}, otherwise |<=mem_bot|}
528 @!buf_size=500; {maximum number of characters simultaneously present in
529 current lines of open files and in control sequences between
530 \.{\\csname} and \.{\\endcsname}; must not exceed |max_halfword|}
531 @!error_line=72; {width of context lines on terminal error messages}
532 @!half_error_line=42; {width of first lines of contexts in terminal
533 error messages; should be between 30 and |error_line-15|}
534 @!max_print_line=79; {width of longest text lines output; should be at least 60}
535 @!stack_size=200; {maximum number of simultaneous input sources}
536 @!max_in_open=6; {maximum number of input files and error insertions that
537 can be going on simultaneously}
538 @!font_max=75; {maximum internal font number; must not exceed |max_quarterword|
539 and must be at most |font_base+256|}
540 @!font_mem_size=20000; {number of words of |font_info| for all fonts}
541 @!param_size=60; {maximum number of simultaneous macro parameters}
542 @!nest_size=40; {maximum number of semantic levels simultaneously active}
543 @!max_strings=3000; {maximum number of strings; must not exceed |max_halfword|}
544 @!string_vacancies=8000; {the minimum number of characters that should be
545 available for the user's control sequences and font names,
546 after \TeX's own error messages are stored}
547 @!pool_size=32000; {maximum number of characters in strings, including all
548 error messages and help texts, and the names of all fonts and
549 control sequences; must exceed |string_vacancies| by the total
550 length of \TeX's own strings, which is currently about 23000}
551 @!save_size=600; {space for saving values outside of current group; must be
552 at most |max_halfword|}
553 @!trie_size=8000; {space for hyphenation patterns; should be larger for
554 \.{INITEX} than it is in production versions of \TeX}
555 @!trie_op_size=500; {space for ``opcodes'' in the hyphenation patterns}
556 @!dvi_buf_size=800; {size of the output buffer; must be a multiple of 8}
557 @!file_name_size=40; {file names shouldn't be longer than this}
558 @!pool_name='TeXformats:TEX.POOL ';
559 {string of length |file_name_size|; tells where the string pool appears}
560 @.TeXformats@>
561
562 @ Like the preceding parameters, the following quantities can be changed
563 at compile time to extend or reduce \TeX's capacity. But if they are changed,
564 it is necessary to rerun the initialization program \.{INITEX}
565 @.INITEX@>
566 to generate new tables for the production \TeX\ program.
567 One can't simply make helter-skelter changes to the following constants,
568 since certain rather complex initialization
569 numbers are computed from them. They are defined here using
570 \.{WEB} macros, instead of being put into \PASCAL's |const| list, in order to
571 emphasize this distinction.
572
573 @d mem_bot=0 {smallest index in the |mem| array dumped by \.{INITEX};
574 must not be less than |mem_min|}
575 @d mem_top==30000 {largest index in the |mem| array dumped by \.{INITEX};
576 must be substantially larger than |mem_bot|
577 and not greater than |mem_max|}
578 @d font_base=0 {smallest internal font number; must not be less
579 than |min_quarterword|}
580 @d hash_size=2100 {maximum number of control sequences; it should be at most
581 about |(mem_max-mem_min)/10|}
582 @d hash_prime=1777 {a prime number equal to about 85\pct! of |hash_size|}
583 @d hyph_size=307 {another prime; the number of \.{\\hyphenation} exceptions}
584 @^system dependencies@>
585
586 @ In case somebody has inadvertently made bad settings of the ``constants,''
587 \TeX\ checks them using a global variable called |bad|.
588
589 This is the first of many sections of \TeX\ where global variables are
590 defined.
591
592 @<Glob...@>=
593 @!bad:integer; {is some ``constant'' wrong?}
594
595 @ Later on we will say `\ignorespaces|if mem_max>=max_halfword then bad:=14|',
596 or something similar. (We can't do that until |max_halfword| has been defined.)
597
598 @<Check the ``constant'' values for consistency@>=
599 bad:=0;
600 if (half_error_line<30)or(half_error_line>error_line-15) then bad:=1;
601 if max_print_line<60 then bad:=2;
602 if dvi_buf_size mod 8<>0 then bad:=3;
603 if mem_bot+1100>mem_top then bad:=4;
604 if hash_prime>hash_size then bad:=5;
605 if max_in_open>=128 then bad:=6;
606 if mem_top<256+11 then bad:=7; {we will want |null_list>255|}
607
608 @ Labels are given symbolic names by the following definitions, so that
609 occasional |goto| statements will be meaningful. We insert the label
610 `|exit|' just before the `\ignorespaces|end|\unskip' of a procedure in
611 which we have used the `|return|' statement defined below; the label
612 `|restart|' is occasionally used at the very beginning of a procedure; and
613 the label `|reswitch|' is occasionally used just prior to a |case|
614 statement in which some cases change the conditions and we wish to branch
615 to the newly applicable case. Loops that are set up with the |loop|
616 construction defined below are commonly exited by going to `|done|' or to
617 `|found|' or to `|not_found|', and they are sometimes repeated by going to
618 `|continue|'. If two or more parts of a subroutine start differently but
619 end up the same, the shared code may be gathered together at
620 `|common_ending|'.
621
622 Incidentally, this program never declares a label that isn't actually used,
623 because some fussy \PASCAL\ compilers will complain about redundant labels.
624
625 @d exit=10 {go here to leave a procedure}
626 @d restart=20 {go here to start a procedure again}
627 @d reswitch=21 {go here to start a case statement again}
628 @d continue=22 {go here to resume a loop}
629 @d done=30 {go here to exit a loop}
630 @d done1=31 {like |done|, when there is more than one loop}
631 @d done2=32 {for exiting the second loop in a long block}
632 @d done3=33 {for exiting the third loop in a very long block}
633 @d done4=34 {for exiting the fourth loop in an extremely long block}
634 @d done5=35 {for exiting the fifth loop in an immense block}
635 @d done6=36 {for exiting the sixth loop in a block}
636 @d found=40 {go here when you've found it}
637 @d found1=41 {like |found|, when there's more than one per routine}
638 @d found2=42 {like |found|, when there's more than two per routine}
639 @d not_found=45 {go here when you've found nothing}
640 @d not_found1=46 {like |not_found|, when there's more than one}
641 @d not_found2=47 {like |not_found|, when there's more than two}
642 @d not_found3=48 {like |not_found|, when there's more than three}
643 @d not_found4=49 {like |not_found|, when there's more than four}
644 @d common_ending=50 {go here when you want to merge with another branch}
645
646 @ Here are some macros for common programming idioms.
647
648 @d incr(#) == #:=#+1 {increase a variable by unity}
649 @d decr(#) == #:=#-1 {decrease a variable by unity}
650 @d negate(#) == #:=-# {change the sign of a variable}
651 @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
652 @f loop == xclause
653 {\.{WEB}'s |xclause| acts like `\ignorespaces|while true do|\unskip'}
654 @d do_nothing == {empty statement}
655 @d return == goto exit {terminate a procedure call}
656 @f return == nil
657 @d empty=0 {symbolic name for a null constant}
658
659 @* \[2] The character set.
660 In order to make \TeX\ readily portable to a wide variety of
661 computers, all of its input text is converted to an internal eight-bit
662 code that includes standard ASCII, the ``American Standard Code for
663 Information Interchange.'' This conversion is done immediately when each
664 character is read in. Conversely, characters are converted from ASCII to
665 the user's external representation just before they are output to a
666 text file.
667
668 Such an internal code is relevant to users of \TeX\ primarily because it
669 governs the positions of characters in the fonts. For example, the
670 character `\.A' has ASCII code $65=@'101$, and when \TeX\ typesets
671 this letter it specifies character number 65 in the current font.
672 If that font actually has `\.A' in a different position, \TeX\ doesn't
673 know what the real position is; the program that does the actual printing from
674 \TeX's device-independent files is responsible for converting from ASCII to
675 a particular font encoding.
676 @^ASCII code@>
677
678 \TeX's internal code also defines the value of constants
679 that begin with a reverse apostrophe; and it provides an index to the
680 \.{\\catcode}, \.{\\mathcode}, \.{\\uccode}, \.{\\lccode}, and \.{\\delcode}
681 tables.
682
683 @ Characters of text that have been converted to \TeX's internal form
684 are said to be of type |ASCII_code|, which is a subrange of the integers.
685
686 @<Types...@>=
687 @!ASCII_code=0..255; {eight-bit numbers}
688
689 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
690 character sets were common, so it did not make provision for lowercase
691 letters. Nowadays, of course, we need to deal with both capital and small
692 letters in a convenient way, especially in a program for typesetting;
693 so the present specification of \TeX\ has been written under the assumption
694 that the \PASCAL\ compiler and run-time system permit the use of text files
695 with more than 64 distinguishable characters. More precisely, we assume that
696 the character set contains at least the letters and symbols associated
697 with ASCII codes @'40 through @'176; all of these characters are now
698 available on most computer terminals.
699
700 Since we are dealing with more characters than were present in the first
701 \PASCAL\ compilers, we have to decide what to call the associated data
702 type. Some \PASCAL s use the original name |char| for the
703 characters in text files, even though there now are more than 64 such
704 characters, while other \PASCAL s consider |char| to be a 64-element
705 subrange of a larger data type that has some other name.
706
707 In order to accommodate this difference, we shall use the name |text_char|
708 to stand for the data type of the characters that are converted to and
709 from |ASCII_code| when they are input and output. We shall also assume
710 that |text_char| consists of the elements |chr(first_text_char)| through
711 |chr(last_text_char)|, inclusive. The following definitions should be
712 adjusted if necessary.
713 @^system dependencies@>
714
715 @d text_char == char {the data type of characters in text files}
716 @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
717 @d last_text_char=255 {ordinal number of the largest element of |text_char|}
718
719 @<Local variables for init...@>=
720 @!i:integer;
721
722 @ The \TeX\ processor converts between ASCII code and
723 the user's external character set by means of arrays |xord| and |xchr|
724 that are analogous to \PASCAL's |ord| and |chr| functions.
725
726 @<Glob...@>=
727 @!xord: array [text_char] of ASCII_code;
728 {specifies conversion of input characters}
729 @!xchr: array [ASCII_code] of text_char;
730 {specifies conversion of output characters}
731
732 @ Since we are assuming that our \PASCAL\ system is able to read and
733 write the visible characters of standard ASCII (although not
734 necessarily using the ASCII codes to represent them), the following
735 assignment statements initialize the standard part of the |xchr| array
736 properly, without needing any system-dependent changes. On the other
737 hand, it is possible to implement \TeX\ with less complete character
738 sets, and in such cases it will be necessary to change something here.
739 @^system dependencies@>
740
741 @<Set init...@>=
742 xchr[@'40]:=' ';
743 xchr[@'41]:='!';
744 xchr[@'42]:='"';
745 xchr[@'43]:='#';
746 xchr[@'44]:='$';
747 xchr[@'45]:='%';
748 xchr[@'46]:='&';
749 xchr[@'47]:='''';@/
750 xchr[@'50]:='(';
751 xchr[@'51]:=')';
752 xchr[@'52]:='*';
753 xchr[@'53]:='+';
754 xchr[@'54]:=',';
755 xchr[@'55]:='-';
756 xchr[@'56]:='.';
757 xchr[@'57]:='/';@/
758 xchr[@'60]:='0';
759 xchr[@'61]:='1';
760 xchr[@'62]:='2';
761 xchr[@'63]:='3';
762 xchr[@'64]:='4';
763 xchr[@'65]:='5';
764 xchr[@'66]:='6';
765 xchr[@'67]:='7';@/
766 xchr[@'70]:='8';
767 xchr[@'71]:='9';
768 xchr[@'72]:=':';
769 xchr[@'73]:=';';
770 xchr[@'74]:='<';
771 xchr[@'75]:='=';
772 xchr[@'76]:='>';
773 xchr[@'77]:='?';@/
774 xchr[@'100]:='@@';
775 xchr[@'101]:='A';
776 xchr[@'102]:='B';
777 xchr[@'103]:='C';
778 xchr[@'104]:='D';
779 xchr[@'105]:='E';
780 xchr[@'106]:='F';
781 xchr[@'107]:='G';@/
782 xchr[@'110]:='H';
783 xchr[@'111]:='I';
784 xchr[@'112]:='J';
785 xchr[@'113]:='K';
786 xchr[@'114]:='L';
787 xchr[@'115]:='M';
788 xchr[@'116]:='N';
789 xchr[@'117]:='O';@/
790 xchr[@'120]:='P';
791 xchr[@'121]:='Q';
792 xchr[@'122]:='R';
793 xchr[@'123]:='S';
794 xchr[@'124]:='T';
795 xchr[@'125]:='U';
796 xchr[@'126]:='V';
797 xchr[@'127]:='W';@/
798 xchr[@'130]:='X';
799 xchr[@'131]:='Y';
800 xchr[@'132]:='Z';
801 xchr[@'133]:='[';
802 xchr[@'134]:='\';
803 xchr[@'135]:=']';
804 xchr[@'136]:='^';
805 xchr[@'137]:='_';@/
806 xchr[@'140]:='`';
807 xchr[@'141]:='a';
808 xchr[@'142]:='b';
809 xchr[@'143]:='c';
810 xchr[@'144]:='d';
811 xchr[@'145]:='e';
812 xchr[@'146]:='f';
813 xchr[@'147]:='g';@/
814 xchr[@'150]:='h';
815 xchr[@'151]:='i';
816 xchr[@'152]:='j';
817 xchr[@'153]:='k';
818 xchr[@'154]:='l';
819 xchr[@'155]:='m';
820 xchr[@'156]:='n';
821 xchr[@'157]:='o';@/
822 xchr[@'160]:='p';
823 xchr[@'161]:='q';
824 xchr[@'162]:='r';
825 xchr[@'163]:='s';
826 xchr[@'164]:='t';
827 xchr[@'165]:='u';
828 xchr[@'166]:='v';
829 xchr[@'167]:='w';@/
830 xchr[@'170]:='x';
831 xchr[@'171]:='y';
832 xchr[@'172]:='z';
833 xchr[@'173]:='{';
834 xchr[@'174]:='|';
835 xchr[@'175]:='}';
836 xchr[@'176]:='~';@/
837
838 @ Some of the ASCII codes without visible characters have been given symbolic
839 names in this program because they are used with a special meaning.
840
841 @d null_code=@'0 {ASCII code that might disappear}
842 @d carriage_return=@'15 {ASCII code used at end of line}
843 @d invalid_code=@'177 {ASCII code that many systems prohibit in text files}
844
845 @ The ASCII code is ``standard'' only to a certain extent, since many
846 computer installations have found it advantageous to have ready access
847 to more than 94 printing characters. Appendix~C of {\sl The \TeX book\/}
848 gives a complete specification of the intended correspondence between
849 characters and \TeX's internal representation.
850 @:TeXbook}{\sl The \TeX book@>
851
852 If \TeX\ is being used
853 on a garden-variety \PASCAL\ for which only standard ASCII
854 codes will appear in the input and output files, it doesn't really matter
855 what codes are specified in |xchr[0..@'37]|, but the safest policy is to
856 blank everything out by using the code shown below.
857
858 However, other settings of |xchr| will make \TeX\ more friendly on
859 computers that have an extended character set, so that users can type things
860 like `\.^^Z' instead of `\.{\\ne}'. People with extended character sets can
861 assign codes arbitrarily, giving an |xchr| equivalent to whatever
862 characters the users of \TeX\ are allowed to have in their input files.
863 It is best to make the codes correspond to the intended interpretations as
864 shown in Appendix~C whenever possible; but this is not necessary. For
865 example, in countries with an alphabet of more than 26 letters, it is
866 usually best to map the additional letters into codes less than~@'40.
867 To get the most ``permissive'' character set, change |' '| on the
868 right of these assignment statements to |chr(i)|.
869 @^character set dependencies@>
870 @^system dependencies@>
871
872 @<Set init...@>=
873 for i:=0 to @'37 do xchr[i]:=' ';
874 for i:=@'177 to @'377 do xchr[i]:=' ';
875
876 @ The following system-independent code makes the |xord| array contain a
877 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
878 where |i<j<@'177|, the value of |xord[xchr[i]]| will turn out to be
879 |j| or more; hence, standard ASCII code numbers will be used instead of
880 codes below @'40 in case there is a coincidence.
881
882 @<Set init...@>=
883 for i:=first_text_char to last_text_char do xord[chr(i)]:=invalid_code;
884 for i:=@'200 to @'377 do xord[xchr[i]]:=i;
885 for i:=0 to @'176 do xord[xchr[i]]:=i;
886
887 @* \[3] Input and output.
888 The bane of portability is the fact that different operating systems treat
889 input and output quite differently, perhaps because computer scientists
890 have not given sufficient attention to this problem. People have felt somehow
891 that input and output are not part of ``real'' programming. Well, it is true
892 that some kinds of programming are more fun than others. With existing
893 input/output conventions being so diverse and so messy, the only sources of
894 joy in such parts of the code are the rare occasions when one can find a
895 way to make the program a little less bad than it might have been. We have
896 two choices, either to attack I/O now and get it over with, or to postpone
897 I/O until near the end. Neither prospect is very attractive, so let's
898 get it over with.
899
900 The basic operations we need to do are (1)~inputting and outputting of
901 text, to or from a file or the user's terminal; (2)~inputting and
902 outputting of eight-bit bytes, to or from a file; (3)~instructing the
903 operating system to initiate (``open'') or to terminate (``close'') input or
904 output from a specified file; (4)~testing whether the end of an input
905 file has been reached.
906
907 \TeX\ needs to deal with two kinds of files.
908 We shall use the term |alpha_file| for a file that contains textual data,
909 and the term |byte_file| for a file that contains eight-bit binary information.
910 These two types turn out to be the same on many computers, but
911 sometimes there is a significant distinction, so we shall be careful to
912 distinguish between them. Standard protocols for transferring
913 such files from computer to computer, via high-speed networks, are
914 now becoming available to more and more communities of users.
915
916 The program actually makes use also of a third kind of file, called a
917 |word_file|, when dumping and reloading base information for its own
918 initialization. We shall define a word file later; but it will be possible
919 for us to specify simple operations on word files before they are defined.
920
921 @<Types...@>=
922 @!eight_bits=0..255; {unsigned one-byte quantity}
923 @!alpha_file=packed file of text_char; {files that contain textual data}
924 @!byte_file=packed file of eight_bits; {files that contain binary data}
925
926 @ Most of what we need to do with respect to input and output can be handled
927 by the I/O facilities that are standard in \PASCAL, i.e., the routines
928 called |get|, |put|, |eof|, and so on. But
929 standard \PASCAL\ does not allow file variables to be associated with file
930 names that are determined at run time, so it cannot be used to implement
931 \TeX; some sort of extension to \PASCAL's ordinary |reset| and |rewrite|
932 is crucial for our purposes. We shall assume that |name_of_file| is a variable
933 of an appropriate type such that the \PASCAL\ run-time system being used to
934 implement \TeX\ can open a file whose external name is specified by
935 |name_of_file|.
936 @^system dependencies@>
937
938 @<Glob...@>=
939 @!name_of_file:packed array[1..file_name_size] of char;@;@/
940 {on some systems this may be a \&{record} variable}
941 @!name_length:0..file_name_size;@/{this many characters are actually
942 relevant in |name_of_file| (the rest are blank)}
943
944 @ The \ph\ compiler with which the present version of \TeX\ was prepared has
945 extended the rules of \PASCAL\ in a very convenient way. To open file~|f|,
946 we can write
947 $$\vbox{\halign{#\hfil\qquad&#\hfil\cr
948 |reset(f,@t\\{name}@>,'/O')|&for input;\cr
949 |rewrite(f,@t\\{name}@>,'/O')|&for output.\cr}}$$
950 The `\\{name}' parameter, which is of type `{\bf packed array
951 $[\langle\\{any}\rangle]$ of \\{char}}', stands for the name of
952 the external file that is being opened for input or output.
953 Blank spaces that might appear in \\{name} are ignored.
954
955 The `\.{/O}' parameter tells the operating system not to issue its own
956 error messages if something goes wrong. If a file of the specified name
957 cannot be found, or if such a file cannot be opened for some other reason
958 (e.g., someone may already be trying to write the same file), we will have
959 |@!erstat(f)<>0| after an unsuccessful |reset| or |rewrite|. This allows
960 \TeX\ to undertake appropriate corrective action.
961 @:PASCAL H}{\ph@>
962 @^system dependencies@>
963
964 \TeX's file-opening procedures return |false| if no file identified by
965 |name_of_file| could be opened.
966
967 @d reset_OK(#)==erstat(#)=0
968 @d rewrite_OK(#)==erstat(#)=0
969
970 @p function a_open_in(var f:alpha_file):boolean;
971 {open a text file for input}
972 begin reset(f,name_of_file,'/O'); a_open_in:=reset_OK(f);
973 end;
974 @#
975 function a_open_out(var f:alpha_file):boolean;
976 {open a text file for output}
977 begin rewrite(f,name_of_file,'/O'); a_open_out:=rewrite_OK(f);
978 end;
979 @#
980 function b_open_in(var f:byte_file):boolean;
981 {open a binary file for input}
982 begin reset(f,name_of_file,'/O'); b_open_in:=reset_OK(f);
983 end;
984 @#
985 function b_open_out(var f:byte_file):boolean;
986 {open a binary file for output}
987 begin rewrite(f,name_of_file,'/O'); b_open_out:=rewrite_OK(f);
988 end;
989 @#
990 function w_open_in(var f:word_file):boolean;
991 {open a word file for input}
992 begin reset(f,name_of_file,'/O'); w_open_in:=reset_OK(f);
993 end;
994 @#
995 function w_open_out(var f:word_file):boolean;
996 {open a word file for output}
997 begin rewrite(f,name_of_file,'/O'); w_open_out:=rewrite_OK(f);
998 end;
999
1000 @ Files can be closed with the \ph\ routine `|close(f)|', which
1001 @:PASCAL H}{\ph@>
1002 @^system dependencies@>
1003 should be used when all input or output with respect to |f| has been completed.
1004 This makes |f| available to be opened again, if desired; and if |f| was used for
1005 output, the |close| operation makes the corresponding external file appear
1006 on the user's area, ready to be read.
1007
1008 These procedures should not generate error messages if a file is
1009 being closed before it has been successfully opened.
1010
1011 @p procedure a_close(var f:alpha_file); {close a text file}
1012 begin close(f);
1013 end;
1014 @#
1015 procedure b_close(var f:byte_file); {close a binary file}
1016 begin close(f);
1017 end;
1018 @#
1019 procedure w_close(var f:word_file); {close a word file}
1020 begin close(f);
1021 end;
1022
1023 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
1024 procedures, so we don't have to make any other special arrangements for
1025 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
1026 The treatment of text input is more difficult, however, because
1027 of the necessary translation to |ASCII_code| values.
1028 \TeX's conventions should be efficient, and they should
1029 blend nicely with the user's operating environment.
1030
1031 @ Input from text files is read one line at a time, using a routine called
1032 |input_ln|. This function is defined in terms of global variables called
1033 |buffer|, |first|, and |last| that will be described in detail later; for
1034 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
1035 values, and that |first| and |last| are indices into this array
1036 representing the beginning and ending of a line of text.
1037
1038 @<Glob...@>=
1039 @!buffer:array[0..buf_size] of ASCII_code; {lines of characters being read}
1040 @!first:0..buf_size; {the first unused position in |buffer|}
1041 @!last:0..buf_size; {end of the line just input to |buffer|}
1042 @!max_buf_stack:0..buf_size; {largest index used in |buffer|}
1043
1044 @ The |input_ln| function brings the next line of input from the specified
1045 file into available positions of the buffer array and returns the value
1046 |true|, unless the file has already been entirely read, in which case it
1047 returns |false| and sets |last:=first|. In general, the |ASCII_code|
1048 numbers that represent the next line of the file are input into
1049 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
1050 global variable |last| is set equal to |first| plus the length of the
1051 line. Trailing blanks are removed from the line; thus, either |last=first|
1052 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
1053
1054 An overflow error is given, however, if the normal actions of |input_ln|
1055 would make |last>=buf_size|; this is done so that other parts of \TeX\
1056 can safely look at the contents of |buffer[last+1]| without overstepping
1057 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
1058 |first<buf_size| will always hold, so that there is always room for an
1059 ``empty'' line.
1060
1061 The variable |max_buf_stack|, which is used to keep track of how large
1062 the |buf_size| parameter must be to accommodate the present job, is
1063 also kept up to date by |input_ln|.
1064
1065 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
1066 before looking at the first character of the line; this skips over
1067 an |eoln| that was in |f^|. The procedure does not do a |get| when it
1068 reaches the end of the line; therefore it can be used to acquire input
1069 from the user's terminal as well as from ordinary text files.
1070
1071 Standard \PASCAL\ says that a file should have |eoln| immediately
1072 before |eof|, but \TeX\ needs only a weaker restriction: If |eof|
1073 occurs in the middle of a line, the system function |eoln| should return
1074 a |true| result (even though |f^| will be undefined).
1075
1076 Since the inner loop of |input_ln| is part of \TeX's ``inner loop''---each
1077 character of input comes in at this place---it is wise to reduce system
1078 overhead by making use of special routines that read in an entire array
1079 of characters at once, if such routines are available. The following
1080 code uses standard \PASCAL\ to illustrate what needs to be done, but
1081 finer tuning is often possible at well-developed \PASCAL\ sites.
1082 @^inner loop@>
1083
1084 @p function input_ln(var f:alpha_file;@!bypass_eoln:boolean):boolean;
1085 {inputs the next line or returns |false|}
1086 var last_nonblank:0..buf_size; {|last| with trailing blanks removed}
1087 begin if bypass_eoln then if not eof(f) then get(f);
1088 {input the first character of the line into |f^|}
1089 last:=first; {cf.\ Matthew 19\thinspace:\thinspace30}
1090 if eof(f) then input_ln:=false
1091 else begin last_nonblank:=first;
1092 while not eoln(f) do
1093 begin if last>=max_buf_stack then
1094 begin max_buf_stack:=last+1;
1095 if max_buf_stack=buf_size then
1096 @<Report overflow of the input buffer, and abort@>;
1097 end;
1098 buffer[last]:=xord[f^]; get(f); incr(last);
1099 if buffer[last-1]<>" " then last_nonblank:=last;
1100 end;
1101 last:=last_nonblank; input_ln:=true;
1102 end;
1103 end;
1104
1105 @ The user's terminal acts essentially like other files of text, except
1106 that it is used both for input and for output. When the terminal is
1107 considered an input file, the file variable is called |term_in|, and when it
1108 is considered an output file the file variable is |term_out|.
1109 @^system dependencies@>
1110
1111 @<Glob...@>=
1112 @!term_in:alpha_file; {the terminal as an input file}
1113 @!term_out:alpha_file; {the terminal as an output file}
1114
1115 @ Here is how to open the terminal files
1116 in \ph. The `\.{/I}' switch suppresses the first |get|.
1117 @:PASCAL H}{\ph@>
1118 @^system dependencies@>
1119
1120 @d t_open_in==reset(term_in,'TTY:','/O/I') {open the terminal for text input}
1121 @d t_open_out==rewrite(term_out,'TTY:','/O') {open the terminal for text output}
1122
1123 @ Sometimes it is necessary to synchronize the input/output mixture that
1124 happens on the user's terminal, and three system-dependent
1125 procedures are used for this
1126 purpose. The first of these, |update_terminal|, is called when we want
1127 to make sure that everything we have output to the terminal so far has
1128 actually left the computer's internal buffers and been sent.
1129 The second, |clear_terminal|, is called when we wish to cancel any
1130 input that the user may have typed ahead (since we are about to
1131 issue an unexpected error message). The third, |wake_up_terminal|,
1132 is supposed to revive the terminal if the user has disabled it by
1133 some instruction to the operating system. The following macros show how
1134 these operations can be specified in \ph:
1135 @:PASCAL H}{\ph@>
1136 @^system dependencies@>
1137
1138 @d update_terminal == break(term_out) {empty the terminal output buffer}
1139 @d clear_terminal == break_in(term_in,true) {clear the terminal input buffer}
1140 @d wake_up_terminal == do_nothing {cancel the user's cancellation of output}
1141
1142 @ We need a special routine to read the first line of \TeX\ input from
1143 the user's terminal. This line is different because it is read before we
1144 have opened the transcript file; there is sort of a ``chicken and
1145 egg'' problem here. If the user types `\.{\\input paper}' on the first
1146 line, or if some macro invoked by that line does such an \.{\\input},
1147 the transcript file will be named `\.{paper.log}'; but if no \.{\\input}
1148 commands are performed during the first line of terminal input, the transcript
1149 file will acquire its default name `\.{texput.log}'. (The transcript file
1150 will not contain error messages generated by the first line before the
1151 first \.{\\input} command.)
1152 @.texput@>
1153
1154 The first line is even more special if we are lucky enough to have an operating
1155 system that treats \TeX\ differently from a run-of-the-mill \PASCAL\ object
1156 program. It's nice to let the user start running a \TeX\ job by typing
1157 a command line like `\.{tex paper}'; in such a case, \TeX\ will operate
1158 as if the first line of input were `\.{paper}', i.e., the first line will
1159 consist of the remainder of the command line, after the part that invoked
1160 \TeX.
1161
1162 The first line is special also because it may be read before \TeX\ has
1163 input a format file. In such cases, normal error messages cannot yet
1164 be given. The following code uses concepts that will be explained later.
1165 (If the \PASCAL\ compiler does not support non-local |@!goto|\unskip, the
1166 @^system dependencies@>
1167 statement `|goto final_end|' should be replaced by something that
1168 quietly terminates the program.)
1169
1170 @<Report overflow of the input buffer, and abort@>=
1171 if format_ident=0 then
1172 begin write_ln(term_out,'Buffer size exceeded!'); goto final_end;
1173 @.Buffer size exceeded@>
1174 end
1175 else begin cur_input.loc_field:=first; cur_input.limit_field:=last-1;
1176 overflow("buffer size",buf_size);
1177 @:TeX capacity exceeded buffer size}{\quad buffer size@>
1178 end
1179
1180 @ Different systems have different ways to get started. But regardless of
1181 what conventions are adopted, the routine that initializes the terminal
1182 should satisfy the following specifications:
1183
1184 \yskip\textindent{1)}It should open file |term_in| for input from the
1185 terminal. (The file |term_out| will already be open for output to the
1186 terminal.)
1187
1188 \textindent{2)}If the user has given a command line, this line should be
1189 considered the first line of terminal input. Otherwise the
1190 user should be prompted with `\.{**}', and the first line of input
1191 should be whatever is typed in response.
1192
1193 \textindent{3)}The first line of input, which might or might not be a
1194 command line, should appear in locations |first| to |last-1| of the
1195 |buffer| array.
1196
1197 \textindent{4)}The global variable |loc| should be set so that the
1198 character to be read next by \TeX\ is in |buffer[loc]|. This
1199 character should not be blank, and we should have |loc<last|.
1200
1201 \yskip\noindent(It may be necessary to prompt the user several times
1202 before a non-blank line comes in. The prompt is `\.{**}' instead of the
1203 later `\.*' because the meaning is slightly different: `\.{\\input}' need
1204 not be typed immediately after~`\.{**}'.)
1205
1206 @d loc==cur_input.loc_field {location of first unread character in |buffer|}
1207
1208 @ The following program does the required initialization
1209 without retrieving a possible command line.
1210 It should be clear how to modify this routine to deal with command lines,
1211 if the system permits them.
1212 @^system dependencies@>
1213
1214 @p function init_terminal:boolean; {gets the terminal input started}
1215 label exit;
1216 begin t_open_in;
1217 loop@+begin wake_up_terminal; write(term_out,'**'); update_terminal;
1218 @.**@>
1219 if not input_ln(term_in,true) then {this shouldn't happen}
1220 begin write_ln(term_out);
1221 write(term_out,'! End of file on the terminal... why?');
1222 @.End of file on the terminal@>
1223 init_terminal:=false; return;
1224 end;
1225 loc:=first;
1226 while (loc<last)and(buffer[loc]=" ") do incr(loc);
1227 if loc<last then
1228 begin init_terminal:=true;
1229 return; {return unless the line was all blank}
1230 end;
1231 write_ln(term_out,'Please type the name of your input file.');
1232 end;
1233 exit:end;
1234
1235 @* \[4] String handling.
1236 Control sequence names and diagnostic messages are variable-length strings
1237 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
1238 mechanism, \TeX\ does all of its string processing by homegrown methods.
1239
1240 Elaborate facilities for dynamic strings are not needed, so all of the
1241 necessary operations can be handled with a simple data structure.
1242 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
1243 of the strings, and the array |str_start| contains indices of the starting
1244 points of each string. Strings are referred to by integer numbers, so that
1245 string number |s| comprises the characters |str_pool[j]| for
1246 |str_start[s]<=j<str_start[s+1]|. Additional integer variables
1247 |pool_ptr| and |str_ptr| indicate the number of entries used so far
1248 in |str_pool| and |str_start|, respectively; locations
1249 |str_pool[pool_ptr]| and |str_start[str_ptr]| are
1250 ready for the next string to be allocated.
1251
1252 String numbers 0 to 255 are reserved for strings that correspond to single
1253 ASCII characters. This is in accordance with the conventions of \.{WEB},
1254 @.WEB@>
1255 which converts single-character strings into the ASCII code number of the
1256 single character involved, while it converts other strings into integers
1257 and builds a string pool file. Thus, when the string constant \.{"."} appears
1258 in the program below, \.{WEB} converts it into the integer 46, which is the
1259 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1260 into some integer greater than~255. String number 46 will presumably be the
1261 single character `\..'; but some ASCII codes have no standard visible
1262 representation, and \TeX\ sometimes needs to be able to print an arbitrary
1263 ASCII character, so the first 256 strings are used to specify exactly what
1264 should be printed for each of the 256 possibilities.
1265
1266 Elements of the |str_pool| array must be ASCII codes that can actually
1267 be printed; i.e., they must have an |xchr| equivalent in the local
1268 character set. (This restriction applies only to preloaded strings,
1269 not to those generated dynamically by the user.)
1270
1271 Some \PASCAL\ compilers won't pack integers into a single byte unless the
1272 integers lie in the range |-128..127|. To accommodate such systems
1273 we access the string pool only via macros that can easily be redefined.
1274 @^system dependencies@>
1275
1276 @d si(#) == # {convert from |ASCII_code| to |packed_ASCII_code|}
1277 @d so(#) == # {convert from |packed_ASCII_code| to |ASCII_code|}
1278
1279 @<Types...@>=
1280 @!pool_pointer = 0..pool_size; {for variables that point into |str_pool|}
1281 @!str_number = 0..max_strings; {for variables that point into |str_start|}
1282 @!packed_ASCII_code = 0..255; {elements of |str_pool| array}
1283
1284 @ @<Glob...@>=
1285 @!str_pool:packed array[pool_pointer] of packed_ASCII_code; {the characters}
1286 @!str_start : array[str_number] of pool_pointer; {the starting pointers}
1287 @!pool_ptr : pool_pointer; {first unused position in |str_pool|}
1288 @!str_ptr : str_number; {number of the current string being created}
1289 @!init_pool_ptr : pool_pointer; {the starting value of |pool_ptr|}
1290 @!init_str_ptr : str_number; {the starting value of |str_ptr|}
1291
1292 @ Several of the elementary string operations are performed using \.{WEB}
1293 macros instead of \PASCAL\ procedures, because many of the
1294 operations are done quite frequently and we want to avoid the
1295 overhead of procedure calls. For example, here is
1296 a simple macro that computes the length of a string.
1297 @.WEB@>
1298
1299 @d length(#)==(str_start[#+1]-str_start[#]) {the number of characters
1300 in string number \#}
1301
1302 @ The length of the current string is called |cur_length|:
1303
1304 @d cur_length == (pool_ptr - str_start[str_ptr])
1305
1306 @ Strings are created by appending character codes to |str_pool|.
1307 The |append_char| macro, defined here, does not check to see if the
1308 value of |pool_ptr| has gotten too high; this test is supposed to be
1309 made before |append_char| is used. There is also a |flush_char|
1310 macro, which erases the last character appended.
1311
1312 To test if there is room to append |l| more characters to |str_pool|,
1313 we shall write |str_room(l)|, which aborts \TeX\ and gives an
1314 apologetic error message if there isn't enough room.
1315
1316 @d append_char(#) == {put |ASCII_code| \# at the end of |str_pool|}
1317 begin str_pool[pool_ptr]:=si(#); incr(pool_ptr);
1318 end
1319 @d flush_char == decr(pool_ptr) {forget the last character in the pool}
1320 @d str_room(#) == {make sure that the pool hasn't overflowed}
1321 begin if pool_ptr+# > pool_size then
1322 overflow("pool size",pool_size-init_pool_ptr);
1323 @:TeX capacity exceeded pool size}{\quad pool size@>
1324 end
1325
1326 @ Once a sequence of characters has been appended to |str_pool|, it
1327 officially becomes a string when the function |make_string| is called.
1328 This function returns the identification number of the new string as its
1329 value.
1330
1331 @p function make_string : str_number; {current string enters the pool}
1332 begin if str_ptr=max_strings then
1333 overflow("number of strings",max_strings-init_str_ptr);
1334 @:TeX capacity exceeded number of strings}{\quad number of strings@>
1335 incr(str_ptr); str_start[str_ptr]:=pool_ptr;
1336 make_string:=str_ptr-1;
1337 end;
1338
1339 @ To destroy the most recently made string, we say |flush_string|.
1340
1341 @d flush_string==begin decr(str_ptr); pool_ptr:=str_start[str_ptr];
1342 end
1343
1344 @ The following subroutine compares string |s| with another string of the
1345 same length that appears in |buffer| starting at position |k|;
1346 the result is |true| if and only if the strings are equal.
1347 Empirical tests indicate that |str_eq_buf| is used in such a way that
1348 it tends to return |true| about 80 percent of the time.
1349
1350 @p function str_eq_buf(@!s:str_number;@!k:integer):boolean;
1351 {test equality of strings}
1352 label not_found; {loop exit}
1353 var j: pool_pointer; {running index}
1354 @!result: boolean; {result of comparison}
1355 begin j:=str_start[s];
1356 while j<str_start[s+1] do
1357 begin if so(str_pool[j])<>buffer[k] then
1358 begin result:=false; goto not_found;
1359 end;
1360 incr(j); incr(k);
1361 end;
1362 result:=true;
1363 not_found: str_eq_buf:=result;
1364 end;
1365
1366 @ Here is a similar routine, but it compares two strings in the string pool,
1367 and it does not assume that they have the same length.
1368
1369 @p function str_eq_str(@!s,@!t:str_number):boolean;
1370 {test equality of strings}
1371 label not_found; {loop exit}
1372 var j,@!k: pool_pointer; {running indices}
1373 @!result: boolean; {result of comparison}
1374 begin result:=false;
1375 if length(s)<>length(t) then goto not_found;
1376 j:=str_start[s]; k:=str_start[t];
1377 while j<str_start[s+1] do
1378 begin if str_pool[j]<>str_pool[k] then goto not_found;
1379 incr(j); incr(k);
1380 end;
1381 result:=true;
1382 not_found: str_eq_str:=result;
1383 end;
1384
1385 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1386 and |str_ptr| are computed by the \.{INITEX} program, based in part
1387 on the information that \.{WEB} has output while processing \TeX.
1388 @.INITEX@>
1389 @^string pool@>
1390
1391 @p @!init function get_strings_started:boolean; {initializes the string pool,
1392 but returns |false| if something goes wrong}
1393 label done,exit;
1394 var k,@!l:0..255; {small indices or counters}
1395 @!m,@!n:text_char; {characters input from |pool_file|}
1396 @!g:str_number; {garbage}
1397 @!a:integer; {accumulator for check sum}
1398 @!c:boolean; {check sum has been checked}
1399 begin pool_ptr:=0; str_ptr:=0; str_start[0]:=0;
1400 @<Make the first 256 strings@>;
1401 @<Read the other strings from the \.{TEX.POOL} file and return |true|,
1402 or give an error message and return |false|@>;
1403 exit:end;
1404 tini
1405
1406 @ @d app_lc_hex(#)==l:=#;
1407 if l<10 then append_char(l+"0")@+else append_char(l-10+"a")
1408
1409 @<Make the first 256...@>=
1410 for k:=0 to 255 do
1411 begin if (@<Character |k| cannot be printed@>) then
1412 begin append_char("^"); append_char("^");
1413 if k<@'100 then append_char(k+@'100)
1414 else if k<@'200 then append_char(k-@'100)
1415 else begin app_lc_hex(k div 16); app_lc_hex(k mod 16);
1416 end;
1417 end
1418 else append_char(k);
1419 g:=make_string;
1420 end
1421
1422 @ The first 128 strings will contain 95 standard ASCII characters, and the
1423 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1424 unless a system-dependent change is made here. Installations that have
1425 an extended character set, where for example |xchr[@'32]=@t\.{\'^^Z\'}@>|,
1426 would like string @'32 to be the single character @'32 instead of the
1427 three characters @'136, @'136, @'132 (\.{\^\^Z}). On the other hand,
1428 even people with an extended character set will want to represent string
1429 @'15 by \.{\^\^M}, since @'15 is |carriage_return|; the idea is to
1430 produce visible strings instead of tabs or line-feeds or carriage-returns
1431 or bell-rings or characters that are treated anomalously in text files.
1432
1433 Unprintable characters of codes 128--255 are, similarly, rendered
1434 \.{\^\^80}--\.{\^\^ff}.
1435
1436 The boolean expression defined here should be |true| unless \TeX\
1437 internal code number~|k| corresponds to a non-troublesome visible
1438 symbol in the local character set. An appropriate formula for the
1439 extended character set recommended in {\sl The \TeX book\/} would, for
1440 example, be `|k in [0,@'10..@'12,@'14,@'15,@'33,@'177..@'377]|'.
1441 If character |k| cannot be printed, and |k<@'200|, then character |k+@'100| or
1442 |k-@'100| must be printable; moreover, ASCII codes |[@'41..@'46,
1443 @'60..@'71, @'136, @'141..@'146, @'160..@'171]| must be printable.
1444 Thus, at least 80 printable characters are needed.
1445 @:TeXbook}{\sl The \TeX book@>
1446 @^character set dependencies@>
1447 @^system dependencies@>
1448
1449 @<Character |k| cannot be printed@>=
1450 (k<" ")or(k>"~")
1451
1452 @ When the \.{WEB} system program called \.{TANGLE} processes the \.{TEX.WEB}
1453 description that you are now reading, it outputs the \PASCAL\ program
1454 \.{TEX.PAS} and also a string pool file called \.{TEX.POOL}. The \.{INITEX}
1455 @.WEB@>@.INITEX@>
1456 program reads the latter file, where each string appears as a two-digit decimal
1457 length followed by the string itself, and the information is recorded in
1458 \TeX's string memory.
1459
1460 @<Glob...@>=
1461 @!init @!pool_file:alpha_file; {the string-pool file output by \.{TANGLE}}
1462 tini
1463
1464 @ @d bad_pool(#)==begin wake_up_terminal; write_ln(term_out,#);
1465 a_close(pool_file); get_strings_started:=false; return;
1466 end
1467 @<Read the other strings...@>=
1468 name_of_file:=pool_name; {we needn't set |name_length|}
1469 if a_open_in(pool_file) then
1470 begin c:=false;
1471 repeat @<Read one string, but return |false| if the
1472 string memory space is getting too tight for comfort@>;
1473 until c;
1474 a_close(pool_file); get_strings_started:=true;
1475 end
1476 else bad_pool('! I can''t read TEX.POOL.')
1477 @.I can't read TEX.POOL@>
1478
1479 @ @<Read one string...@>=
1480 begin if eof(pool_file) then bad_pool('! TEX.POOL has no check sum.');
1481 @.TEX.POOL has no check sum@>
1482 read(pool_file,m,n); {read two digits of string length}
1483 if m='*' then @<Check the pool check sum@>
1484 else begin if (xord[m]<"0")or(xord[m]>"9")or@|
1485 (xord[n]<"0")or(xord[n]>"9") then
1486 bad_pool('! TEX.POOL line doesn''t begin with two digits.');
1487 @.TEX.POOL line doesn't...@>
1488 l:=xord[m]*10+xord[n]-"0"*11; {compute the length}
1489 if pool_ptr+l+string_vacancies>pool_size then
1490 bad_pool('! You have to increase POOLSIZE.');
1491 @.You have to increase POOLSIZE@>
1492 for k:=1 to l do
1493 begin if eoln(pool_file) then m:=' '@+else read(pool_file,m);
1494 append_char(xord[m]);
1495 end;
1496 read_ln(pool_file); g:=make_string;
1497 end;
1498 end
1499
1500 @ The \.{WEB} operation \.{@@\$} denotes the value that should be at the
1501 end of this \.{TEX.POOL} file; any other value means that the wrong pool
1502 file has been loaded.
1503 @^check sum@>
1504
1505 @<Check the pool check sum@>=
1506 begin a:=0; k:=1;
1507 loop@+ begin if (xord[n]<"0")or(xord[n]>"9") then
1508 bad_pool('! TEX.POOL check sum doesn''t have nine digits.');
1509 @.TEX.POOL check sum...@>
1510 a:=10*a+xord[n]-"0";
1511 if k=9 then goto done;
1512 incr(k); read(pool_file,n);
1513 end;
1514 done: if a<>@$ then bad_pool('! TEX.POOL doesn''t match; TANGLE me again.');
1515 @.TEX.POOL doesn't match@>
1516 c:=true;
1517 end
1518
1519 @* \[5] On-line and off-line printing.
1520 Messages that are sent to a user's terminal and to the transcript-log file
1521 are produced by several `|print|' procedures. These procedures will
1522 direct their output to a variety of places, based on the setting of
1523 the global variable |selector|, which has the following possible
1524 values:
1525
1526 \yskip
1527 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1528 transcript file.
1529
1530 \hang |log_only|, prints only on the transcript file.
1531
1532 \hang |term_only|, prints only on the terminal.
1533
1534 \hang |no_print|, doesn't print at all. This is used only in rare cases
1535 before the transcript file is open.
1536
1537 \hang |pseudo|, puts output into a cyclic buffer that is used
1538 by the |show_context| routine; when we get to that routine we shall discuss
1539 the reasoning behind this curious mode.
1540
1541 \hang |new_string|, appends the output to the current string in the
1542 string pool.
1543
1544 \hang 0 to 15, prints on one of the sixteen files for \.{\\write} output.
1545
1546 \yskip
1547 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1548 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1549 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.
1550
1551 Three additional global variables, |tally| and |term_offset| and
1552 |file_offset|, record the number of characters that have been printed
1553 since they were most recently cleared to zero. We use |tally| to record
1554 the length of (possibly very long) stretches of printing; |term_offset|
1555 and |file_offset|, on the other hand, keep track of how many characters
1556 have appeared so far on the current line that has been output to the
1557 terminal or to the transcript file, respectively.
1558
1559 @d no_print=16 {|selector| setting that makes data disappear}
1560 @d term_only=17 {printing is destined for the terminal only}
1561 @d log_only=18 {printing is destined for the transcript file only}
1562 @d term_and_log=19 {normal |selector| setting}
1563 @d pseudo=20 {special |selector| setting for |show_context|}
1564 @d new_string=21 {printing is deflected to the string pool}
1565 @d max_selector=21 {highest selector setting}
1566
1567 @<Glob...@>=
1568 @!log_file : alpha_file; {transcript of \TeX\ session}
1569 @!selector : 0..max_selector; {where to print a message}
1570 @!dig : array[0..22] of 0..15; {digits in a number being output}
1571 @!tally : integer; {the number of characters recently printed}
1572 @!term_offset : 0..max_print_line;
1573 {the number of characters on the current terminal line}
1574 @!file_offset : 0..max_print_line;
1575 {the number of characters on the current file line}
1576 @!trick_buf:array[0..error_line] of ASCII_code; {circular buffer for
1577 pseudoprinting}
1578 @!trick_count: integer; {threshold for pseudoprinting, explained later}
1579 @!first_count: integer; {another variable for pseudoprinting}
1580
1581 @ @<Initialize the output routines@>=
1582 selector:=term_only; tally:=0; term_offset:=0; file_offset:=0;
1583
1584 @ Macro abbreviations for output to the terminal and to the log file are
1585 defined here for convenience. Some systems need special conventions
1586 for terminal output, and it is possible to adhere to those conventions
1587 by changing |wterm|, |wterm_ln|, and |wterm_cr| in this section.
1588 @^system dependencies@>
1589
1590 @d wterm(#)==write(term_out,#)
1591 @d wterm_ln(#)==write_ln(term_out,#)
1592 @d wterm_cr==write_ln(term_out)
1593 @d wlog(#)==write(log_file,#)
1594 @d wlog_ln(#)==write_ln(log_file,#)
1595 @d wlog_cr==write_ln(log_file)
1596
1597 @ To end a line of text output, we call |print_ln|.
1598
1599 @<Basic print...@>=
1600 procedure print_ln; {prints an end-of-line}
1601 begin case selector of
1602 term_and_log: begin wterm_cr; wlog_cr;
1603 term_offset:=0; file_offset:=0;
1604 end;
1605 log_only: begin wlog_cr; file_offset:=0;
1606 end;
1607 term_only: begin wterm_cr; term_offset:=0;
1608 end;
1609 no_print,pseudo,new_string: do_nothing;
1610 othercases write_ln(write_file[selector])
1611 endcases;@/
1612 end; {|tally| is not affected}
1613
1614 @ The |print_char| procedure sends one character to the desired destination,
1615 using the |xchr| array to map it into an external character compatible with
1616 |input_ln|. All printing comes through |print_ln| or |print_char|.
1617
1618 @<Basic printing...@>=
1619 procedure print_char(@!s:ASCII_code); {prints a single character}
1620 label exit;
1621 begin if @<Character |s| is the current new-line character@> then
1622 if selector<pseudo then
1623 begin print_ln; return;
1624 end;
1625 case selector of
1626 term_and_log: begin wterm(xchr[s]); wlog(xchr[s]);
1627 incr(term_offset); incr(file_offset);
1628 if term_offset=max_print_line then
1629 begin wterm_cr; term_offset:=0;
1630 end;
1631 if file_offset=max_print_line then
1632 begin wlog_cr; file_offset:=0;
1633 end;
1634 end;
1635 log_only: begin wlog(xchr[s]); incr(file_offset);
1636 if file_offset=max_print_line then print_ln;
1637 end;
1638 term_only: begin wterm(xchr[s]); incr(term_offset);
1639 if term_offset=max_print_line then print_ln;
1640 end;
1641 no_print: do_nothing;
1642 pseudo: if tally<trick_count then trick_buf[tally mod error_line]:=s;
1643 new_string: begin if pool_ptr<pool_size then append_char(s);
1644 end; {we drop characters if the string space is full}
1645 othercases write(write_file[selector],xchr[s])
1646 endcases;@/
1647 incr(tally);
1648 exit:end;
1649
1650 @ An entire string is output by calling |print|. Note that if we are outputting
1651 the single standard ASCII character \.c, we could call |print("c")|, since
1652 |"c"=99| is the number of a single-character string, as explained above. But
1653 |print_char("c")| is quicker, so \TeX\ goes directly to the |print_char|
1654 routine when it knows that this is safe. (The present implementation
1655 assumes that it is always safe to print a visible ASCII character.)
1656 @^system dependencies@>
1657
1658 @<Basic print...@>=
1659 procedure print(@!s:integer); {prints string |s|}
1660 label exit;
1661 var j:pool_pointer; {current character code position}
1662 @!nl:integer; {new-line character to restore}
1663 begin if s>=str_ptr then s:="???" {this can't happen}
1664 @.???@>
1665 else if s<256 then
1666 if s<0 then s:="???" {can't happen}
1667 else begin if selector>pseudo then
1668 begin print_char(s); return; {internal strings are not expanded}
1669 end;
1670 if (@<Character |s| is the current new-line character@>) then
1671 if selector<pseudo then
1672 begin print_ln; return;
1673 end;
1674 nl:=new_line_char; new_line_char:=-1;
1675 {temporarily disable new-line character}
1676 j:=str_start[s];
1677 while j<str_start[s+1] do
1678 begin print_char(so(str_pool[j])); incr(j);
1679 end;
1680 new_line_char:=nl; return;
1681 end;
1682 j:=str_start[s];
1683 while j<str_start[s+1] do
1684 begin print_char(so(str_pool[j])); incr(j);
1685 end;
1686 exit:end;
1687
1688 @ Control sequence names, file names, and strings constructed with
1689 \.{\\string} might contain |ASCII_code| values that can't
1690 be printed using |print_char|. Therefore we use |slow_print| for them:
1691
1692 @<Basic print...@>=
1693 procedure slow_print(@!s:integer); {prints string |s|}
1694 var j:pool_pointer; {current character code position}
1695 begin if (s>=str_ptr) or (s<256) then print(s)
1696 else begin j:=str_start[s];
1697 while j<str_start[s+1] do
1698 begin print(so(str_pool[j])); incr(j);
1699 end;
1700 end;
1701 end;
1702
1703 @ Here is the very first thing that \TeX\ prints: a headline that identifies
1704 the version number and format package. The |term_offset| variable is temporarily
1705 incorrect, but the discrepancy is not serious since we assume that this
1706 part of the program is system dependent.
1707 @^system dependencies@>
1708
1709 @<Initialize the output...@>=
1710 wterm(banner);
1711 if format_ident=0 then wterm_ln(' (no format preloaded)')
1712 else begin slow_print(format_ident); print_ln;
1713 end;
1714 update_terminal;
1715
1716 @ The procedure |print_nl| is like |print|, but it makes sure that the
1717 string appears at the beginning of a new line.
1718
1719 @<Basic print...@>=
1720 procedure print_nl(@!s:str_number); {prints string |s| at beginning of line}
1721 begin if ((term_offset>0)and(odd(selector)))or@|
1722 ((file_offset>0)and(selector>=log_only)) then print_ln;
1723 print(s);
1724 end;
1725
1726 @ The procedure |print_esc| prints a string that is preceded by
1727 the user's escape character (which is usually a backslash).
1728
1729 @<Basic print...@>=
1730 procedure print_esc(@!s:str_number); {prints escape character, then |s|}
1731 var c:integer; {the escape character code}
1732 begin @<Set variable |c| to the current escape character@>;
1733 if c>=0 then if c<256 then print(c);
1734 slow_print(s);
1735 end;
1736
1737 @ An array of digits in the range |0..15| is printed by |print_the_digs|.
1738
1739 @<Basic print...@>=
1740 procedure print_the_digs(@!k:eight_bits);
1741 {prints |dig[k-1]|$\,\ldots\,$|dig[0]|}
1742 begin while k>0 do
1743 begin decr(k);
1744 if dig[k]<10 then print_char("0"+dig[k])
1745 else print_char("A"-10+dig[k]);
1746 end;
1747 end;
1748
1749 @ The following procedure, which prints out the decimal representation of a
1750 given integer |n|, has been written carefully so that it works properly
1751 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1752 to negative arguments, since such operations are not implemented consistently
1753 by all \PASCAL\ compilers.
1754
1755 @<Basic print...@>=
1756 procedure print_int(@!n:longinteger); {prints an integer in decimal form}
1757 var k:0..23; {index to current digit; we assume that $\vert n\vert<10^{23}$}
1758 @!m:longinteger; {used to negate |n| in possibly dangerous cases}
1759 begin k:=0;
1760 if n<0 then
1761 begin print_char("-");
1762 if n>-100000000 then negate(n)
1763 else begin m:=-1-n; n:=m div 10; m:=(m mod 10)+1; k:=1;
1764 if m<10 then dig[0]:=m
1765 else begin dig[0]:=0; incr(n);
1766 end;
1767 end;
1768 end;
1769 repeat dig[k]:=n mod 10; n:=n div 10; incr(k);
1770 until n=0;
1771 print_the_digs(k);
1772 end;
1773
1774 @ Here is a trivial procedure to print two digits; it is usually called with
1775 a parameter in the range |0<=n<=99|.
1776
1777 @p procedure print_two(@!n:integer); {prints two least significant digits}
1778 begin n:=abs(n) mod 100; print_char("0"+(n div 10));
1779 print_char("0"+(n mod 10));
1780 end;
1781
1782 @ Hexadecimal printing of nonnegative integers is accomplished by |print_hex|.
1783
1784 @p procedure print_hex(@!n:integer);
1785 {prints a positive integer in hexadecimal form}
1786 var k:0..22; {index to current digit; we assume that $0\L n<16^{22}$}
1787 begin k:=0; print_char("""");
1788 repeat dig[k]:=n mod 16; n:=n div 16; incr(k);
1789 until n=0;
1790 print_the_digs(k);
1791 end;
1792
1793 @ Old versions of \TeX\ needed a procedure called |print_ASCII| whose function
1794 is now subsumed by |print|. We retain the old name here as a possible aid to
1795 future software arch\ae ologists.
1796
1797 @d print_ASCII == print
1798
1799 @ Roman numerals are produced by the |print_roman_int| routine. Readers
1800 who like puzzles might enjoy trying to figure out how this tricky code
1801 works; therefore no explanation will be given. Notice that 1990 yields
1802 \.{mcmxc}, not \.{mxm}.
1803
1804 @p procedure print_roman_int(@!n:integer);
1805 label exit;
1806 var j,@!k: pool_pointer; {mysterious indices into |str_pool|}
1807 @!u,@!v: nonnegative_integer; {mysterious numbers}
1808 begin j:=str_start["m2d5c2l5x2v5i"]; v:=1000;
1809 loop@+ begin while n>=v do
1810 begin print_char(so(str_pool[j])); n:=n-v;
1811 end;
1812 if n<=0 then return; {nonpositive input produces no output}
1813 k:=j+2; u:=v div (so(str_pool[k-1])-"0");
1814 if str_pool[k-1]=si("2") then
1815 begin k:=k+2; u:=u div (so(str_pool[k-1])-"0");
1816 end;
1817 if n+u>=v then
1818 begin print_char(so(str_pool[k])); n:=n+u;
1819 end
1820 else begin j:=j+2; v:=v div (so(str_pool[j-1])-"0");
1821 end;
1822 end;
1823 exit:end;
1824
1825 @ The |print| subroutine will not print a string that is still being
1826 created. The following procedure will.
1827
1828 @p procedure print_current_string; {prints a yet-unmade string}
1829 var j:pool_pointer; {points to current character code}
1830 begin j:=str_start[str_ptr];
1831 while j<pool_ptr do
1832 begin print_char(so(str_pool[j])); incr(j);
1833 end;
1834 end;
1835
1836 @ Here is a procedure that asks the user to type a line of input,
1837 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1838 The input is placed into locations |first| through |last-1| of the
1839 |buffer| array, and echoed on the transcript file if appropriate.
1840
1841 This procedure is never called when |interaction<scroll_mode|.
1842
1843 @d prompt_input(#)==begin wake_up_terminal; print(#); term_input;
1844 end {prints a string and gets a line of input}
1845
1846 @p procedure term_input; {gets a line from the terminal}
1847 var k:0..buf_size; {index into |buffer|}
1848 begin update_terminal; {now the user sees the prompt for sure}
1849 if not input_ln(term_in,true) then fatal_error("End of file on the terminal!");
1850 @.End of file on the terminal@>
1851 term_offset:=0; {the user's line ended with \<\rm return>}
1852 decr(selector); {prepare to echo the input}
1853 if last<>first then for k:=first to last-1 do print(buffer[k]);
1854 print_ln; incr(selector); {restore previous status}
1855 end;
1856
1857 @* \[6] Reporting errors.
1858 When something anomalous is detected, \TeX\ typically does something like this:
1859 $$\vbox{\halign{#\hfil\cr
1860 |print_err("Something anomalous has been detected");|\cr
1861 |help3("This is the first line of my offer to help.")|\cr
1862 |("This is the second line. I'm trying to")|\cr
1863 |("explain the best way for you to proceed.");|\cr
1864 |error;|\cr}}$$
1865 A two-line help message would be given using |help2|, etc.; these informal
1866 helps should use simple vocabulary that complements the words used in the
1867 official error message that was printed. (Outside the U.S.A., the help
1868 messages should preferably be translated into the local vernacular. Each
1869 line of help is at most 60 characters long, in the present implementation,
1870 so that |max_print_line| will not be exceeded.)
1871
1872 The |print_err| procedure supplies a `\.!' before the official message,
1873 and makes sure that the terminal is awake if a stop is going to occur.
1874 The |error| procedure supplies a `\..' after the official message, then it
1875 shows the location of the error; and if |interaction=error_stop_mode|,
1876 it also enters into a dialog with the user, during which time the help
1877 message may be printed.
1878 @^system dependencies@>
1879
1880 @ The global variable |interaction| has four settings, representing increasing
1881 amounts of user interaction:
1882
1883 @d batch_mode=0 {omits all stops and omits terminal output}
1884 @d nonstop_mode=1 {omits all stops}
1885 @d scroll_mode=2 {omits error stops}
1886 @d error_stop_mode=3 {stops at every opportunity to interact}
1887 @d print_err(#)==begin if interaction=error_stop_mode then wake_up_terminal;
1888 print_nl("! "); print(#);
1889 end
1890 @d print_ignored_err(#)==begin
1891 {An error in original \TeX, but we want to send it only to the log in
1892 other engines, and without the word |"error"|, which humans and
1893 software look for.}
1894 old_selector_ignored_err := selector;
1895 selector := log_only;
1896 wlog_cr; wlog('ignored: '); print(#);
1897 selector := old_selector_ignored_err;
1898 end
1899
1900 @<Glob...@>=
1901 @!interaction:batch_mode..error_stop_mode; {current level of interaction}
1902
1903 @ @<Set init...@>=interaction:=error_stop_mode;
1904
1905 @ \TeX\ is careful not to call |error| when the print |selector| setting
1906 might be unusual. The only possible values of |selector| at the time of
1907 error messages are
1908
1909 \yskip\hang|no_print| (when |interaction=batch_mode|
1910 and |log_file| not yet open);
1911
1912 \hang|term_only| (when |interaction>batch_mode| and |log_file| not yet open);
1913
1914 \hang|log_only| (when |interaction=batch_mode| and |log_file| is open);
1915
1916 \hang|term_and_log| (when |interaction>batch_mode| and |log_file| is open).
1917
1918 @<Initialize the print |selector| based on |interaction|@>=
1919 if interaction=batch_mode then selector:=no_print@+else selector:=term_only
1920
1921 @ A global variable |deletions_allowed| is set |false| if the |get_next|
1922 routine is active when |error| is called; this ensures that |get_next|
1923 and related routines like |get_token| will never be called recursively.
1924 A similar interlock is provided by |set_box_allowed|.
1925 @^recursion@>
1926
1927 The global variable |history| records the worst level of error that
1928 has been detected. It has four possible values: |spotless|, |warning_issued|,
1929 |error_message_issued|, and |fatal_error_stop|.
1930
1931 Another global variable, |error_count|, is increased by one when an
1932 |error| occurs without an interactive dialog, and it is reset to zero at
1933 the end of every paragraph. If |error_count| reaches 100, \TeX\ decides
1934 that there is no point in continuing further.
1935
1936 @d spotless=0 {|history| value when nothing has been amiss yet}
1937 @d warning_issued=1 {|history| value when |begin_diagnostic| has been called}
1938 @d error_message_issued=2 {|history| value when |error| has been called}
1939 @d fatal_error_stop=3 {|history| value when termination was premature}
1940
1941 @<Glob...@>=
1942 @!deletions_allowed:boolean; {is it safe for |error| to call |get_token|?}
1943 @!set_box_allowed:boolean; {is it safe to do a \.{\\setbox} assignment?}
1944 @!history:spotless..fatal_error_stop; {has the source input been clean so far?}
1945 @!error_count:-1..100; {the number of scrolled errors since the
1946 last paragraph ended}
1947
1948 @ The value of |history| is initially |fatal_error_stop|, but it will
1949 be changed to |spotless| if \TeX\ survives the initialization process.
1950
1951 @<Set init...@>=
1952 deletions_allowed:=true; set_box_allowed:=true;
1953 error_count:=0; {|history| is initialized elsewhere}
1954
1955 @ Since errors can be detected almost anywhere in \TeX, we want to declare the
1956 error procedures near the beginning of the program. But the error procedures
1957 in turn use some other procedures, which need to be declared |forward|
1958 before we get to |error| itself.
1959
1960 It is possible for |error| to be called recursively if some error arises
1961 when |get_token| is being used to delete a token, and/or if some fatal error
1962 occurs while \TeX\ is trying to fix a non-fatal one. But such recursion
1963 @^recursion@>
1964 is never more than two levels deep.
1965
1966 @<Error handling...@>=
1967 procedure@?normalize_selector; forward;@t\2@>@/
1968 procedure@?get_token; forward;@t\2@>@/
1969 procedure@?term_input; forward;@t\2@>@/
1970 procedure@?show_context; forward;@t\2@>@/
1971 procedure@?begin_file_reading; forward;@t\2@>@/
1972 procedure@?open_log_file; forward;@t\2@>@/
1973 procedure@?close_files_and_terminate; forward;@t\2@>@/
1974 procedure@?clear_for_error_prompt; forward;@t\2@>@/
1975 procedure@?give_err_help; forward;@t\2@>@/
1976 @t\4\hskip-\fontdimen2\font@>@;@+@!debug@+procedure@?debug_help;
1977 forward;@;@+gubed
1978
1979 @ Individual lines of help are recorded in the array |help_line|, which
1980 contains entries in positions |0..(help_ptr-1)|. They should be printed
1981 in reverse order, i.e., with |help_line[0]| appearing last.
1982
1983 @d hlp1(#)==help_line[0]:=#;@+end
1984 @d hlp2(#)==help_line[1]:=#; hlp1
1985 @d hlp3(#)==help_line[2]:=#; hlp2
1986 @d hlp4(#)==help_line[3]:=#; hlp3
1987 @d hlp5(#)==help_line[4]:=#; hlp4
1988 @d hlp6(#)==help_line[5]:=#; hlp5
1989 @d help0==help_ptr:=0 {sometimes there might be no help}
1990 @d help1==@+begin help_ptr:=1; hlp1 {use this with one help line}
1991 @d help2==@+begin help_ptr:=2; hlp2 {use this with two help lines}
1992 @d help3==@+begin help_ptr:=3; hlp3 {use this with three help lines}
1993 @d help4==@+begin help_ptr:=4; hlp4 {use this with four help lines}
1994 @d help5==@+begin help_ptr:=5; hlp5 {use this with five help lines}
1995 @d help6==@+begin help_ptr:=6; hlp6 {use this with six help lines}
1996
1997 @<Glob...@>=
1998 @!help_line:array[0..5] of str_number; {helps for the next |error|}
1999 @!help_ptr:0..6; {the number of help lines present}
2000 @!use_err_help:boolean; {should the |err_help| list be shown?}
2001
2002 @ @<Set init...@>=
2003 help_ptr:=0; use_err_help:=false;
2004
2005 @ The |jump_out| procedure just cuts across all active procedure levels and
2006 goes to |end_of_TEX|. This is the only nontrivial |@!goto| statement in the
2007 whole program. It is used when there is no recovery from a particular error.
2008
2009 Some \PASCAL\ compilers do not implement non-local |goto| statements.
2010 @^system dependencies@>
2011 In such cases the body of |jump_out| should simply be
2012 `|close_files_and_terminate|;\thinspace' followed by a call on some system
2013 procedure that quietly terminates the program.
2014
2015 @<Error hand...@>=
2016 procedure jump_out;
2017 begin goto end_of_TEX;
2018 end;
2019
2020 @ Here now is the general |error| routine.
2021
2022 @<Error hand...@>=
2023 procedure error; {completes the job of error reporting}
2024 label continue,exit;
2025 var c:ASCII_code; {what the user types}
2026 @!s1,@!s2,@!s3,@!s4:integer;
2027 {used to save global variables when deleting tokens}
2028 begin if history<error_message_issued then history:=error_message_issued;
2029 print_char("."); show_context;
2030 if interaction=error_stop_mode then
2031 @<Get user's advice and |return|@>;
2032 incr(error_count);
2033 if error_count=100 then
2034 begin print_nl("(That makes 100 errors; please try again.)");
2035 @.That makes 100 errors...@>
2036 history:=fatal_error_stop; jump_out;
2037 end;
2038 @<Put help message on the transcript file@>;
2039 exit:end;
2040
2041 @ @<Get user's advice...@>=
2042 loop@+begin continue: if interaction<>error_stop_mode then return;
2043 clear_for_error_prompt; prompt_input("? ");
2044 @.?\relax@>
2045 if last=first then return;
2046 c:=buffer[first];
2047 if c>="a" then c:=c+"A"-"a"; {convert to uppercase}
2048 @<Interpret code |c| and |return| if done@>;
2049 end
2050
2051 @ It is desirable to provide an `\.E' option here that gives the user
2052 an easy way to return from \TeX\ to the system editor, with the offending
2053 line ready to be edited. But such an extension requires some system
2054 wizardry, so the present implementation simply types out the name of the
2055 file that should be
2056 edited and the relevant line number.
2057 @^system dependencies@>
2058
2059 There is a secret `\.D' option available when the debugging routines haven't
2060 been commented~out.
2061 @^debugging@>
2062
2063 @<Interpret code |c| and |return| if done@>=
2064 case c of
2065 "0","1","2","3","4","5","6","7","8","9": if deletions_allowed then
2066 @<Delete \(c)|c-"0"| tokens and |goto continue|@>;
2067 @t\4\4@>@;@+@!debug "D": begin debug_help; goto continue;@+end;@+gubed@/
2068 "E": if base_ptr>0 then if input_stack[base_ptr].name_field>=256 then
2069 begin print_nl("You want to edit file ");
2070 @.You want to edit file x@>
2071 slow_print(input_stack[base_ptr].name_field);
2072 print(" at line "); print_int(line);
2073 interaction:=scroll_mode; jump_out;
2074 end;
2075 "H": @<Print the help information and |goto continue|@>;
2076 "I":@<Introduce new material from the terminal and |return|@>;
2077 "Q","R","S":@<Change the interaction level and |return|@>;
2078 "X":begin interaction:=scroll_mode; jump_out;
2079 end;
2080 othercases do_nothing
2081 endcases;@/
2082 @<Print the menu of available options@>
2083
2084 @ @<Print the menu...@>=
2085 begin print("Type <return> to proceed, S to scroll future error messages,");@/
2086 @.Type <return> to proceed...@>
2087 print_nl("R to run without stopping, Q to run quietly,");@/
2088 print_nl("I to insert something, ");
2089 if base_ptr>0 then if input_stack[base_ptr].name_field>=256 then
2090 print("E to edit your file,");
2091 if deletions_allowed then
2092 print_nl("1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2093 print_nl("H for help, X to quit.");
2094 end
2095
2096 @ Here the author of \TeX\ apologizes for making use of the numerical
2097 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2098 |batch_mode|, |nonstop_mode|, |scroll_mode|.
2099 @^Knuth, Donald Ervin@>
2100
2101 @<Change the interaction...@>=
2102 begin error_count:=0; interaction:=batch_mode+c-"Q";
2103 print("OK, entering ");
2104 case c of
2105 "Q":begin print_esc("batchmode"); decr(selector);
2106 end;
2107 "R":print_esc("nonstopmode");
2108 "S":print_esc("scrollmode");
2109 end; {there are no other cases}
2110 print("..."); print_ln; update_terminal; return;
2111 end
2112
2113 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2114 contain the material inserted by the user; otherwise another prompt will
2115 be given. In order to understand this part of the program fully, you need
2116 to be familiar with \TeX's input stacks.
2117
2118 @<Introduce new material...@>=
2119 begin begin_file_reading; {enter a new syntactic level for terminal input}
2120 {now |state=mid_line|, so an initial blank space will count as a blank}
2121 if last>first+1 then
2122 begin loc:=first+1; buffer[first]:=" ";
2123 end
2124 else begin prompt_input("insert>"); loc:=first;
2125 @.insert>@>
2126 end;
2127 first:=last;
2128 cur_input.limit_field:=last-1; {no |end_line_char| ends this line}
2129 return;
2130 end
2131
2132 @ We allow deletion of up to 99 tokens at a time.
2133
2134 @<Delete \(c)|c-"0"| tokens...@>=
2135 begin s1:=cur_tok; s2:=cur_cmd; s3:=cur_chr; s4:=align_state;
2136 align_state:=1000000; OK_to_interrupt:=false;
2137 if (last>first+1) and (buffer[first+1]>="0")and(buffer[first+1]<="9") then
2138 c:=c*10+buffer[first+1]-"0"*11
2139 else c:=c-"0";
2140 while c>0 do
2141 begin get_token; {one-level recursive call of |error| is possible}
2142 decr(c);
2143 end;
2144 cur_tok:=s1; cur_cmd:=s2; cur_chr:=s3; align_state:=s4; OK_to_interrupt:=true;
2145 help2("I have just deleted some text, as you asked.")@/
2146 ("You can now delete more, or insert, or whatever.");
2147 show_context; goto continue;
2148 end
2149
2150 @ @<Print the help info...@>=
2151 begin if use_err_help then
2152 begin give_err_help; use_err_help:=false;
2153 end
2154 else begin if help_ptr=0 then
2155 help2("Sorry, I don't know how to help in this situation.")@/
2156 @t\kern1em@>("Maybe you should try asking a human?");
2157 repeat decr(help_ptr); print(help_line[help_ptr]); print_ln;
2158 until help_ptr=0;
2159 end;
2160 help4("Sorry, I already gave what help I could...")@/
2161 ("Maybe you should try asking a human?")@/
2162 ("An error might have occurred before I noticed any problems.")@/
2163 ("``If all else fails, read the instructions.''");@/
2164 goto continue;
2165 end
2166
2167 @ @<Put help message on the transcript file@>=
2168 if interaction>batch_mode then decr(selector); {avoid terminal output}
2169 if use_err_help then
2170 begin print_ln; give_err_help;
2171 end
2172 else while help_ptr>0 do
2173 begin decr(help_ptr); print_nl(help_line[help_ptr]);
2174 end;
2175 print_ln;
2176 if interaction>batch_mode then incr(selector); {re-enable terminal output}
2177 print_ln
2178
2179 @ A dozen or so error messages end with a parenthesized integer, so we
2180 save a teeny bit of program space by declaring the following procedure:
2181
2182 @p procedure int_error(@!n:integer);
2183 begin print(" ("); print_int(n); print_char(")"); error;
2184 end;
2185
2186 @ In anomalous cases, the print selector might be in an unknown state;
2187 the following subroutine is called to fix things just enough to keep
2188 running a bit longer.
2189
2190 @p procedure normalize_selector;
2191 begin if log_opened then selector:=term_and_log
2192 else selector:=term_only;
2193 if job_name=0 then open_log_file;
2194 if interaction=batch_mode then decr(selector);
2195 end;
2196
2197 @ The following procedure prints \TeX's last words before dying.
2198
2199 @d succumb==begin if interaction=error_stop_mode then
2200 interaction:=scroll_mode; {no more interaction}
2201 if log_opened then error;
2202 @!debug if interaction>batch_mode then debug_help;@+gubed@;@/
2203 history:=fatal_error_stop; jump_out; {irrecoverable error}
2204 end
2205
2206 @<Error hand...@>=
2207 procedure fatal_error(@!s:str_number); {prints |s|, and that's it}
2208 begin normalize_selector;@/
2209 print_err("Emergency stop"); help1(s); succumb;
2210 @.Emergency stop@>
2211 end;
2212
2213 @ Here is the most dreaded error message.
2214
2215 @<Error hand...@>=
2216 procedure overflow(@!s:str_number;@!n:integer); {stop due to finiteness}
2217 begin normalize_selector;
2218 print_err("TeX capacity exceeded, sorry [");
2219 @.TeX capacity exceeded ...@>
2220 print(s); print_char("="); print_int(n); print_char("]");
2221 help2("If you really absolutely need more capacity,")@/
2222 ("you can ask a wizard to enlarge me.");
2223 succumb;
2224 end;
2225
2226 @ The program might sometime run completely amok, at which point there is
2227 no choice but to stop. If no previous error has been detected, that's bad
2228 news; a message is printed that is really intended for the \TeX\
2229 maintenance person instead of the user (unless the user has been
2230 particularly diabolical). The index entries for `this can't happen' may
2231 help to pinpoint the problem.
2232 @^dry rot@>
2233
2234 @<Error hand...@>=
2235 procedure confusion(@!s:str_number);
2236 {consistency check violated; |s| tells where}
2237 begin normalize_selector;
2238 if history<error_message_issued then
2239 begin print_err("This can't happen ("); print(s); print_char(")");
2240 @.This can't happen@>
2241 help1("I'm broken. Please show this to someone who can fix can fix");
2242 end
2243 else begin print_err("I can't go on meeting you like this");
2244 @.I can't go on...@>
2245 help2("One of your faux pas seems to have wounded me deeply...")@/
2246 ("in fact, I'm barely conscious. Please fix it and try again.");
2247 end;
2248 succumb;
2249 end;
2250
2251 @ Users occasionally want to interrupt \TeX\ while it's running.
2252 If the \PASCAL\ runtime system allows this, one can implement
2253 a routine that sets the global variable |interrupt| to some nonzero value
2254 when such an interrupt is signalled. Otherwise there is probably at least
2255 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2256 @^system dependencies@>
2257 @^debugging@>
2258
2259 @d check_interrupt==begin if interrupt<>0 then pause_for_instructions;
2260 end
2261
2262 @<Global...@>=
2263 @!interrupt:integer; {should \TeX\ pause for instructions?}
2264 @!OK_to_interrupt:boolean; {should interrupts be observed?}
2265
2266 @ @<Set init...@>=
2267 interrupt:=0; OK_to_interrupt:=true;
2268
2269 @ When an interrupt has been detected, the program goes into its
2270 highest interaction level and lets the user have nearly the full flexibility of
2271 the |error| routine. \TeX\ checks for interrupts only at times when it is
2272 safe to do this.
2273
2274 @p procedure pause_for_instructions;
2275 begin if OK_to_interrupt then
2276 begin interaction:=error_stop_mode;
2277 if (selector=log_only)or(selector=no_print) then
2278 incr(selector);
2279 print_err("Interruption");
2280 @.Interruption@>
2281 help3("You rang?")@/
2282 ("Try to insert an instruction for me (e.g., `I\showlists'),")@/
2283 ("unless you just want to quit by typing `X'.");
2284 deletions_allowed:=false; error; deletions_allowed:=true;
2285 interrupt:=0;
2286 end;
2287 end;
2288
2289 @* \[7] Arithmetic with scaled dimensions.
2290 The principal computations performed by \TeX\ are done entirely in terms of
2291 integers less than $2^{31}$ in magnitude; and divisions are done only when both
2292 dividend and divisor are nonnegative. Thus, the arithmetic specified in this
2293 program can be carried out in exactly the same way on a wide variety of
2294 computers, including some small ones. Why? Because the arithmetic
2295 calculations need to be spelled out precisely in order to guarantee that
2296 \TeX\ will produce identical output on different machines. If some
2297 quantities were rounded differently in different implementations, we would
2298 find that line breaks and even page breaks might occur in different places.
2299 Hence the arithmetic of \TeX\ has been designed with care, and systems that
2300 claim to be implementations of \TeX82 should follow precisely the
2301 @:TeX82}{\TeX82@>
2302 calculations as they appear in the present program.
2303
2304 (Actually there are three places where \TeX\ uses |div| with a possibly negative
2305 numerator. These are harmless; see |div| in the index. Also if the user
2306 sets the \.{\\time} or the \.{\\year} to a negative value, some diagnostic
2307 information will involve negative-numerator division. The same remarks
2308 apply for |mod| as well as for |div|.)
2309
2310 @ Here is a routine that calculates half of an integer, using an
2311 unambiguous convention with respect to signed odd numbers.
2312
2313 @p function half(@!x:integer):integer;
2314 begin if odd(x) then half:=(x+1) div 2
2315 else half:=x @!div 2;
2316 end;
2317
2318 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2319 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2320 positions from the right end of a binary computer word.
2321
2322 @d unity == @'200000 {$2^{16}$, represents 1.00000}
2323 @d two == @'400000 {$2^{17}$, represents 2.00000}
2324
2325 @<Types...@>=
2326 @!scaled = integer; {this type is used for scaled integers}
2327 @!nonnegative_integer=0..@'17777777777; {$0\L x<2^{31}$}
2328 @!small_number=0..63; {this type is self-explanatory}
2329
2330 @ The following function is used to create a scaled integer from a given decimal
2331 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2332 given in |dig[i]|, and the calculation produces a correctly rounded result.
2333
2334 @p function round_decimals(@!k:small_number) : scaled;
2335 {converts a decimal fraction}
2336 var a:integer; {the accumulator}
2337 begin a:=0;
2338 while k>0 do
2339 begin decr(k); a:=(a+dig[k]*two) div 10;
2340 end;
2341 round_decimals:=(a+1) div 2;
2342 end;
2343
2344 @ Conversely, here is a procedure analogous to |print_int|. If the output
2345 of this procedure is subsequently read by \TeX\ and converted by the
2346 |round_decimals| routine above, it turns out that the original value will
2347 be reproduced exactly; the ``simplest'' such decimal number is output,
2348 but there is always at least one digit following the decimal point.
2349
2350 The invariant relation in the \&{repeat} loop is that a sequence of
2351 decimal digits yet to be printed will yield the original number if and only if
2352 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2353 We can stop if and only if $f=0$ satisfies this condition; the loop will
2354 terminate before $s$ can possibly become zero.
2355
2356 @p procedure print_scaled(@!s:scaled); {prints scaled real, rounded to five
2357 digits}
2358 var delta:scaled; {amount of allowable inaccuracy}
2359 begin if s<0 then
2360 begin print_char("-"); negate(s); {print the sign, if negative}
2361 end;
2362 print_int(s div unity); {print the integer part}
2363 print_char(".");
2364 s:=10*(s mod unity)+5; delta:=10;
2365 repeat if delta>unity then s:=s+@'100000-50000; {round the last digit}
2366 print_char("0"+(s div unity)); s:=10*(s mod unity); delta:=delta*10;
2367 until s<=delta;
2368 end;
2369
2370 @ Physical sizes that a \TeX\ user specifies for portions of documents are
2371 represented internally as scaled points. Thus, if we define an `sp' (scaled
2372 @^sp@>
2373 point) as a unit equal to $2^{-16}$ printer's points, every dimension
2374 inside of \TeX\ is an integer number of sp. There are exactly
2375 4,736,286.72 sp per inch. Users are not allowed to specify dimensions
2376 larger than $2^{30}-1$ sp, which is a distance of about 18.892 feet (5.7583
2377 meters); two such quantities can be added without overflow on a 32-bit
2378 computer.
2379
2380 The present implementation of \TeX\ does not check for overflow when
2381 @^overflow in arithmetic@>
2382 dimensions are added or subtracted. This could be done by inserting a
2383 few dozen tests of the form `\ignorespaces|if x>=@'10000000000 then
2384 @t\\{report\_overflow}@>|', but the chance of overflow is so remote that
2385 such tests do not seem worthwhile.
2386
2387 \TeX\ needs to do only a few arithmetic operations on scaled quantities,
2388 other than addition and subtraction, and the following subroutines do most of
2389 the work. A single computation might use several subroutine calls, and it is
2390 desirable to avoid producing multiple error messages in case of arithmetic
2391 overflow; so the routines set the global variable |arith_error| to |true|
2392 instead of reporting errors directly to the user. Another global variable,
2393 |remainder|, holds the remainder after a division.
2394
2395 @<Glob...@>=
2396 @!arith_error:boolean; {has arithmetic overflow occurred recently?}
2397 @!remainder:scaled; {amount subtracted to get an exact division}
2398
2399 @ The first arithmetical subroutine we need computes $nx+y$, where |x|
2400 and~|y| are |scaled| and |n| is an integer. We will also use it to
2401 multiply integers.
2402
2403 @d nx_plus_y(#)==mult_and_add(#,@'7777777777)
2404 @d mult_integers(#)==mult_and_add(#,0,@'17777777777)
2405
2406 @p function mult_and_add(@!n:integer;@!x,@!y,@!max_answer:scaled):scaled;
2407 begin if n<0 then
2408 begin negate(x); negate(n);
2409 end;
2410 if n=0 then mult_and_add:=y
2411 else if ((x<=(max_answer-y) div n)and(-x<=(max_answer+y) div n)) then
2412 mult_and_add:=n*x+y
2413 else begin arith_error:=true; mult_and_add:=0;
2414 end;
2415 end;
2416
2417 @ We also need to divide scaled dimensions by integers.
2418
2419 @p function x_over_n(@!x:scaled;@!n:integer):scaled;
2420 var negative:boolean; {should |remainder| be negated?}
2421 begin negative:=false;
2422 if n=0 then
2423 begin arith_error:=true; x_over_n:=0; remainder:=x;
2424 end
2425 else begin if n<0 then
2426 begin negate(x); negate(n); negative:=true;
2427 end;
2428 if x>=0 then
2429 begin x_over_n:=x div n; remainder:=x mod n;
2430 end
2431 else begin x_over_n:=-((-x) div n); remainder:=-((-x) mod n);
2432 end;
2433 end;
2434 if negative then negate(remainder);
2435 end;
2436
2437 @ Then comes the multiplication of a scaled number by a fraction |n/d|,
2438 where |n| and |d| are nonnegative integers |<=@t$2^{16}$@>| and |d| is
2439 positive. It would be too dangerous to multiply by~|n| and then divide
2440 by~|d|, in separate operations, since overflow might well occur; and it
2441 would be too inaccurate to divide by |d| and then multiply by |n|. Hence
2442 this subroutine simulates 1.5-precision arithmetic.
2443
2444 @p function xn_over_d(@!x:scaled; @!n,@!d:integer):scaled;
2445 var positive:boolean; {was |x>=0|?}
2446 @!t,@!u,@!v:nonnegative_integer; {intermediate quantities}
2447 begin if x>=0 then positive:=true
2448 else begin negate(x); positive:=false;
2449 end;
2450 t:=(x mod @'100000)*n;
2451 u:=(x div @'100000)*n+(t div @'100000);
2452 v:=(u mod d)*@'100000 + (t mod @'100000);
2453 if u div d>=@'100000 then arith_error:=true
2454 else u:=@'100000*(u div d) + (v div d);
2455 if positive then
2456 begin xn_over_d:=u; remainder:=v mod d;
2457 end
2458 else begin xn_over_d:=-u; remainder:=-(v mod d);
2459 end;
2460 end;
2461
2462 @ The next subroutine is used to compute the ``badness'' of glue, when a
2463 total~|t| is supposed to be made from amounts that sum to~|s|. According
2464 to {\sl The \TeX book}, the badness of this situation is $100(t/s)^3$;
2465 however, badness is simply a heuristic, so we need not squeeze out the
2466 last drop of accuracy when computing it. All we really want is an
2467 approximation that has similar properties.
2468 @:TeXbook}{\sl The \TeX book@>
2469
2470 The actual method used to compute the badness is easier to read from the
2471 program than to describe in words. It produces an integer value that is a
2472 reasonably close approximation to $100(t/s)^3$, and all implementations
2473 of \TeX\ should use precisely this method. Any badness of $2^{13}$ or more is
2474 treated as infinitely bad, and represented by 10000.
2475
2476 It is not difficult to prove that $$\hbox{|badness(t+1,s)>=badness(t,s)
2477 >=badness(t,s+1)|}.$$ The badness function defined here is capable of
2478 computing at most 1095 distinct values, but that is plenty.
2479
2480 @d inf_bad = 10000 {infinitely bad value}
2481
2482 @p function badness(@!t,@!s:scaled):halfword; {compute badness, given |t>=0|}
2483 var r:integer; {approximation to $\alpha t/s$, where $\alpha^3\approx
2484 100\cdot2^{18}$}
2485 begin if t=0 then badness:=0
2486 else if s<=0 then badness:=inf_bad
2487 else begin if t<=7230584 then r:=(t*297) div s {$297^3=99.94\times2^{18}$}
2488 else if s>=1663497 then r:=t div (s div 297)
2489 else r:=t;
2490 if r>1290 then badness:=inf_bad {$1290^3<2^{31}<1291^3$}
2491 else badness:=(r*r*r+@'400000) div @'1000000;
2492 end; {that was $r^3/2^{18}$, rounded to the nearest integer}
2493 end;
2494
2495 @ When \TeX\ ``packages'' a list into a box, it needs to calculate the
2496 proportionality ratio by which the glue inside the box should stretch
2497 or shrink. This calculation does not affect \TeX's decision making,
2498 so the precise details of rounding, etc., in the glue calculation are not
2499 of critical importance for the consistency of results on different computers.
2500
2501 We shall use the type |glue_ratio| for such proportionality ratios.
2502 A glue ratio should take the same amount of memory as an
2503 |integer| (usually 32 bits) if it is to blend smoothly with \TeX's
2504 other data structures. Thus |glue_ratio| should be equivalent to
2505 |short_real| in some implementations of \PASCAL. Alternatively,
2506 it is possible to deal with glue ratios using nothing but fixed-point
2507 arithmetic; see {\sl TUGboat \bf3},1 (March 1982), 10--27. (But the
2508 routines cited there must be modified to allow negative glue ratios.)
2509 @^system dependencies@>
2510
2511 @d set_glue_ratio_zero(#) == #:=0.0 {store the representation of zero ratio}
2512 @d set_glue_ratio_one(#) == #:=1.0 {store the representation of unit ratio}
2513 @d float(#) == # {convert from |glue_ratio| to type |real|}
2514 @d unfloat(#) == # {convert from |real| to type |glue_ratio|}
2515 @d float_constant(#) == #.0 {convert |integer| constant to |real|}
2516
2517 @<Types...@>=
2518 @!glue_ratio=real; {one-word representation of a glue expansion factor}
2519
2520 @* \[7b] Random numbers.
2521 %
2522 \font\tenlogo=logo10 % font used for the METAFONT logo
2523 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
2524 %
2525 This section is (almost) straight from \MP. I had to change
2526 the types (use |integer| instead of |fraction|), but that should
2527 not have any influence on the actual calculations (the original
2528 comments refer to quantities like |fraction_four| ($2^{30}$), and
2529 that is the same as the numeric representation of |maxdimen|).
2530
2531 I've copied the low-level variables and routines that are needed, but
2532 only those (e.g.~|m_log|), not the accompanying ones like |m_exp|. Most
2533 of the following low-level numeric routines are only needed within the
2534 calculation of |norm_rand|. I've been forced to rename |make_fraction|
2535 to |make_frac| because TeX already has a routine by that name with
2536 a wholly different function (it creates a |fraction_noad| for math
2537 typesetting) -- Taco.
2538
2539 And now let's complete our collection of numeric utility routines
2540 by considering random number generation.
2541 \MP\ generates pseudo-random numbers with the additive scheme recommended
2542 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
2543 results are random fractions between 0 and |fraction_one-1|, inclusive.
2544
2545 There's an auxiliary array |randoms| that contains 55 pseudo-random
2546 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
2547 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
2548 The global variable |j_random| tells which element has most recently
2549 been consumed.
2550
2551 @<Glob...@>=
2552 @!randoms:array[0..54] of integer; {the last 55 random values generated}
2553 @!j_random:0..54; {the number of unused |randoms|}
2554 @!random_seed:scaled; {the default random seed}
2555
2556 @ A small bit of \MF\ is needed.
2557
2558 @d fraction_half==@'1000000000 {$2^{27}$, represents 0.50000000}
2559 @d fraction_one==@'2000000000 {$2^{28}$, represents 1.00000000}
2560 @d fraction_four==@'10000000000 {$2^{30}$, represents 4.00000000}
2561 @d el_gordo == @'17777777777 {$2^{31}-1$, the largest value that \MP\ likes}
2562 @d halfp(#)==(#) div 2
2563 @d double(#) == #:=#+# {multiply a variable by two}
2564
2565 @ The |make_frac| routine produces the |fraction| equivalent of
2566 |p/q|, given integers |p| and~|q|; it computes the integer
2567 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2568 positive. If |p| and |q| are both of the same scaled type |t|,
2569 the ``type relation'' |make_frac(t,t)=fraction| is valid;
2570 and it's also possible to use the subroutine ``backwards,'' using
2571 the relation |make_frac(t,fraction)=t| between scaled types.
2572
2573 If the result would have magnitude $2^{31}$ or more, |make_frac|
2574 sets |arith_error:=true|. Most of \MP's internal computations have
2575 been designed to avoid this sort of error.
2576
2577 If this subroutine were programmed in assembly language on a typical
2578 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2579 double-precision product can often be input to a fixed-point division
2580 instruction. But when we are restricted to \PASCAL\ arithmetic it
2581 is necessary either to resort to multiple-precision maneuvering
2582 or to use a simple but slow iteration. The multiple-precision technique
2583 would be about three times faster than the code adopted here, but it
2584 would be comparatively long and tricky, involving about sixteen
2585 additional multiplications and divisions.
2586
2587 This operation is part of \MP's ``inner loop''; indeed, it will
2588 consume nearly 10\pct! of the running time (exclusive of input and output)
2589 if the code below is left unchanged. A machine-dependent recoding
2590 will therefore make \MP\ run faster. The present implementation
2591 is highly portable, but slow; it avoids multiplication and division
2592 except in the initial stage. System wizards should be careful to
2593 replace it with a routine that is guaranteed to produce identical
2594 results in all cases.
2595 @^system dependencies@>
2596
2597 As noted below, a few more routines should also be replaced by machine-dependent
2598 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2599 such changes aren't advisable; simplicity and robustness are
2600 preferable to trickery, unless the cost is too high.
2601 @^inner loop@>
2602
2603 @p function make_frac(@!p,@!q:integer):integer;
2604 var @!f:integer; {the fraction bits, with a leading 1 bit}
2605 @!n:integer; {the integer part of $\vert p/q\vert$}
2606 @!negative:boolean; {should the result be negated?}
2607 @!be_careful:integer; {disables certain compiler optimizations}
2608 begin if p>=0 then negative:=false
2609 else begin negate(p); negative:=true;
2610 end;
2611 if q<=0 then
2612 begin debug if q=0 then confusion("/");@;@+gubed@;@/
2613 @:this can't happen /}{\quad \./@>
2614 negate(q); negative:=not negative;
2615 end;
2616 n:=p div q; p:=p mod q;
2617 if n>=8 then
2618 begin arith_error:=true;
2619 if negative then make_frac:=-el_gordo@+else make_frac:=el_gordo;
2620 end
2621 else begin n:=(n-1)*fraction_one;
2622 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2623 if negative then make_frac:=-(f+n)@+else make_frac:=f+n;
2624 end;
2625 end;
2626
2627 @ The |repeat| loop here preserves the following invariant relations
2628 between |f|, |p|, and~|q|:
2629 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2630 $p_0$ is the original value of~$p$.
2631
2632 Notice that the computation specifies
2633 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2634 Let us hope that optimizing compilers do not miss this point; a
2635 special variable |be_careful| is used to emphasize the necessary
2636 order of computation. Optimizing compilers should keep |be_careful|
2637 in a register, not store it in memory.
2638 @^inner loop@>
2639
2640 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2641 f:=1;
2642 repeat be_careful:=p-q; p:=be_careful+p;
2643 if p>=0 then f:=f+f+1
2644 else begin double(f); p:=p+q;
2645 end;
2646 until f>=fraction_one;
2647 be_careful:=p-q;
2648 if be_careful+p>=0 then incr(f)
2649
2650 @
2651
2652 @p function take_frac(@!q:integer;@!f:integer):integer;
2653 var @!p:integer; {the fraction so far}
2654 @!negative:boolean; {should the result be negated?}
2655 @!n:integer; {additional multiple of $q$}
2656 @!be_careful:integer; {disables certain compiler optimizations}
2657 begin @<Reduce to the case that |f>=0| and |q>0|@>;
2658 if f<fraction_one then n:=0
2659 else begin n:=f div fraction_one; f:=f mod fraction_one;
2660 if q<=el_gordo div n then n:=n*q
2661 else begin arith_error:=true; n:=el_gordo;
2662 end;
2663 end;
2664 f:=f+fraction_one;
2665 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2666 be_careful:=n-el_gordo;
2667 if be_careful+p>0 then
2668 begin arith_error:=true; n:=el_gordo-p;
2669 end;
2670 if negative then take_frac:=-(n+p)
2671 else take_frac:=n+p;
2672 end;
2673
2674 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2675 if f>=0 then negative:=false
2676 else begin negate(f); negative:=true;
2677 end;
2678 if q<0 then
2679 begin negate(q); negative:=not negative;
2680 end;
2681
2682 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2683 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2684 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2685 @^inner loop@>
2686
2687 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2688 p:=fraction_half; {that's $2^{27}$; the invariants hold now with $k=28$}
2689 if q<fraction_four then
2690 repeat if odd(f) then p:=halfp(p+q)@+else p:=halfp(p);
2691 f:=halfp(f);
2692 until f=1
2693 else repeat if odd(f) then p:=p+halfp(q-p)@+else p:=halfp(p);
2694 f:=halfp(f);
2695 until f=1
2696
2697 @ The subroutines for logarithm and exponential involve two tables.
2698 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
2699 a bit more calculation, which the author claims to have done correctly:
2700 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
2701 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
2702 nearest integer.
2703
2704 @<Glob...@>=
2705 @!two_to_the:array[0..30] of integer; {powers of two}
2706 @!spec_log:array[1..28] of integer; {special logarithms}
2707
2708
2709 @ @<Set init...@>=
2710 two_to_the[0]:=1;
2711 for k:=1 to 30 do two_to_the[k]:=2*two_to_the[k-1];
2712 spec_log[1]:=93032640;
2713 spec_log[2]:=38612034;
2714 spec_log[3]:=17922280;
2715 spec_log[4]:=8662214;
2716 spec_log[5]:=4261238;
2717 spec_log[6]:=2113709;
2718 spec_log[7]:=1052693;
2719 spec_log[8]:=525315;
2720 spec_log[9]:=262400;
2721 spec_log[10]:=131136;
2722 spec_log[11]:=65552;
2723 spec_log[12]:=32772;
2724 spec_log[13]:=16385;
2725 for k:=14 to 27 do spec_log[k]:=two_to_the[27-k];
2726 spec_log[28]:=1;
2727
2728 @
2729
2730 @p function m_log(@!x:integer):integer;
2731 var @!y,@!z:integer; {auxiliary registers}
2732 @!k:integer; {iteration counter}
2733 begin if x<=0 then @<Handle non-positive logarithm@>
2734 else begin y:=1302456956+4-100; {$14\times2^{27}\ln2\approx1302456956.421063$}
2735 z:=27595+6553600; {and $2^{16}\times .421063\approx 27595$}
2736 while x<fraction_four do
2737 begin double(x); y:=y-93032639; z:=z-48782;
2738 end; {$2^{27}\ln2\approx 93032639.74436163$
2739 and $2^{16}\times.74436163\approx 48782$}
2740 y:=y+(z div unity); k:=2;
2741 while x>fraction_four+4 do
2742 @<Increase |k| until |x| can be multiplied by a
2743 factor of $2^{-k}$, and adjust $y$ accordingly@>;
2744 m_log:=y div 8;
2745 end;
2746 end;
2747
2748 @ @<Increase |k| until |x| can...@>=
2749 begin z:=((x-1) div two_to_the[k])+1; {$z=\lceil x/2^k\rceil$}
2750 while x<fraction_four+z do
2751 begin z:=halfp(z+1); k:=k+1;
2752 end;
2753 y:=y+spec_log[k]; x:=x-z;
2754 end
2755
2756 @ @<Handle non-positive logarithm@>=
2757 begin print_err("Logarithm of ");
2758 @.Logarithm...replaced by 0@>
2759 print_scaled(x); print(" has been replaced by 0");
2760 help2("Since I don't take logs of non-positive numbers,")@/
2761 ("I'm zeroing this one. Proceed, with fingers crossed.");
2762 error; m_log:=0;
2763 end
2764
2765 @ The following somewhat different subroutine tests rigorously if $ab$ is
2766 greater than, equal to, or less than~$cd$,
2767 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
2768 The result is $+1$, 0, or~$-1$ in the three respective cases.
2769
2770 @d return_sign(#)==begin ab_vs_cd:=#; return;
2771 end
2772
2773 @p function ab_vs_cd(@!a,b,c,d:integer):integer;
2774 label exit;
2775 var @!q,@!r:integer; {temporary registers}
2776 begin @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
2777 loop@+ begin q := a div d; r := c div b;
2778 if q<>r then
2779 if q>r then return_sign(1)@+else return_sign(-1);
2780 q := a mod d; r := c mod b;
2781 if r=0 then
2782 if q=0 then return_sign(0)@+else return_sign(1);
2783 if q=0 then return_sign(-1);
2784 a:=b; b:=q; c:=d; d:=r;
2785 end; {now |a>d>0| and |c>b>0|}
2786 exit:end;
2787
2788 @ @<Reduce to the case that |a...@>=
2789 if a<0 then
2790 begin negate(a); negate(b);
2791 end;
2792 if c<0 then
2793 begin negate(c); negate(d);
2794 end;
2795 if d<=0 then
2796 begin if b>=0 then
2797 if ((a=0)or(b=0))and((c=0)or(d=0)) then return_sign(0)
2798 else return_sign(1);
2799 if d=0 then
2800 if a=0 then return_sign(0)@+else return_sign(-1);
2801 q:=a; a:=c; c:=q; q:=-b; b:=-d; d:=q;
2802 end
2803 else if b<=0 then
2804 begin if b<0 then if a>0 then return_sign(-1);
2805 if c=0 then return_sign(0) else return_sign(-1);
2806 end
2807
2808 @ To consume a random integer, the program below will say `|next_random|'
2809 and then it will fetch |randoms[j_random]|.
2810
2811 @d next_random==if j_random=0 then new_randoms
2812 else decr(j_random)
2813
2814 @p procedure new_randoms;
2815 var @!k:0..54; {index into |randoms|}
2816 @!x:integer; {accumulator}
2817 begin for k:=0 to 23 do
2818 begin x:=randoms[k]-randoms[k+31];
2819 if x<0 then x:=x+fraction_one;
2820 randoms[k]:=x;
2821 end;
2822 for k:=24 to 54 do
2823 begin x:=randoms[k]-randoms[k-24];
2824 if x<0 then x:=x+fraction_one;
2825 randoms[k]:=x;
2826 end;
2827 j_random:=54;
2828 end;
2829
2830 @ To initialize the |randoms| table, we call the following routine.
2831
2832 @p procedure init_randoms(@!seed:integer);
2833 var @!j,@!jj,@!k:integer; {more or less random integers}
2834 @!i:0..54; {index into |randoms|}
2835 begin j:=abs(seed);
2836 while j>=fraction_one do j:=halfp(j);
2837 k:=1;
2838 for i:=0 to 54 do
2839 begin jj:=k; k:=j-k; j:=jj;
2840 if k<0 then k:=k+fraction_one;
2841 randoms[(i*21)mod 55]:=j;
2842 end;
2843 new_randoms; new_randoms; new_randoms; {``warm up'' the array}
2844 end;
2845
2846 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
2847 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
2848
2849 Note that the call of |take_frac| will produce the values 0 and~|x|
2850 with about half the probability that it will produce any other particular
2851 values between 0 and~|x|, because it rounds its answers.
2852
2853 @p function unif_rand(@!x:integer):integer;
2854 var @!y:integer; {trial value}
2855 begin next_random; y:=take_frac(abs(x),randoms[j_random]);
2856 if y=abs(x) then unif_rand:=0
2857 else if x>0 then unif_rand:=y
2858 else unif_rand:=-y;
2859 end;
2860
2861 @ Finally, a normal deviate with mean zero and unit standard deviation
2862 can readily be obtained with the ratio method (Algorithm 3.4.1R in
2863 {\sl The Art of Computer Programming\/}).
2864
2865 @p function norm_rand:integer;
2866 var @!x,@!u,@!l:integer; {what the book would call $2^{16}X$, $2^{28}U$,
2867 and $-2^{24}\ln U$}
2868 begin repeat
2869 repeat next_random;
2870 x:=take_frac(112429,randoms[j_random]-fraction_half);
2871 {$2^{16}\sqrt{8/e}\approx 112428.82793$}
2872 next_random; u:=randoms[j_random];
2873 until abs(x)<u;
2874 x:=make_frac(x,u);
2875 l:=139548960-m_log(u); {$2^{24}\cdot12\ln2\approx139548959.6165$}
2876 until ab_vs_cd(1024,l,x,x)>=0;
2877 norm_rand:=x;
2878 end;
2879
2880 @* \[8] Packed data.
2881 In order to make efficient use of storage space, \TeX\ bases its major data
2882 structures on a |memory_word|, which contains either a (signed) integer,
2883 possibly scaled, or a (signed) |glue_ratio|, or a small number of
2884 fields that are one half or one quarter of the size used for storing
2885 integers.
2886
2887 If |x| is a variable of type |memory_word|, it contains up to four
2888 fields that can be referred to as follows:
2889 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
2890 |x|&.|int|&(an |integer|)\cr
2891 |x|&.|sc|\qquad&(a |scaled| integer)\cr
2892 |x|&.|gr|&(a |glue_ratio|)\cr
2893 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
2894 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
2895 field)\cr
2896 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
2897 &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
2898 This is somewhat cumbersome to write, and not very readable either, but
2899 macros will be used to make the notation shorter and more transparent.
2900 The \PASCAL\ code below gives a formal definition of |memory_word| and
2901 its subsidiary types, using packed variant records. \TeX\ makes no
2902 assumptions about the relative positions of the fields within a word.
2903
2904 Since we are assuming 32-bit integers, a halfword must contain at least
2905 16 bits, and a quarterword must contain at least 8 bits.
2906 @^system dependencies@>
2907 But it doesn't hurt to have more bits; for example, with enough 36-bit
2908 words you might be able to have |mem_max| as large as 262142, which is
2909 eight times as much memory as anybody had during the first four years of
2910 \TeX's existence.
2911
2912 N.B.: Valuable memory space will be dreadfully wasted unless \TeX\ is compiled
2913 by a \PASCAL\ that packs all of the |memory_word| variants into
2914 the space of a single integer. This means, for example, that |glue_ratio|
2915 words should be |short_real| instead of |real| on some computers. Some
2916 \PASCAL\ compilers will pack an integer whose subrange is `|0..255|' into
2917 an eight-bit field, but others insist on allocating space for an additional
2918 sign bit; on such systems you can get 256 values into a quarterword only
2919 if the subrange is `|-128..127|'.
2920
2921 The present implementation tries to accommodate as many variations as possible,
2922 so it makes few assumptions. If integers having the subrange
2923 `|min_quarterword..max_quarterword|' can be packed into a quarterword,
2924 and if integers having the subrange `|min_halfword..max_halfword|'
2925 can be packed into a halfword, everything should work satisfactorily.
2926
2927 It is usually most efficient to have |min_quarterword=min_halfword=0|,
2928 so one should try to achieve this unless it causes a severe problem.
2929 The values defined here are recommended for most 32-bit computers.
2930
2931 @d min_quarterword=0 {smallest allowable value in a |quarterword|}
2932 @d max_quarterword=255 {largest allowable value in a |quarterword|}
2933 @d min_halfword==0 {smallest allowable value in a |halfword|}
2934 @d max_halfword==65535 {largest allowable value in a |halfword|}
2935
2936 @ Here are the inequalities that the quarterword and halfword values
2937 must satisfy (or rather, the inequalities that they mustn't satisfy):
2938
2939 @<Check the ``constant''...@>=
2940 init if (mem_min<>mem_bot)or(mem_max<>mem_top) then bad:=10;@+tini@;@/
2941 if (mem_min>mem_bot)or(mem_max<mem_top) then bad:=10;
2942 if (min_quarterword>0)or(max_quarterword<127) then bad:=11;
2943 if (min_halfword>0)or(max_halfword<32767) then bad:=12;
2944 if (min_quarterword<min_halfword)or@|
2945 (max_quarterword>max_halfword) then bad:=13;
2946 if (mem_min<min_halfword)or(mem_max>=max_halfword)or@|
2947 (mem_bot-mem_min>max_halfword+1) then bad:=14;
2948 if (font_base<min_quarterword)or(font_max>max_quarterword) then bad:=15;
2949 if font_max>font_base+256 then bad:=16;
2950 if (save_size>max_halfword)or(max_strings>max_halfword) then bad:=17;
2951 if buf_size>max_halfword then bad:=18;
2952 if max_quarterword-min_quarterword<255 then bad:=19;
2953
2954 @ The operation of adding or subtracting |min_quarterword| occurs quite
2955 frequently in \TeX, so it is convenient to abbreviate this operation
2956 by using the macros |qi| and |qo| for input and output to and from
2957 quarterword format.
2958
2959 The inner loop of \TeX\ will run faster with respect to compilers
2960 that don't optimize expressions like `|x+0|' and `|x-0|', if these
2961 macros are simplified in the obvious way when |min_quarterword=0|.
2962 @^inner loop@>@^system dependencies@>
2963
2964 @d qi(#)==#+min_quarterword
2965 {to put an |eight_bits| item into a quarterword}
2966 @d qo(#)==#-min_quarterword
2967 {to take an |eight_bits| item out of a quarterword}
2968 @d hi(#)==#+min_halfword
2969 {to put a sixteen-bit item into a halfword}
2970 @d ho(#)==#-min_halfword
2971 {to take a sixteen-bit item from a halfword}
2972
2973 @ The reader should study the following definitions closely:
2974 @^system dependencies@>
2975
2976 @d sc==int {|scaled| data is equivalent to |integer|}
2977
2978 @<Types...@>=
2979 @!quarterword = min_quarterword..max_quarterword; {1/4 of a word}
2980 @!halfword=min_halfword..max_halfword; {1/2 of a word}
2981 @!two_choices = 1..2; {used when there are two variants in a record}
2982 @!four_choices = 1..4; {used when there are four variants in a record}
2983 @!two_halves = packed record@;@/
2984 @!rh:halfword;
2985 case two_choices of
2986 1: (@!lh:halfword);
2987 2: (@!b0:quarterword; @!b1:quarterword);
2988 end;
2989 @!four_quarters = packed record@;@/
2990 @!b0:quarterword;
2991 @!b1:quarterword;
2992 @!b2:quarterword;
2993 @!b3:quarterword;
2994 end;
2995 @!memory_word = record@;@/
2996 case four_choices of
2997 1: (@!int:integer);
2998 2: (@!gr:glue_ratio);
2999 3: (@!hh:two_halves);
3000 4: (@!qqqq:four_quarters);
3001 end;
3002 @!word_file = file of memory_word;
3003
3004 @ When debugging, we may want to print a |memory_word| without knowing
3005 what type it is; so we print it in all modes.
3006 @^dirty \PASCAL@>@^debugging@>
3007
3008 @p @!debug procedure print_word(@!w:memory_word);
3009 {prints |w| in all ways}
3010 begin print_int(w.int); print_char(" ");@/
3011 print_scaled(w.sc); print_char(" ");@/
3012 print_scaled(round(unity*float(w.gr))); print_ln;@/
3013 @^real multiplication@>
3014 print_int(w.hh.lh); print_char("="); print_int(w.hh.b0); print_char(":");
3015 print_int(w.hh.b1); print_char(";"); print_int(w.hh.rh); print_char(" ");@/
3016 print_int(w.qqqq.b0); print_char(":"); print_int(w.qqqq.b1); print_char(":");
3017 print_int(w.qqqq.b2); print_char(":"); print_int(w.qqqq.b3);
3018 end;
3019 gubed
3020
3021 @* \[9] Dynamic memory allocation.
3022 The \TeX\ system does nearly all of its own memory allocation, so that it
3023 can readily be transported into environments that do not have automatic
3024 facilities for strings, garbage collection, etc., and so that it can be in
3025 control of what error messages the user receives. The dynamic storage
3026 requirements of \TeX\ are handled by providing a large array |mem| in
3027 which consecutive blocks of words are used as nodes by the \TeX\ routines.
3028
3029 Pointer variables are indices into this array, or into another array
3030 called |eqtb| that will be explained later. A pointer variable might
3031 also be a special flag that lies outside the bounds of |mem|, so we
3032 allow pointers to assume any |halfword| value. The minimum halfword
3033 value represents a null pointer. \TeX\ does not assume that |mem[null]| exists.
3034
3035 @d pointer==halfword {a flag or a location in |mem| or |eqtb|}
3036 @d null==min_halfword {the null pointer}
3037
3038 @<Glob...@>=
3039 @!temp_ptr:pointer; {a pointer variable for occasional emergency use}
3040
3041 @ The |mem| array is divided into two regions that are allocated separately,
3042 but the dividing line between these two regions is not fixed; they grow
3043 together until finding their ``natural'' size in a particular job.
3044 Locations less than or equal to |lo_mem_max| are used for storing
3045 variable-length records consisting of two or more words each. This region
3046 is maintained using an algorithm similar to the one described in exercise
3047 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3048 appears in the allocated nodes; the program is responsible for knowing the
3049 relevant size when a node is freed. Locations greater than or equal to
3050 |hi_mem_min| are used for storing one-word records; a conventional
3051 \.{AVAIL} stack is used for allocation in this region.
3052
3053 Locations of |mem| between |mem_bot| and |mem_top| may be dumped as part
3054 of preloaded format files, by the \.{INITEX} preprocessor.
3055 @.INITEX@>
3056 Production versions of \TeX\ may extend the memory at both ends in order to
3057 provide more space; locations between |mem_min| and |mem_bot| are always
3058 used for variable-size nodes, and locations between |mem_top| and |mem_max|
3059 are always used for single-word nodes.
3060
3061 The key pointers that govern |mem| allocation have a prescribed order:
3062 $$\advance\thickmuskip-2mu
3063 \hbox{|null<=mem_min<=mem_bot<lo_mem_max<
3064 hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3065
3066 Empirical tests show that the present implementation of \TeX\ tends to
3067 spend about 9\pct! of its running time allocating nodes, and about 6\pct!
3068 deallocating them after their use.
3069
3070 @<Glob...@>=
3071 @!mem : array[mem_min..mem_max] of memory_word; {the big dynamic storage area}
3072 @!lo_mem_max : pointer; {the largest location of variable-size memory in use}
3073 @!hi_mem_min : pointer; {the smallest location of one-word memory in use}
3074
3075 @ In order to study the memory requirements of particular applications, it
3076 is possible to prepare a version of \TeX\ that keeps track of current and
3077 maximum memory usage. When code between the delimiters |@!stat| $\ldots$
3078 |tats| is not ``commented out,'' \TeX\ will run a bit slower but it will
3079 report these statistics when |tracing_stats| is sufficiently large.
3080
3081 @<Glob...@>=
3082 @!var_used, @!dyn_used : integer; {how much memory is in use}
3083
3084 @ Let's consider the one-word memory region first, since it's the
3085 simplest. The pointer variable |mem_end| holds the highest-numbered location
3086 of |mem| that has ever been used. The free locations of |mem| that
3087 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3088 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3089 and |rh| fields of |mem[p]| when it is of this type. The single-word
3090 free locations form a linked list
3091 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3092 terminated by |null|.
3093
3094 @d link(#) == mem[#].hh.rh {the |link| field of a memory word}
3095 @d info(#) == mem[#].hh.lh {the |info| field of a memory word}
3096
3097 @<Glob...@>=
3098 @!avail : pointer; {head of the list of available one-word nodes}
3099 @!mem_end : pointer; {the last one-word node used in |mem|}
3100
3101 @ If memory is exhausted, it might mean that the user has forgotten
3102 a right brace. We will define some procedures later that try to help
3103 pinpoint the trouble.
3104
3105 @p @<Declare the procedure called |show_token_list|@>@/
3106 @<Declare the procedure called |runaway|@>
3107
3108 @ The function |get_avail| returns a pointer to a new one-word node whose
3109 |link| field is null. However, \TeX\ will halt if there is no more room left.
3110 @^inner loop@>
3111
3112 If the available-space list is empty, i.e., if |avail=null|,
3113 we try first to increase |mem_end|. If that cannot be done, i.e., if
3114 |mem_end=mem_max|, we try to decrease |hi_mem_min|. If that cannot be
3115 done, i.e., if |hi_mem_min=lo_mem_max+1|, we have to quit.
3116
3117 @p function get_avail : pointer; {single-word node allocation}
3118 var p:pointer; {the new node being got}
3119 begin p:=avail; {get top location in the |avail| stack}
3120 if p<>null then avail:=link(avail) {and pop it off}
3121 else if mem_end<mem_max then {or go into virgin territory}
3122 begin incr(mem_end); p:=mem_end;
3123 end
3124 else begin decr(hi_mem_min); p:=hi_mem_min;
3125 if hi_mem_min<=lo_mem_max then
3126 begin runaway; {if memory is exhausted, display possible runaway text}
3127 overflow("main memory size",mem_max+1-mem_min);
3128 {quit; all one-word nodes are busy}
3129 @:TeX capacity exceeded main memory size}{\quad main memory size@>
3130 end;
3131 end;
3132 link(p):=null; {provide an oft-desired initialization of the new node}
3133 @!stat incr(dyn_used);@+tats@;{maintain statistics}
3134 get_avail:=p;
3135 end;
3136
3137 @ Conversely, a one-word node is recycled by calling |free_avail|.
3138 This routine is part of \TeX's ``inner loop,'' so we want it to be fast.
3139 @^inner loop@>
3140
3141 @d free_avail(#)== {single-word node liberation}
3142 begin link(#):=avail; avail:=#;
3143 @!stat decr(dyn_used);@+tats@/
3144 end
3145
3146 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3147 overhead at the expense of extra programming. This routine is used in
3148 the places that would otherwise account for the most calls of |get_avail|.
3149 @^inner loop@>
3150
3151 @d fast_get_avail(#)==@t@>@;@/
3152 begin #:=avail; {avoid |get_avail| if possible, to save time}
3153 if #=null then #:=get_avail
3154 else begin avail:=link(#); link(#):=null;
3155 @!stat incr(dyn_used);@+tats@/
3156 end;
3157 end
3158
3159 @ The procedure |flush_list(p)| frees an entire linked list of
3160 one-word nodes that starts at position |p|.
3161 @^inner loop@>
3162
3163 @p procedure flush_list(@!p:pointer); {makes list of single-word nodes
3164 available}
3165 var @!q,@!r:pointer; {list traversers}
3166 begin if p<>null then
3167 begin r:=p;
3168 repeat q:=r; r:=link(r); @!stat decr(dyn_used);@+tats@/
3169 until r=null; {now |q| is the last node on the list}
3170 link(q):=avail; avail:=p;
3171 end;
3172 end;
3173
3174 @ The available-space list that keeps track of the variable-size portion
3175 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3176 pointed to by the roving pointer |rover|.
3177
3178 Each empty node has size 2 or more; the first word contains the special
3179 value |max_halfword| in its |link| field and the size in its |info| field;
3180 the second word contains the two pointers for double linking.
3181
3182 Each nonempty node also has size 2 or more. Its first word is of type
3183 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3184 Otherwise there is complete flexibility with respect to the contents
3185 of its other fields and its other words.
3186
3187 (We require |mem_max<max_halfword| because terrible things can happen
3188 when |max_halfword| appears in the |link| field of a nonempty node.)
3189
3190 @d empty_flag == max_halfword {the |link| of an empty variable-size node}
3191 @d is_empty(#) == (link(#)=empty_flag) {tests for empty node}
3192 @d node_size == info {the size field in empty variable-size nodes}
3193 @d llink(#) == info(#+1) {left link in doubly-linked list of empty nodes}
3194 @d rlink(#) == link(#+1) {right link in doubly-linked list of empty nodes}
3195
3196 @<Glob...@>=
3197 @!rover : pointer; {points to some node in the list of empties}
3198
3199 @ A call to |get_node| with argument |s| returns a pointer to a new node
3200 of size~|s|, which must be 2~or more. The |link| field of the first word
3201 of this new node is set to null. An overflow stop occurs if no suitable
3202 space exists.
3203
3204 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
3205 areas and returns the value |max_halfword|.
3206
3207 @p function get_node(@!s:integer):pointer; {variable-size node allocation}
3208 label found,exit,restart;
3209 var p:pointer; {the node currently under inspection}
3210 @!q:pointer; {the node physically after node |p|}
3211 @!r:integer; {the newly allocated node, or a candidate for this honor}
3212 @!t:integer; {temporary register}
3213 begin restart: p:=rover; {start at some free node in the ring}
3214 repeat @<Try to allocate within node |p| and its physical successors,
3215 and |goto found| if allocation was possible@>;
3216 @^inner loop@>
3217 p:=rlink(p); {move to the next node in the ring}
3218 until p=rover; {repeat until the whole list has been traversed}
3219 if s=@'10000000000 then
3220 begin get_node:=max_halfword; return;
3221 end;
3222 if lo_mem_max+2<hi_mem_min then if lo_mem_max+2<=mem_bot+max_halfword then
3223 @<Grow more variable-size memory and |goto restart|@>;
3224 overflow("main memory size",mem_max+1-mem_min);
3225 {sorry, nothing satisfactory is left}
3226 @:TeX capacity exceeded main memory size}{\quad main memory size@>
3227 found: link(r):=null; {this node is now nonempty}
3228 @!stat var_used:=var_used+s; {maintain usage statistics}
3229 tats@;@/
3230 get_node:=r;
3231 exit:end;
3232
3233 @ The lower part of |mem| grows by 1000 words at a time, unless
3234 we are very close to going under. When it grows, we simply link
3235 a new node into the available-space list. This method of controlled
3236 growth helps to keep the |mem| usage consecutive when \TeX\ is
3237 implemented on ``virtual memory'' systems.
3238 @^virtual memory@>
3239
3240 @<Grow more variable-size memory and |goto restart|@>=
3241 begin if hi_mem_min-lo_mem_max>=1998 then t:=lo_mem_max+1000
3242 else t:=lo_mem_max+1+(hi_mem_min-lo_mem_max) div 2;
3243 {|lo_mem_max+2<=t<hi_mem_min|}
3244 p:=llink(rover); q:=lo_mem_max; rlink(p):=q; llink(rover):=q;@/
3245 if t>mem_bot+max_halfword then t:=mem_bot+max_halfword;
3246 rlink(q):=rover; llink(q):=p; link(q):=empty_flag; node_size(q):=t-lo_mem_max;@/
3247 lo_mem_max:=t; link(lo_mem_max):=null; info(lo_mem_max):=null;
3248 rover:=q; goto restart;
3249 end
3250
3251 @ Empirical tests show that the routine in this section performs a
3252 node-merging operation about 0.75 times per allocation, on the average,
3253 after which it finds that |r>p+1| about 95\pct! of the time.
3254
3255 @<Try to allocate...@>=
3256 q:=p+node_size(p); {find the physical successor}
3257 @^inner loop@>
3258 while is_empty(q) do {merge node |p| with node |q|}
3259 begin t:=rlink(q);
3260 if q=rover then rover:=t;
3261 llink(t):=llink(q); rlink(llink(q)):=t;@/
3262 q:=q+node_size(q);
3263 end;
3264 r:=q-s;
3265 if r>p+1 then @<Allocate from the top of node |p| and |goto found|@>;
3266 if r=p then if rlink(p)<>p then
3267 @<Allocate entire node |p| and |goto found|@>;
3268 node_size(p):=q-p {reset the size in case it grew}
3269
3270 @ @<Allocate from the top...@>=
3271 begin node_size(p):=r-p; {store the remaining size}
3272 @^inner loop@>
3273 rover:=p; {start searching here next time}
3274 goto found;
3275 end
3276
3277 @ Here we delete node |p| from the ring, and let |rover| rove around.
3278
3279 @<Allocate entire...@>=
3280 begin rover:=rlink(p); t:=llink(p);
3281 llink(rover):=t; rlink(t):=rover;
3282 goto found;
3283 end
3284
3285 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
3286 the operation |free_node(p,s)| will make its words available, by inserting
3287 |p| as a new empty node just before where |rover| now points.
3288 @^inner loop@>
3289
3290 @p procedure free_node(@!p:pointer; @!s:halfword); {variable-size node
3291 liberation}
3292 var q:pointer; {|llink(rover)|}
3293 begin node_size(p):=s; link(p):=empty_flag;
3294 q:=llink(rover); llink(p):=q; rlink(p):=rover; {set both links}
3295 llink(rover):=p; rlink(q):=p; {insert |p| into the ring}
3296 @!stat var_used:=var_used-s;@+tats@;{maintain statistics}
3297 end;
3298
3299 @ Just before \.{INITEX} writes out the memory, it sorts the doubly linked
3300 available space list. The list is probably very short at such times, so a
3301 simple insertion sort is used. The smallest available location will be
3302 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
3303
3304 @p @!init procedure sort_avail; {sorts the available variable-size nodes
3305 by location}
3306 var p,@!q,@!r: pointer; {indices into |mem|}
3307 @!old_rover:pointer; {initial |rover| setting}
3308 begin p:=get_node(@'10000000000); {merge adjacent free areas}
3309 p:=rlink(rover); rlink(rover):=max_halfword; old_rover:=rover;
3310 while p<>old_rover do @<Sort \(p)|p| into the list starting at |rover|
3311 and advance |p| to |rlink(p)|@>;
3312 p:=rover;
3313 while rlink(p)<>max_halfword do
3314 begin llink(rlink(p)):=p; p:=rlink(p);
3315 end;
3316 rlink(p):=rover; llink(rover):=p;
3317 end;
3318 tini
3319
3320 @ The following |while| loop is guaranteed to
3321 terminate, since the list that starts at
3322 |rover| ends with |max_halfword| during the sorting procedure.
3323
3324 @<Sort \(p)|p|...@>=
3325 if p<rover then
3326 begin q:=p; p:=rlink(q); rlink(q):=rover; rover:=q;
3327 end
3328 else begin q:=rover;
3329 while rlink(q)<p do q:=rlink(q);
3330 r:=rlink(p); rlink(p):=rlink(q); rlink(q):=p; p:=r;
3331 end
3332
3333 @* \[10] Data structures for boxes and their friends.
3334 From the computer's standpoint, \TeX's chief mission is to create
3335 horizontal and vertical lists. We shall now investigate how the elements
3336 of these lists are represented internally as nodes in the dynamic memory.
3337
3338 A horizontal or vertical list is linked together by |link| fields in
3339 the first word of each node. Individual nodes represent boxes, glue,
3340 penalties, or special things like discretionary hyphens; because of this
3341 variety, some nodes are longer than others, and we must distinguish different
3342 kinds of nodes. We do this by putting a `|type|' field in the first word,
3343 together with the link and an optional `|subtype|'.
3344
3345 @d type(#) == mem[#].hh.b0 {identifies what kind of node this is}
3346 @d subtype(#) == mem[#].hh.b1 {secondary identification in some cases}
3347
3348 @ A |@!char_node|, which represents a single character, is the most important
3349 kind of node because it accounts for the vast majority of all boxes.
3350 Special precautions are therefore taken to ensure that a |char_node| does
3351 not take up much memory space. Every such node is one word long, and in fact
3352 it is identifiable by this property, since other kinds of nodes have at least
3353 two words, and they appear in |mem| locations less than |hi_mem_min|.
3354 This makes it possible to omit the |type| field in a |char_node|, leaving
3355 us room for two bytes that identify a |font| and a |character| within
3356 that font.
3357
3358 Note that the format of a |char_node| allows for up to 256 different
3359 fonts and up to 256 characters per font; but most implementations will
3360 probably limit the total number of fonts to fewer than 75 per job,
3361 and most fonts will stick to characters whose codes are
3362 less than 128 (since higher codes
3363 are more difficult to access on most keyboards).
3364
3365 Extensions of \TeX\ intended for oriental languages will need even more
3366 than $256\times256$ possible characters, when we consider different sizes
3367 @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
3368 and styles of type. It is suggested that Chinese and Japanese fonts be
3369 handled by representing such characters in two consecutive |char_node|
3370 entries: The first of these has |font=font_base|, and its |link| points
3371 to the second;
3372 the second identifies the font and the character dimensions.
3373 The saving feature about oriental characters is that most of them have
3374 the same box dimensions. The |character| field of the first |char_node|
3375 is a ``\\{charext}'' that distinguishes between graphic symbols whose
3376 dimensions are identical for typesetting purposes. (See the \MF\ manual.)
3377 Such an extension of \TeX\ would not be difficult; further details are
3378 left to the reader.
3379
3380 In order to make sure that the |character| code fits in a quarterword,
3381 \TeX\ adds the quantity |min_quarterword| to the actual code.
3382
3383 Character nodes appear only in horizontal lists, never in vertical lists.
3384
3385 @d is_char_node(#) == (#>=hi_mem_min)
3386 {does the argument point to a |char_node|?}
3387 @d font == type {the font code in a |char_node|}
3388 @d character == subtype {the character code in a |char_node|}
3389
3390 @ An |hlist_node| stands for a box that was made from a horizontal list.
3391 Each |hlist_node| is seven words long, and contains the following fields
3392 (in addition to the mandatory |type| and |link|, which we shall not
3393 mention explicitly when discussing the other node types): The |height| and
3394 |width| and |depth| are scaled integers denoting the dimensions of the
3395 box. There is also a |shift_amount| field, a scaled integer indicating
3396 how much this box should be lowered (if it appears in a horizontal list),
3397 or how much it should be moved to the right (if it appears in a vertical
3398 list). There is a |list_ptr| field, which points to the beginning of the
3399 list from which this box was fabricated; if |list_ptr| is |null|, the box
3400 is empty. Finally, there are three fields that represent the setting of
3401 the glue: |glue_set(p)| is a word of type |glue_ratio| that represents
3402 the proportionality constant for glue setting; |glue_sign(p)| is
3403 |stretching| or |shrinking| or |normal| depending on whether or not the
3404 glue should stretch or shrink or remain rigid; and |glue_order(p)|
3405 specifies the order of infinity to which glue setting applies (|normal|,
3406 |fil|, |fill|, or |filll|). The |subtype| field is not used in \TeX.
3407 In \eTeX\ the |subtype| field records the box direction mode |box_lr|.
3408
3409 @d hlist_node=0 {|type| of hlist nodes}
3410 @d box_node_size=7 {number of words to allocate for a box node}
3411 @d width_offset=1 {position of |width| field in a box node}
3412 @d depth_offset=2 {position of |depth| field in a box node}
3413 @d height_offset=3 {position of |height| field in a box node}
3414 @d width(#) == mem[#+width_offset].sc {width of the box, in sp}
3415 @d depth(#) == mem[#+depth_offset].sc {depth of the box, in sp}
3416 @d height(#) == mem[#+height_offset].sc {height of the box, in sp}
3417 @d shift_amount(#) == mem[#+4].sc {repositioning distance, in sp}
3418 @d list_offset=5 {position of |list_ptr| field in a box node}
3419 @d list_ptr(#) == link(#+list_offset) {beginning of the list inside the box}
3420 @d glue_order(#) == subtype(#+list_offset) {applicable order of infinity}
3421 @d glue_sign(#) == type(#+list_offset) {stretching or shrinking}
3422 @d normal=0 {the most common case when several cases are named}
3423 @d stretching = 1 {glue setting applies to the stretch components}
3424 @d shrinking = 2 {glue setting applies to the shrink components}
3425 @d glue_offset = 6 {position of |glue_set| in a box node}
3426 @d glue_set(#) == mem[#+glue_offset].gr
3427 {a word of type |glue_ratio| for glue setting}
3428
3429 @ The |new_null_box| function returns a pointer to an |hlist_node| in
3430 which all subfields have the values corresponding to `\.{\\hbox\{\}}'.
3431 (The |subtype| field is set to |min_quarterword|, for historic reasons
3432 that are no longer relevant.)
3433
3434 @p function new_null_box:pointer; {creates a new box node}
3435 var p:pointer; {the new node}
3436 begin p:=get_node(box_node_size); type(p):=hlist_node;
3437 subtype(p):=min_quarterword;
3438 width(p):=0; depth(p):=0; height(p):=0; shift_amount(p):=0; list_ptr(p):=null;
3439 glue_sign(p):=normal; glue_order(p):=normal; set_glue_ratio_zero(glue_set(p));
3440 new_null_box:=p;
3441 end;
3442
3443 @ A |vlist_node| is like an |hlist_node| in all respects except that it
3444 contains a vertical list.
3445
3446 @d vlist_node=1 {|type| of vlist nodes}
3447
3448 @ A |rule_node| stands for a solid black rectangle; it has |width|,
3449 |depth|, and |height| fields just as in an |hlist_node|. However, if
3450 any of these dimensions is $-2^{30}$, the actual value will be determined
3451 by running the rule up to the boundary of the innermost enclosing box.
3452 This is called a ``running dimension.'' The |width| is never running in
3453 an hlist; the |height| and |depth| are never running in a~vlist.
3454
3455 @d rule_node=2 {|type| of rule nodes}
3456 @d rule_node_size=4 {number of words to allocate for a rule node}
3457 @d null_flag==-@'10000000000 {$-2^{30}$, signifies a missing item}
3458 @d is_running(#) == (#=null_flag) {tests for a running dimension}
3459
3460 @ A new rule node is delivered by the |new_rule| function. It
3461 makes all the dimensions ``running,'' so you have to change the
3462 ones that are not allowed to run.
3463
3464 @p function new_rule:pointer;
3465 var p:pointer; {the new node}
3466 begin p:=get_node(rule_node_size); type(p):=rule_node;
3467 subtype(p):=0; {the |subtype| is not used}
3468 width(p):=null_flag; depth(p):=null_flag; height(p):=null_flag;
3469 new_rule:=p;
3470 end;
3471
3472 @ Insertions are represented by |ins_node| records, where the |subtype|
3473 indicates the corresponding box number. For example, `\.{\\insert 250}'
3474 leads to an |ins_node| whose |subtype| is |250+min_quarterword|.
3475 The |height| field of an |ins_node| is slightly misnamed; it actually holds
3476 the natural height plus depth of the vertical list being inserted.
3477 The |depth| field holds the |split_max_depth| to be used in case this
3478 insertion is split, and the |split_top_ptr| points to the corresponding
3479 |split_top_skip|. The |float_cost| field holds the |floating_penalty| that
3480 will be used if this insertion floats to a subsequent page after a
3481 split insertion of the same class. There is one more field, the
3482 |ins_ptr|, which points to the beginning of the vlist for the insertion.
3483
3484 @d ins_node=3 {|type| of insertion nodes}
3485 @d ins_node_size=5 {number of words to allocate for an insertion}
3486 @d float_cost(#)==mem[#+1].int {the |floating_penalty| to be used}
3487 @d ins_ptr(#)==info(#+4) {the vertical list to be inserted}
3488 @d split_top_ptr(#)==link(#+4) {the |split_top_skip| to be used}
3489
3490 @ A |mark_node| has a |mark_ptr| field that points to the reference count
3491 of a token list that contains the user's \.{\\mark} text.
3492 In addition there is a |mark_class| field that contains the mark class.
3493
3494 @d mark_node=4 {|type| of a mark node}
3495 @d small_node_size=2 {number of words to allocate for most node types}
3496 @d mark_ptr(#)==link(#+1) {head of the token list for a mark}
3497 @d mark_class(#)==info(#+1) {the mark class}
3498
3499 @ An |adjust_node|, which occurs only in horizontal lists,
3500 specifies material that will be moved out into the surrounding
3501 vertical list; i.e., it is used to implement \TeX's `\.{\\vadjust}'
3502 operation. The |adjust_ptr| field points to the vlist containing this
3503 material.
3504
3505 @d adjust_node=5 {|type| of an adjust node}
3506 @d adjust_pre == subtype {<>0 => pre-adjustment}
3507 @#{|append_list| is used to append a list to |tail|}
3508 @d append_list(#) == begin link(tail) := link(#); append_list_end
3509 @d append_list_end(#) == tail := #; end
3510
3511 @d adjust_ptr(#)==mem[#+1].int
3512 {vertical list to be moved out of horizontal list}
3513
3514 @ A |ligature_node|, which occurs only in horizontal lists, specifies
3515 a character that was fabricated from the interaction of two or more
3516 actual characters. The second word of the node, which is called the
3517 |lig_char| word, contains |font| and |character| fields just as in a
3518 |char_node|. The characters that generated the ligature have not been
3519 forgotten, since they are needed for diagnostic messages and for
3520 hyphenation; the |lig_ptr| field points to a linked list of character
3521 nodes for all original characters that have been deleted. (This list
3522 might be empty if the characters that generated the ligature were
3523 retained in other nodes.)
3524
3525 The |subtype| field is 0, plus 2 and/or 1 if the original source of the
3526 ligature included implicit left and/or right boundaries.
3527
3528 @d ligature_node=6 {|type| of a ligature node}
3529 @d lig_char(#)==#+1 {the word where the ligature is to be found}
3530 @d lig_ptr(#)==link(lig_char(#)) {the list of characters}
3531
3532 @ The |new_ligature| function creates a ligature node having given
3533 contents of the |font|, |character|, and |lig_ptr| fields. We also have
3534 a |new_lig_item| function, which returns a two-word node having a given
3535 |character| field. Such nodes are used for temporary processing as ligatures
3536 are being created.
3537
3538 @p function new_ligature(@!f,@!c:quarterword; @!q:pointer):pointer;
3539 var p:pointer; {the new node}
3540 begin p:=get_node(small_node_size); type(p):=ligature_node;
3541 font(lig_char(p)):=f; character(lig_char(p)):=c; lig_ptr(p):=q;
3542 subtype(p):=0; new_ligature:=p;
3543 end;
3544 @#
3545 function new_lig_item(@!c:quarterword):pointer;
3546 var p:pointer; {the new node}
3547 begin p:=get_node(small_node_size); character(p):=c; lig_ptr(p):=null;
3548 new_lig_item:=p;
3549 end;
3550
3551 @ A |disc_node|, which occurs only in horizontal lists, specifies a
3552 ``dis\-cretion\-ary'' line break. If such a break occurs at node |p|, the text
3553 that starts at |pre_break(p)| will precede the break, the text that starts at
3554 |post_break(p)| will follow the break, and text that appears in the next
3555 |replace_count(p)| nodes will be ignored. For example, an ordinary
3556 discretionary hyphen, indicated by `\.{\\-}', yields a |disc_node| with
3557 |pre_break| pointing to a |char_node| containing a hyphen, |post_break=null|,
3558 and |replace_count=0|. All three of the discretionary texts must be
3559 lists that consist entirely of character, kern, box, rule, and ligature nodes.
3560
3561 If |pre_break(p)=null|, the |ex_hyphen_penalty| will be charged for this
3562 break. Otherwise the |hyphen_penalty| will be charged. The texts will
3563 actually be substituted into the list by the line-breaking algorithm if it
3564 decides to make the break, and the discretionary node will disappear at
3565 that time; thus, the output routine sees only discretionaries that were
3566 not chosen.
3567
3568 @d disc_node=7 {|type| of a discretionary node}
3569 @d replace_count==subtype {how many subsequent nodes to replace}
3570 @d pre_break==llink {text that precedes a discretionary break}
3571 @d post_break==rlink {text that follows a discretionary break}
3572
3573 @p function new_disc:pointer; {creates an empty |disc_node|}
3574 var p:pointer; {the new node}
3575 begin p:=get_node(small_node_size); type(p):=disc_node;
3576 replace_count(p):=0; pre_break(p):=null; post_break(p):=null;
3577 new_disc:=p;
3578 end;
3579
3580 @ A |whatsit_node| is a wild card reserved for extensions to \TeX. The
3581 |subtype| field in its first word says what `\\{whatsit}' it is, and
3582 implicitly determines the node size (which must be 2 or more) and the
3583 format of the remaining words. When a |whatsit_node| is encountered
3584 in a list, special actions are invoked; knowledgeable people who are
3585 careful not to mess up the rest of \TeX\ are able to make \TeX\ do new
3586 things by adding code at the end of the program. For example, there
3587 might be a `\TeX nicolor' extension to specify different colors of ink,
3588 @^extensions to \TeX@>
3589 and the whatsit node might contain the desired parameters.
3590
3591 The present implementation of \TeX\ treats the features associated with
3592 `\.{\\write}' and `\.{\\special}' as if they were extensions, in order to
3593 illustrate how such routines might be coded. We shall defer further
3594 discussion of extensions until the end of this program.
3595
3596 @d whatsit_node=8 {|type| of special extension nodes}
3597
3598 @ A |math_node|, which occurs only in horizontal lists, appears before and
3599 after mathematical formulas. The |subtype| field is |before| before the
3600 formula and |after| after it. There is a |width| field, which represents
3601 the amount of surrounding space inserted by \.{\\mathsurround}.
3602
3603 In addition a |math_node| with |subtype>after| and |width=0| will be
3604 (ab)used to record a regular |math_node| reinserted after being
3605 discarded at a line break or one of the text direction primitives (
3606 \.{\\beginL}, \.{\\endL}, \.{\\beginR}, and \.{\\endR} ).
3607
3608 @d math_node=9 {|type| of a math node}
3609 @d before=0 {|subtype| for math node that introduces a formula}
3610 @d after=1 {|subtype| for math node that winds up a formula}
3611 @#
3612 @d M_code=2
3613 @d begin_M_code=M_code+before {|subtype| for \.{\\beginM} node}
3614 @d end_M_code=M_code+after {|subtype| for \.{\\endM} node}
3615 @d L_code=4
3616 @d begin_L_code=L_code+begin_M_code {|subtype| for \.{\\beginL} node}
3617 @d end_L_code=L_code+end_M_code {|subtype| for \.{\\endL} node}
3618 @d R_code=L_code+L_code
3619 @d begin_R_code=R_code+begin_M_code {|subtype| for \.{\\beginR} node}
3620 @d end_R_code=R_code+end_M_code {|subtype| for \.{\\endR} node}
3621 @#
3622 @d end_LR(#)==odd(subtype(#))
3623 @d end_LR_type(#)==(L_code*(subtype(#) div L_code)+end_M_code)
3624 @d begin_LR_type(#)==(#-after+before)
3625
3626 @p function new_math(@!w:scaled;@!s:small_number):pointer;
3627 var p:pointer; {the new node}
3628 begin p:=get_node(small_node_size); type(p):=math_node;
3629 subtype(p):=s; width(p):=w; new_math:=p;
3630 end;
3631
3632 @ \TeX\ makes use of the fact that |hlist_node|, |vlist_node|,
3633 |rule_node|, |ins_node|, |mark_node|, |adjust_node|, |ligature_node|,
3634 |disc_node|, |whatsit_node|, and |math_node| are at the low end of the
3635 type codes, by permitting a break at glue in a list if and only if the
3636 |type| of the previous node is less than |math_node|. Furthermore, a
3637 node is discarded after a break if its type is |math_node| or~more.
3638
3639 @d precedes_break(#)==(type(#)<math_node)
3640 @d non_discardable(#)==(type(#)<math_node)
3641
3642 @ A |glue_node| represents glue in a list. However, it is really only
3643 a pointer to a separate glue specification, since \TeX\ makes use of the
3644 fact that many essentially identical nodes of glue are usually present.
3645 If |p| points to a |glue_node|, |glue_ptr(p)| points to
3646 another packet of words that specify the stretch and shrink components, etc.
3647
3648 Glue nodes also serve to represent leaders; the |subtype| is used to
3649 distinguish between ordinary glue (which is called |normal|) and the three
3650 kinds of leaders (which are called |a_leaders|, |c_leaders|, and |x_leaders|).
3651 The |leader_ptr| field points to a rule node or to a box node containing the
3652 leaders; it is set to |null| in ordinary glue nodes.
3653
3654 Many kinds of glue are computed from \TeX's ``skip'' parameters, and
3655 it is helpful to know which parameter has led to a particular glue node.
3656 Therefore the |subtype| is set to indicate the source of glue, whenever
3657 it originated as a parameter. We will be defining symbolic names for the
3658 parameter numbers later (e.g., |line_skip_code=0|, |baseline_skip_code=1|,
3659 etc.); it suffices for now to say that the |subtype| of parametric glue
3660 will be the same as the parameter number, plus~one.
3661
3662 In math formulas there are two more possibilities for the |subtype| in a
3663 glue node: |mu_glue| denotes an \.{\\mskip} (where the units are scaled \.{mu}
3664 instead of scaled \.{pt}); and |cond_math_glue| denotes the `\.{\\nonscript}'
3665 feature that cancels the glue node immediately following if it appears
3666 in a subscript.
3667
3668 @d glue_node=10 {|type| of node that points to a glue specification}
3669 @d cond_math_glue=98 {special |subtype| to suppress glue in the next node}
3670 @d mu_glue=99 {|subtype| for math glue}
3671 @d a_leaders=100 {|subtype| for aligned leaders}
3672 @d c_leaders=101 {|subtype| for centered leaders}
3673 @d x_leaders=102 {|subtype| for expanded leaders}
3674 @d glue_ptr==llink {pointer to a glue specification}
3675 @d leader_ptr==rlink {pointer to box or rule node for leaders}
3676
3677 @ A glue specification has a halfword reference count in its first word,
3678 @^reference counts@>
3679 representing |null| plus the number of glue nodes that point to it (less one).
3680 Note that the reference count appears in the same position as
3681 the |link| field in list nodes; this is the field that is initialized
3682 to |null| when a node is allocated, and it is also the field that is flagged
3683 by |empty_flag| in empty nodes.
3684
3685 Glue specifications also contain three |scaled| fields, for the |width|,
3686 |stretch|, and |shrink| dimensions. Finally, there are two one-byte
3687 fields called |stretch_order| and |shrink_order|; these contain the
3688 orders of infinity (|normal|, |fil|, |fill|, or |filll|)
3689 corresponding to the stretch and shrink values.
3690
3691 @d glue_spec_size=4 {number of words to allocate for a glue specification}
3692 @d glue_ref_count(#) == link(#) {reference count of a glue specification}
3693 @d stretch(#) == mem[#+2].sc {the stretchability of this glob of glue}
3694 @d shrink(#) == mem[#+3].sc {the shrinkability of this glob of glue}
3695 @d stretch_order == type {order of infinity for stretching}
3696 @d shrink_order == subtype {order of infinity for shrinking}
3697 @d fil=1 {first-order infinity}
3698 @d fill=2 {second-order infinity}
3699 @d filll=3 {third-order infinity}
3700
3701 @<Types...@>=
3702 @!glue_ord=normal..filll; {infinity to the 0, 1, 2, or 3 power}
3703
3704 @ Here is a function that returns a pointer to a copy of a glue spec.
3705 The reference count in the copy is |null|, because there is assumed
3706 to be exactly one reference to the new specification.
3707
3708 @p function new_spec(@!p:pointer):pointer; {duplicates a glue specification}
3709 var q:pointer; {the new spec}
3710 begin q:=get_node(glue_spec_size);@/
3711 mem[q]:=mem[p]; glue_ref_count(q):=null;@/
3712 width(q):=width(p); stretch(q):=stretch(p); shrink(q):=shrink(p);
3713 new_spec:=q;
3714 end;
3715
3716 @ And here's a function that creates a glue node for a given parameter
3717 identified by its code number; for example,
3718 |new_param_glue(line_skip_code)| returns a pointer to a glue node for the
3719 current \.{\\lineskip}.
3720
3721 @p function new_param_glue(@!n:small_number):pointer;
3722 var p:pointer; {the new node}
3723 @!q:pointer; {the glue specification}
3724 begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=n+1;
3725 leader_ptr(p):=null;@/
3726 q:=@<Current |mem| equivalent of glue parameter number |n|@>@t@>;
3727 glue_ptr(p):=q; incr(glue_ref_count(q));
3728 new_param_glue:=p;
3729 end;
3730
3731 @ Glue nodes that are more or less anonymous are created by |new_glue|,
3732 whose argument points to a glue specification.
3733
3734 @p function new_glue(@!q:pointer):pointer;
3735 var p:pointer; {the new node}
3736 begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=normal;
3737 leader_ptr(p):=null; glue_ptr(p):=q; incr(glue_ref_count(q));
3738 new_glue:=p;
3739 end;
3740
3741 @ Still another subroutine is needed: This one is sort of a combination
3742 of |new_param_glue| and |new_glue|. It creates a glue node for one of
3743 the current glue parameters, but it makes a fresh copy of the glue
3744 specification, since that specification will probably be subject to change,
3745 while the parameter will stay put. The global variable |temp_ptr| is
3746 set to the address of the new spec.
3747
3748 @p function new_skip_param(@!n:small_number):pointer;
3749 var p:pointer; {the new node}
3750 begin temp_ptr:=new_spec(@<Current |mem| equivalent of glue parameter...@>);
3751 p:=new_glue(temp_ptr); glue_ref_count(temp_ptr):=null; subtype(p):=n+1;
3752 new_skip_param:=p;
3753 end;
3754
3755 @ A |kern_node| has a |width| field to specify a (normally negative)
3756 amount of spacing. This spacing correction appears in horizontal lists
3757 between letters like A and V when the font designer said that it looks
3758 better to move them closer together or further apart. A kern node can
3759 also appear in a vertical list, when its `|width|' denotes additional
3760 spacing in the vertical direction. The |subtype| is either |normal| (for
3761 kerns inserted from font information or math mode calculations) or |explicit|
3762 (for kerns inserted from \.{\\kern} and \.{\\/} commands) or |acc_kern|
3763 (for kerns inserted from non-math accents) or |mu_glue| (for kerns
3764 inserted from \.{\\mkern} specifications in math formulas).
3765
3766 @d kern_node=11 {|type| of a kern node}
3767 @d explicit=1 {|subtype| of kern nodes from \.{\\kern} and \.{\\/}}
3768 @d acc_kern=2 {|subtype| of kern nodes from accents}
3769 @d auto_kern=3 {|subtype| of kern nodes created by |get_auto_kern|}
3770
3771 @# {memory structure for marginal kerns}
3772 @d margin_kern_node = 40
3773 @d margin_kern_node_size = 3
3774 @d margin_char(#) == info(# + 2)
3775
3776 @# {|subtype| of marginal kerns}
3777 @d left_side == 0
3778 @d right_side == 1
3779
3780 @# {base for lp/rp/ef codes starts from 2:
3781 0 for |hyphen_char|,
3782 1 for |skew_char|}
3783 @d lp_code_base == 2
3784 @d rp_code_base == 3
3785 @d ef_code_base == 4
3786 @d tag_code == 5
3787 @d kn_bs_code_base == 7
3788 @d st_bs_code_base == 8
3789 @d sh_bs_code_base == 9
3790 @d kn_bc_code_base == 10
3791 @d kn_ac_code_base == 11
3792
3793
3794 @d no_lig_code == 6
3795
3796 @d max_hlist_stack = 512 {maximum fill level for |hlist_stack|}
3797 {maybe good if larger than |2 * max_quarterword|, so that box nesting level would overflow first}
3798
3799 @ The |new_kern| function creates a kern node having a given width.
3800
3801 @p function new_kern(@!w:scaled):pointer;
3802 var p:pointer; {the new node}
3803 begin p:=get_node(small_node_size); type(p):=kern_node;
3804 subtype(p):=normal;
3805 width(p):=w;
3806 new_kern:=p;
3807 end;
3808
3809 @ A |penalty_node| specifies the penalty associated with line or page
3810 breaking, in its |penalty| field. This field is a fullword integer, but
3811 the full range of integer values is not used: Any penalty |>=10000| is
3812 treated as infinity, and no break will be allowed for such high values.
3813 Similarly, any penalty |<=-10000| is treated as negative infinity, and a
3814 break will be forced.
3815
3816 @d penalty_node=12 {|type| of a penalty node}
3817 @d inf_penalty=inf_bad {``infinite'' penalty value}
3818 @d eject_penalty=-inf_penalty {``negatively infinite'' penalty value}
3819 @d penalty(#) == mem[#+1].int {the added cost of breaking a list here}
3820
3821 @ Anyone who has been reading the last few sections of the program will
3822 be able to guess what comes next.
3823
3824 @p function new_penalty(@!m:integer):pointer;
3825 var p:pointer; {the new node}
3826 begin p:=get_node(small_node_size); type(p):=penalty_node;
3827 subtype(p):=0; {the |subtype| is not used}
3828 penalty(p):=m; new_penalty:=p;
3829 end;
3830
3831 @ You might think that we have introduced enough node types by now. Well,
3832 almost, but there is one more: An |unset_node| has nearly the same format
3833 as an |hlist_node| or |vlist_node|; it is used for entries in \.{\\halign}
3834 or \.{\\valign} that are not yet in their final form, since the box
3835 dimensions are their ``natural'' sizes before any glue adjustment has been
3836 made. The |glue_set| word is not present; instead, we have a |glue_stretch|
3837 field, which contains the total stretch of order |glue_order| that is
3838 present in the hlist or vlist being boxed.
3839 Similarly, the |shift_amount| field is replaced by a |glue_shrink| field,
3840 containing the total shrink of order |glue_sign| that is present.
3841 The |subtype| field is called |span_count|; an unset box typically
3842 contains the data for |qo(span_count)+1| columns.
3843 Unset nodes will be changed to box nodes when alignment is completed.
3844
3845 @d unset_node=13 {|type| for an unset node}
3846 @d glue_stretch(#)==mem[#+glue_offset].sc {total stretch in an unset node}
3847 @d glue_shrink==shift_amount {total shrink in an unset node}
3848 @d span_count==subtype {indicates the number of spanned columns}
3849
3850 @ In fact, there are still more types coming. When we get to math formula
3851 processing we will see that a |style_node| has |type=14|; and a number
3852 of larger type codes will also be defined, for use in math mode only.
3853
3854 @ Warning: If any changes are made to these data structure layouts, such as
3855 changing any of the node sizes or even reordering the words of nodes,
3856 the |copy_node_list| procedure and the memory initialization code
3857 below may have to be changed. Such potentially dangerous parts of the
3858 program are listed in the index under `data structure assumptions'.
3859 @!@^data structure assumptions@>
3860 However, other references to the nodes are made symbolically in terms of
3861 the \.{WEB} macro definitions above, so that format changes will leave
3862 \TeX's other algorithms intact.
3863 @^system dependencies@>
3864
3865 @* \[11] Memory layout.
3866 Some areas of |mem| are dedicated to fixed usage, since static allocation is
3867 more efficient than dynamic allocation when we can get away with it. For
3868 example, locations |mem_bot| to |mem_bot+3| are always used to store the
3869 specification for glue that is `\.{0pt plus 0pt minus 0pt}'. The
3870 following macro definitions accomplish the static allocation by giving
3871 symbolic names to the fixed positions. Static variable-size nodes appear
3872 in locations |mem_bot| through |lo_mem_stat_max|, and static single-word nodes
3873 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive. It is
3874 harmless to let |lig_trick| and |garbage| share the same location of |mem|.
3875
3876 @d zero_glue==mem_bot {specification for \.{0pt plus 0pt minus 0pt}}
3877 @d fil_glue==zero_glue+glue_spec_size {\.{0pt plus 1fil minus 0pt}}
3878 @d fill_glue==fil_glue+glue_spec_size {\.{0pt plus 1fill minus 0pt}}
3879 @d ss_glue==fill_glue+glue_spec_size {\.{0pt plus 1fil minus 1fil}}
3880 @d fil_neg_glue==ss_glue+glue_spec_size {\.{0pt plus -1fil minus 0pt}}
3881 @d lo_mem_stat_max==fil_neg_glue+glue_spec_size-1 {largest statically
3882 allocated word in the variable-size |mem|}
3883 @#
3884 @d page_ins_head==mem_top {list of insertion data for current page}
3885 @d contrib_head==mem_top-1 {vlist of items not yet on current page}
3886 @d page_head==mem_top-2 {vlist for current page}
3887 @d temp_head==mem_top-3 {head of a temporary list of some kind}
3888 @d hold_head==mem_top-4 {head of a temporary list of another kind}
3889 @d adjust_head==mem_top-5 {head of adjustment list returned by |hpack|}
3890 @d active==mem_top-7 {head of active list in |line_break|, needs two words}
3891 @d align_head==mem_top-8 {head of preamble list for alignments}
3892 @d end_span==mem_top-9 {tail of spanned-width lists}
3893 @d omit_template==mem_top-10 {a constant token list}
3894 @d null_list==mem_top-11 {permanently empty list}
3895 @d lig_trick==mem_top-12 {a ligature masquerading as a |char_node|}
3896 @d garbage==mem_top-12 {used for scrap information}
3897 @d backup_head==mem_top-13 {head of token list built by |scan_keyword|}
3898 @d pre_adjust_head==mem_top-14 {head of pre-adjustment list returned by |hpack|}
3899 @d hi_mem_stat_min==mem_top-14 {smallest statically allocated word in
3900 the one-word |mem|}
3901 @d hi_mem_stat_usage=15 {the number of one-word nodes always present}
3902
3903 @ The following code gets |mem| off to a good start, when \TeX\ is
3904 initializing itself the slow~way.
3905
3906 @<Local variables for init...@>=
3907 @!k:integer; {index into |mem|, |eqtb|, etc.}
3908
3909 @ @<Initialize table entries...@>=
3910 for k:=mem_bot+1 to lo_mem_stat_max do mem[k].sc:=0;
3911 {all glue dimensions are zeroed}
3912 @^data structure assumptions@>
3913 k:=mem_bot;@+while k<=lo_mem_stat_max do
3914 {set first words of glue specifications}
3915 begin glue_ref_count(k):=null+1;
3916 stretch_order(k):=normal; shrink_order(k):=normal;
3917 k:=k+glue_spec_size;
3918 end;
3919 stretch(fil_glue):=unity; stretch_order(fil_glue):=fil;@/
3920 stretch(fill_glue):=unity; stretch_order(fill_glue):=fill;@/
3921 stretch(ss_glue):=unity; stretch_order(ss_glue):=fil;@/
3922 shrink(ss_glue):=unity; shrink_order(ss_glue):=fil;@/
3923 stretch(fil_neg_glue):=-unity; stretch_order(fil_neg_glue):=fil;@/
3924 rover:=lo_mem_stat_max+1;
3925 link(rover):=empty_flag; {now initialize the dynamic memory}
3926 node_size(rover):=1000; {which is a 1000-word available node}
3927 llink(rover):=rover; rlink(rover):=rover;@/
3928 lo_mem_max:=rover+1000; link(lo_mem_max):=null; info(lo_mem_max):=null;@/
3929 for k:=hi_mem_stat_min to mem_top do
3930 mem[k]:=mem[lo_mem_max]; {clear list heads}
3931 @<Initialize the special list heads and constant nodes@>;
3932 avail:=null; mem_end:=mem_top;
3933 hi_mem_min:=hi_mem_stat_min; {initialize the one-word memory}
3934 var_used:=lo_mem_stat_max+1-mem_bot; dyn_used:=hi_mem_stat_usage;
3935 {initialize statistics}
3936
3937 @ If \TeX\ is extended improperly, the |mem| array might get screwed up.
3938 For example, some pointers might be wrong, or some ``dead'' nodes might not
3939 have been freed when the last reference to them disappeared. Procedures
3940 |check_mem| and |search_mem| are available to help diagnose such
3941 problems. These procedures make use of two arrays called |free| and
3942 |was_free| that are present only if \TeX's debugging routines have
3943 been included. (You may want to decrease the size of |mem| while you
3944 @^debugging@>
3945 are debugging.)
3946
3947 @<Glob...@>=
3948 @!debug @!free: packed array [mem_min..mem_max] of boolean; {free cells}
3949 @t\hskip10pt@>@!was_free: packed array [mem_min..mem_max] of boolean;
3950 {previously free cells}
3951 @t\hskip10pt@>@!was_mem_end,@!was_lo_max,@!was_hi_min: pointer;
3952 {previous |mem_end|, |lo_mem_max|, and |hi_mem_min|}
3953 @t\hskip10pt@>@!panicking:boolean; {do we want to check memory constantly?}
3954 gubed
3955
3956 @ @<Set initial...@>=
3957 @!debug was_mem_end:=mem_min; {indicate that everything was previously free}
3958 was_lo_max:=mem_min; was_hi_min:=mem_max;
3959 panicking:=false;
3960 gubed
3961
3962 @ Procedure |check_mem| makes sure that the available space lists of
3963 |mem| are well formed, and it optionally prints out all locations
3964 that are reserved now but were free the last time this procedure was called.
3965
3966 @p @!debug procedure check_mem(@!print_locs : boolean);
3967 label done1,done2; {loop exits}
3968 var p,@!q:pointer; {current locations of interest in |mem|}
3969 @!clobbered:boolean; {is something amiss?}
3970 begin for p:=mem_min to lo_mem_max do free[p]:=false; {you can probably
3971 do this faster}
3972 for p:=hi_mem_min to mem_end do free[p]:=false; {ditto}
3973 @<Check single-word |avail| list@>;
3974 @<Check variable-size |avail| list@>;
3975 @<Check flags of unavailable nodes@>;
3976 if print_locs then @<Print newly busy locations@>;
3977 for p:=mem_min to lo_mem_max do was_free[p]:=free[p];
3978 for p:=hi_mem_min to mem_end do was_free[p]:=free[p];
3979 {|was_free:=free| might be faster}
3980 was_mem_end:=mem_end; was_lo_max:=lo_mem_max; was_hi_min:=hi_mem_min;
3981 end;
3982 gubed
3983
3984 @ @<Check single-word...@>=
3985 p:=avail; q:=null; clobbered:=false;
3986 while p<>null do
3987 begin if (p>mem_end)or(p<hi_mem_min) then clobbered:=true
3988 else if free[p] then clobbered:=true;
3989 if clobbered then
3990 begin print_nl("AVAIL list clobbered at ");
3991 @.AVAIL list clobbered...@>
3992 print_int(q); goto done1;
3993 end;
3994 free[p]:=true; q:=p; p:=link(q);
3995 end;
3996 done1:
3997
3998 @ @<Check variable-size...@>=
3999 p:=rover; q:=null; clobbered:=false;
4000 repeat if (p>=lo_mem_max)or(p<mem_min) then clobbered:=true
4001 else if (rlink(p)>=lo_mem_max)or(rlink(p)<mem_min) then clobbered:=true
4002 else if not(is_empty(p))or(node_size(p)<2)or@|
4003 (p+node_size(p)>lo_mem_max)or@| (llink(rlink(p))<>p) then clobbered:=true;
4004 if clobbered then
4005 begin print_nl("Double-AVAIL list clobbered at ");
4006 print_int(q); goto done2;
4007 end;
4008 for q:=p to p+node_size(p)-1 do {mark all locations free}
4009 begin if free[q] then
4010 begin print_nl("Doubly free location at ");
4011 @.Doubly free location...@>
4012 print_int(q); goto done2;
4013 end;
4014 free[q]:=true;
4015 end;
4016 q:=p; p:=rlink(p);
4017 until p=rover;
4018 done2:
4019
4020 @ @<Check flags...@>=
4021 p:=mem_min;
4022 while p<=lo_mem_max do {node |p| should not be empty}
4023 begin if is_empty(p) then
4024 begin print_nl("Bad flag at "); print_int(p);
4025 @.Bad flag...@>
4026 end;
4027 while (p<=lo_mem_max) and not free[p] do incr(p);
4028 while (p<=lo_mem_max) and free[p] do incr(p);
4029 end
4030
4031 @ @<Print newly busy...@>=
4032 begin print_nl("New busy locs:");
4033 for p:=mem_min to lo_mem_max do
4034 if not free[p] and ((p>was_lo_max) or was_free[p]) then
4035 begin print_char(" "); print_int(p);
4036 end;
4037 for p:=hi_mem_min to mem_end do
4038 if not free[p] and
4039 ((p<was_hi_min) or (p>was_mem_end) or was_free[p]) then
4040 begin print_char(" "); print_int(p);
4041 end;
4042 end
4043
4044 @ The |search_mem| procedure attempts to answer the question ``Who points
4045 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4046 that might not be of type |two_halves|. Strictly speaking, this is
4047 @^dirty \PASCAL@>
4048 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4049 point to |p| purely by coincidence). But for debugging purposes, we want
4050 to rule out the places that do {\sl not\/} point to |p|, so a few false
4051 drops are tolerable.
4052
4053 @p @!debug procedure search_mem(@!p:pointer); {look for pointers to |p|}
4054 var q:integer; {current position being searched}
4055 begin for q:=mem_min to lo_mem_max do
4056 begin if link(q)=p then
4057 begin print_nl("LINK("); print_int(q); print_char(")");
4058 end;
4059 if info(q)=p then
4060 begin print_nl("INFO("); print_int(q); print_char(")");
4061 end;
4062 end;
4063 for q:=hi_mem_min to mem_end do
4064 begin if link(q)=p then
4065 begin print_nl("LINK("); print_int(q); print_char(")");
4066 end;
4067 if info(q)=p then
4068 begin print_nl("INFO("); print_int(q); print_char(")");
4069 end;
4070 end;
4071 @<Search |eqtb| for equivalents equal to |p|@>;
4072 @<Search |save_stack| for equivalents that point to |p|@>;
4073 @<Search |hyph_list| for pointers to |p|@>;
4074 end;
4075 gubed
4076
4077 @<Declare procedures that need to be declared forward for \pdfTeX@>@;
4078
4079 @* \[12] Displaying boxes.
4080 We can reinforce our knowledge of the data structures just introduced
4081 by considering two procedures that display a list in symbolic form.
4082 The first of these, called |short_display|, is used in ``overfull box''
4083 messages to give the top-level description of a list. The other one,
4084 called |show_node_list|, prints a detailed description of exactly what
4085 is in the data structure.
4086
4087 The philosophy of |short_display| is to ignore the fine points about exactly
4088 what is inside boxes, except that ligatures and discretionary breaks are
4089 expanded. As a result, |short_display| is a recursive procedure, but the
4090 recursion is never more than one level deep.
4091 @^recursion@>
4092
4093 A global variable |font_in_short_display| keeps track of the font code that
4094 is assumed to be present when |short_display| begins; deviations from this
4095 font will be printed.
4096
4097 @<Glob...@>=
4098 @!font_in_short_display:integer; {an internal font number}
4099
4100 @ Boxes, rules, inserts, whatsits, marks, and things in general that are
4101 sort of ``complicated'' are indicated only by printing `\.{[]}'.
4102
4103 @p
4104 procedure print_font_identifier(f: internal_font_number);
4105 begin
4106 if pdf_font_blink[f] = null_font then
4107 print_esc(font_id_text(f))
4108 else
4109 print_esc(font_id_text(pdf_font_blink[f]));
4110 if pdf_tracing_fonts > 0 then begin
4111 print(" (");
4112 print(font_name[f]);
4113 if font_size[f] <> font_dsize[f] then begin
4114 print("@@");
4115 print_scaled(font_size[f]);
4116 print("pt");
4117 end;
4118 print(")");
4119 end else
4120 if pdf_font_expand_ratio[f] <> 0 then begin
4121 print(" (");
4122 if pdf_font_expand_ratio[f] > 0 then
4123 print("+");
4124 print_int(pdf_font_expand_ratio[f]);
4125 print(")");
4126 end;
4127 end;
4128
4129 procedure short_display(@!p:integer); {prints highlights of list |p|}
4130 var n:integer; {for replacement counts}
4131 begin while p>mem_min do
4132 begin if is_char_node(p) then
4133 begin if p<=mem_end then
4134 begin if font(p)<>font_in_short_display then
4135 begin if (font(p)<font_base)or(font(p)>font_max) then
4136 print_char("*")
4137 @.*\relax@>
4138 else print_font_identifier(font(p));
4139 print_char(" "); font_in_short_display:=font(p);
4140 end;
4141 print_ASCII(qo(character(p)));
4142 end;
4143 end
4144 else @<Print a short indication of the contents of node |p|@>;
4145 p:=link(p);
4146 end;
4147 end;
4148
4149 @ @<Print a short indication of the contents of node |p|@>=
4150 case type(p) of
4151 hlist_node,vlist_node,ins_node,whatsit_node,mark_node,adjust_node,
4152 unset_node: print("[]");
4153 rule_node: print_char("|");
4154 glue_node: if glue_ptr(p)<>zero_glue then print_char(" ");
4155 math_node: if subtype(p)>=L_code then print("[]")
4156 else print_char("$");
4157 ligature_node: short_display(lig_ptr(p));
4158 disc_node: begin short_display(pre_break(p));
4159 short_display(post_break(p));@/
4160 n:=replace_count(p);
4161 while n>0 do
4162 begin if link(p)<>null then p:=link(p);
4163 decr(n);
4164 end;
4165 end;
4166 othercases do_nothing
4167 endcases
4168
4169 @ The |show_node_list| routine requires some auxiliary subroutines: one to
4170 print a font-and-character combination, one to print a token list without
4171 its reference count, and one to print a rule dimension.
4172
4173 @p procedure print_font_and_char(@!p:integer); {prints |char_node| data}
4174 begin if p>mem_end then print_esc("CLOBBERED.")
4175 else begin if (font(p)<font_base)or(font(p)>font_max) then print_char("*")
4176 @.*\relax@>
4177 else print_font_identifier(font(p));
4178 print_char(" "); print_ASCII(qo(character(p)));
4179 end;
4180 end;
4181 @#
4182 procedure print_mark(@!p:integer); {prints token list data in braces}
4183 begin print_char("{");
4184 if (p<hi_mem_min)or(p>mem_end) then print_esc("CLOBBERED.")
4185 else show_token_list(link(p),null,max_print_line-10);
4186 print_char("}");
4187 end;
4188 @#
4189 procedure print_rule_dimen(@!d:scaled); {prints dimension in rule node}
4190 begin if is_running(d) then print_char("*") else print_scaled(d);
4191 @.*\relax@>
4192 end;
4193
4194 @ Then there is a subroutine that prints glue stretch and shrink, possibly
4195 followed by the name of finite units:
4196
4197 @p procedure print_glue(@!d:scaled;@!order:integer;@!s:str_number);
4198 {prints a glue component}
4199 begin print_scaled(d);
4200 if (order<normal)or(order>filll) then print("foul")
4201 else if order>normal then
4202 begin print("fil");
4203 while order>fil do
4204 begin print_char("l"); decr(order);
4205 end;
4206 end
4207 else if s<>0 then print(s);
4208 end;
4209
4210 @ The next subroutine prints a whole glue specification.
4211
4212 @p procedure print_spec(@!p:integer;@!s:str_number);
4213 {prints a glue specification}
4214 begin if (p<mem_min)or(p>=lo_mem_max) then print_char("*")
4215 @.*\relax@>
4216 else begin print_scaled(width(p));
4217 if s<>0 then print(s);
4218 if stretch(p)<>0 then
4219 begin print(" plus "); print_glue(stretch(p),stretch_order(p),s);
4220 end;
4221 if shrink(p)<>0 then
4222 begin print(" minus "); print_glue(shrink(p),shrink_order(p),s);
4223 end;
4224 end;
4225 end;
4226
4227 @ We also need to declare some procedures that appear later in this
4228 documentation.
4229
4230 @p @<Declare procedures needed for displaying the elements of mlists@>@;
4231 @<Declare the procedure called |print_skip_param|@>
4232
4233 @ Since boxes can be inside of boxes, |show_node_list| is inherently recursive,
4234 @^recursion@>
4235 up to a given maximum number of levels. The history of nesting is indicated
4236 by the current string, which will be printed at the beginning of each line;
4237 the length of this string, namely |cur_length|, is the depth of nesting.
4238
4239 Recursive calls on |show_node_list| therefore use the following pattern:
4240
4241 @d node_list_display(#)==
4242 begin append_char("."); show_node_list(#); flush_char;
4243 end {|str_room| need not be checked; see |show_box| below}
4244
4245 @ A global variable called |depth_threshold| is used to record the maximum
4246 depth of nesting for which |show_node_list| will show information. If we
4247 have |depth_threshold=0|, for example, only the top level information will
4248 be given and no sublists will be traversed. Another global variable, called
4249 |breadth_max|, tells the maximum number of items to show at each level;
4250 |breadth_max| had better be positive, or you won't see anything.
4251
4252 @<Glob...@>=
4253 @!depth_threshold : integer; {maximum nesting depth in box displays}
4254 @!breadth_max : integer; {maximum number of items shown at the same list level}
4255
4256 @ Now we are ready for |show_node_list| itself. This procedure has been
4257 written to be ``extra robust'' in the sense that it should not crash or get
4258 into a loop even if the data structures have been messed up by bugs in
4259 the rest of the program. You can safely call its parent routine
4260 |show_box(p)| for arbitrary values of |p| when you are debugging \TeX.
4261 However, in the presence of bad data, the procedure may
4262 @^dirty \PASCAL@>@^debugging@>
4263 fetch a |memory_word| whose variant is different from the way it was stored;
4264 for example, it might try to read |mem[p].hh| when |mem[p]|
4265 contains a scaled integer, if |p| is a pointer that has been
4266 clobbered or chosen at random.
4267
4268 @p procedure show_node_list(@!p:integer); {prints a node list symbolically}
4269 label exit;
4270 var n:integer; {the number of items already printed at this level}
4271 @!g:real; {a glue ratio, as a floating point number}
4272 begin if cur_length>depth_threshold then
4273 begin if p>null then print(" []");
4274 {indicate that there's been some truncation}
4275 return;
4276 end;
4277 n:=0;
4278 while p>mem_min do
4279 begin print_ln; print_current_string; {display the nesting history}
4280 if p>mem_end then {pointer out of range}
4281 begin print("Bad link, display aborted."); return;
4282 @.Bad link...@>
4283 end;
4284 incr(n); if n>breadth_max then {time to stop}
4285 begin print("etc."); return;
4286 @.etc@>
4287 end;
4288 @<Display node |p|@>;
4289 p:=link(p);
4290 end;
4291 exit:
4292 end;
4293
4294 @ @<Display node |p|@>=
4295 if is_char_node(p) then print_font_and_char(p)
4296 else case type(p) of
4297 hlist_node,vlist_node,unset_node: @<Display box |p|@>;
4298 rule_node: @<Display rule |p|@>;
4299 ins_node: @<Display insertion |p|@>;
4300 whatsit_node: @<Display the whatsit node |p|@>;
4301 glue_node: @<Display glue |p|@>;
4302 margin_kern_node: begin
4303 print_esc("kern");
4304 print_scaled(width(p));
4305 if subtype(p) = left_side then
4306 print(" (left margin)")
4307 else
4308 print(" (right margin)");
4309 end;
4310 kern_node: @<Display kern |p|@>;
4311 math_node: @<Display math node |p|@>;
4312 ligature_node: @<Display ligature |p|@>;
4313 penalty_node: @<Display penalty |p|@>;
4314 disc_node: @<Display discretionary |p|@>;
4315 mark_node: @<Display mark |p|@>;
4316 adjust_node: @<Display adjustment |p|@>;
4317 @t\4@>@<Cases of |show_node_list| that arise in mlists only@>@;
4318 othercases print("Unknown node type!")
4319 endcases
4320
4321 @ @<Display box |p|@>=
4322 begin if type(p)=hlist_node then print_esc("h")
4323 else if type(p)=vlist_node then print_esc("v")
4324 else print_esc("unset");
4325 print("box("); print_scaled(height(p)); print_char("+");
4326 print_scaled(depth(p)); print(")x"); print_scaled(width(p));
4327 if type(p)=unset_node then
4328 @<Display special fields of the unset node |p|@>
4329 else begin @<Display the value of |glue_set(p)|@>;
4330 if shift_amount(p)<>0 then
4331 begin print(", shifted "); print_scaled(shift_amount(p));
4332 end;
4333 if eTeX_ex then @<Display if this box is never to be reversed@>;
4334 end;
4335 node_list_display(list_ptr(p)); {recursive call}
4336 end
4337
4338 @ @<Display special fields of the unset node |p|@>=
4339 begin if span_count(p)<>min_quarterword then
4340 begin print(" ("); print_int(qo(span_count(p))+1);
4341 print(" columns)");
4342 end;
4343 if glue_stretch(p)<>0 then
4344 begin print(", stretch "); print_glue(glue_stretch(p),glue_order(p),0);
4345 end;
4346 if glue_shrink(p)<>0 then
4347 begin print(", shrink "); print_glue(glue_shrink(p),glue_sign(p),0);
4348 end;
4349 end
4350
4351 @ The code will have to change in this place if |glue_ratio| is
4352 a structured type instead of an ordinary |real|. Note that this routine
4353 should avoid arithmetic errors even if the |glue_set| field holds an
4354 arbitrary random value. The following code assumes that a properly
4355 formed nonzero |real| number has absolute value $2^{20}$ or more when
4356 it is regarded as an integer; this precaution was adequate to prevent
4357 floating point underflow on the author's computer.
4358 @^system dependencies@>
4359 @^dirty \PASCAL@>
4360
4361 @<Display the value of |glue_set(p)|@>=
4362 g:=float(glue_set(p));
4363 if (g<>float_constant(0))and(glue_sign(p)<>normal) then
4364 begin print(", glue set ");
4365 if glue_sign(p)=shrinking then print("- ");
4366 if abs(mem[p+glue_offset].int)<@'4000000 then print("?.?")
4367 else if abs(g)>float_constant(20000) then
4368 begin if g>float_constant(0) then print_char(">")
4369 else print("< -");
4370 print_glue(20000*unity,glue_order(p),0);
4371 end
4372 else print_glue(round(unity*g),glue_order(p),0);
4373 @^real multiplication@>
4374 end
4375
4376 @ @<Display rule |p|@>=
4377 begin print_esc("rule("); print_rule_dimen(height(p)); print_char("+");
4378 print_rule_dimen(depth(p)); print(")x"); print_rule_dimen(width(p));
4379 end
4380
4381 @ @<Display insertion |p|@>=
4382 begin print_esc("insert"); print_int(qo(subtype(p)));
4383 print(", natural size "); print_scaled(height(p));
4384 print("; split("); print_spec(split_top_ptr(p),0);
4385 print_char(","); print_scaled(depth(p));
4386 print("); float cost "); print_int(float_cost(p));
4387 node_list_display(ins_ptr(p)); {recursive call}
4388 end
4389
4390 @ @<Display glue |p|@>=
4391 if subtype(p)>=a_leaders then @<Display leaders |p|@>
4392 else begin print_esc("glue");
4393 if subtype(p)<>normal then
4394 begin print_char("(");
4395 if subtype(p)<cond_math_glue then
4396 print_skip_param(subtype(p)-1)
4397 else if subtype(p)=cond_math_glue then print_esc("nonscript")
4398 else print_esc("mskip");
4399 print_char(")");
4400 end;
4401 if subtype(p)<>cond_math_glue then
4402 begin print_char(" ");
4403 if subtype(p)<cond_math_glue then print_spec(glue_ptr(p),0)
4404 else print_spec(glue_ptr(p),"mu");
4405 end;
4406 end
4407
4408 @ @<Display leaders |p|@>=
4409 begin print_esc("");
4410 if subtype(p)=c_leaders then print_char("c")
4411 else if subtype(p)=x_leaders then print_char("x");
4412 print("leaders "); print_spec(glue_ptr(p),0);
4413 node_list_display(leader_ptr(p)); {recursive call}
4414 end
4415
4416 @ An ``explicit'' kern value is indicated implicitly by an explicit space.
4417
4418 @<Display kern |p|@>=
4419 if subtype(p)<>mu_glue then
4420 begin print_esc("kern");
4421 if subtype(p)<>normal then print_char(" ");
4422 print_scaled(width(p));
4423 if subtype(p)=acc_kern then print(" (for accent)");
4424 @.for accent@>
4425 if subtype(p)=auto_kern then print(" (for \pdfprependkern/\pdfappendkern)");
4426 end
4427 else begin print_esc("mkern"); print_scaled(width(p)); print("mu");
4428 end
4429
4430 @ @<Display math node |p|@>=
4431 if subtype(p)>after then
4432 begin if end_LR(p) then print_esc("end")
4433 else print_esc("begin");
4434 if subtype(p)>R_code then print_char("R")
4435 else if subtype(p)>L_code then print_char("L")
4436 else print_char("M");
4437 end else
4438 begin print_esc("math");
4439 if subtype(p)=before then print("on")
4440 else print("off");
4441 if width(p)<>0 then
4442 begin print(", surrounded "); print_scaled(width(p));
4443 end;
4444 end
4445
4446 @ @<Display ligature |p|@>=
4447 begin print_font_and_char(lig_char(p)); print(" (ligature ");
4448 if subtype(p)>1 then print_char("|");
4449 font_in_short_display:=font(lig_char(p)); short_display(lig_ptr(p));
4450 if odd(subtype(p)) then print_char("|");
4451 print_char(")");
4452 end
4453
4454 @ @<Display penalty |p|@>=
4455 begin print_esc("penalty "); print_int(penalty(p));
4456 end
4457
4458 @ The |post_break| list of a discretionary node is indicated by a prefixed
4459 `\.{\char'174}' instead of the `\..' before the |pre_break| list.
4460
4461 @<Display discretionary |p|@>=
4462 begin print_esc("discretionary");
4463 if replace_count(p)>0 then
4464 begin print(" replacing "); print_int(replace_count(p));
4465 end;
4466 node_list_display(pre_break(p)); {recursive call}
4467 append_char("|"); show_node_list(post_break(p)); flush_char; {recursive call}
4468 end
4469
4470 @ @<Display mark |p|@>=
4471 begin print_esc("mark");
4472 if mark_class(p)<>0 then
4473 begin print_char("s"); print_int(mark_class(p));
4474 end;
4475 print_mark(mark_ptr(p));
4476 end
4477
4478 @ @<Display adjustment |p|@>=
4479 begin print_esc("vadjust"); if adjust_pre(p) <> 0 then print(" pre ");
4480 node_list_display(adjust_ptr(p)); {recursive call}
4481 end
4482
4483 @ The recursive machinery is started by calling |show_box|.
4484 @^recursion@>
4485
4486 @p procedure show_box(@!p:pointer);
4487 begin @<Assign the values |depth_threshold:=show_box_depth| and
4488 |breadth_max:=show_box_breadth|@>;
4489 if breadth_max<=0 then breadth_max:=5;
4490 if pool_ptr+depth_threshold>=pool_size then
4491 depth_threshold:=pool_size-pool_ptr-1;
4492 {now there's enough room for prefix string}
4493 show_node_list(p); {the show starts at |p|}
4494 print_ln;
4495 end;
4496
4497 @* \[13] Destroying boxes.
4498 When we are done with a node list, we are obliged to return it to free
4499 storage, including all of its sublists. The recursive procedure
4500 |flush_node_list| does this for us.
4501
4502 @ First, however, we shall consider two non-recursive procedures that do
4503 simpler tasks. The first of these, |delete_token_ref|, is called when
4504 a pointer to a token list's reference count is being removed. This means
4505 that the token list should disappear if the reference count was |null|,
4506 otherwise the count should be decreased by one.
4507 @^reference counts@>
4508
4509 @d token_ref_count(#) == info(#) {reference count preceding a token list}
4510
4511 @p procedure delete_token_ref(@!p:pointer); {|p| points to the reference count
4512 of a token list that is losing one reference}
4513 begin if token_ref_count(p)=null then flush_list(p)
4514 else decr(token_ref_count(p));
4515 end;
4516
4517 @ Similarly, |delete_glue_ref| is called when a pointer to a glue
4518 specification is being withdrawn.
4519 @^reference counts@>
4520 @d fast_delete_glue_ref(#)==@t@>@;@/
4521 begin if glue_ref_count(#)=null then free_node(#,glue_spec_size)
4522 else decr(glue_ref_count(#));
4523 end
4524
4525 @p procedure delete_glue_ref(@!p:pointer); {|p| points to a glue specification}
4526 fast_delete_glue_ref(p);
4527
4528 @ Now we are ready to delete any node list, recursively.
4529 In practice, the nodes deleted are usually charnodes (about 2/3 of the time),
4530 and they are glue nodes in about half of the remaining cases.
4531 @^recursion@>
4532
4533 @p procedure flush_node_list(@!p:pointer); {erase list of nodes starting at |p|}
4534 label done; {go here when node |p| has been freed}
4535 var q:pointer; {successor to node |p|}
4536 begin while p<>null do
4537 @^inner loop@>
4538 begin q:=link(p);
4539 if is_char_node(p) then free_avail(p)
4540 else begin case type(p) of
4541 hlist_node,vlist_node,unset_node: begin flush_node_list(list_ptr(p));
4542 free_node(p,box_node_size); goto done;
4543 end;
4544 rule_node: begin free_node(p,rule_node_size); goto done;
4545 end;
4546 ins_node: begin flush_node_list(ins_ptr(p));
4547 delete_glue_ref(split_top_ptr(p));
4548 free_node(p,ins_node_size); goto done;
4549 end;
4550 whatsit_node: @<Wipe out the whatsit node |p| and |goto done|@>;
4551 glue_node: begin fast_delete_glue_ref(glue_ptr(p));
4552 if leader_ptr(p)<>null then flush_node_list(leader_ptr(p));
4553 end;
4554 kern_node,math_node,penalty_node: do_nothing;
4555 margin_kern_node: begin
4556 free_avail(margin_char(p));
4557 free_node(p, margin_kern_node_size);
4558 goto done;
4559 end;
4560 ligature_node: flush_node_list(lig_ptr(p));
4561 mark_node: delete_token_ref(mark_ptr(p));
4562 disc_node: begin flush_node_list(pre_break(p));
4563 flush_node_list(post_break(p));
4564 end;
4565 adjust_node: flush_node_list(adjust_ptr(p));
4566 @t\4@>@<Cases of |flush_node_list| that arise in mlists only@>@;
4567 othercases confusion("flushing")
4568 @:this can't happen flushing}{\quad flushing@>
4569 endcases;@/
4570 free_node(p,small_node_size);
4571 done:end;
4572 p:=q;
4573 end;
4574 end;
4575
4576 @* \[14] Copying boxes.
4577 Another recursive operation that acts on boxes is sometimes needed: The
4578 procedure |copy_node_list| returns a pointer to another node list that has
4579 the same structure and meaning as the original. Note that since glue
4580 specifications and token lists have reference counts, we need not make
4581 copies of them. Reference counts can never get too large to fit in a
4582 halfword, since each pointer to a node is in a different memory address,
4583 and the total number of memory addresses fits in a halfword.
4584 @^recursion@>
4585 @^reference counts@>
4586
4587 (Well, there actually are also references from outside |mem|; if the
4588 |save_stack| is made arbitrarily large, it would theoretically be possible
4589 to break \TeX\ by overflowing a reference count. But who would want to do that?)
4590
4591 @d add_token_ref(#)==incr(token_ref_count(#)) {new reference to a token list}
4592 @d add_glue_ref(#)==incr(glue_ref_count(#)) {new reference to a glue spec}
4593
4594 @ The copying procedure copies words en masse without bothering
4595 to look at their individual fields. If the node format changes---for
4596 example, if the size is altered, or if some link field is moved to another
4597 relative position---then this code may need to be changed too.
4598 @^data structure assumptions@>
4599
4600 @p function copy_node_list(@!p:pointer):pointer; {makes a duplicate of the
4601 node list that starts at |p| and returns a pointer to the new list}
4602 var h:pointer; {temporary head of copied list}
4603 @!q:pointer; {previous position in new list}
4604 @!r:pointer; {current node being fabricated for new list}
4605 @!words:0..5; {number of words remaining to be copied}
4606 begin h:=get_avail; q:=h;
4607 while p<>null do
4608 begin @<Make a copy of node |p| in node |r|@>;
4609 link(q):=r; q:=r; p:=link(p);
4610 end;
4611 link(q):=null; q:=link(h); free_avail(h);
4612 copy_node_list:=q;
4613 end;
4614
4615 @ @<Make a copy of node |p|...@>=
4616 words:=1; {this setting occurs in more branches than any other}
4617 if is_char_node(p) then r:=get_avail
4618 else @<Case statement to copy different types and set |words| to the number
4619 of initial words not yet copied@>;
4620 while words>0 do
4621 begin decr(words); mem[r+words]:=mem[p+words];
4622 end
4623
4624 @ @<Case statement to copy...@>=
4625 case type(p) of
4626 hlist_node,vlist_node,unset_node: begin r:=get_node(box_node_size);
4627 mem[r+6]:=mem[p+6]; mem[r+5]:=mem[p+5]; {copy the last two words}
4628 list_ptr(r):=copy_node_list(list_ptr(p)); {this affects |mem[r+5]|}
4629 words:=5;
4630 end;
4631 rule_node: begin r:=get_node(rule_node_size); words:=rule_node_size;
4632 end;
4633 ins_node: begin r:=get_node(ins_node_size); mem[r+4]:=mem[p+4];
4634 add_glue_ref(split_top_ptr(p));
4635 ins_ptr(r):=copy_node_list(ins_ptr(p)); {this affects |mem[r+4]|}
4636 words:=ins_node_size-1;
4637 end;
4638 whatsit_node:@<Make a partial copy of the whatsit node |p| and make |r|
4639 point to it; set |words| to the number of initial words not yet copied@>;
4640 glue_node: begin r:=get_node(small_node_size); add_glue_ref(glue_ptr(p));
4641 glue_ptr(r):=glue_ptr(p); leader_ptr(r):=copy_node_list(leader_ptr(p));
4642 end;
4643 kern_node,math_node,penalty_node: begin r:=get_node(small_node_size);
4644 words:=small_node_size;
4645 end;
4646 margin_kern_node: begin
4647 r := get_node(margin_kern_node_size);
4648 fast_get_avail(margin_char(r));
4649 font(margin_char(r)) := font(margin_char(p));
4650 character(margin_char(r)) := character(margin_char(p));
4651 words := small_node_size;
4652 end;
4653 ligature_node: begin r:=get_node(small_node_size);
4654 mem[lig_char(r)]:=mem[lig_char(p)]; {copy |font| and |character|}
4655 lig_ptr(r):=copy_node_list(lig_ptr(p));
4656 end;
4657 disc_node: begin r:=get_node(small_node_size);
4658 pre_break(r):=copy_node_list(pre_break(p));
4659 post_break(r):=copy_node_list(post_break(p));
4660 end;
4661 mark_node: begin r:=get_node(small_node_size); add_token_ref(mark_ptr(p));
4662 words:=small_node_size;
4663 end;
4664 adjust_node: begin r:=get_node(small_node_size);
4665 adjust_ptr(r):=copy_node_list(adjust_ptr(p));
4666 end; {|words=1=small_node_size-1|}
4667 othercases confusion("copying")
4668 @:this can't happen copying}{\quad copying@>
4669 endcases
4670
4671 @* \[15] The command codes.
4672 Before we can go any further, we need to define symbolic names for the internal
4673 code numbers that represent the various commands obeyed by \TeX. These codes
4674 are somewhat arbitrary, but not completely so. For example, the command
4675 codes for character types are fixed by the language, since a user says,
4676 e.g., `\.{\\catcode \`\\\${} = 3}' to make \.{\char'44} a math delimiter,
4677 and the command code |math_shift| is equal to~3. Some other codes have
4678 been made adjacent so that |case| statements in the program need not consider
4679 cases that are widely spaced, or so that |case| statements can be replaced
4680 by |if| statements.
4681
4682 At any rate, here is the list, for future reference. First come the
4683 ``catcode'' commands, several of which share their numeric codes with
4684 ordinary commands when the catcode cannot emerge from \TeX's scanning routine.
4685
4686 @d escape=0 {escape delimiter (called \.\\ in {\sl The \TeX book\/})}
4687 @:TeXbook}{\sl The \TeX book@>
4688 @d relax=0 {do nothing ( \.{\\relax} )}
4689 @d left_brace=1 {beginning of a group ( \.\{ )}
4690 @d right_brace=2 {ending of a group ( \.\} )}
4691 @d math_shift=3 {mathematics shift character ( \.\$ )}
4692 @d tab_mark=4 {alignment delimiter ( \.\&, \.{\\span} )}
4693 @d car_ret=5 {end of line ( |carriage_return|, \.{\\cr}, \.{\\crcr} )}
4694 @d out_param=5 {output a macro parameter}
4695 @d mac_param=6 {macro parameter symbol ( \.\# )}
4696 @d sup_mark=7 {superscript ( \.{\char'136} )}
4697 @d sub_mark=8 {subscript ( \.{\char'137} )}
4698 @d ignore=9 {characters to ignore ( \.{\^\^@@} )}
4699 @d endv=9 {end of \<v_j> list in alignment template}
4700 @d spacer=10 {characters equivalent to blank space ( \.{\ } )}
4701 @d letter=11 {characters regarded as letters ( \.{A..Z}, \.{a..z} )}
4702 @d other_char=12 {none of the special character types}
4703 @d active_char=13 {characters that invoke macros ( \.{\char`\~} )}
4704 @d par_end=13 {end of paragraph ( \.{\\par} )}
4705 @d match=13 {match a macro parameter}
4706 @d comment=14 {characters that introduce comments ( \.\% )}
4707 @d end_match=14 {end of parameters to macro}
4708 @d stop=14 {end of job ( \.{\\end}, \.{\\dump} )}
4709 @d invalid_char=15 {characters that shouldn't appear ( \.{\^\^?} )}
4710 @d delim_num=15 {specify delimiter numerically ( \.{\\delimiter} )}
4711 @d max_char_code=15 {largest catcode for individual characters}
4712
4713 @ Next are the ordinary run-of-the-mill command codes. Codes that are
4714 |min_internal| or more represent internal quantities that might be
4715 expanded by `\.{\\the}'.
4716
4717 @d char_num=16 {character specified numerically ( \.{\\char} )}
4718 @d math_char_num=17 {explicit math code ( \.{\\mathchar} )}
4719 @d mark=18 {mark definition ( \.{\\mark} )}
4720 @d xray=19 {peek inside of \TeX\ ( \.{\\show}, \.{\\showbox}, etc.~)}
4721 @d make_box=20 {make a box ( \.{\\box}, \.{\\copy}, \.{\\hbox}, etc.~)}
4722 @d hmove=21 {horizontal motion ( \.{\\moveleft}, \.{\\moveright} )}
4723 @d vmove=22 {vertical motion ( \.{\\raise}, \.{\\lower} )}
4724 @d un_hbox=23 {unglue a box ( \.{\\unhbox}, \.{\\unhcopy} )}
4725 @d un_vbox=24 {unglue a box ( \.{\\unvbox}, \.{\\unvcopy} )}
4726 {( or \.{\\pagediscards}, \.{\\splitdiscards} )}
4727 @d remove_item=25 {nullify last item ( \.{\\unpenalty},
4728 \.{\\unkern}, \.{\\unskip} )}
4729 @d hskip=26 {horizontal glue ( \.{\\hskip}, \.{\\hfil}, etc.~)}
4730 @d vskip=27 {vertical glue ( \.{\\vskip}, \.{\\vfil}, etc.~)}
4731 @d mskip=28 {math glue ( \.{\\mskip} )}
4732 @d kern=29 {fixed space ( \.{\\kern} )}
4733 @d mkern=30 {math kern ( \.{\\mkern} )}
4734 @d leader_ship=31 {use a box ( \.{\\shipout}, \.{\\leaders}, etc.~)}
4735 @d halign=32 {horizontal table alignment ( \.{\\halign} )}
4736 @d valign=33 {vertical table alignment ( \.{\\valign} )}
4737 {or text direction directives ( \.{\\beginL}, etc.~)}
4738 @d no_align=34 {temporary escape from alignment ( \.{\\noalign} )}
4739 @d vrule=35 {vertical rule ( \.{\\vrule} )}
4740 @d hrule=36 {horizontal rule ( \.{\\hrule} )}
4741 @d insert=37 {vlist inserted in box ( \.{\\insert} )}
4742 @d vadjust=38 {vlist inserted in enclosing paragraph ( \.{\\vadjust} )}
4743 @d ignore_spaces=39 {gobble |spacer| tokens ( \.{\\ignorespaces} )}
4744 @d after_assignment=40 {save till assignment is done ( \.{\\afterassignment} )}
4745 @d after_group=41 {save till group is done ( \.{\\aftergroup} )}
4746 @d break_penalty=42 {additional badness ( \.{\\penalty} )}
4747 @d start_par=43 {begin paragraph ( \.{\\indent}, \.{\\noindent} )}
4748 @d ital_corr=44 {italic correction ( \.{\\/} )}
4749 @d accent=45 {attach accent in text ( \.{\\accent} )}
4750 @d math_accent=46 {attach accent in math ( \.{\\mathaccent} )}
4751 @d discretionary=47 {discretionary texts ( \.{\\-}, \.{\\discretionary} )}
4752 @d eq_no=48 {equation number ( \.{\\eqno}, \.{\\leqno} )}
4753 @d left_right=49 {variable delimiter ( \.{\\left}, \.{\\right} )}
4754 {( or \.{\\middle} )}
4755 @d math_comp=50 {component of formula ( \.{\\mathbin}, etc.~)}
4756 @d limit_switch=51 {diddle limit conventions ( \.{\\displaylimits}, etc.~)}
4757 @d above=52 {generalized fraction ( \.{\\above}, \.{\\atop}, etc.~)}
4758 @d math_style=53 {style specification ( \.{\\displaystyle}, etc.~)}
4759 @d math_choice=54 {choice specification ( \.{\\mathchoice} )}
4760 @d non_script=55 {conditional math glue ( \.{\\nonscript} )}
4761 @d vcenter=56 {vertically center a vbox ( \.{\\vcenter} )}
4762 @d case_shift=57 {force specific case ( \.{\\lowercase}, \.{\\uppercase}~)}
4763 @d message=58 {send to user ( \.{\\message}, \.{\\errmessage} )}
4764 @d extension=59 {extensions to \TeX\ ( \.{\\write}, \.{\\special}, etc.~)}
4765 @d in_stream=60 {files for reading ( \.{\\openin}, \.{\\closein} )}
4766 @d begin_group=61 {begin local grouping ( \.{\\begingroup} )}
4767 @d end_group=62 {end local grouping ( \.{\\endgroup} )}
4768 @d omit=63 {omit alignment template ( \.{\\omit} )}
4769 @d ex_space=64 {explicit space ( \.{\\\ } )}
4770 @d no_boundary=65 {suppress boundary ligatures ( \.{\\noboundary} )}
4771 @d radical=66 {square root and similar signs ( \.{\\radical} )}
4772 @d end_cs_name=67 {end control sequence ( \.{\\endcsname} )}
4773 @d min_internal=68 {the smallest code that can follow \.{\\the}}
4774 @d char_given=68 {character code defined by \.{\\chardef}}
4775 @d math_given=69 {math code defined by \.{\\mathchardef}}
4776 @d last_item=70 {most recent item ( \.{\\lastpenalty},
4777 \.{\\lastkern}, \.{\\lastskip} )}
4778 @d max_non_prefixed_command=70 {largest command code that can't be \.{\\global}}
4779
4780 @ The next codes are special; they all relate to mode-independent
4781 assignment of values to \TeX's internal registers or tables.
4782 Codes that are |max_internal| or less represent internal quantities
4783 that might be expanded by `\.{\\the}'.
4784
4785 @d toks_register=71 {token list register ( \.{\\toks} )}
4786 @d assign_toks=72 {special token list ( \.{\\output}, \.{\\everypar}, etc.~)}
4787 @d assign_int=73 {user-defined integer ( \.{\\tolerance}, \.{\\day}, etc.~)}
4788 @d assign_dimen=74 {user-defined length ( \.{\\hsize}, etc.~)}
4789 @d assign_glue=75 {user-defined glue ( \.{\\baselineskip}, etc.~)}
4790 @d assign_mu_glue=76 {user-defined muglue ( \.{\\thinmuskip}, etc.~)}
4791 @d assign_font_dimen=77 {user-defined font dimension ( \.{\\fontdimen} )}
4792 @d assign_font_int=78 {user-defined font integer ( \.{\\hyphenchar},
4793 \.{\\skewchar} )}
4794 @d set_aux=79 {specify state info ( \.{\\spacefactor}, \.{\\prevdepth} )}
4795 @d set_prev_graf=80 {specify state info ( \.{\\prevgraf} )}
4796 @d set_page_dimen=81 {specify state info ( \.{\\pagegoal}, etc.~)}
4797 @d set_page_int=82 {specify state info ( \.{\\deadcycles},
4798 \.{\\insertpenalties} )}
4799 {( or \.{\\interactionmode} )}
4800 @d set_box_dimen=83 {change dimension of box ( \.{\\wd}, \.{\\ht}, \.{\\dp} )}
4801 @d set_shape=84 {specify fancy paragraph shape ( \.{\\parshape} )}
4802 {(or \.{\\interlinepenalties}, etc.~)}
4803 @d def_code=85 {define a character code ( \.{\\catcode}, etc.~)}
4804 @d def_family=86 {declare math fonts ( \.{\\textfont}, etc.~)}
4805 @d set_font=87 {set current font ( font identifiers )}
4806 @d def_font=88 {define a font file ( \.{\\font} )}
4807 @d register=89 {internal register ( \.{\\count}, \.{\\dimen}, etc.~)}
4808 @d max_internal=89 {the largest code that can follow \.{\\the}}
4809 @d advance=90 {advance a register or parameter ( \.{\\advance} )}
4810 @d multiply=91 {multiply a register or parameter ( \.{\\multiply} )}
4811 @d divide=92 {divide a register or parameter ( \.{\\divide} )}
4812 @d prefix=93 {qualify a definition ( \.{\\global}, \.{\\long}, \.{\\outer} )}
4813 {( or \.{\\protected} )}
4814 @d let=94 {assign a command code ( \.{\\let}, \.{\\futurelet} )}
4815 @d shorthand_def=95 {code definition ( \.{\\chardef}, \.{\\countdef}, etc.~)}
4816 @d read_to_cs=96 {read into a control sequence ( \.{\\read} )}
4817 {( or \.{\\readline} )}
4818 @d def=97 {macro definition ( \.{\\def}, \.{\\gdef}, \.{\\xdef}, \.{\\edef} )}
4819 @d set_box=98 {set a box ( \.{\\setbox} )}
4820 @d hyph_data=99 {hyphenation data ( \.{\\hyphenation}, \.{\\patterns} )}
4821 @d set_interaction=100 {define level of interaction ( \.{\\batchmode}, etc.~)}
4822 @d letterspace_font=101 {letterspace a font ( \.{\\letterspacefont} )}
4823 @d pdf_copy_font=102 {create a new font instance ( \.{\\pdfcopyfont} )}
4824 @d max_command=102 {the largest command code seen at |big_switch|}
4825
4826 @ The remaining command codes are extra special, since they cannot get through
4827 \TeX's scanner to the main control routine. They have been given values higher
4828 than |max_command| so that their special nature is easily discernible.
4829 The ``expandable'' commands come first.
4830
4831 @d undefined_cs=max_command+1 {initial state of most |eq_type| fields}
4832 @d expand_after=max_command+2 {special expansion ( \.{\\expandafter} )}
4833 @d no_expand=max_command+3 {special nonexpansion ( \.{\\noexpand} )}
4834 @d input=max_command+4 {input a source file ( \.{\\input}, \.{\\endinput} )}
4835 {( or \.{\\scantokens} )}
4836 @d if_test=max_command+5 {conditional text ( \.{\\if}, \.{\\ifcase}, etc.~)}
4837 @d fi_or_else=max_command+6 {delimiters for conditionals ( \.{\\else}, etc.~)}
4838 @d cs_name=max_command+7 {make a control sequence from tokens ( \.{\\csname} )}
4839 @d convert=max_command+8 {convert to text ( \.{\\number}, \.{\\string}, etc.~)}
4840 @d the=max_command+9 {expand an internal quantity ( \.{\\the} )}
4841 {( or \.{\\unexpanded}, \.{\\detokenize} )}
4842 @d top_bot_mark=max_command+10 {inserted mark ( \.{\\topmark}, etc.~)}
4843 @d call=max_command+11 {non-long, non-outer control sequence}
4844 @d long_call=max_command+12 {long, non-outer control sequence}
4845 @d outer_call=max_command+13 {non-long, outer control sequence}
4846 @d long_outer_call=max_command+14 {long, outer control sequence}
4847 @d end_template=max_command+15 {end of an alignment template}
4848 @d dont_expand=max_command+16 {the following token was marked by \.{\\noexpand}}
4849 @d glue_ref=max_command+17 {the equivalent points to a glue specification}
4850 @d shape_ref=max_command+18 {the equivalent points to a parshape specification}
4851 @d box_ref=max_command+19 {the equivalent points to a box node, or is |null|}
4852 @d data=max_command+20 {the equivalent is simply a halfword number}
4853
4854 @* \[16] The semantic nest.
4855 \TeX\ is typically in the midst of building many lists at once. For example,
4856 when a math formula is being processed, \TeX\ is in math mode and
4857 working on an mlist; this formula has temporarily interrupted \TeX\ from
4858 being in horizontal mode and building the hlist of a paragraph; and this
4859 paragraph has temporarily interrupted \TeX\ from being in vertical mode
4860 and building the vlist for the next page of a document. Similarly, when a
4861 \.{\\vbox} occurs inside of an \.{\\hbox}, \TeX\ is temporarily
4862 interrupted from working in restricted horizontal mode, and it enters
4863 internal vertical mode. The ``semantic nest'' is a stack that
4864 keeps track of what lists and modes are currently suspended.
4865
4866 At each level of processing we are in one of six modes:
4867
4868 \yskip\hang|vmode| stands for vertical mode (the page builder);
4869
4870 \hang|hmode| stands for horizontal mode (the paragraph builder);
4871
4872 \hang|mmode| stands for displayed formula mode;
4873
4874 \hang|-vmode| stands for internal vertical mode (e.g., in a \.{\\vbox});
4875
4876 \hang|-hmode| stands for restricted horizontal mode (e.g., in an \.{\\hbox});
4877
4878 \hang|-mmode| stands for math formula mode (not displayed).
4879
4880 \yskip\noindent The mode is temporarily set to zero while processing \.{\\write}
4881 texts.
4882
4883 Numeric values are assigned to |vmode|, |hmode|, and |mmode| so that
4884 \TeX's ``big semantic switch'' can select the appropriate thing to
4885 do by computing the value |abs(mode)+cur_cmd|, where |mode| is the current
4886 mode and |cur_cmd| is the current command code.
4887
4888 @d vmode=1 {vertical mode}
4889 @d hmode=vmode+max_command+1 {horizontal mode}
4890 @d mmode=hmode+max_command+1 {math mode}
4891
4892 @p procedure print_mode(@!m:integer); {prints the mode represented by |m|}
4893 begin if m>0 then
4894 case m div (max_command+1) of
4895 0:print("vertical");
4896 1:print("horizontal");
4897 2:print("display math");
4898 end
4899 else if m=0 then print("no")
4900 else case (-m) div (max_command+1) of
4901 0:print("internal vertical");
4902 1:print("restricted horizontal");
4903 2:print("math");
4904 end;
4905 print(" mode");
4906 end;
4907
4908 @ The state of affairs at any semantic level can be represented by
4909 five values:
4910
4911 \yskip\hang|mode| is the number representing the semantic mode, as
4912 just explained.
4913
4914 \yskip\hang|head| is a |pointer| to a list head for the list being built;
4915 |link(head)| therefore points to the first element of the list, or
4916 to |null| if the list is empty.
4917
4918 \yskip\hang|tail| is a |pointer| to the final node of the list being
4919 built; thus, |tail=head| if and only if the list is empty.
4920
4921 \yskip\hang|prev_graf| is the number of lines of the current paragraph that
4922 have already been put into the present vertical list.
4923
4924 \yskip\hang|aux| is an auxiliary |memory_word| that gives further information
4925 that is needed to characterize the situation.
4926
4927 \yskip\noindent
4928 In vertical mode, |aux| is also known as |prev_depth|; it is the scaled
4929 value representing the depth of the previous box, for use in baseline
4930 calculations, or it is |<=-1000|pt if the next box on the vertical list is to
4931 be exempt from baseline calculations. In horizontal mode, |aux| is also
4932 known as |space_factor| and |clang|; it holds the current space factor used in
4933 spacing calculations, and the current language used for hyphenation.
4934 (The value of |clang| is undefined in restricted horizontal mode.)
4935 In math mode, |aux| is also known as |incompleat_noad|; if
4936 not |null|, it points to a record that represents the numerator of a
4937 generalized fraction for which the denominator is currently being formed
4938 in the current list.
4939
4940 There is also a sixth quantity, |mode_line|, which correlates
4941 the semantic nest with the user's input; |mode_line| contains the source
4942 line number at which the current level of nesting was entered. The negative
4943 of this line number is the |mode_line| at the level of the
4944 user's output routine.
4945
4946 A seventh quantity, |eTeX_aux|, is used by the extended features \eTeX.
4947 In vertical modes it is known as |LR_save| and holds the LR stack when a
4948 paragraph is interrupted by a displayed formula. In display math mode
4949 it is known as |LR_box| and holds a pointer to a prototype box for the
4950 display. In math mode it is known as |delim_ptr| and points to the most
4951 recent |left_noad| or |middle_noad| of a |math_left_group|.
4952
4953 In horizontal mode, the |prev_graf| field is used for initial language data.
4954
4955 The semantic nest is an array called |nest| that holds the |mode|, |head|,
4956 |tail|, |prev_graf|, |aux|, and |mode_line| values for all semantic levels
4957 below the currently active one. Information about the currently active
4958 level is kept in the global quantities |mode|, |head|, |tail|, |prev_graf|,
4959 |aux|, and |mode_line|, which live in a \PASCAL\ record that is ready to
4960 be pushed onto |nest| if necessary.
4961
4962 @d ignore_depth==-65536000 {magic dimension value to mean `ignore me'}
4963
4964 @<Types...@>=
4965 @!list_state_record=record@!mode_field:-mmode..mmode;@+
4966 @!head_field,@!tail_field: pointer;
4967 @!eTeX_aux_field: pointer;
4968 @!pg_field,@!ml_field: integer;@+
4969 @!aux_field: memory_word;
4970 end;
4971
4972 @ @d mode==cur_list.mode_field {current mode}
4973 @d head==cur_list.head_field {header node of current list}
4974 @d tail==cur_list.tail_field {final node on current list}
4975 @d eTeX_aux==cur_list.eTeX_aux_field {auxiliary data for \eTeX}
4976 @d LR_save==eTeX_aux {LR stack when a paragraph is interrupted}
4977 @d LR_box==eTeX_aux {prototype box for display}
4978 @d delim_ptr==eTeX_aux {most recent left or right noad of a math left group}
4979 @d prev_graf==cur_list.pg_field {number of paragraph lines accumulated}
4980 @d aux==cur_list.aux_field {auxiliary data about the current list}
4981 @d prev_depth==aux.sc {the name of |aux| in vertical mode}
4982 @d space_factor==aux.hh.lh {part of |aux| in horizontal mode}
4983 @d clang==aux.hh.rh {the other part of |aux| in horizontal mode}
4984 @d incompleat_noad==aux.int {the name of |aux| in math mode}
4985 @d mode_line==cur_list.ml_field {source file line number at beginning of list}
4986
4987 @<Glob...@>=
4988 @!nest:array[0..nest_size] of list_state_record;
4989 @!nest_ptr:0..nest_size; {first unused location of |nest|}
4990 @!max_nest_stack:0..nest_size; {maximum of |nest_ptr| when pushing}
4991 @!cur_list:list_state_record; {the ``top'' semantic state}
4992 @!shown_mode:-mmode..mmode; {most recent mode shown by \.{\\tracingcommands}}
4993 @!save_tail: pointer; {save |tail| so we can examine whether we have an auto
4994 kern before a glue}
4995 @!prev_tail: pointer; {value of |tail| before the last call to |tail_append|}
4996
4997 @ Here is a common way to make the current list grow:
4998
4999 @d tail_append(#)==begin prev_tail:=tail; link(tail):=#; tail:=link(tail);
5000 end
5001 @d insert_before_tail(#) == begin
5002 link(prev_tail) := #;
5003 link(#) := tail;
5004 prev_tail := #;
5005 end
5006
5007 @ We will see later that the vertical list at the bottom semantic level is split
5008 into two parts; the ``current page'' runs from |page_head| to |page_tail|,
5009 and the ``contribution list'' runs from |contrib_head| to |tail| of
5010 semantic level zero. The idea is that contributions are first formed in
5011 vertical mode, then ``contributed'' to the current page (during which time
5012 the page-breaking decisions are made). For now, we don't need to know
5013 any more details about the page-building process.
5014
5015 @<Set init...@>=
5016 nest_ptr:=0; max_nest_stack:=0;
5017 mode:=vmode; head:=contrib_head; tail:=contrib_head;
5018 eTeX_aux:=null; save_tail:=null;
5019 prev_depth:=ignore_depth; mode_line:=0;
5020 prev_graf:=0; shown_mode:=0;
5021 @<Start a new current page@>;
5022
5023 @ When \TeX's work on one level is interrupted, the state is saved by
5024 calling |push_nest|. This routine changes |head| and |tail| so that
5025 a new (empty) list is begun; it does not change |mode| or |aux|.
5026
5027 @p procedure push_nest; {enter a new semantic level, save the old}
5028 begin if nest_ptr>max_nest_stack then
5029 begin max_nest_stack:=nest_ptr;
5030 if nest_ptr=nest_size then overflow("semantic nest size",nest_size);
5031 @:TeX capacity exceeded semantic nest size}{\quad semantic nest size@>
5032 end;
5033 nest[nest_ptr]:=cur_list; {stack the record}
5034 incr(nest_ptr); head:=get_avail; tail:=head; prev_graf:=0; mode_line:=line;
5035 eTeX_aux:=null;
5036 end;
5037
5038 @ Conversely, when \TeX\ is finished on the current level, the former
5039 state is restored by calling |pop_nest|. This routine will never be
5040 called at the lowest semantic level, nor will it be called unless |head|
5041 is a node that should be returned to free memory.
5042
5043 @p procedure pop_nest; {leave a semantic level, re-enter the old}
5044 begin free_avail(head); decr(nest_ptr); cur_list:=nest[nest_ptr];
5045 end;
5046
5047 @ Here is a procedure that displays what \TeX\ is working on, at all levels.
5048
5049 @p procedure@?print_totals; forward;@t\2@>
5050 procedure show_activities;
5051 var p:0..nest_size; {index into |nest|}
5052 @!m:-mmode..mmode; {mode}
5053 @!a:memory_word; {auxiliary}
5054 @!q,@!r:pointer; {for showing the current page}
5055 @!t:integer; {ditto}
5056 begin nest[nest_ptr]:=cur_list; {put the top level into the array}
5057 print_nl(""); print_ln;
5058 for p:=nest_ptr downto 0 do
5059 begin m:=nest[p].mode_field; a:=nest[p].aux_field;
5060 print_nl("### "); print_mode(m);
5061 print(" entered at line "); print_int(abs(nest[p].ml_field));
5062 if m=hmode then if nest[p].pg_field <> @'40600000 then
5063 begin print(" (language"); print_int(nest[p].pg_field mod @'200000);
5064 print(":hyphenmin"); print_int(nest[p].pg_field div @'20000000);
5065 print_char(","); print_int((nest[p].pg_field div @'200000) mod @'100);
5066 print_char(")");
5067 end;
5068 if nest[p].ml_field<0 then print(" (\output routine)");
5069 if p=0 then
5070 begin @<Show the status of the current page@>;
5071 if link(contrib_head)<>null then
5072 print_nl("### recent contributions:");
5073 end;
5074 show_box(link(nest[p].head_field));
5075 @<Show the auxiliary field, |a|@>;
5076 end;
5077 end;
5078
5079 @ @<Show the auxiliary...@>=
5080 case abs(m) div (max_command+1) of
5081 0: begin print_nl("prevdepth ");
5082 if a.sc<=pdf_ignored_dimen then print("ignored")
5083 else print_scaled(a.sc);
5084 if nest[p].pg_field<>0 then
5085 begin print(", prevgraf ");
5086 print_int(nest[p].pg_field); print(" line");
5087 if nest[p].pg_field<>1 then print_char("s");
5088 end;
5089 end;
5090 1: begin print_nl("spacefactor "); print_int(a.hh.lh);
5091 if m>0 then@+ if a.hh.rh>0 then
5092 begin print(", current language "); print_int(a.hh.rh);@+
5093 end;
5094 end;
5095 2: if a.int<>null then
5096 begin print("this will begin denominator of:"); show_box(a.int);@+
5097 end;
5098 end {there are no other cases}
5099
5100 @* \[17] The table of equivalents.
5101 Now that we have studied the data structures for \TeX's semantic routines,
5102 we ought to consider the data structures used by its syntactic routines. In
5103 other words, our next concern will be
5104 the tables that \TeX\ looks at when it is scanning
5105 what the user has written.
5106
5107 The biggest and most important such table is called |eqtb|. It holds the
5108 current ``equivalents'' of things; i.e., it explains what things mean
5109 or what their current values are, for all quantities that are subject to
5110 the nesting structure provided by \TeX's grouping mechanism. There are six
5111 parts to |eqtb|:
5112
5113 \yskip\hangg 1) |eqtb[active_base..(hash_base-1)]| holds the current
5114 equivalents of single-character control sequences.
5115
5116 \yskip\hangg 2) |eqtb[hash_base..(glue_base-1)]| holds the current
5117 equivalents of multiletter control sequences.
5118
5119 \yskip\hangg 3) |eqtb[glue_base..(local_base-1)]| holds the current
5120 equivalents of glue parameters like the current baselineskip.
5121
5122 \yskip\hangg 4) |eqtb[local_base..(int_base-1)]| holds the current
5123 equivalents of local halfword quantities like the current box registers,
5124 the current ``catcodes,'' the current font, and a pointer to the current
5125 paragraph shape.
5126
5127 \yskip\hangg 5) |eqtb[int_base..(dimen_base-1)]| holds the current
5128 equivalents of fullword integer parameters like the current hyphenation
5129 penalty.
5130
5131 \yskip\hangg 6) |eqtb[dimen_base..eqtb_size]| holds the current equivalents
5132 of fullword dimension parameters like the current hsize or amount of
5133 hanging indentation.
5134
5135 \yskip\noindent Note that, for example, the current amount of
5136 baselineskip glue is determined by the setting of a particular location
5137 in region~3 of |eqtb|, while the current meaning of the control sequence
5138 `\.{\\baselineskip}' (which might have been changed by \.{\\def} or
5139 \.{\\let}) appears in region~2.
5140
5141 @ Each entry in |eqtb| is a |memory_word|. Most of these words are of type
5142 |two_halves|, and subdivided into three fields:
5143
5144 \yskip\hangg 1) The |eq_level| (a quarterword) is the level of grouping at
5145 which this equivalent was defined. If the level is |level_zero|, the
5146 equivalent has never been defined; |level_one| refers to the outer level
5147 (outside of all groups), and this level is also used for global
5148 definitions that never go away. Higher levels are for equivalents that
5149 will disappear at the end of their group. @^global definitions@>
5150
5151 \yskip\hangg 2) The |eq_type| (another quarterword) specifies what kind of
5152 entry this is. There are many types, since each \TeX\ primitive like
5153 \.{\\hbox}, \.{\\def}, etc., has its own special code. The list of
5154 command codes above includes all possible settings of the |eq_type| field.
5155
5156 \yskip\hangg 3) The |equiv| (a halfword) is the current equivalent value.
5157 This may be a font number, a pointer into |mem|, or a variety of other
5158 things.
5159
5160 @d eq_level_field(#)==#.hh.b1
5161 @d eq_type_field(#)==#.hh.b0
5162 @d equiv_field(#)==#.hh.rh
5163 @d eq_level(#)==eq_level_field(eqtb[#]) {level of definition}
5164 @d eq_type(#)==eq_type_field(eqtb[#]) {command code for equivalent}
5165 @d equiv(#)==equiv_field(eqtb[#]) {equivalent value}
5166 @d level_zero=min_quarterword {level for undefined quantities}
5167 @d level_one=level_zero+1 {outermost level for defined quantities}
5168
5169 @ Many locations in |eqtb| have symbolic names. The purpose of the next
5170 paragraphs is to define these names, and to set up the initial values of the
5171 equivalents.
5172
5173 In the first region we have 256 equivalents for ``active characters'' that
5174 act as control sequences, followed by 256 equivalents for single-character
5175 control sequences.
5176
5177 Then comes region~2, which corresponds to the hash table that we will
5178 define later. The maximum address in this region is used for a dummy
5179 control sequence that is perpetually undefined. There also are several
5180 locations for control sequences that are perpetually defined
5181 (since they are used in error recovery).
5182
5183 @d active_base=1 {beginning of region 1, for active character equivalents}
5184 @d single_base=active_base+256 {equivalents of one-character control sequences}
5185 @d null_cs=single_base+256 {equivalent of \.{\\csname\\endcsname}}
5186 @d hash_base=null_cs+1 {beginning of region 2, for the hash table}
5187 @d frozen_control_sequence=hash_base+hash_size {for error recovery}
5188 @d frozen_protection=frozen_control_sequence {inaccessible but definable}
5189 @d frozen_cr=frozen_control_sequence+1 {permanent `\.{\\cr}'}
5190 @d frozen_end_group=frozen_control_sequence+2 {permanent `\.{\\endgroup}'}
5191 @d frozen_right=frozen_control_sequence+3 {permanent `\.{\\right}'}
5192 @d frozen_fi=frozen_control_sequence+4 {permanent `\.{\\fi}'}
5193 @d frozen_end_template=frozen_control_sequence+5 {permanent `\.{\\endtemplate}'}
5194 @d frozen_endv=frozen_control_sequence+6 {second permanent `\.{\\endtemplate}'}
5195 @d frozen_relax=frozen_control_sequence+7 {permanent `\.{\\relax}'}
5196 @d end_write=frozen_control_sequence+8 {permanent `\.{\\endwrite}'}
5197 @d frozen_dont_expand=frozen_control_sequence+9
5198 {permanent `\.{\\notexpanded:}'}
5199 @d prim_size=2100 {maximum number of primitives }
5200 @d frozen_null_font=frozen_control_sequence+10
5201 {permanent `\.{\\nullfont}'}
5202 @d frozen_primitive=frozen_control_sequence+11
5203 {permanent `\.{\\pdfprimitive}'}
5204 @d prim_eqtb_base=frozen_primitive+1
5205 @d font_id_base=frozen_null_font-font_base
5206 {begins table of 257 permanent font identifiers}
5207 @d undefined_control_sequence=frozen_null_font+257 {dummy location}
5208 @d glue_base=undefined_control_sequence+1 {beginning of region 3}
5209
5210 @<Initialize table entries...@>=
5211 eq_type(undefined_control_sequence):=undefined_cs;
5212 equiv(undefined_control_sequence):=null;
5213 eq_level(undefined_control_sequence):=level_zero;
5214 for k:=active_base to undefined_control_sequence-1 do
5215 eqtb[k]:=eqtb[undefined_control_sequence];
5216
5217 @ Here is a routine that displays the current meaning of an |eqtb| entry
5218 in region 1 or~2. (Similar routines for the other regions will appear
5219 below.)
5220
5221 @<Show equivalent |n|, in region 1 or 2@>=
5222 begin sprint_cs(n); print_char("="); print_cmd_chr(eq_type(n),equiv(n));
5223 if eq_type(n)>=call then
5224 begin print_char(":"); show_token_list(link(equiv(n)),null,32);
5225 end;
5226 end
5227
5228 @ Region 3 of |eqtb| contains the 256 \.{\\skip} registers, as well as the
5229 glue parameters defined here. It is important that the ``muskip''
5230 parameters have larger numbers than the others.
5231
5232 @d line_skip_code=0 {interline glue if |baseline_skip| is infeasible}
5233 @d baseline_skip_code=1 {desired glue between baselines}
5234 @d par_skip_code=2 {extra glue just above a paragraph}
5235 @d above_display_skip_code=3 {extra glue just above displayed math}
5236 @d below_display_skip_code=4 {extra glue just below displayed math}
5237 @d above_display_short_skip_code=5
5238 {glue above displayed math following short lines}
5239 @d below_display_short_skip_code=6
5240 {glue below displayed math following short lines}
5241 @d left_skip_code=7 {glue at left of justified lines}
5242 @d right_skip_code=8 {glue at right of justified lines}
5243 @d top_skip_code=9 {glue at top of main pages}
5244 @d split_top_skip_code=10 {glue at top of split pages}
5245 @d tab_skip_code=11 {glue between aligned entries}
5246 @d space_skip_code=12 {glue between words (if not |zero_glue|)}
5247 @d xspace_skip_code=13 {glue after sentences (if not |zero_glue|)}
5248 @d par_fill_skip_code=14 {glue on last line of paragraph}
5249 @d thin_mu_skip_code=15 {thin space in math formula}
5250 @d med_mu_skip_code=16 {medium space in math formula}
5251 @d thick_mu_skip_code=17 {thick space in math formula}
5252 @d glue_pars=18 {total number of glue parameters}
5253 @d skip_base=glue_base+glue_pars {table of 256 ``skip'' registers}
5254 @d mu_skip_base=skip_base+256 {table of 256 ``muskip'' registers}
5255 @d local_base=mu_skip_base+256 {beginning of region 4}
5256 @#
5257 @d skip(#)==equiv(skip_base+#) {|mem| location of glue specification}
5258 @d mu_skip(#)==equiv(mu_skip_base+#) {|mem| location of math glue spec}
5259 @d glue_par(#)==equiv(glue_base+#) {|mem| location of glue specification}
5260 @d line_skip==glue_par(line_skip_code)
5261 @d baseline_skip==glue_par(baseline_skip_code)
5262 @d par_skip==glue_par(par_skip_code)
5263 @d above_display_skip==glue_par(above_display_skip_code)
5264 @d below_display_skip==glue_par(below_display_skip_code)
5265 @d above_display_short_skip==glue_par(above_display_short_skip_code)
5266 @d below_display_short_skip==glue_par(below_display_short_skip_code)
5267 @d left_skip==glue_par(left_skip_code)
5268 @d right_skip==glue_par(right_skip_code)
5269 @d top_skip==glue_par(top_skip_code)
5270 @d split_top_skip==glue_par(split_top_skip_code)
5271 @d tab_skip==glue_par(tab_skip_code)
5272 @d space_skip==glue_par(space_skip_code)
5273 @d xspace_skip==glue_par(xspace_skip_code)
5274 @d par_fill_skip==glue_par(par_fill_skip_code)
5275 @d thin_mu_skip==glue_par(thin_mu_skip_code)
5276 @d med_mu_skip==glue_par(med_mu_skip_code)
5277 @d thick_mu_skip==glue_par(thick_mu_skip_code)
5278
5279 @<Current |mem| equivalent of glue parameter number |n|@>=glue_par(n)
5280
5281 @ Sometimes we need to convert \TeX's internal code numbers into symbolic
5282 form. The |print_skip_param| routine gives the symbolic name of a glue
5283 parameter.
5284
5285 @<Declare the procedure called |print_skip_param|@>=
5286 procedure print_skip_param(@!n:integer);
5287 begin case n of
5288 line_skip_code: print_esc("lineskip");
5289 baseline_skip_code: print_esc("baselineskip");
5290 par_skip_code: print_esc("parskip");
5291 above_display_skip_code: print_esc("abovedisplayskip");
5292 below_display_skip_code: print_esc("belowdisplayskip");
5293 above_display_short_skip_code: print_esc("abovedisplayshortskip");
5294 below_display_short_skip_code: print_esc("belowdisplayshortskip");
5295 left_skip_code: print_esc("leftskip");
5296 right_skip_code: print_esc("rightskip");
5297 top_skip_code: print_esc("topskip");
5298 split_top_skip_code: print_esc("splittopskip");
5299 tab_skip_code: print_esc("tabskip");
5300 space_skip_code: print_esc("spaceskip");
5301 xspace_skip_code: print_esc("xspaceskip");
5302 par_fill_skip_code: print_esc("parfillskip");
5303 thin_mu_skip_code: print_esc("thinmuskip");
5304 med_mu_skip_code: print_esc("medmuskip");
5305 thick_mu_skip_code: print_esc("thickmuskip");
5306 othercases print("[unknown glue parameter!]")
5307 endcases;
5308 end;
5309
5310 @ The symbolic names for glue parameters are put into \TeX's hash table
5311 by using the routine called |primitive|, defined below. Let us enter them
5312 now, so that we don't have to list all those parameter names anywhere else.
5313
5314 @<Put each of \TeX's primitives into the hash table@>=
5315 primitive("lineskip",assign_glue,glue_base+line_skip_code);@/
5316 @!@:line_skip_}{\.{\\lineskip} primitive@>
5317 primitive("baselineskip",assign_glue,glue_base+baseline_skip_code);@/
5318 @!@:baseline_skip_}{\.{\\baselineskip} primitive@>
5319 primitive("parskip",assign_glue,glue_base+par_skip_code);@/
5320 @!@:par_skip_}{\.{\\parskip} primitive@>
5321 primitive("abovedisplayskip",assign_glue,glue_base+above_display_skip_code);@/
5322 @!@:above_display_skip_}{\.{\\abovedisplayskip} primitive@>
5323 primitive("belowdisplayskip",assign_glue,glue_base+below_display_skip_code);@/
5324 @!@:below_display_skip_}{\.{\\belowdisplayskip} primitive@>
5325 primitive("abovedisplayshortskip",
5326 assign_glue,glue_base+above_display_short_skip_code);@/
5327 @!@:above_display_short_skip_}{\.{\\abovedisplayshortskip} primitive@>
5328 primitive("belowdisplayshortskip",
5329 assign_glue,glue_base+below_display_short_skip_code);@/
5330 @!@:below_display_short_skip_}{\.{\\belowdisplayshortskip} primitive@>
5331 primitive("leftskip",assign_glue,glue_base+left_skip_code);@/
5332 @!@:left_skip_}{\.{\\leftskip} primitive@>
5333 primitive("rightskip",assign_glue,glue_base+right_skip_code);@/
5334 @!@:right_skip_}{\.{\\rightskip} primitive@>
5335 primitive("topskip",assign_glue,glue_base+top_skip_code);@/
5336 @!@:top_skip_}{\.{\\topskip} primitive@>
5337 primitive("splittopskip",assign_glue,glue_base+split_top_skip_code);@/
5338 @!@:split_top_skip_}{\.{\\splittopskip} primitive@>
5339 primitive("tabskip",assign_glue,glue_base+tab_skip_code);@/
5340 @!@:tab_skip_}{\.{\\tabskip} primitive@>
5341 primitive("spaceskip",assign_glue,glue_base+space_skip_code);@/
5342 @!@:space_skip_}{\.{\\spaceskip} primitive@>
5343 primitive("xspaceskip",assign_glue,glue_base+xspace_skip_code);@/
5344 @!@:xspace_skip_}{\.{\\xspaceskip} primitive@>
5345 primitive("parfillskip",assign_glue,glue_base+par_fill_skip_code);@/
5346 @!@:par_fill_skip_}{\.{\\parfillskip} primitive@>
5347 primitive("thinmuskip",assign_mu_glue,glue_base+thin_mu_skip_code);@/
5348 @!@:thin_mu_skip_}{\.{\\thinmuskip} primitive@>
5349 primitive("medmuskip",assign_mu_glue,glue_base+med_mu_skip_code);@/
5350 @!@:med_mu_skip_}{\.{\\medmuskip} primitive@>
5351 primitive("thickmuskip",assign_mu_glue,glue_base+thick_mu_skip_code);@/
5352 @!@:thick_mu_skip_}{\.{\\thickmuskip} primitive@>
5353
5354 @ @<Cases of |print_cmd_chr| for symbolic printing of primitives@>=
5355 assign_glue,assign_mu_glue: if chr_code<skip_base then
5356 print_skip_param(chr_code-glue_base)
5357 else if chr_code<mu_skip_base then
5358 begin print_esc("skip"); print_int(chr_code-skip_base);
5359 end
5360 else begin print_esc("muskip"); print_int(chr_code-mu_skip_base);
5361 end;
5362
5363 @ All glue parameters and registers are initially `\.{0pt plus0pt minus0pt}'.
5364
5365 @<Initialize table entries...@>=
5366 equiv(glue_base):=zero_glue; eq_level(glue_base):=level_one;
5367 eq_type(glue_base):=glue_ref;
5368 for k:=glue_base+1 to local_base-1 do eqtb[k]:=eqtb[glue_base];
5369 glue_ref_count(zero_glue):=glue_ref_count(zero_glue)+local_base-glue_base;
5370
5371 @ @<Show equivalent |n|, in region 3@>=
5372 if n<skip_base then
5373 begin print_skip_param(n-glue_base); print_char("=");
5374 if n<glue_base+thin_mu_skip_code then print_spec(equiv(n),"pt")
5375 else print_spec(equiv(n),"mu");
5376 end
5377 else if n<mu_skip_base then
5378 begin print_esc("skip"); print_int(n-skip_base); print_char("=");
5379 print_spec(equiv(n),"pt");
5380 end
5381 else begin print_esc("muskip"); print_int(n-mu_skip_base); print_char("=");
5382 print_spec(equiv(n),"mu");
5383 end
5384
5385 @ Region 4 of |eqtb| contains the local quantities defined here. The
5386 bulk of this region is taken up by five tables that are indexed by eight-bit
5387 characters; these tables are important to both the syntactic and semantic
5388 portions of \TeX. There are also a bunch of special things like font and
5389 token parameters, as well as the tables of \.{\\toks} and \.{\\box}
5390 registers.
5391
5392 @d par_shape_loc=local_base {specifies paragraph shape}
5393 @d output_routine_loc=local_base+1 {points to token list for \.{\\output}}
5394 @d every_par_loc=local_base+2 {points to token list for \.{\\everypar}}
5395 @d every_math_loc=local_base+3 {points to token list for \.{\\everymath}}
5396 @d every_display_loc=local_base+4 {points to token list for \.{\\everydisplay}}
5397 @d every_hbox_loc=local_base+5 {points to token list for \.{\\everyhbox}}
5398 @d every_vbox_loc=local_base+6 {points to token list for \.{\\everyvbox}}
5399 @d every_job_loc=local_base+7 {points to token list for \.{\\everyjob}}
5400 @d every_cr_loc=local_base+8 {points to token list for \.{\\everycr}}
5401 @d err_help_loc=local_base+9 {points to token list for \.{\\errhelp}}
5402 @d tex_toks=local_base+10 {end of \TeX's token list parameters}
5403 @#
5404 @d pdftex_first_loc = tex_toks {base for \pdfTeX's token list parameters}
5405 @d pdf_pages_attr_loc = pdftex_first_loc + 0 {points to token list for \.{\\pdfpagesattr}}
5406 @d pdf_page_attr_loc = pdftex_first_loc + 1 {points to token list for \.{\\pdfpageattr}}
5407 @d pdf_page_resources_loc = pdftex_first_loc + 2 {points to token list for \.{\\pdfpageresources}}
5408 @d pdf_pk_mode_loc = pdftex_first_loc + 3 {points to token list for \.{\\pdfpkmode}}
5409 @d pdf_toks=pdftex_first_loc+4 {end of \pdfTeX's token list parameters}
5410 @#
5411 @d etex_toks_base=pdf_toks {base for \eTeX's token list parameters}
5412 @d every_eof_loc=etex_toks_base {points to token list for \.{\\everyeof}}
5413 @d etex_toks=etex_toks_base+1 {end of \eTeX's token list parameters}
5414 @#
5415 @d toks_base=etex_toks {table of 256 token list registers}
5416 @#
5417 @d etex_pen_base=toks_base+256 {start of table of \eTeX's penalties}
5418 @d inter_line_penalties_loc=etex_pen_base {additional penalties between lines}
5419 @d club_penalties_loc=etex_pen_base+1 {penalties for creating club lines}
5420 @d widow_penalties_loc=etex_pen_base+2 {penalties for creating widow lines}
5421 @d display_widow_penalties_loc=etex_pen_base+3 {ditto, just before a display}
5422 @d etex_pens=etex_pen_base+4 {end of table of \eTeX's penalties}
5423 @#
5424 @d box_base=etex_pens {table of 256 box registers}
5425 @d cur_font_loc=box_base+256 {internal font number outside math mode}
5426 @d math_font_base=cur_font_loc+1 {table of 48 math font numbers}
5427 @d cat_code_base=math_font_base+48
5428 {table of 256 command codes (the ``catcodes'')}
5429 @d lc_code_base=cat_code_base+256 {table of 256 lowercase mappings}
5430 @d uc_code_base=lc_code_base+256 {table of 256 uppercase mappings}
5431 @d sf_code_base=uc_code_base+256 {table of 256 spacefactor mappings}
5432 @d math_code_base=sf_code_base+256 {table of 256 math mode mappings}
5433 @d int_base=math_code_base+256 {beginning of region 5}
5434 @#
5435 @d par_shape_ptr==equiv(par_shape_loc)
5436 @d output_routine==equiv(output_routine_loc)
5437 @d every_par==equiv(every_par_loc)
5438 @d every_math==equiv(every_math_loc)
5439 @d every_display==equiv(every_display_loc)
5440 @d every_hbox==equiv(every_hbox_loc)
5441 @d every_vbox==equiv(every_vbox_loc)
5442 @d every_job==equiv(every_job_loc)
5443 @d every_cr==equiv(every_cr_loc)
5444 @d err_help==equiv(err_help_loc)
5445 @d pdf_pages_attr==equiv(pdf_pages_attr_loc)
5446 @d pdf_page_attr==equiv(pdf_page_attr_loc)
5447 @d pdf_page_resources==equiv(pdf_page_resources_loc)
5448 @d pdf_pk_mode==equiv(pdf_pk_mode_loc)
5449 @d toks(#)==equiv(toks_base+#)
5450 @d box(#)==equiv(box_base+#)
5451 @d cur_font==equiv(cur_font_loc)
5452 @d fam_fnt(#)==equiv(math_font_base+#)
5453 @d cat_code(#)==equiv(cat_code_base+#)
5454 @d lc_code(#)==equiv(lc_code_base+#)
5455 @d uc_code(#)==equiv(uc_code_base+#)
5456 @d sf_code(#)==equiv(sf_code_base+#)
5457 @d math_code(#)==equiv(math_code_base+#)
5458 {Note: |math_code(c)| is the true math code plus |min_halfword|}
5459
5460 @<Put each...@>=
5461 primitive("output",assign_toks,output_routine_loc);
5462 @!@:output_}{\.{\\output} primitive@>
5463 primitive("everypar",assign_toks,every_par_loc);
5464 @!@:every_par_}{\.{\\everypar} primitive@>
5465 primitive("everymath",assign_toks,every_math_loc);
5466 @!@:every_math_}{\.{\\everymath} primitive@>
5467 primitive("everydisplay",assign_toks,every_display_loc);
5468 @!@:every_display_}{\.{\\everydisplay} primitive@>
5469 primitive("everyhbox",assign_toks,every_hbox_loc);
5470 @!@:every_hbox_}{\.{\\everyhbox} primitive@>
5471 primitive("everyvbox",assign_toks,every_vbox_loc);
5472 @!@:every_vbox_}{\.{\\everyvbox} primitive@>
5473 primitive("everyjob",assign_toks,every_job_loc);
5474 @!@:every_job_}{\.{\\everyjob} primitive@>
5475 primitive("everycr",assign_toks,every_cr_loc);
5476 @!@:every_cr_}{\.{\\everycr} primitive@>
5477 primitive("errhelp",assign_toks,err_help_loc);
5478 @!@:err_help_}{\.{\\errhelp} primitive@>
5479 primitive("pdfpagesattr",assign_toks,pdf_pages_attr_loc);
5480 @!@:pdf_pages_attr_}{\.{\\pdfpagesattr} primitive@>
5481 primitive("pdfpageattr",assign_toks,pdf_page_attr_loc);
5482 @!@:pdf_page_attr_}{\.{\\pdfpageattr} primitive@>
5483 primitive("pdfpageresources",assign_toks,pdf_page_resources_loc);
5484 @!@:pdf_page_resources_}{\.{\\pdfpageresources} primitive@>
5485 primitive("pdfpkmode",assign_toks,pdf_pk_mode_loc);
5486 @!@:pdf_pk_mode_}{\.{\\pdfpkmode} primitive@>
5487
5488 @ @<Cases of |print_cmd_chr|...@>=
5489 assign_toks: if chr_code>=toks_base then
5490 begin print_esc("toks"); print_int(chr_code-toks_base);
5491 end
5492 else case chr_code of
5493 output_routine_loc: print_esc("output");
5494 every_par_loc: print_esc("everypar");
5495 every_math_loc: print_esc("everymath");
5496 every_display_loc: print_esc("everydisplay");
5497 every_hbox_loc: print_esc("everyhbox");
5498 every_vbox_loc: print_esc("everyvbox");
5499 every_job_loc: print_esc("everyjob");
5500 every_cr_loc: print_esc("everycr");
5501 @/@<Cases of |assign_toks| for |print_cmd_chr|@>@/
5502 pdf_pages_attr_loc: print_esc("pdfpagesattr");
5503 pdf_page_attr_loc: print_esc("pdfpageattr");
5504 pdf_page_resources_loc: print_esc("pdfpageresources");
5505 pdf_pk_mode_loc: print_esc("pdfpkmode");
5506 othercases print_esc("errhelp")
5507 endcases;
5508
5509 @ We initialize most things to null or undefined values. An undefined font
5510 is represented by the internal code |font_base|.
5511
5512 However, the character code tables are given initial values based on the
5513 conventional interpretation of ASCII code. These initial values should
5514 not be changed when \TeX\ is adapted for use with non-English languages;
5515 all changes to the initialization conventions should be made in format
5516 packages, not in \TeX\ itself, so that global interchange of formats is
5517 possible.
5518
5519 @d null_font==font_base
5520 @d var_code==@'70000 {math code meaning ``use the current family''}
5521
5522 @<Initialize table entries...@>=
5523 par_shape_ptr:=null; eq_type(par_shape_loc):=shape_ref;
5524 eq_level(par_shape_loc):=level_one;@/
5525 for k:=etex_pen_base to etex_pens-1 do
5526 eqtb[k]:=eqtb[par_shape_loc];
5527 for k:=output_routine_loc to toks_base+255 do
5528 eqtb[k]:=eqtb[undefined_control_sequence];
5529 box(0):=null; eq_type(box_base):=box_ref; eq_level(box_base):=level_one;
5530 for k:=box_base+1 to box_base+255 do eqtb[k]:=eqtb[box_base];
5531 cur_font:=null_font; eq_type(cur_font_loc):=data;
5532 eq_level(cur_font_loc):=level_one;@/
5533 for k:=math_font_base to math_font_base+47 do eqtb[k]:=eqtb[cur_font_loc];
5534 equiv(cat_code_base):=0; eq_type(cat_code_base):=data;
5535 eq_level(cat_code_base):=level_one;@/
5536 for k:=cat_code_base+1 to int_base-1 do eqtb[k]:=eqtb[cat_code_base];
5537 for k:=0 to 255 do
5538 begin cat_code(k):=other_char; math_code(k):=hi(k); sf_code(k):=1000;
5539 end;
5540 cat_code(carriage_return):=car_ret; cat_code(" "):=spacer;
5541 cat_code("\"):=escape; cat_code("%"):=comment;
5542 cat_code(invalid_code):=invalid_char; cat_code(null_code):=ignore;
5543 for k:="0" to "9" do math_code(k):=hi(k+var_code);
5544 for k:="A" to "Z" do
5545 begin cat_code(k):=letter; cat_code(k+"a"-"A"):=letter;@/
5546 math_code(k):=hi(k+var_code+@"100);
5547 math_code(k+"a"-"A"):=hi(k+"a"-"A"+var_code+@"100);@/
5548 lc_code(k):=k+"a"-"A"; lc_code(k+"a"-"A"):=k+"a"-"A";@/
5549 uc_code(k):=k; uc_code(k+"a"-"A"):=k;@/
5550 sf_code(k):=999;
5551 end;
5552
5553 @ @<Show equivalent |n|, in region 4@>=
5554 if (n=par_shape_loc) or ((n>=etex_pen_base) and (n<etex_pens)) then
5555 begin print_cmd_chr(set_shape,n); print_char("=");
5556 if equiv(n)=null then print_char("0")
5557 else if n>par_shape_loc then
5558 begin print_int(penalty(equiv(n))); print_char(" ");
5559 print_int(penalty(equiv(n)+1));
5560 if penalty(equiv(n))>1 then print_esc("ETC.");
5561 end
5562 else print_int(info(par_shape_ptr));
5563 end
5564 else if n<toks_base then
5565 begin print_cmd_chr(assign_toks,n); print_char("=");
5566 if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
5567 end
5568 else if n<box_base then
5569 begin print_esc("toks"); print_int(n-toks_base); print_char("=");
5570 if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
5571 end
5572 else if n<cur_font_loc then
5573 begin print_esc("box"); print_int(n-box_base); print_char("=");
5574 if equiv(n)=null then print("void")
5575 else begin depth_threshold:=0; breadth_max:=1; show_node_list(equiv(n));
5576 end;
5577 end
5578 else if n<cat_code_base then @<Show the font identifier in |eqtb[n]|@>
5579 else @<Show the halfword code in |eqtb[n]|@>
5580
5581 @ @<Show the font identifier in |eqtb[n]|@>=
5582 begin if n=cur_font_loc then print("current font")
5583 else if n<math_font_base+16 then
5584 begin print_esc("textfont"); print_int(n-math_font_base);
5585 end
5586 else if n<math_font_base+32 then
5587 begin print_esc("scriptfont"); print_int(n-math_font_base-16);
5588 end
5589 else begin print_esc("scriptscriptfont"); print_int(n-math_font_base-32);
5590 end;
5591 print_char("=");@/
5592 print_esc(hash[font_id_base+equiv(n)].rh);
5593 {that's |font_id_text(equiv(n))|}
5594 end
5595
5596 @ @<Show the halfword code in |eqtb[n]|@>=
5597 if n<math_code_base then
5598 begin if n<lc_code_base then
5599 begin print_esc("catcode"); print_int(n-cat_code_base);
5600 end
5601 else if n<uc_code_base then
5602 begin print_esc("lccode"); print_int(n-lc_code_base);
5603 end
5604 else if n<sf_code_base then
5605 begin print_esc("uccode"); print_int(n-uc_code_base);
5606 end
5607 else begin print_esc("sfcode"); print_int(n-sf_code_base);
5608 end;
5609 print_char("="); print_int(equiv(n));
5610 end
5611 else begin print_esc("mathcode"); print_int(n-math_code_base);
5612 print_char("="); print_int(ho(equiv(n)));
5613 end
5614
5615 @ Region 5 of |eqtb| contains the integer parameters and registers defined
5616 here, as well as the |del_code| table. The latter table differs from the
5617 |cat_code..math_code| tables that precede it, since delimiter codes are
5618 fullword integers while the other kinds of codes occupy at most a
5619 halfword. This is what makes region~5 different from region~4. We will
5620 store the |eq_level| information in an auxiliary array of quarterwords
5621 that will be defined later.
5622
5623 @d pretolerance_code=0 {badness tolerance before hyphenation}
5624 @d tolerance_code=1 {badness tolerance after hyphenation}
5625 @d line_penalty_code=2 {added to the badness of every line}
5626 @d hyphen_penalty_code=3 {penalty for break after discretionary hyphen}
5627 @d ex_hyphen_penalty_code=4 {penalty for break after explicit hyphen}
5628 @d club_penalty_code=5 {penalty for creating a club line}
5629 @d widow_penalty_code=6 {penalty for creating a widow line}
5630 @d display_widow_penalty_code=7 {ditto, just before a display}
5631 @d broken_penalty_code=8 {penalty for breaking a page at a broken line}
5632 @d bin_op_penalty_code=9 {penalty for breaking after a binary operation}
5633 @d rel_penalty_code=10 {penalty for breaking after a relation}
5634 @d pre_display_penalty_code=11
5635 {penalty for breaking just before a displayed formula}
5636 @d post_display_penalty_code=12
5637 {penalty for breaking just after a displayed formula}
5638 @d inter_line_penalty_code=13 {additional penalty between lines}
5639 @d double_hyphen_demerits_code=14 {demerits for double hyphen break}
5640 @d final_hyphen_demerits_code=15 {demerits for final hyphen break}
5641 @d adj_demerits_code=16 {demerits for adjacent incompatible lines}
5642 @d mag_code=17 {magnification ratio}
5643 @d delimiter_factor_code=18 {ratio for variable-size delimiters}
5644 @d looseness_code=19 {change in number of lines for a paragraph}
5645 @d time_code=20 {current time of day}
5646 @d day_code=21 {current day of the month}
5647 @d month_code=22 {current month of the year}
5648 @d year_code=23 {current year of our Lord}
5649 @d show_box_breadth_code=24 {nodes per level in |show_box|}
5650 @d show_box_depth_code=25 {maximum level in |show_box|}
5651 @d hbadness_code=26 {hboxes exceeding this badness will be shown by |hpack|}
5652 @d vbadness_code=27 {vboxes exceeding this badness will be shown by |vpack|}
5653 @d pausing_code=28 {pause after each line is read from a file}
5654 @d tracing_online_code=29 {show diagnostic output on terminal}
5655 @d tracing_macros_code=30 {show macros as they are being expanded}
5656 @d tracing_stats_code=31 {show memory usage if \TeX\ knows it}
5657 @d tracing_paragraphs_code=32 {show line-break calculations}
5658 @d tracing_pages_code=33 {show page-break calculations}
5659 @d tracing_output_code=34 {show boxes when they are shipped out}
5660 @d tracing_lost_chars_code=35 {show characters that aren't in the font}
5661 @d tracing_commands_code=36 {show command codes at |big_switch|}
5662 @d tracing_restores_code=37 {show equivalents when they are restored}
5663 @d uc_hyph_code=38 {hyphenate words beginning with a capital letter}
5664 @d output_penalty_code=39 {penalty found at current page break}
5665 @d max_dead_cycles_code=40 {bound on consecutive dead cycles of output}
5666 @d hang_after_code=41 {hanging indentation changes after this many lines}
5667 @d floating_penalty_code=42 {penalty for insertions held over after a split}
5668 @d global_defs_code=43 {override \.{\\global} specifications}
5669 @d cur_fam_code=44 {current family}
5670 @d escape_char_code=45 {escape character for token output}
5671 @d default_hyphen_char_code=46 {value of \.{\\hyphenchar} when a font is loaded}
5672 @d default_skew_char_code=47 {value of \.{\\skewchar} when a font is loaded}
5673 @d end_line_char_code=48 {character placed at the right end of the buffer}
5674 @d new_line_char_code=49 {character that prints as |print_ln|}
5675 @d language_code=50 {current hyphenation table}
5676 @d left_hyphen_min_code=51 {minimum left hyphenation fragment size}
5677 @d right_hyphen_min_code=52 {minimum right hyphenation fragment size}
5678 @d holding_inserts_code=53 {do not remove insertion nodes from \.{\\box255}}
5679 @d error_context_lines_code=54 {maximum intermediate line pairs shown}
5680 @d tex_int_pars=55 {total number of \TeX's integer parameters}
5681 @#
5682 @d pdftex_first_integer_code = tex_int_pars {base for \pdfTeX's integer parameters}
5683 @d pdf_output_code = pdftex_first_integer_code + 0 {switch on PDF output if positive}
5684 @d pdf_compress_level_code = pdftex_first_integer_code + 1 {compress level of streams}
5685 @d pdf_decimal_digits_code = pdftex_first_integer_code + 2 {digits after the decimal point of numbers}
5686 @d pdf_move_chars_code = pdftex_first_integer_code + 3 {move chars 0..31 to higher area if possible}
5687 @d pdf_image_resolution_code = pdftex_first_integer_code + 4 {default image resolution}
5688 @d pdf_pk_resolution_code = pdftex_first_integer_code + 5 {default resolution of PK font}
5689 @d pdf_unique_resname_code = pdftex_first_integer_code + 6 {generate unique names for resouces}
5690 @d pdf_option_always_use_pdfpagebox_code = pdftex_first_integer_code + 7 {if the PDF inclusion should always use a specific PDF page box}
5691 @d pdf_option_pdf_inclusion_errorlevel_code = pdftex_first_integer_code + 8 {if the PDF inclusion should treat pdfs newer than |pdf_minor_version| as an error}
5692 @d pdf_major_version_code = pdftex_first_integer_code + 9 {integer part of the PDF version produced}
5693 @d pdf_minor_version_code = pdftex_first_integer_code + 10 {fractional part of the PDF version produced}
5694 @d pdf_force_pagebox_code = pdftex_first_integer_code + 11 {if the PDF inclusion should always use a specific PDF page box}
5695 @d pdf_pagebox_code = pdftex_first_integer_code + 12 {default pagebox to use for PDF inclusion}
5696 @d pdf_inclusion_errorlevel_code = pdftex_first_integer_code + 13 {if the PDF inclusion should treat pdfs newer than |pdf_minor_version| as an error}
5697 @d pdf_gamma_code = pdftex_first_integer_code + 14
5698 @d pdf_image_gamma_code = pdftex_first_integer_code + 15
5699 @d pdf_image_hicolor_code = pdftex_first_integer_code + 16
5700 @d pdf_image_apply_gamma_code = pdftex_first_integer_code + 17
5701 @d pdf_adjust_spacing_code = pdftex_first_integer_code + 18 {level of spacing adjusting}
5702 @d pdf_protrude_chars_code = pdftex_first_integer_code + 19 {protrude chars at left/right edge of paragraphs}
5703 @d pdf_tracing_fonts_code = pdftex_first_integer_code + 20 {level of font detail in log}
5704 @d pdf_objcompresslevel_code = pdftex_first_integer_code + 21 {activate object streams}
5705 @d pdf_adjust_interword_glue_code = pdftex_first_integer_code + 22 {adjust interword glue?}
5706 @d pdf_prepend_kern_code = pdftex_first_integer_code + 23 {prepend kern before certain characters?}
5707 @d pdf_append_kern_code = pdftex_first_integer_code + 24 {append kern before certain characters?}
5708 @d pdf_gen_tounicode_code = pdftex_first_integer_code + 25 {generate ToUnicode for fonts?}
5709 @d pdf_draftmode_code = pdftex_first_integer_code + 26 {switch on draftmode if positive}
5710 @d pdf_inclusion_copy_font_code = pdftex_first_integer_code + 27 {generate ToUnicode for fonts?}
5711 @d pdf_suppress_warning_dup_dest_code = pdftex_first_integer_code + 28 {suppress warning about duplicated destinations}
5712 @d pdf_suppress_warning_dup_map_code = pdftex_first_integer_code + 29 {suppress warning about duplicated map lines}
5713 @d pdf_suppress_warning_page_group_code = pdftex_first_integer_code + 30 {suppress warning about multiple pdfs with page group}
5714 @d pdf_info_omit_date_code = pdftex_first_integer_code + 31 {omit generating CreationDate and ModDate}
5715 @d pdf_suppress_ptex_info_code = pdftex_first_integer_code + 32 {suppress /PTEX.* entries in PDF dictionaries}
5716 @d pdf_omit_charset_code = pdftex_first_integer_code + 33 {omit CharSet in Font dict}
5717 @d pdf_omit_info_dict_code = pdftex_first_integer_code + 34 {omit Info dict}
5718 @d pdf_omit_procset_code = pdftex_first_integer_code + 35 {omit ProcSet in resources dict}
5719 @d pdf_ptex_use_underscore_code = pdftex_first_integer_code + 36 {use underscore for PTEX prefix}
5720 @d pdf_int_pars=pdftex_first_integer_code + 37 {total number of \pdfTeX's integer parameters}
5721 @#
5722 @d etex_int_base=pdf_int_pars {base for \eTeX's integer parameters}
5723 @d tracing_assigns_code=etex_int_base {show assignments}
5724 @d tracing_groups_code=etex_int_base+1 {show save/restore groups}
5725 @d tracing_ifs_code=etex_int_base+2 {show conditionals}
5726 @d tracing_scan_tokens_code=etex_int_base+3 {show pseudo file open and close}
5727 @d tracing_nesting_code=etex_int_base+4 {show incomplete groups and ifs within files}
5728 @d pre_display_direction_code=etex_int_base+5 {text direction preceding a display}
5729 @d last_line_fit_code=etex_int_base+6 {adjustment for last line of paragraph}
5730 @d saving_vdiscards_code=etex_int_base+7 {save items discarded from vlists}
5731 @d saving_hyph_codes_code=etex_int_base+8 {save hyphenation codes for languages}
5732 @d ignore_primitive_error_code=etex_int_base+9 {ignore some primitive/engine errors}
5733 @d eTeX_state_code=etex_int_base+10 {\eTeX\ state variables}
5734 @d etex_int_pars=eTeX_state_code+eTeX_states {total number of \eTeX's integer parameters}
5735 @#
5736 @d int_pars=etex_int_pars {total number of integer parameters}
5737 @d count_base=int_base+int_pars {256 user \.{\\count} registers}
5738 @d del_code_base=count_base+256 {256 delimiter code mappings}
5739 @d dimen_base=del_code_base+256 {beginning of region 6}
5740 @#
5741 @d del_code(#)==eqtb[del_code_base+#].int
5742 @d count(#)==eqtb[count_base+#].int
5743 @d int_par(#)==eqtb[int_base+#].int {an integer parameter}
5744 @d pretolerance==int_par(pretolerance_code)
5745 @d tolerance==int_par(tolerance_code)
5746 @d line_penalty==int_par(line_penalty_code)
5747 @d hyphen_penalty==int_par(hyphen_penalty_code)
5748 @d ex_hyphen_penalty==int_par(ex_hyphen_penalty_code)
5749 @d club_penalty==int_par(club_penalty_code)
5750 @d widow_penalty==int_par(widow_penalty_code)
5751 @d display_widow_penalty==int_par(display_widow_penalty_code)
5752 @d broken_penalty==int_par(broken_penalty_code)
5753 @d bin_op_penalty==int_par(bin_op_penalty_code)
5754 @d rel_penalty==int_par(rel_penalty_code)
5755 @d pre_display_penalty==int_par(pre_display_penalty_code)
5756 @d post_display_penalty==int_par(post_display_penalty_code)
5757 @d inter_line_penalty==int_par(inter_line_penalty_code)
5758 @d double_hyphen_demerits==int_par(double_hyphen_demerits_code)
5759 @d final_hyphen_demerits==int_par(final_hyphen_demerits_code)
5760 @d adj_demerits==int_par(adj_demerits_code)
5761 @d mag==int_par(mag_code)
5762 @d delimiter_factor==int_par(delimiter_factor_code)
5763 @d looseness==int_par(looseness_code)
5764 @d time==int_par(time_code)
5765 @d day==int_par(day_code)
5766 @d month==int_par(month_code)
5767 @d year==int_par(year_code)
5768 @d show_box_breadth==int_par(show_box_breadth_code)
5769 @d show_box_depth==int_par(show_box_depth_code)
5770 @d hbadness==int_par(hbadness_code)
5771 @d vbadness==int_par(vbadness_code)
5772 @d pausing==int_par(pausing_code)
5773 @d tracing_online==int_par(tracing_online_code)
5774 @d tracing_macros==int_par(tracing_macros_code)
5775 @d tracing_stats==int_par(tracing_stats_code)
5776 @d tracing_paragraphs==int_par(tracing_paragraphs_code)
5777 @d tracing_pages==int_par(tracing_pages_code)
5778 @d tracing_output==int_par(tracing_output_code)
5779 @d tracing_lost_chars==int_par(tracing_lost_chars_code)
5780 @d tracing_commands==int_par(tracing_commands_code)
5781 @d tracing_restores==int_par(tracing_restores_code)
5782 @d uc_hyph==int_par(uc_hyph_code)
5783 @d output_penalty==int_par(output_penalty_code)
5784 @d max_dead_cycles==int_par(max_dead_cycles_code)
5785 @d hang_after==int_par(hang_after_code)
5786 @d floating_penalty==int_par(floating_penalty_code)
5787 @d global_defs==int_par(global_defs_code)
5788 @d cur_fam==int_par(cur_fam_code)
5789 @d escape_char==int_par(escape_char_code)
5790 @d default_hyphen_char==int_par(default_hyphen_char_code)
5791 @d default_skew_char==int_par(default_skew_char_code)
5792 @d end_line_char==int_par(end_line_char_code)
5793 @d new_line_char==int_par(new_line_char_code)
5794 @d language==int_par(language_code)
5795 @d left_hyphen_min==int_par(left_hyphen_min_code)
5796 @d right_hyphen_min==int_par(right_hyphen_min_code)
5797 @d holding_inserts==int_par(holding_inserts_code)
5798 @d error_context_lines==int_par(error_context_lines_code)
5799 @#
5800 @d pdf_adjust_spacing == int_par(pdf_adjust_spacing_code)
5801 @d pdf_protrude_chars == int_par(pdf_protrude_chars_code)
5802 @d pdf_tracing_fonts == int_par(pdf_tracing_fonts_code)
5803 @d pdf_adjust_interword_glue == int_par(pdf_adjust_interword_glue_code)
5804 @d pdf_prepend_kern == int_par(pdf_prepend_kern_code)
5805 @d pdf_append_kern == int_par(pdf_append_kern_code)
5806 @d pdf_gen_tounicode == int_par(pdf_gen_tounicode_code)
5807 @d pdf_output == int_par(pdf_output_code)
5808 @d pdf_compress_level == int_par(pdf_compress_level_code)
5809 @d pdf_objcompresslevel == int_par(pdf_objcompresslevel_code)
5810 @d pdf_decimal_digits == int_par(pdf_decimal_digits_code)
5811 @d pdf_move_chars == int_par(pdf_move_chars_code)
5812 @d pdf_image_resolution == int_par(pdf_image_resolution_code)
5813 @d pdf_pk_resolution == int_par(pdf_pk_resolution_code)
5814 @d pdf_unique_resname == int_par(pdf_unique_resname_code)
5815 @d pdf_option_always_use_pdfpagebox == int_par(pdf_option_always_use_pdfpagebox_code)
5816 @d pdf_option_pdf_inclusion_errorlevel == int_par(pdf_option_pdf_inclusion_errorlevel_code)
5817 @d pdf_major_version == int_par(pdf_major_version_code)
5818 @d pdf_minor_version == int_par(pdf_minor_version_code)
5819 @d pdf_force_pagebox == int_par(pdf_force_pagebox_code)
5820 @d pdf_pagebox == int_par(pdf_pagebox_code)
5821 @d pdf_inclusion_errorlevel == int_par(pdf_inclusion_errorlevel_code)
5822 @d pdf_gamma == int_par(pdf_gamma_code)
5823 @d pdf_image_gamma == int_par(pdf_image_gamma_code)
5824 @d pdf_image_hicolor == int_par(pdf_image_hicolor_code)
5825 @d pdf_image_apply_gamma == int_par(pdf_image_apply_gamma_code)
5826 @d pdf_draftmode == int_par(pdf_draftmode_code)
5827 @d pdf_inclusion_copy_font == int_par(pdf_inclusion_copy_font_code)
5828 @d pdf_suppress_warning_dup_dest == int_par(pdf_suppress_warning_dup_dest_code)
5829 @d pdf_suppress_warning_dup_map == int_par(pdf_suppress_warning_dup_map_code)
5830 @d pdf_suppress_warning_page_group == int_par(pdf_suppress_warning_page_group_code)
5831 @d pdf_info_omit_date == int_par(pdf_info_omit_date_code)
5832 @d pdf_suppress_ptex_info == int_par(pdf_suppress_ptex_info_code)
5833 @d pdf_omit_charset == int_par(pdf_omit_charset_code)
5834 @d pdf_omit_info_dict == int_par(pdf_omit_info_dict_code)
5835 @d pdf_omit_procset == int_par(pdf_omit_procset_code)
5836 @d pdf_ptex_use_underscore == int_par(pdf_ptex_use_underscore_code)
5837 @#
5838 @d tracing_assigns==int_par(tracing_assigns_code)
5839 @d tracing_groups==int_par(tracing_groups_code)
5840 @d tracing_ifs==int_par(tracing_ifs_code)
5841 @d tracing_scan_tokens==int_par(tracing_scan_tokens_code)
5842 @d tracing_nesting==int_par(tracing_nesting_code)
5843 @d pre_display_direction==int_par(pre_display_direction_code)
5844 @d last_line_fit==int_par(last_line_fit_code)
5845 @d saving_vdiscards==int_par(saving_vdiscards_code)
5846 @d saving_hyph_codes==int_par(saving_hyph_codes_code)
5847 @d ignore_primitive_error==int_par(ignore_primitive_error_code)
5848
5849 @<Assign the values |depth_threshold:=show_box_depth|...@>=
5850 depth_threshold:=show_box_depth;
5851 breadth_max:=show_box_breadth
5852
5853 @ We can print the symbolic name of an integer parameter as follows.
5854
5855 @p procedure print_param(@!n:integer);
5856 begin case n of
5857 pretolerance_code:print_esc("pretolerance");
5858 tolerance_code:print_esc("tolerance");
5859 line_penalty_code:print_esc("linepenalty");
5860 hyphen_penalty_code:print_esc("hyphenpenalty");
5861 ex_hyphen_penalty_code:print_esc("exhyphenpenalty");
5862 club_penalty_code:print_esc("clubpenalty");
5863 widow_penalty_code:print_esc("widowpenalty");
5864 display_widow_penalty_code:print_esc("displaywidowpenalty");
5865 broken_penalty_code:print_esc("brokenpenalty");
5866 bin_op_penalty_code:print_esc("binoppenalty");
5867 rel_penalty_code:print_esc("relpenalty");
5868 pre_display_penalty_code:print_esc("predisplaypenalty");
5869 post_display_penalty_code:print_esc("postdisplaypenalty");
5870 inter_line_penalty_code:print_esc("interlinepenalty");
5871 double_hyphen_demerits_code:print_esc("doublehyphendemerits");
5872 final_hyphen_demerits_code:print_esc("finalhyphendemerits");
5873 adj_demerits_code:print_esc("adjdemerits");
5874 mag_code:print_esc("mag");
5875 delimiter_factor_code:print_esc("delimiterfactor");
5876 looseness_code:print_esc("looseness");
5877 time_code:print_esc("time");
5878 day_code:print_esc("day");
5879 month_code:print_esc("month");
5880 year_code:print_esc("year");
5881 show_box_breadth_code:print_esc("showboxbreadth");
5882 show_box_depth_code:print_esc("showboxdepth");
5883 hbadness_code:print_esc("hbadness");
5884 vbadness_code:print_esc("vbadness");
5885 pausing_code:print_esc("pausing");
5886 tracing_online_code:print_esc("tracingonline");
5887 tracing_macros_code:print_esc("tracingmacros");
5888 tracing_stats_code:print_esc("tracingstats");
5889 tracing_paragraphs_code:print_esc("tracingparagraphs");
5890 tracing_pages_code:print_esc("tracingpages");
5891 tracing_output_code:print_esc("tracingoutput");
5892 tracing_lost_chars_code:print_esc("tracinglostchars");
5893 tracing_commands_code:print_esc("tracingcommands");
5894 tracing_restores_code:print_esc("tracingrestores");
5895 uc_hyph_code:print_esc("uchyph");
5896 output_penalty_code:print_esc("outputpenalty");
5897 max_dead_cycles_code:print_esc("maxdeadcycles");
5898 hang_after_code:print_esc("hangafter");
5899 floating_penalty_code:print_esc("floatingpenalty");
5900 global_defs_code:print_esc("globaldefs");
5901 cur_fam_code:print_esc("fam");
5902 escape_char_code:print_esc("escapechar");
5903 default_hyphen_char_code:print_esc("defaulthyphenchar");
5904 default_skew_char_code:print_esc("defaultskewchar");
5905 end_line_char_code:print_esc("endlinechar");
5906 new_line_char_code:print_esc("newlinechar");
5907 language_code:print_esc("language");
5908 left_hyphen_min_code:print_esc("lefthyphenmin");
5909 right_hyphen_min_code:print_esc("righthyphenmin");
5910 holding_inserts_code:print_esc("holdinginserts");
5911 error_context_lines_code:print_esc("errorcontextlines");
5912 @#
5913 pdf_output_code: print_esc("pdfoutput");
5914 pdf_compress_level_code: print_esc("pdfcompresslevel");
5915 pdf_objcompresslevel_code: print_esc("pdfobjcompresslevel");
5916 pdf_decimal_digits_code: print_esc("pdfdecimaldigits");
5917 pdf_move_chars_code: print_esc("pdfmovechars");
5918 pdf_image_resolution_code: print_esc("pdfimageresolution");
5919 pdf_pk_resolution_code: print_esc("pdfpkresolution");
5920 pdf_unique_resname_code: print_esc("pdfuniqueresname");
5921 pdf_option_always_use_pdfpagebox_code: print_esc("pdfoptionalwaysusepdfpagebox");
5922 pdf_option_pdf_inclusion_errorlevel_code: print_esc("pdfoptionpdfinclusionerrorlevel");
5923 pdf_major_version_code: print_esc("pdfmajorversion");
5924 pdf_minor_version_code: print_esc("pdfminorversion");
5925 pdf_force_pagebox_code: print_esc("pdfforcepagebox");
5926 pdf_pagebox_code: print_esc("pdfpagebox");
5927 pdf_inclusion_errorlevel_code: print_esc("pdfinclusionerrorlevel");
5928 pdf_gamma_code: print_esc("pdfgamma");
5929 pdf_image_gamma_code: print_esc("pdfimagegamma");
5930 pdf_image_hicolor_code: print_esc("pdfimagehicolor");
5931 pdf_image_apply_gamma_code: print_esc("pdfimageapplygamma");
5932 pdf_adjust_spacing_code: print_esc("pdfadjustspacing");
5933 pdf_protrude_chars_code: print_esc("pdfprotrudechars");
5934 pdf_tracing_fonts_code: print_esc("pdftracingfonts");
5935 pdf_adjust_interword_glue_code: print_esc("pdfadjustinterwordglue");
5936 pdf_prepend_kern_code: print_esc("pdfprependkern");
5937 pdf_append_kern_code: print_esc("pdfappendkern");
5938 pdf_gen_tounicode_code: print_esc("pdfgentounicode");
5939 pdf_draftmode_code: print_esc("pdfdraftmode");
5940 pdf_inclusion_copy_font_code: print_esc("pdfinclusioncopyfonts");
5941 pdf_suppress_warning_dup_dest_code: print_esc("pdfsuppresswarningdupdest");
5942 pdf_suppress_warning_dup_map_code: print_esc("pdfsuppresswarningdupmap");
5943 pdf_suppress_warning_page_group_code:print_esc("pdfsuppresswarningpagegroup");
5944 pdf_info_omit_date_code:print_esc("pdfinfoomitdate");
5945 pdf_suppress_ptex_info_code: print_esc("pdfsuppressptexinfo");
5946 pdf_omit_charset_code: print_esc("pdfomitcharset");
5947 pdf_omit_info_dict_code: print_esc("pdfomitinfodict");
5948 pdf_omit_procset_code: print_esc("pdfomitprocset");
5949 pdf_ptex_use_underscore_code: print_esc("pdfptexuseunderscore");
5950 @/@<Cases for |print_param|@>@/
5951 othercases print("[unknown integer parameter!]")
5952 endcases;
5953 end;
5954
5955 @ The integer parameter names must be entered into the hash table.
5956
5957 @<Put each...@>=
5958 primitive("pretolerance",assign_int,int_base+pretolerance_code);@/
5959 @!@:pretolerance_}{\.{\\pretolerance} primitive@>
5960 primitive("tolerance",assign_int,int_base+tolerance_code);@/
5961 @!@:tolerance_}{\.{\\tolerance} primitive@>
5962 primitive("linepenalty",assign_int,int_base+line_penalty_code);@/
5963 @!@:line_penalty_}{\.{\\linepenalty} primitive@>
5964 primitive("hyphenpenalty",assign_int,int_base+hyphen_penalty_code);@/
5965 @!@:hyphen_penalty_}{\.{\\hyphenpenalty} primitive@>
5966 primitive("exhyphenpenalty",assign_int,int_base+ex_hyphen_penalty_code);@/
5967 @!@:ex_hyphen_penalty_}{\.{\\exhyphenpenalty} primitive@>
5968 primitive("clubpenalty",assign_int,int_base+club_penalty_code);@/
5969 @!@:club_penalty_}{\.{\\clubpenalty} primitive@>
5970 primitive("widowpenalty",assign_int,int_base+widow_penalty_code);@/
5971 @!@:widow_penalty_}{\.{\\widowpenalty} primitive@>
5972 primitive("displaywidowpenalty",
5973 assign_int,int_base+display_widow_penalty_code);@/
5974 @!@:display_widow_penalty_}{\.{\\displaywidowpenalty} primitive@>
5975 primitive("brokenpenalty",assign_int,int_base+broken_penalty_code);@/
5976 @!@:broken_penalty_}{\.{\\brokenpenalty} primitive@>
5977 primitive("binoppenalty",assign_int,int_base+bin_op_penalty_code);@/
5978 @!@:bin_op_penalty_}{\.{\\binoppenalty} primitive@>
5979 primitive("relpenalty",assign_int,int_base+rel_penalty_code);@/
5980 @!@:rel_penalty_}{\.{\\relpenalty} primitive@>
5981 primitive("predisplaypenalty",assign_int,int_base+pre_display_penalty_code);@/
5982 @!@:pre_display_penalty_}{\.{\\predisplaypenalty} primitive@>
5983 primitive("postdisplaypenalty",assign_int,int_base+post_display_penalty_code);@/
5984 @!@:post_display_penalty_}{\.{\\postdisplaypenalty} primitive@>
5985 primitive("interlinepenalty",assign_int,int_base+inter_line_penalty_code);@/
5986 @!@:inter_line_penalty_}{\.{\\interlinepenalty} primitive@>
5987 primitive("doublehyphendemerits",
5988 assign_int,int_base+double_hyphen_demerits_code);@/
5989 @!@:double_hyphen_demerits_}{\.{\\doublehyphendemerits} primitive@>
5990 primitive("finalhyphendemerits",
5991 assign_int,int_base+final_hyphen_demerits_code);@/
5992 @!@:final_hyphen_demerits_}{\.{\\finalhyphendemerits} primitive@>
5993 primitive("adjdemerits",assign_int,int_base+adj_demerits_code);@/
5994 @!@:adj_demerits_}{\.{\\adjdemerits} primitive@>
5995 primitive("mag",assign_int,int_base+mag_code);@/
5996 @!@:mag_}{\.{\\mag} primitive@>
5997 primitive("delimiterfactor",assign_int,int_base+delimiter_factor_code);@/
5998 @!@:delimiter_factor_}{\.{\\delimiterfactor} primitive@>
5999 primitive("looseness",assign_int,int_base+looseness_code);@/
6000 @!@:looseness_}{\.{\\looseness} primitive@>
6001 primitive("time",assign_int,int_base+time_code);@/
6002 @!@:time_}{\.{\\time} primitive@>
6003 primitive("day",assign_int,int_base+day_code);@/
6004 @!@:day_}{\.{\\day} primitive@>
6005 primitive("month",assign_int,int_base+month_code);@/
6006 @!@:month_}{\.{\\month} primitive@>
6007 primitive("year",assign_int,int_base+year_code);@/
6008 @!@:year_}{\.{\\year} primitive@>
6009 primitive("showboxbreadth",assign_int,int_base+show_box_breadth_code);@/
6010 @!@:show_box_breadth_}{\.{\\showboxbreadth} primitive@>
6011 primitive("showboxdepth",assign_int,int_base+show_box_depth_code);@/
6012 @!@:show_box_depth_}{\.{\\showboxdepth} primitive@>
6013 primitive("hbadness",assign_int,int_base+hbadness_code);@/
6014 @!@:hbadness_}{\.{\\hbadness} primitive@>
6015 primitive("vbadness",assign_int,int_base+vbadness_code);@/
6016 @!@:vbadness_}{\.{\\vbadness} primitive@>
6017 primitive("pausing",assign_int,int_base+pausing_code);@/
6018 @!@:pausing_}{\.{\\pausing} primitive@>
6019 primitive("tracingonline",assign_int,int_base+tracing_online_code);@/
6020 @!@:tracing_online_}{\.{\\tracingonline} primitive@>
6021 primitive("tracingmacros",assign_int,int_base+tracing_macros_code);@/
6022 @!@:tracing_macros_}{\.{\\tracingmacros} primitive@>
6023 primitive("tracingstats",assign_int,int_base+tracing_stats_code);@/
6024 @!@:tracing_stats_}{\.{\\tracingstats} primitive@>
6025 primitive("tracingparagraphs",assign_int,int_base+tracing_paragraphs_code);@/
6026 @!@:tracing_paragraphs_}{\.{\\tracingparagraphs} primitive@>
6027 primitive("tracingpages",assign_int,int_base+tracing_pages_code);@/
6028 @!@:tracing_pages_}{\.{\\tracingpages} primitive@>
6029 primitive("tracingoutput",assign_int,int_base+tracing_output_code);@/
6030 @!@:tracing_output_}{\.{\\tracingoutput} primitive@>
6031 primitive("tracinglostchars",assign_int,int_base+tracing_lost_chars_code);@/
6032 @!@:tracing_lost_chars_}{\.{\\tracinglostchars} primitive@>
6033 primitive("tracingcommands",assign_int,int_base+tracing_commands_code);@/
6034 @!@:tracing_commands_}{\.{\\tracingcommands} primitive@>
6035 primitive("tracingrestores",assign_int,int_base+tracing_restores_code);@/
6036 @!@:tracing_restores_}{\.{\\tracingrestores} primitive@>
6037 primitive("uchyph",assign_int,int_base+uc_hyph_code);@/
6038 @!@:uc_hyph_}{\.{\\uchyph} primitive@>
6039 primitive("outputpenalty",assign_int,int_base+output_penalty_code);@/
6040 @!@:output_penalty_}{\.{\\outputpenalty} primitive@>
6041 primitive("maxdeadcycles",assign_int,int_base+max_dead_cycles_code);@/
6042 @!@:max_dead_cycles_}{\.{\\maxdeadcycles} primitive@>
6043 primitive("hangafter",assign_int,int_base+hang_after_code);@/
6044 @!@:hang_after_}{\.{\\hangafter} primitive@>
6045 primitive("floatingpenalty",assign_int,int_base+floating_penalty_code);@/
6046 @!@:floating_penalty_}{\.{\\floatingpenalty} primitive@>
6047 primitive("globaldefs",assign_int,int_base+global_defs_code);@/
6048 @!@:global_defs_}{\.{\\globaldefs} primitive@>
6049 primitive("fam",assign_int,int_base+cur_fam_code);@/
6050 @!@:fam_}{\.{\\fam} primitive@>
6051 primitive("escapechar",assign_int,int_base+escape_char_code);@/
6052 @!@:escape_char_}{\.{\\escapechar} primitive@>
6053 primitive("defaulthyphenchar",assign_int,int_base+default_hyphen_char_code);@/
6054 @!@:default_hyphen_char_}{\.{\\defaulthyphenchar} primitive@>
6055 primitive("defaultskewchar",assign_int,int_base+default_skew_char_code);@/
6056 @!@:default_skew_char_}{\.{\\defaultskewchar} primitive@>
6057 primitive("endlinechar",assign_int,int_base+end_line_char_code);@/
6058 @!@:end_line_char_}{\.{\\endlinechar} primitive@>
6059 primitive("newlinechar",assign_int,int_base+new_line_char_code);@/
6060 @!@:new_line_char_}{\.{\\newlinechar} primitive@>
6061 primitive("language",assign_int,int_base+language_code);@/
6062 @!@:language_}{\.{\\language} primitive@>
6063 primitive("lefthyphenmin",assign_int,int_base+left_hyphen_min_code);@/
6064 @!@:left_hyphen_min_}{\.{\\lefthyphenmin} primitive@>
6065 primitive("righthyphenmin",assign_int,int_base+right_hyphen_min_code);@/
6066 @!@:right_hyphen_min_}{\.{\\righthyphenmin} primitive@>
6067 primitive("holdinginserts",assign_int,int_base+holding_inserts_code);@/
6068 @!@:holding_inserts_}{\.{\\holdinginserts} primitive@>
6069 primitive("errorcontextlines",assign_int,int_base+error_context_lines_code);@/
6070 @!@:error_context_lines_}{\.{\\errorcontextlines} primitive@>
6071 primitive("pdfoutput",assign_int,int_base+pdf_output_code);@/
6072 @!@:pdf_output_}{\.{\\pdfoutput} primitive@>
6073 primitive("pdfcompresslevel",assign_int,int_base+pdf_compress_level_code);@/
6074 @!@:pdf_compress_level_}{\.{\\pdfcompresslevel} primitive@>
6075 primitive("pdfobjcompresslevel",assign_int,int_base+pdf_objcompresslevel_code);@/
6076 @!@:pdf_objcompresslevel_}{\.{\\pdfobjcompresslevel} primitive@>
6077 primitive("pdfdecimaldigits",assign_int,int_base+pdf_decimal_digits_code);@/
6078 @!@:pdf_decimal_digits_}{\.{\\pdfdecimaldigits} primitive@>
6079 primitive("pdfmovechars",assign_int,int_base+pdf_move_chars_code);@/
6080 @!@:pdf_move_chars_}{\.{\\pdfmovechars} primitive@>
6081 primitive("pdfimageresolution",assign_int,int_base+pdf_image_resolution_code);@/
6082 @!@:pdf_image_resolution_}{\.{\\pdfimageresolution} primitive@>
6083 primitive("pdfpkresolution",assign_int,int_base+pdf_pk_resolution_code);@/
6084 @!@:pdf_pk_resolution_}{\.{\\pdfpkresolution} primitive@>
6085 primitive("pdfuniqueresname",assign_int,int_base+pdf_unique_resname_code);@/
6086 @!@:pdf_unique_resname_}{\.{\\pdfuniqueresname} primitive@>
6087 primitive("pdfoptionpdfminorversion",assign_int,int_base+pdf_minor_version_code);@/
6088 @!@:pdf_minor_version_}{\.{\\pdfoptionpdfminorversion} primitive@>
6089 primitive("pdfoptionalwaysusepdfpagebox",assign_int,int_base+pdf_option_always_use_pdfpagebox_code);@/
6090 @!@:pdf_option_always_use_pdfpagebox_}{\.{\\pdfoptionalwaysusepdfpagebox} primitive@>
6091 primitive("pdfoptionpdfinclusionerrorlevel",assign_int,int_base+pdf_option_pdf_inclusion_errorlevel_code);@/
6092 @!@:pdf_option_pdf_inclusion_errorlevel_}{\.{\\pdfoptionpdfinclusionerrorlevel} primitive@>
6093 primitive("pdfmajorversion",assign_int,int_base+pdf_major_version_code);@/
6094 @!@:pdf_major_version_}{\.{\\pdfmajorversion} primitive@>
6095 primitive("pdfminorversion",assign_int,int_base+pdf_minor_version_code);@/
6096 @!@:pdf_minor_version_}{\.{\\pdfminorversion} primitive@>
6097 primitive("pdfforcepagebox",assign_int,int_base+pdf_force_pagebox_code);@/
6098 @!@:pdf_force_pagebox_}{\.{\\pdfforcepagebox} primitive@>
6099 primitive("pdfpagebox",assign_int,int_base+pdf_pagebox_code);@/
6100 @!@:pdf_pagebox_}{\.{\\pdfpagebox} primitive@>
6101 primitive("pdfinclusionerrorlevel",assign_int,int_base+pdf_inclusion_errorlevel_code);@/
6102 @!@:pdf_inclusion_errorlevel_}{\.{\\pdfinclusionerrorlevel} primitive@>
6103 primitive("pdfgamma",assign_int,int_base+pdf_gamma_code);@/
6104 @!@:pdf_gamma_}{\.{\\pdfgamma} primitive@>
6105 primitive("pdfimagegamma",assign_int,int_base+pdf_image_gamma_code);@/
6106 @!@:pdf_image_gamma_}{\.{\\pdfimagegamma} primitive@>
6107 primitive("pdfimagehicolor",assign_int,int_base+pdf_image_hicolor_code);@/
6108 @!@:pdf_image_hicolor_}{\.{\\pdfimagehicolor} primitive@>
6109 primitive("pdfimageapplygamma",assign_int,int_base+pdf_image_apply_gamma_code);@/
6110 @!@:pdf_image_apply_gamma_}{\.{\\pdfimageapplygamma} primitive@>
6111 primitive("pdfadjustspacing",assign_int,int_base+pdf_adjust_spacing_code);@/
6112 @!@:pdf_adjust_spacing_}{\.{\\pdfadjustspacing} primitive@>
6113 primitive("pdfprotrudechars",assign_int,int_base+pdf_protrude_chars_code);@/
6114 @!@:pdf_protrude_chars_}{\.{\\pdfprotrudechars} primitive@>
6115 primitive("pdftracingfonts",assign_int,int_base+pdf_tracing_fonts_code);@/
6116 @!@:pdf_tracing_fonts_}{\.{\\pdftracingfonts} primitive@>
6117 primitive("pdfadjustinterwordglue",assign_int,int_base+pdf_adjust_interword_glue_code);@/
6118 @!@:pdf_adjust_interword_glue_}{\.{\\pdfadjustinterwordglue} primitive@>
6119 primitive("pdfprependkern",assign_int,int_base+pdf_prepend_kern_code);@/
6120 @!@:pdf_prepend_kern_}{\.{\\pdfprependkern} primitive@>
6121 primitive("pdfappendkern",assign_int,int_base+pdf_append_kern_code);@/
6122 @!@:pdf_append_kern_}{\.{\\pdfappendkern} primitive@>
6123 primitive("pdfgentounicode",assign_int,int_base+pdf_gen_tounicode_code);@/
6124 @!@:pdf_gen_tounicode_}{\.{\\pdfgentounicode} primitive@>
6125 primitive("pdfdraftmode",assign_int,int_base+pdf_draftmode_code);@/
6126 @!@:pdf_draftmode_}{\.{\\pdfdraftmode} primitive@>
6127 primitive("pdfinclusioncopyfonts",assign_int,int_base+pdf_inclusion_copy_font_code);@/
6128 @!@:pdf_inclusion_copy_font_}{\.{\\pdfinclusioncopyfonts} primitive@>
6129
6130 primitive("pdfsuppresswarningdupdest",assign_int,int_base+pdf_suppress_warning_dup_dest_code);@/
6131 @!@:pdf_suppress_warning_dup_dest_}{\.{\\pdfsuppresswarningdupdest} primitive@>
6132
6133 primitive("pdfsuppresswarningdupmap",assign_int,int_base+pdf_suppress_warning_dup_map_code);@/
6134 @!@:pdf_suppress_warning_dup_map_}{\.{\\pdfsuppresswarningdupmap} primitive@>
6135
6136 primitive("pdfsuppresswarningpagegroup",assign_int,int_base+pdf_suppress_warning_page_group_code);@/
6137 @!@:pdf_suppress_warning_page_group_}{\.{\\pdfsuppresswarningpagegroup} primitive@>
6138
6139 primitive("pdfinfoomitdate",assign_int,int_base+pdf_info_omit_date_code);@/
6140 @!@:pdf_info_omit_date_}{\.{\\pdfinfoomitdate} primitive@>
6141
6142 primitive("pdfsuppressptexinfo",assign_int,int_base+pdf_suppress_ptex_info_code);@/
6143 @!@:pdf_suppress_ptex_info_}{\.{\\pdfsuppressptexinfo} primitive@>
6144
6145 primitive("pdfomitcharset",assign_int,int_base+pdf_omit_charset_code);@/
6146 @!@:pdf_omit_charset}{\.{\\pdfomitcharset} primitive@>
6147
6148 primitive("pdfomitinfodict",assign_int,int_base+pdf_omit_info_dict_code);@/
6149 @!@:pdf_omit_info_dict}{\.{\\pdfomitinfodict} primitive@>
6150
6151 primitive("pdfomitprocset",assign_int,int_base+pdf_omit_procset_code);@/
6152 @!@:pdf_omit_procset}{\.{\\pdfomitprocset} primitive@>
6153
6154 primitive("pdfptexuseunderscore",assign_int,int_base+pdf_ptex_use_underscore_code);@/
6155 @!@:pdf_ptex_use_underscore}{\.{\\pdfptexuseunderscore} primitive@>
6156
6157 @ @<Cases of |print_cmd_chr|...@>=
6158 assign_int: if chr_code<count_base then print_param(chr_code-int_base)
6159 else begin print_esc("count"); print_int(chr_code-count_base);
6160 end;
6161
6162 @ The integer parameters should really be initialized by a macro package;
6163 the following initialization does the minimum to keep \TeX\ from
6164 complete failure.
6165 @^null delimiter@>
6166
6167 @<Initialize table entries...@>=
6168 for k:=int_base to del_code_base-1 do eqtb[k].int:=0;
6169 mag:=1000; tolerance:=10000; hang_after:=1; max_dead_cycles:=25;
6170 escape_char:="\"; end_line_char:=carriage_return;
6171 for k:=0 to 255 do del_code(k):=-1;
6172 del_code("."):=0; {this null delimiter is used in error recovery}
6173
6174 @ The following procedure, which is called just before \TeX\ initializes its
6175 input and output, establishes the initial values of the date and time.
6176 @^system dependencies@>
6177 Since standard \PASCAL\ cannot provide such information, something special
6178 is needed. The program here simply assumes that suitable values appear in
6179 the global variables \\{sys\_time}, \\{sys\_day}, \\{sys\_month}, and
6180 \\{sys\_year} (which are initialized to noon on 4 July 1776,
6181 in case the implementor is careless).
6182
6183 @p procedure fix_date_and_time;
6184 begin sys_time:=12*60;
6185 sys_day:=4; sys_month:=7; sys_year:=1776; {self-evident truths}
6186 time:=sys_time; {minutes since midnight}
6187 day:=sys_day; {day of the month}
6188 month:=sys_month; {month of the year}
6189 year:=sys_year; {Anno Domini}
6190 end;
6191
6192 @ @<Show equivalent |n|, in region 5@>=
6193 begin if n<count_base then print_param(n-int_base)
6194 else if n<del_code_base then
6195 begin print_esc("count"); print_int(n-count_base);
6196 end
6197 else begin print_esc("delcode"); print_int(n-del_code_base);
6198 end;
6199 print_char("="); print_int(eqtb[n].int);
6200 end
6201
6202 @ @<Set variable |c| to the current escape character@>=c:=escape_char
6203
6204 @ @<Character |s| is the current new-line character@>=s=new_line_char
6205
6206 @ \TeX\ is occasionally supposed to print diagnostic information that
6207 goes only into the transcript file, unless |tracing_online| is positive.
6208 Here are two routines that adjust the destination of print commands:
6209
6210 @p procedure begin_diagnostic; {prepare to do some tracing}
6211 begin old_setting:=selector;
6212 if (tracing_online<=0)and(selector=term_and_log) then
6213 begin decr(selector);
6214 if history=spotless then history:=warning_issued;
6215 end;
6216 end;
6217 @#
6218 procedure end_diagnostic(@!blank_line:boolean);
6219 {restore proper conditions after tracing}
6220 begin print_nl("");
6221 if blank_line then print_ln;
6222 selector:=old_setting;
6223 end;
6224
6225 @ Of course we had better declare a few more global variables, if the previous
6226 routines are going to work.
6227
6228 @<Glob...@>=
6229 @!old_setting:0..max_selector;
6230 @!old_selector_ignored_err:0..max_selector; { for |print_ignored_err|}
6231
6232 @!sys_time,@!sys_day,@!sys_month,@!sys_year:integer;
6233 {date and time supplied by external system}
6234
6235 @ The final region of |eqtb| contains the dimension parameters defined
6236 here, and the 256 \.{\\dimen} registers.
6237
6238 @d par_indent_code=0 {indentation of paragraphs}
6239 @d math_surround_code=1 {space around math in text}
6240 @d line_skip_limit_code=2 {threshold for |line_skip| instead of |baseline_skip|}
6241 @d hsize_code=3 {line width in horizontal mode}
6242 @d vsize_code=4 {page height in vertical mode}
6243 @d max_depth_code=5 {maximum depth of boxes on main pages}
6244 @d split_max_depth_code=6 {maximum depth of boxes on split pages}
6245 @d box_max_depth_code=7 {maximum depth of explicit vboxes}
6246 @d hfuzz_code=8 {tolerance for overfull hbox messages}
6247 @d vfuzz_code=9 {tolerance for overfull vbox messages}
6248 @d delimiter_shortfall_code=10 {maximum amount uncovered by variable delimiters}
6249 @d null_delimiter_space_code=11 {blank space in null delimiters}
6250 @d script_space_code=12 {extra space after subscript or superscript}
6251 @d pre_display_size_code=13 {length of text preceding a display}
6252 @d display_width_code=14 {length of line for displayed equation}
6253 @d display_indent_code=15 {indentation of line for displayed equation}
6254 @d overfull_rule_code=16 {width of rule that identifies overfull hboxes}
6255 @d hang_indent_code=17 {amount of hanging indentation}
6256 @d h_offset_code=18 {amount of horizontal offset when shipping pages out}
6257 @d v_offset_code=19 {amount of vertical offset when shipping pages out}
6258 @d emergency_stretch_code=20 {reduces badnesses on final pass of line-breaking}
6259 @d pdftex_first_dimen_code = 21 {first number defined in this section}
6260 @d pdf_h_origin_code = pdftex_first_dimen_code + 0 {horigin of the PDF output}
6261 @d pdf_v_origin_code = pdftex_first_dimen_code + 1 {vorigin of the PDF output}
6262 @d pdf_page_width_code = pdftex_first_dimen_code + 2 {page width of the PDF output}
6263 @d pdf_page_height_code = pdftex_first_dimen_code + 3 {page height of the PDF output}
6264 @d pdf_link_margin_code = pdftex_first_dimen_code + 4 {link margin in the PDF output}
6265 @d pdf_dest_margin_code = pdftex_first_dimen_code + 5 {dest margin in the PDF output}
6266 @d pdf_thread_margin_code = pdftex_first_dimen_code + 6 {thread margin in the PDF output}
6267 @d pdf_first_line_height_code = pdftex_first_dimen_code + 7
6268 @d pdf_last_line_depth_code = pdftex_first_dimen_code + 8
6269 @d pdf_each_line_height_code = pdftex_first_dimen_code + 9
6270 @d pdf_each_line_depth_code = pdftex_first_dimen_code + 10
6271 @d pdf_ignored_dimen_code = pdftex_first_dimen_code + 11
6272 @d pdf_px_dimen_code = pdftex_first_dimen_code + 12
6273 @d pdftex_last_dimen_code = pdftex_first_dimen_code + 12 {last number defined in this section}
6274 @d dimen_pars = pdftex_last_dimen_code + 1 {total number of dimension parameters}
6275 @d scaled_base=dimen_base+dimen_pars
6276 {table of 256 user-defined \.{\\dimen} registers}
6277 @d eqtb_size=scaled_base+255 {largest subscript of |eqtb|}
6278 @#
6279 @d dimen(#)==eqtb[scaled_base+#].sc
6280 @d dimen_par(#)==eqtb[dimen_base+#].sc {a scaled quantity}
6281 @d par_indent==dimen_par(par_indent_code)
6282 @d math_surround==dimen_par(math_surround_code)
6283 @d line_skip_limit==dimen_par(line_skip_limit_code)
6284 @d hsize==dimen_par(hsize_code)
6285 @d vsize==dimen_par(vsize_code)
6286 @d max_depth==dimen_par(max_depth_code)
6287 @d split_max_depth==dimen_par(split_max_depth_code)
6288 @d box_max_depth==dimen_par(box_max_depth_code)
6289 @d hfuzz==dimen_par(hfuzz_code)
6290 @d vfuzz==dimen_par(vfuzz_code)
6291 @d delimiter_shortfall==dimen_par(delimiter_shortfall_code)
6292 @d null_delimiter_space==dimen_par(null_delimiter_space_code)
6293 @d script_space==dimen_par(script_space_code)
6294 @d pre_display_size==dimen_par(pre_display_size_code)
6295 @d display_width==dimen_par(display_width_code)
6296 @d display_indent==dimen_par(display_indent_code)
6297 @d overfull_rule==dimen_par(overfull_rule_code)
6298 @d hang_indent==dimen_par(hang_indent_code)
6299 @d h_offset==dimen_par(h_offset_code)
6300 @d v_offset==dimen_par(v_offset_code)
6301 @d emergency_stretch==dimen_par(emergency_stretch_code)
6302 @d pdf_h_origin == dimen_par(pdf_h_origin_code)
6303 @d pdf_v_origin == dimen_par(pdf_v_origin_code)
6304 @d pdf_page_width == dimen_par(pdf_page_width_code)
6305 @d pdf_page_height == dimen_par(pdf_page_height_code)
6306 @d pdf_link_margin == dimen_par(pdf_link_margin_code)
6307 @d pdf_dest_margin == dimen_par(pdf_dest_margin_code)
6308 @d pdf_thread_margin == dimen_par(pdf_thread_margin_code)
6309 @d pdf_first_line_height == dimen_par(pdf_first_line_height_code)
6310 @d pdf_last_line_depth == dimen_par(pdf_last_line_depth_code)
6311 @d pdf_each_line_height == dimen_par(pdf_each_line_height_code)
6312 @d pdf_each_line_depth == dimen_par(pdf_each_line_depth_code)
6313 @d pdf_ignored_dimen == dimen_par(pdf_ignored_dimen_code)
6314 @d pdf_px_dimen == dimen_par(pdf_px_dimen_code)
6315
6316 @p procedure print_length_param(@!n:integer);
6317 begin case n of
6318 par_indent_code:print_esc("parindent");
6319 math_surround_code:print_esc("mathsurround");
6320 line_skip_limit_code:print_esc("lineskiplimit");
6321 hsize_code:print_esc("hsize");
6322 vsize_code:print_esc("vsize");
6323 max_depth_code:print_esc("maxdepth");
6324 split_max_depth_code:print_esc("splitmaxdepth");
6325 box_max_depth_code:print_esc("boxmaxdepth");
6326 hfuzz_code:print_esc("hfuzz");
6327 vfuzz_code:print_esc("vfuzz");
6328 delimiter_shortfall_code:print_esc("delimitershortfall");
6329 null_delimiter_space_code:print_esc("nulldelimiterspace");
6330 script_space_code:print_esc("scriptspace");
6331 pre_display_size_code:print_esc("predisplaysize");
6332 display_width_code:print_esc("displaywidth");
6333 display_indent_code:print_esc("displayindent");
6334 overfull_rule_code:print_esc("overfullrule");
6335 hang_indent_code:print_esc("hangindent");
6336 h_offset_code:print_esc("hoffset");
6337 v_offset_code:print_esc("voffset");
6338 emergency_stretch_code:print_esc("emergencystretch");
6339 pdf_h_origin_code: print_esc("pdfhorigin");
6340 pdf_v_origin_code: print_esc("pdfvorigin");
6341 pdf_page_width_code: print_esc("pdfpagewidth");
6342 pdf_page_height_code: print_esc("pdfpageheight");
6343 pdf_link_margin_code: print_esc("pdflinkmargin");
6344 pdf_dest_margin_code: print_esc("pdfdestmargin");
6345 pdf_thread_margin_code: print_esc("pdfthreadmargin");
6346 pdf_first_line_height_code: print_esc("pdffirstlineheight");
6347 pdf_last_line_depth_code: print_esc("pdflastlinedepth");
6348 pdf_each_line_height_code: print_esc("pdfeachlineheight");
6349 pdf_each_line_depth_code: print_esc("pdfeachlinedepth");
6350 pdf_ignored_dimen_code: print_esc("pdfignoreddimen");
6351 pdf_px_dimen_code: print_esc("pdfpxdimen");
6352 othercases print("[unknown dimen parameter!]")
6353 endcases;
6354 end;
6355
6356 @ @<Put each...@>=
6357 primitive("parindent",assign_dimen,dimen_base+par_indent_code);@/
6358 @!@:par_indent_}{\.{\\parindent} primitive@>
6359 primitive("mathsurround",assign_dimen,dimen_base+math_surround_code);@/
6360 @!@:math_surround_}{\.{\\mathsurround} primitive@>
6361 primitive("lineskiplimit",assign_dimen,dimen_base+line_skip_limit_code);@/
6362 @!@:line_skip_limit_}{\.{\\lineskiplimit} primitive@>
6363 primitive("hsize",assign_dimen,dimen_base+hsize_code);@/
6364 @!@:hsize_}{\.{\\hsize} primitive@>
6365 primitive("vsize",assign_dimen,dimen_base+vsize_code);@/
6366 @!@:vsize_}{\.{\\vsize} primitive@>
6367 primitive("maxdepth",assign_dimen,dimen_base+max_depth_code);@/
6368 @!@:max_depth_}{\.{\\maxdepth} primitive@>
6369 primitive("splitmaxdepth",assign_dimen,dimen_base+split_max_depth_code);@/
6370 @!@:split_max_depth_}{\.{\\splitmaxdepth} primitive@>
6371 primitive("boxmaxdepth",assign_dimen,dimen_base+box_max_depth_code);@/
6372 @!@:box_max_depth_}{\.{\\boxmaxdepth} primitive@>
6373 primitive("hfuzz",assign_dimen,dimen_base+hfuzz_code);@/
6374 @!@:hfuzz_}{\.{\\hfuzz} primitive@>
6375 primitive("vfuzz",assign_dimen,dimen_base+vfuzz_code);@/
6376 @!@:vfuzz_}{\.{\\vfuzz} primitive@>
6377 primitive("delimitershortfall",
6378 assign_dimen,dimen_base+delimiter_shortfall_code);@/
6379 @!@:delimiter_shortfall_}{\.{\\delimitershortfall} primitive@>
6380 primitive("nulldelimiterspace",
6381 assign_dimen,dimen_base+null_delimiter_space_code);@/
6382 @!@:null_delimiter_space_}{\.{\\nulldelimiterspace} primitive@>
6383 primitive("scriptspace",assign_dimen,dimen_base+script_space_code);@/
6384 @!@:script_space_}{\.{\\scriptspace} primitive@>
6385 primitive("predisplaysize",assign_dimen,dimen_base+pre_display_size_code);@/
6386 @!@:pre_display_size_}{\.{\\predisplaysize} primitive@>
6387 primitive("displaywidth",assign_dimen,dimen_base+display_width_code);@/
6388 @!@:display_width_}{\.{\\displaywidth} primitive@>
6389 primitive("displayindent",assign_dimen,dimen_base+display_indent_code);@/
6390 @!@:display_indent_}{\.{\\displayindent} primitive@>
6391 primitive("overfullrule",assign_dimen,dimen_base+overfull_rule_code);@/
6392 @!@:overfull_rule_}{\.{\\overfullrule} primitive@>
6393 primitive("hangindent",assign_dimen,dimen_base+hang_indent_code);@/
6394 @!@:hang_indent_}{\.{\\hangindent} primitive@>
6395 primitive("hoffset",assign_dimen,dimen_base+h_offset_code);@/
6396 @!@:h_offset_}{\.{\\hoffset} primitive@>
6397 primitive("voffset",assign_dimen,dimen_base+v_offset_code);@/
6398 @!@:v_offset_}{\.{\\voffset} primitive@>
6399 primitive("emergencystretch",assign_dimen,dimen_base+emergency_stretch_code);@/
6400 @!@:emergency_stretch_}{\.{\\emergencystretch} primitive@>
6401 primitive("pdfhorigin",assign_dimen,dimen_base+pdf_h_origin_code);@/
6402 @!@:pdf_h_origin_}{\.{\\pdfhorigin} primitive@>
6403 primitive("pdfvorigin",assign_dimen,dimen_base+pdf_v_origin_code);@/
6404 @!@:pdf_v_origin_}{\.{\\pdfvorigin} primitive@>
6405 primitive("pdfpagewidth",assign_dimen,dimen_base+pdf_page_width_code);@/
6406 @!@:pdf_page_width_}{\.{\\pdfpagewidth} primitive@>
6407 primitive("pdfpageheight",assign_dimen,dimen_base+pdf_page_height_code);@/
6408 @!@:pdf_page_height_}{\.{\\pdfpageheight} primitive@>
6409 primitive("pdflinkmargin",assign_dimen,dimen_base+pdf_link_margin_code);@/
6410 @!@:pdf_link_margin_}{\.{\\pdflinkmargin} primitive@>
6411 primitive("pdfdestmargin",assign_dimen,dimen_base+pdf_dest_margin_code);@/
6412 @!@:pdf_dest_margin_}{\.{\\pdfdestmargin} primitive@>
6413 primitive("pdfthreadmargin",assign_dimen,dimen_base+pdf_thread_margin_code);@/
6414 @!@:pdf_thread_margin_}{\.{\\pdfthreadmargin} primitive@>
6415 primitive("pdffirstlineheight",assign_dimen,dimen_base+pdf_first_line_height_code);@/
6416 @!@:pdf_first_line_height_}{\.{\\pdffirstlineheight} primitive@>
6417 primitive("pdflastlinedepth",assign_dimen,dimen_base+pdf_last_line_depth_code);@/
6418 @!@:pdf_last_line_depth_}{\.{\\pdflastlinedepth} primitive@>
6419 primitive("pdfeachlineheight",assign_dimen,dimen_base+pdf_each_line_height_code);@/
6420 @!@:pdf_each_line_height_}{\.{\\pdfeachlineheight} primitive@>
6421 primitive("pdfeachlinedepth",assign_dimen,dimen_base+pdf_each_line_depth_code);@/
6422 @!@:pdf_each_line_depth_}{\.{\\pdfeachlinedepth} primitive@>
6423 primitive("pdfignoreddimen",assign_dimen,dimen_base+pdf_ignored_dimen_code);@/
6424 @!@:pdf_ignored_dimen_}{\.{\\pdfignoreddimen} primitive@>
6425 primitive("pdfpxdimen",assign_dimen,dimen_base+pdf_px_dimen_code);@/
6426 @!@:pdf_px_dimen_}{\.{\\pdfpxdimen} primitive@>
6427
6428 @ @<Cases of |print_cmd_chr|...@>=
6429 assign_dimen: if chr_code<scaled_base then
6430 print_length_param(chr_code-dimen_base)
6431 else begin print_esc("dimen"); print_int(chr_code-scaled_base);
6432 end;
6433
6434 @ @<Initialize table entries...@>=
6435 for k:=dimen_base to eqtb_size do eqtb[k].sc:=0;
6436
6437 @ @<Show equivalent |n|, in region 6@>=
6438 begin if n<scaled_base then print_length_param(n-dimen_base)
6439 else begin print_esc("dimen"); print_int(n-scaled_base);
6440 end;
6441 print_char("="); print_scaled(eqtb[n].sc); print("pt");
6442 end
6443
6444 @ Here is a procedure that displays the contents of |eqtb[n]|
6445 symbolically.
6446
6447 @p@t\4@>@<Declare the procedure called |print_cmd_chr|@>@;@/
6448 @!stat procedure show_eqtb(@!n:pointer);
6449 begin if n<active_base then print_char("?") {this can't happen}
6450 else if n<glue_base then @<Show equivalent |n|, in region 1 or 2@>
6451 else if n<local_base then @<Show equivalent |n|, in region 3@>
6452 else if n<int_base then @<Show equivalent |n|, in region 4@>
6453 else if n<dimen_base then @<Show equivalent |n|, in region 5@>
6454 else if n<=eqtb_size then @<Show equivalent |n|, in region 6@>
6455 else print_char("?"); {this can't happen either}
6456 end;
6457 tats
6458
6459 @ The last two regions of |eqtb| have fullword values instead of the
6460 three fields |eq_level|, |eq_type|, and |equiv|. An |eq_type| is unnecessary,
6461 but \TeX\ needs to store the |eq_level| information in another array
6462 called |xeq_level|.
6463
6464 @<Glob...@>=
6465 @!eqtb:array[active_base..eqtb_size] of memory_word;
6466 @!xeq_level:array[int_base..eqtb_size] of quarterword;
6467
6468 @ @<Set init...@>=
6469 for k:=int_base to eqtb_size do xeq_level[k]:=level_one;
6470
6471 @ When the debugging routine |search_mem| is looking for pointers having a
6472 given value, it is interested only in regions 1 to~3 of~|eqtb|, and in the
6473 first part of region~4.
6474
6475 @<Search |eqtb| for equivalents equal to |p|@>=
6476 for q:=active_base to box_base+255 do
6477 begin if equiv(q)=p then
6478 begin print_nl("EQUIV("); print_int(q); print_char(")");
6479 end;
6480 end
6481
6482 @* \[18] The hash table.
6483 Control sequences are stored and retrieved by means of a fairly standard hash
6484 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
6485 in {\sl The Art of Computer Programming\/}). Once a control sequence enters the
6486 table, it is never removed, because there are complicated situations
6487 involving \.{\\gdef} where the removal of a control sequence at the end of
6488 a group would be a mistake preventable only by the introduction of a
6489 complicated reference-count mechanism.
6490
6491 The actual sequence of letters forming a control sequence identifier is
6492 stored in the |str_pool| array together with all the other strings. An
6493 auxiliary array |hash| consists of items with two halfword fields per
6494 word. The first of these, called |next(p)|, points to the next identifier
6495 belonging to the same coalesced list as the identifier corresponding to~|p|;
6496 and the other, called |text(p)|, points to the |str_start| entry for
6497 |p|'s identifier. If position~|p| of the hash table is empty, we have
6498 |text(p)=0|; if position |p| is either empty or the end of a coalesced
6499 hash list, we have |next(p)=0|. An auxiliary pointer variable called
6500 |hash_used| is maintained in such a way that all locations |p>=hash_used|
6501 are nonempty. The global variable |cs_count| tells how many multiletter
6502 control sequences have been defined, if statistics are being kept.
6503
6504 A global boolean variable called |no_new_control_sequence| is set to
6505 |true| during the time that new hash table entries are forbidden.
6506
6507 @d next(#) == hash[#].lh {link for coalesced lists}
6508 @d text(#) == hash[#].rh {string number for control sequence name}
6509 @d hash_is_full == (hash_used=hash_base) {test if all positions are occupied}
6510 @d font_id_text(#) == text(font_id_base+#) {a frozen font identifier's name}
6511
6512 @<Glob...@>=
6513 @!hash: array[hash_base..undefined_control_sequence-1] of two_halves;
6514 {the hash table}
6515 @!hash_used:pointer; {allocation pointer for |hash|}
6516 @!no_new_control_sequence:boolean; {are new identifiers legal?}
6517 @!cs_count:integer; {total number of known identifiers}
6518
6519 @ Primitive support needs a few extra variables and definitions
6520
6521 @d prim_prime=1777 {about 85\pct! of |primitive_size|}
6522 @d prim_base=1
6523 @d prim_next(#) == prim[#].lh {link for coalesced lists}
6524 @d prim_text(#) == prim[#].rh {string number for control sequence name, plus one}
6525 @d prim_is_full == (prim_used=prim_base) {test if all positions are occupied}
6526 @d prim_eq_level_field(#)==#.hh.b1
6527 @d prim_eq_type_field(#)==#.hh.b0
6528 @d prim_equiv_field(#)==#.hh.rh
6529 @d prim_eq_level(#)==prim_eq_level_field(eqtb[prim_eqtb_base+#]) {level of definition}
6530 @d prim_eq_type(#)==prim_eq_type_field(eqtb[prim_eqtb_base+#]) {command code for equivalent}
6531 @d prim_equiv(#)==prim_equiv_field(eqtb[prim_eqtb_base+#]) {equivalent value}
6532 @d undefined_primitive=0
6533 @d biggest_char=255 { 65535 in XeTeX }
6534
6535 @<Glob...@>=
6536 @!prim: array [0..prim_size] of two_halves; {the primitives table}
6537 @!prim_used:pointer; {allocation pointer for |prim|}
6538
6539 @ @<Set init...@>=
6540 no_new_control_sequence:=true; {new identifiers are usually forbidden}
6541 prim_next(0):=0; prim_text(0):=0;
6542 for k:=1 to prim_size do prim[k]:=prim[0];
6543 next(hash_base):=0; text(hash_base):=0;
6544 for k:=hash_base+1 to undefined_control_sequence-1 do hash[k]:=hash[hash_base];
6545
6546 @ @<Initialize table entries...@>=
6547 prim_used:=prim_size; {nothing is used}
6548 hash_used:=frozen_control_sequence; {nothing is used}
6549 cs_count:=0;
6550 eq_type(frozen_dont_expand):=dont_expand;
6551 text(frozen_dont_expand):="notexpanded:";
6552 @.notexpanded:@>
6553 eq_type(frozen_primitive):=ignore_spaces;
6554 equiv(frozen_primitive):=1;
6555 eq_level(frozen_primitive):=level_one;
6556 text(frozen_primitive):="pdfprimitive";
6557
6558 @ Here is the subroutine that searches the hash table for an identifier
6559 that matches a given string of length |l>1| appearing in |buffer[j..
6560 (j+l-1)]|. If the identifier is found, the corresponding hash table address
6561 is returned. Otherwise, if the global variable |no_new_control_sequence|
6562 is |true|, the dummy address |undefined_control_sequence| is returned.
6563 Otherwise the identifier is inserted into the hash table and its location
6564 is returned.
6565
6566 @p function id_lookup(@!j,@!l:integer):pointer; {search the hash table}
6567 label found; {go here if you found it}
6568 var h:integer; {hash code}
6569 @!d:integer; {number of characters in incomplete current string}
6570 @!p:pointer; {index in |hash| array}
6571 @!k:pointer; {index in |buffer| array}
6572 begin @<Compute the hash code |h|@>;
6573 p:=h+hash_base; {we start searching here; note that |0<=h<hash_prime|}
6574 loop@+begin if text(p)>0 then if length(text(p))=l then
6575 if str_eq_buf(text(p),j) then goto found;
6576 if next(p)=0 then
6577 begin if no_new_control_sequence then
6578 p:=undefined_control_sequence
6579 else @<Insert a new control sequence after |p|, then make
6580 |p| point to it@>;
6581 goto found;
6582 end;
6583 p:=next(p);
6584 end;
6585 found: id_lookup:=p;
6586 end;
6587
6588 @ @<Insert a new control...@>=
6589 begin if text(p)>0 then
6590 begin repeat if hash_is_full then overflow("hash size",hash_size);
6591 @:TeX capacity exceeded hash size}{\quad hash size@>
6592 decr(hash_used);
6593 until text(hash_used)=0; {search for an empty location in |hash|}
6594 next(p):=hash_used; p:=hash_used;
6595 end;
6596 str_room(l); d:=cur_length;
6597 while pool_ptr>str_start[str_ptr] do
6598 begin decr(pool_ptr); str_pool[pool_ptr+l]:=str_pool[pool_ptr];
6599 end; {move current string up to make room for another}
6600 for k:=j to j+l-1 do append_char(buffer[k]);
6601 text(p):=make_string; pool_ptr:=pool_ptr+d;
6602 @!stat incr(cs_count);@+tats@;@/
6603 end
6604
6605 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
6606 should be a prime number. The theory of hashing tells us to expect fewer
6607 than two table probes, on the average, when the search is successful.
6608 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
6609 @^Vitter, Jeffrey Scott@>
6610
6611 @<Compute the hash code |h|@>=
6612 h:=buffer[j];
6613 for k:=j+1 to j+l-1 do
6614 begin h:=h+h+buffer[k];
6615 while h>=hash_prime do h:=h-hash_prime;
6616 end
6617
6618 @ Here is the subroutine that searches the primitive table for an identifier:
6619
6620 @p function prim_lookup(@!s:str_number):pointer; {search the primitives table}
6621 label found; {go here if you found it}
6622 var h:integer; {hash code}
6623 @!p:pointer; {index in |hash| array}
6624 @!k:pointer; {index in string pool}
6625 @!j,@!l:integer;
6626 begin
6627 if s<=biggest_char then begin
6628 if s<0 then begin p:=undefined_primitive; goto found; end
6629 else p:=(s mod prim_prime)+prim_base; {we start searching here}
6630 end
6631 else begin
6632 j:=str_start[s];
6633 if s = str_ptr then l := cur_length else l := length(s);
6634 @<Compute the primitive code |h|@>;
6635 p:=h+prim_base; {we start searching here; note that |0<=h<prim_prime|}
6636 end;
6637 loop@+begin
6638 if prim_text(p)>1+biggest_char then { |p| points a multi-letter primitive }
6639 begin if length(prim_text(p)-1)=l then
6640 if str_eq_str(prim_text(p)-1,s) then goto found;
6641 end
6642 else if prim_text(p)=1+s then goto found; { |p| points a single-letter primitive }
6643 if prim_next(p)=0 then
6644 begin if no_new_control_sequence then
6645 p:=undefined_primitive
6646 else @<Insert a new primitive after |p|, then make
6647 |p| point to it@>;
6648 goto found;
6649 end;
6650 p:=prim_next(p);
6651 end;
6652 found: prim_lookup:=p;
6653 end;
6654
6655 @ @<Insert a new primitive...@>=
6656 begin if prim_text(p)>0 then
6657 begin repeat if prim_is_full then overflow("primitive size",prim_size);
6658 @:TeX capacity exceeded primitive size}{\quad primitive size@>
6659 decr(prim_used);
6660 until prim_text(prim_used)=0; {search for an empty location in |prim|}
6661 prim_next(p):=prim_used; p:=prim_used;
6662 end;
6663 prim_text(p):=s+1;
6664 end
6665
6666 @ The value of |prim_prime| should be roughly 85\pct! of
6667 |prim_size|, and it should be a prime number.
6668
6669 @<Compute the primitive code |h|@>=
6670 h:=str_pool[j];
6671 for k:=j+1 to j+l-1 do
6672 begin h:=h+h+str_pool[k];
6673 while h>=prim_prime do h:=h-prim_prime;
6674 end
6675
6676 @ Single-character control sequences do not need to be looked up in a hash
6677 table, since we can use the character code itself as a direct address.
6678 The procedure |print_cs| prints the name of a control sequence, given
6679 a pointer to its address in |eqtb|. A space is printed after the name
6680 unless it is a single nonletter or an active character. This procedure
6681 might be invoked with invalid data, so it is ``extra robust.'' The
6682 individual characters must be printed one at a time using |print|, since
6683 they may be unprintable.
6684
6685 @<Basic printing...@>=
6686 procedure print_cs(@!p:integer); {prints a purported control sequence}
6687 begin if p<hash_base then {single character}
6688 if p>=single_base then
6689 if p=null_cs then
6690 begin print_esc("csname"); print_esc("endcsname"); print_char(" ");
6691 end
6692 else begin print_esc(p-single_base);
6693 if cat_code(p-single_base)=letter then print_char(" ");
6694 end
6695 else if p<active_base then print_esc("IMPOSSIBLE.")
6696 @.IMPOSSIBLE@>
6697 else print(p-active_base)
6698 else if p>=undefined_control_sequence then print_esc("IMPOSSIBLE.")
6699 else if (text(p)<0)or(text(p)>=str_ptr) then print_esc("NONEXISTENT.")
6700 @.NONEXISTENT@>
6701 else begin
6702 if (p>=prim_eqtb_base)and(p<frozen_null_font) then
6703 print_esc(prim_text(p-prim_eqtb_base)-1) else print_esc(text(p));
6704 print_char(" ");
6705 end;
6706 end;
6707
6708 @ Here is a similar procedure; it avoids the error checks, and it never
6709 prints a space after the control sequence.
6710
6711 @<Basic printing procedures@>=
6712 procedure sprint_cs(@!p:pointer); {prints a control sequence}
6713 begin if p<hash_base then
6714 if p<single_base then print(p-active_base)
6715 else if p<null_cs then print_esc(p-single_base)
6716 else begin print_esc("csname"); print_esc("endcsname");
6717 end
6718 else if (p>=prim_eqtb_base)and(p<frozen_null_font) then
6719 print_esc(prim_text(p-prim_eqtb_base)-1)
6720 else print_esc(text(p));
6721 end;
6722
6723 @ We need to put \TeX's ``primitive'' control sequences into the hash
6724 table, together with their command code (which will be the |eq_type|)
6725 and an operand (which will be the |equiv|). The |primitive| procedure
6726 does this, in a way that no \TeX\ user can. The global value |cur_val|
6727 contains the new |eqtb| pointer after |primitive| has acted.
6728
6729 Until pdf\TeX\ 1.40.19 (released in 2018), a bug in primitive handling
6730 caused, e.g., \.{\\pdfprimitive\\ \\q} to swallow the \.{\\q} instead of
6731 giving an undefined control sequence error. The original report was
6732 posted by Hironori Kitagawa
6733 (\.{tug.org/pipermail/tex-k/2017-October/002816.html}). Largely
6734 quoting from that message:
6735
6736 The cause was |cur_tok| not being set in the ``Cases of |main_control|\dots''
6737 module, because |back_input| unscans the token, but only looks at
6738 |cur_tok|, which represents the internalized \.{\\pdfprimitive} at that
6739 time. So \.{\\pdfprimitive\\vrule\\q} becomes ``(internalized
6740 \.{\\pdfprimitive})''\.{\\q}, hence no error (and \.{\\vrule} disappears).
6741
6742 Hironori's explanation of the previous behavior and fix continues (off-list):
6743
6744 \yskip\textindent{*} |back_input| (and similar routine $\langle\,$Insert token
6745 |p| into \TeX's input$\,\rangle$) only stores |cur_tok| to a token list.
6746
6747 \textindent{*} When \TeX\ gets input from a token list (at module
6748 $\langle\,$Input from token list, |goto restart| \dots$\,\rangle$),
6749 \TeX\ looks at the saved |cur_tok| value $t$, and recover the command
6750 code (|cur_cmd|) and its modifier (|cur_chr|) from it:
6751
6752 {\advance\leftskip by 1.5em
6753 \textindent{--} If |t>=cs_token_flag|, $t$ points to an |eqtb| location
6754 |t - cs_token_flag|.
6755
6756 \textindent{--} If |t<cs_token_flag|, |cur_cmd| and |cur_chr| are set
6757 with |cur_cmd:=t div @'400; cur_chr:=t mod @'400|.
6758
6759 \textindent{--} This $t$ is used to display the token (|show_token_list|).
6760 \par}
6761
6762 \textindent{*} pdf\TeX\ defines |cs_token_flag| as \.{"FFF}. So simply
6763 using |cur_tok:=(cur_cmd*@'400)+cur_chr| by \.{\\pdfprimitive} does not
6764 work correctly with primitives whose command codes |cur_cmd| $\ge16$.
6765
6766 Increasing |cs_token_flag| to \.{"FFFF} or somewhat higher
6767 might suffice for fixing this situation in pdf\TeX.
6768 However, this approach does not seem good, because
6769
6770 \textindent{1)} an (indirect) mapping from |cur_tok| to control sequence
6771 name is needed anyway, for displaying the token, and
6772
6773 \textindent{2)} this does not work in Japanese e-(u)p\TeX.
6774
6775 Thus, we now put |prim_eqtb| entries into the end of region 2 of
6776 |eqtb| (which contains some frozen primitives, such as ``frozen \.{\\fi}''
6777 and ``frozen \.{\\cr}''), thus treating |prim_eqtb| entries as a permanent
6778 location for primitives.
6779
6780 @p @!init procedure primitive(@!s:str_number;@!c:quarterword;@!o:halfword);
6781 var k:pool_pointer; {index into |str_pool|}
6782 @!j:0..buf_size; {index into |buffer|}
6783 @!l:small_number; {length of the string}
6784 @!prim_val:integer; {needed to fill |prim_eqtb|}
6785 begin if s<256 then begin
6786 cur_val:=s+single_base;
6787 prim_val:=prim_lookup(s);
6788 end
6789 else begin k:=str_start[s]; l:=str_start[s+1]-k;
6790 {we will move |s| into the (possibly non-empty) |buffer|}
6791 if first+l>buf_size+1 then
6792 overflow("buffer size",buf_size);
6793 @:TeX capacity exceeded buffer size}{\quad buffer size@>
6794 for j:=0 to l-1 do buffer[first+j]:=so(str_pool[k+j]);
6795 cur_val:=id_lookup(first,l); {|no_new_control_sequence| is |false|}
6796 flush_string; text(cur_val):=s; {we don't want to have the string twice}
6797 prim_val:=prim_lookup(s);
6798 end;
6799 eq_level(cur_val):=level_one; eq_type(cur_val):=c; equiv(cur_val):=o;
6800 prim_eq_level(prim_val):=level_one;
6801 prim_eq_type(prim_val):=c;
6802 prim_equiv(prim_val):=o;
6803 end;
6804 tini
6805
6806 @ Many of \TeX's primitives need no |equiv|, since they are identifiable
6807 by their |eq_type| alone. These primitives are loaded into the hash table
6808 as follows:
6809
6810 @<Put each of \TeX's primitives into the hash table@>=
6811 primitive(" ",ex_space,0);@/
6812 @!@:Single-character primitives /}{\quad\.{\\\ }@>
6813 primitive("/",ital_corr,0);@/
6814 @!@:Single-character primitives /}{\quad\.{\\/}@>
6815 primitive("accent",accent,0);@/
6816 @!@:accent_}{\.{\\accent} primitive@>
6817 primitive("advance",advance,0);@/
6818 @!@:advance_}{\.{\\advance} primitive@>
6819 primitive("afterassignment",after_assignment,0);@/
6820 @!@:after_assignment_}{\.{\\afterassignment} primitive@>
6821 primitive("aftergroup",after_group,0);@/
6822 @!@:after_group_}{\.{\\aftergroup} primitive@>
6823 primitive("begingroup",begin_group,0);@/
6824 @!@:begin_group_}{\.{\\begingroup} primitive@>
6825 primitive("char",char_num,0);@/
6826 @!@:char_}{\.{\\char} primitive@>
6827 primitive("csname",cs_name,0);@/
6828 @!@:cs_name_}{\.{\\csname} primitive@>
6829 primitive("delimiter",delim_num,0);@/
6830 @!@:delimiter_}{\.{\\delimiter} primitive@>
6831 primitive("divide",divide,0);@/
6832 @!@:divide_}{\.{\\divide} primitive@>
6833 primitive("endcsname",end_cs_name,0);@/
6834 @!@:end_cs_name_}{\.{\\endcsname} primitive@>
6835 primitive("endgroup",end_group,0);
6836 @!@:end_group_}{\.{\\endgroup} primitive@>
6837 text(frozen_end_group):="endgroup"; eqtb[frozen_end_group]:=eqtb[cur_val];@/
6838 primitive("expandafter",expand_after,0);@/
6839 @!@:expand_after_}{\.{\\expandafter} primitive@>
6840 primitive("font",def_font,0);@/
6841 @!@:font_}{\.{\\font} primitive@>
6842 primitive("letterspacefont",letterspace_font,0);@/
6843 @!@:letterspace_font_}{\.{\\letterspacefont} primitive@>
6844 primitive("pdfcopyfont",pdf_copy_font,0);@/
6845 @!@:pdf_copy_font_}{\.{\\pdfcopyfont} primitive@>
6846 primitive("fontdimen",assign_font_dimen,0);@/
6847 @!@:font_dimen_}{\.{\\fontdimen} primitive@>
6848 primitive("halign",halign,0);@/
6849 @!@:halign_}{\.{\\halign} primitive@>
6850 primitive("hrule",hrule,0);@/
6851 @!@:hrule_}{\.{\\hrule} primitive@>
6852 primitive("ignorespaces",ignore_spaces,0);@/
6853 @!@:ignore_spaces_}{\.{\\ignorespaces} primitive@>
6854 primitive("insert",insert,0);@/
6855 @!@:insert_}{\.{\\insert} primitive@>
6856 primitive("mark",mark,0);@/
6857 @!@:mark_}{\.{\\mark} primitive@>
6858 primitive("mathaccent",math_accent,0);@/
6859 @!@:math_accent_}{\.{\\mathaccent} primitive@>
6860 primitive("mathchar",math_char_num,0);@/
6861 @!@:math_char_}{\.{\\mathchar} primitive@>
6862 primitive("mathchoice",math_choice,0);@/
6863 @!@:math_choice_}{\.{\\mathchoice} primitive@>
6864 primitive("multiply",multiply,0);@/
6865 @!@:multiply_}{\.{\\multiply} primitive@>
6866 primitive("noalign",no_align,0);@/
6867 @!@:no_align_}{\.{\\noalign} primitive@>
6868 primitive("noboundary",no_boundary,0);@/
6869 @!@:no_boundary_}{\.{\\noboundary} primitive@>
6870 primitive("noexpand",no_expand,0);@/
6871 @!@:no_expand_}{\.{\\noexpand} primitive@>
6872 primitive("pdfprimitive",no_expand,1);@/
6873 @!@:pdfprimitive_}{\.{\\pdfprimitive} primitive@>
6874 primitive("nonscript",non_script,0);@/
6875 @!@:non_script_}{\.{\\nonscript} primitive@>
6876 primitive("omit",omit,0);@/
6877 @!@:omit_}{\.{\\omit} primitive@>
6878 primitive("parshape",set_shape,par_shape_loc);@/
6879 @!@:par_shape_}{\.{\\parshape} primitive@>
6880 primitive("penalty",break_penalty,0);@/
6881 @!@:penalty_}{\.{\\penalty} primitive@>
6882 primitive("prevgraf",set_prev_graf,0);@/
6883 @!@:prev_graf_}{\.{\\prevgraf} primitive@>
6884 primitive("radical",radical,0);@/
6885 @!@:radical_}{\.{\\radical} primitive@>
6886 primitive("read",read_to_cs,0);@/
6887 @!@:read_}{\.{\\read} primitive@>
6888 primitive("relax",relax,256); {cf.\ |scan_file_name|}
6889 @!@:relax_}{\.{\\relax} primitive@>
6890 text(frozen_relax):="relax"; eqtb[frozen_relax]:=eqtb[cur_val];@/
6891 primitive("setbox",set_box,0);@/
6892 @!@:set_box_}{\.{\\setbox} primitive@>
6893 primitive("the",the,0);@/
6894 @!@:the_}{\.{\\the} primitive@>
6895 primitive("toks",toks_register,mem_bot);@/
6896 @!@:toks_}{\.{\\toks} primitive@>
6897 primitive("vadjust",vadjust,0);@/
6898 @!@:vadjust_}{\.{\\vadjust} primitive@>
6899 primitive("valign",valign,0);@/
6900 @!@:valign_}{\.{\\valign} primitive@>
6901 primitive("vcenter",vcenter,0);@/
6902 @!@:vcenter_}{\.{\\vcenter} primitive@>
6903 primitive("vrule",vrule,0);@/
6904 @!@:vrule_}{\.{\\vrule} primitive@>
6905
6906 @ Each primitive has a corresponding inverse, so that it is possible to
6907 display the cryptic numeric contents of |eqtb| in symbolic form.
6908 Every call of |primitive| in this program is therefore accompanied by some
6909 straightforward code that forms part of the |print_cmd_chr| routine
6910 below.
6911
6912 @<Cases of |print_cmd_chr|...@>=
6913 accent: print_esc("accent");
6914 advance: print_esc("advance");
6915 after_assignment: print_esc("afterassignment");
6916 after_group: print_esc("aftergroup");
6917 assign_font_dimen: print_esc("fontdimen");
6918 begin_group: print_esc("begingroup");
6919 break_penalty: print_esc("penalty");
6920 char_num: print_esc("char");
6921 cs_name: print_esc("csname");
6922 def_font: print_esc("font");
6923 letterspace_font: print_esc("letterspacefont");
6924 pdf_copy_font: print_esc("pdfcopyfont");
6925 delim_num: print_esc("delimiter");
6926 divide: print_esc("divide");
6927 end_cs_name: print_esc("endcsname");
6928 end_group: print_esc("endgroup");
6929 ex_space: print_esc(" ");
6930 expand_after: if chr_code=0 then print_esc("expandafter")
6931 @<Cases of |expandafter| for |print_cmd_chr|@>;
6932 halign: print_esc("halign");
6933 hrule: print_esc("hrule");
6934 ignore_spaces: if chr_code=0 then print_esc("ignorespaces") else print_esc("pdfprimitive");
6935 insert: print_esc("insert");
6936 ital_corr: print_esc("/");
6937 mark: begin print_esc("mark");
6938 if chr_code>0 then print_char("s");
6939 end;
6940 math_accent: print_esc("mathaccent");
6941 math_char_num: print_esc("mathchar");
6942 math_choice: print_esc("mathchoice");
6943 multiply: print_esc("multiply");
6944 no_align: print_esc("noalign");
6945 no_boundary:print_esc("noboundary");
6946 no_expand: if chr_code=0 then print_esc("noexpand")
6947 else print_esc("pdfprimitive");
6948 non_script: print_esc("nonscript");
6949 omit: print_esc("omit");
6950 radical: print_esc("radical");
6951 read_to_cs: if chr_code=0 then print_esc("read")
6952 @<Cases of |read| for |print_cmd_chr|@>;
6953 relax: print_esc("relax");
6954 set_box: print_esc("setbox");
6955 set_prev_graf: print_esc("prevgraf");
6956 set_shape: case chr_code of
6957 par_shape_loc: print_esc("parshape");
6958 @<Cases of |set_shape| for |print_cmd_chr|@>@;@/
6959 end; {there are no other cases}
6960 the: if chr_code=0 then print_esc("the")
6961 @<Cases of |the| for |print_cmd_chr|@>;
6962 toks_register: @<Cases of |toks_register| for |print_cmd_chr|@>;
6963 vadjust: print_esc("vadjust");
6964 valign: if chr_code=0 then print_esc("valign")@/
6965 @<Cases of |valign| for |print_cmd_chr|@>;
6966 vcenter: print_esc("vcenter");
6967 vrule: print_esc("vrule");
6968
6969 @ We will deal with the other primitives later, at some point in the program
6970 where their |eq_type| and |equiv| values are more meaningful. For example,
6971 the primitives for math mode will be loaded when we consider the routines
6972 that deal with formulas. It is easy to find where each particular
6973 primitive was treated by looking in the index at the end; for example, the
6974 section where |"radical"| entered |eqtb| is listed under `\.{\\radical}
6975 primitive'. (Primitives consisting of a single nonalphabetic character,
6976 @!like `\.{\\/}', are listed under `Single-character primitives'.)
6977 @!@^Single-character primitives@>
6978
6979 Meanwhile, this is a convenient place to catch up on something we were unable
6980 to do before the hash table was defined:
6981
6982 @* \[19] Saving and restoring equivalents.
6983 The nested structure provided by `$\.{\char'173}\ldots\.{\char'175}$' groups
6984 in \TeX\ means that |eqtb| entries valid in outer groups should be saved
6985 and restored later if they are overridden inside the braces. When a new |eqtb|
6986 value is being assigned, the program therefore checks to see if the previous
6987 entry belongs to an outer level. In such a case, the old value is placed
6988 on the |save_stack| just before the new value enters |eqtb|. At the
6989 end of a grouping level, i.e., when the right brace is sensed, the
6990 |save_stack| is used to restore the outer values, and the inner ones are
6991 destroyed.
6992
6993 Entries on the |save_stack| are of type |memory_word|. The top item on
6994 this stack is |save_stack[p]|, where |p=save_ptr-1|; it contains three
6995 fields called |save_type|, |save_level|, and |save_index|, and it is
6996 interpreted in one of five ways:
6997
6998 \yskip\hangg 1) If |save_type(p)=restore_old_value|, then
6999 |save_index(p)| is a location in |eqtb| whose current value should
7000 be destroyed at the end of the current group and replaced by |save_stack[p-1]|.
7001 Furthermore if |save_index(p)>=int_base|, then |save_level(p)|
7002 should replace the corresponding entry in |xeq_level|.
7003
7004 \yskip\hangg 2) If |save_type(p)=restore_zero|, then |save_index(p)|
7005 is a location in |eqtb| whose current value should be destroyed at the end
7006 of the current group, when it should be
7007 replaced by the value of |eqtb[undefined_control_sequence]|.
7008
7009 \yskip\hangg 3) If |save_type(p)=insert_token|, then |save_index(p)|
7010 is a token that should be inserted into \TeX's input when the current
7011 group ends.
7012
7013 \yskip\hangg 4) If |save_type(p)=level_boundary|, then |save_level(p)|
7014 is a code explaining what kind of group we were previously in, and
7015 |save_index(p)| points to the level boundary word at the bottom of
7016 the entries for that group.
7017 Furthermore, in extended \eTeX\ mode, |save_stack[p-1]| contains the
7018 source line number at which the current level of grouping was entered.
7019
7020 \yskip\hang 5) If |save_type(p)=restore_sa|, then |sa_chain| points to a
7021 chain of sparse array entries to be restored at the end of the current
7022 group. Furthermore |save_index(p)| and |save_level(p)| should replace
7023 the values of |sa_chain| and |sa_level| respectively.
7024
7025 @d save_type(#)==save_stack[#].hh.b0 {classifies a |save_stack| entry}
7026 @d save_level(#)==save_stack[#].hh.b1
7027 {saved level for regions 5 and 6, or group code}
7028 @d save_index(#)==save_stack[#].hh.rh
7029 {|eqtb| location or token or |save_stack| location}
7030 @d restore_old_value=0 {|save_type| when a value should be restored later}
7031 @d restore_zero=1 {|save_type| when an undefined entry should be restored}
7032 @d insert_token=2 {|save_type| when a token is being saved for later use}
7033 @d level_boundary=3 {|save_type| corresponding to beginning of group}
7034 @d restore_sa=4 {|save_type| when sparse array entries should be restored}
7035
7036 @p@t\4@>@<Declare \eTeX\ procedures for tracing and input@>
7037
7038 @ Here are the group codes that are used to discriminate between different
7039 kinds of groups. They allow \TeX\ to decide what special actions, if any,
7040 should be performed when a group ends.
7041 \def\grp{\.{\char'173...\char'175}}
7042
7043 Some groups are not supposed to be ended by right braces. For example,
7044 the `\.\$' that begins a math formula causes a |math_shift_group| to
7045 be started, and this should be terminated by a matching `\.\$'. Similarly,
7046 a group that starts with \.{\\left} should end with \.{\\right}, and
7047 one that starts with \.{\\begingroup} should end with \.{\\endgroup}.
7048
7049 @d bottom_level=0 {group code for the outside world}
7050 @d simple_group=1 {group code for local structure only}
7051 @d hbox_group=2 {code for `\.{\\hbox}\grp'}
7052 @d adjusted_hbox_group=3 {code for `\.{\\hbox}\grp' in vertical mode}
7053 @d vbox_group=4 {code for `\.{\\vbox}\grp'}
7054 @d vtop_group=5 {code for `\.{\\vtop}\grp'}
7055 @d align_group=6 {code for `\.{\\halign}\grp', `\.{\\valign}\grp'}
7056 @d no_align_group=7 {code for `\.{\\noalign}\grp'}
7057 @d output_group=8 {code for output routine}
7058 @d math_group=9 {code for, e.g., `\.{\char'136}\grp'}
7059 @d disc_group=10 {code for `\.{\\discretionary}\grp\grp\grp'}
7060 @d insert_group=11 {code for `\.{\\insert}\grp', `\.{\\vadjust}\grp'}
7061 @d vcenter_group=12 {code for `\.{\\vcenter}\grp'}
7062 @d math_choice_group=13 {code for `\.{\\mathchoice}\grp\grp\grp\grp'}
7063 @d semi_simple_group=14 {code for `\.{\\begingroup...\\endgroup}'}
7064 @d math_shift_group=15 {code for `\.{\$...\$}'}
7065 @d math_left_group=16 {code for `\.{\\left...\\right}'}
7066 @d max_group_code=16
7067
7068 @<Types...@>=
7069 @!group_code=0..max_group_code; {|save_level| for a level boundary}
7070
7071 @ The global variable |cur_group| keeps track of what sort of group we are
7072 currently in. Another global variable, |cur_boundary|, points to the
7073 topmost |level_boundary| word. And |cur_level| is the current depth of
7074 nesting. The routines are designed to preserve the condition that no entry
7075 in the |save_stack| or in |eqtb| ever has a level greater than |cur_level|.
7076
7077 @ @<Glob...@>=
7078 @!save_stack : array[0..save_size] of memory_word;
7079 @!save_ptr : 0..save_size; {first unused entry on |save_stack|}
7080 @!max_save_stack:0..save_size; {maximum usage of save stack}
7081 @!cur_level: quarterword; {current nesting level for groups}
7082 @!cur_group: group_code; {current group type}
7083 @!cur_boundary: 0..save_size; {where the current level begins}
7084
7085 @ At this time it might be a good idea for the reader to review the introduction
7086 to |eqtb| that was given above just before the long lists of parameter names.
7087 Recall that the ``outer level'' of the program is |level_one|, since
7088 undefined control sequences are assumed to be ``defined'' at |level_zero|.
7089
7090 @<Set init...@>=
7091 save_ptr:=0; cur_level:=level_one; cur_group:=bottom_level; cur_boundary:=0;
7092 max_save_stack:=0;
7093
7094 @ The following macro is used to test if there is room for up to seven more
7095 entries on |save_stack|. By making a conservative test like this, we can
7096 get by with testing for overflow in only a few places.
7097
7098 @d check_full_save_stack==if save_ptr>max_save_stack then
7099 begin max_save_stack:=save_ptr;
7100 if max_save_stack>save_size-7 then overflow("save size",save_size);
7101 @:TeX capacity exceeded save size}{\quad save size@>
7102 end
7103
7104 @ Procedure |new_save_level| is called when a group begins. The
7105 argument is a group identification code like `|hbox_group|'. After
7106 calling this routine, it is safe to put five more entries on |save_stack|.
7107
7108 In some cases integer-valued items are placed onto the
7109 |save_stack| just below a |level_boundary| word, because this is a
7110 convenient place to keep information that is supposed to ``pop up'' just
7111 when the group has finished.
7112 For example, when `\.{\\hbox to 100pt}\grp' is being treated, the 100pt
7113 dimension is stored on |save_stack| just before |new_save_level| is
7114 called.
7115
7116 We use the notation |saved(k)| to stand for an integer item that
7117 appears in location |save_ptr+k| of the save stack.
7118
7119 @d saved(#)==save_stack[save_ptr+#].int
7120
7121 @p procedure new_save_level(@!c:group_code); {begin a new level of grouping}
7122 begin check_full_save_stack;
7123 if eTeX_ex then
7124 begin saved(0):=line; incr(save_ptr);
7125 end;
7126 save_type(save_ptr):=level_boundary; save_level(save_ptr):=cur_group;
7127 save_index(save_ptr):=cur_boundary;
7128 if cur_level=max_quarterword then overflow("grouping levels",
7129 @:TeX capacity exceeded grouping levels}{\quad grouping levels@>
7130 max_quarterword-min_quarterword);
7131 {quit if |(cur_level+1)| is too big to be stored in |eqtb|}
7132 cur_boundary:=save_ptr; cur_group:=c;
7133 @!stat if tracing_groups>0 then group_trace(false);@+tats@;@/
7134 incr(cur_level); incr(save_ptr);
7135 end;
7136
7137 @ Just before an entry of |eqtb| is changed, the following procedure should
7138 be called to update the other data structures properly. It is important
7139 to keep in mind that reference counts in |mem| include references from
7140 within |save_stack|, so these counts must be handled carefully.
7141 @^reference counts@>
7142
7143 @p procedure eq_destroy(@!w:memory_word); {gets ready to forget |w|}
7144 var q:pointer; {|equiv| field of |w|}
7145 begin case eq_type_field(w) of
7146 call,long_call,outer_call,long_outer_call: delete_token_ref(equiv_field(w));
7147 glue_ref: delete_glue_ref(equiv_field(w));
7148 shape_ref: begin q:=equiv_field(w); {we need to free a \.{\\parshape} block}
7149 if q<>null then free_node(q,info(q)+info(q)+1);
7150 end; {such a block is |2n+1| words long, where |n=info(q)|}
7151 box_ref: flush_node_list(equiv_field(w));
7152 @/@<Cases for |eq_destroy|@>@/
7153 othercases do_nothing
7154 endcases;
7155 end;
7156
7157 @ To save a value of |eqtb[p]| that was established at level |l|, we
7158 can use the following subroutine.
7159
7160 @p procedure eq_save(@!p:pointer;@!l:quarterword); {saves |eqtb[p]|}
7161 begin check_full_save_stack;
7162 if l=level_zero then save_type(save_ptr):=restore_zero
7163 else begin save_stack[save_ptr]:=eqtb[p]; incr(save_ptr);
7164 save_type(save_ptr):=restore_old_value;
7165 end;
7166 save_level(save_ptr):=l; save_index(save_ptr):=p; incr(save_ptr);
7167 end;
7168
7169 @ The procedure |eq_define| defines an |eqtb| entry having specified
7170 |eq_type| and |equiv| fields, and saves the former value if appropriate.
7171 This procedure is used only for entries in the first four regions of |eqtb|,
7172 i.e., only for entries that have |eq_type| and |equiv| fields.
7173 After calling this routine, it is safe to put four more entries on
7174 |save_stack|, provided that there was room for four more entries before
7175 the call, since |eq_save| makes the necessary test.
7176
7177 @d assign_trace(#)==@!stat if tracing_assigns>0 then restore_trace(#);
7178 tats
7179
7180 @p procedure eq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
7181 {new data for |eqtb|}
7182 label exit;
7183 begin if eTeX_ex and(eq_type(p)=t)and(equiv(p)=e) then
7184 begin assign_trace(p,"reassigning")@;@/
7185 eq_destroy(eqtb[p]); return;
7186 end;
7187 assign_trace(p,"changing")@;@/
7188 if eq_level(p)=cur_level then eq_destroy(eqtb[p])
7189 else if cur_level>level_one then eq_save(p,eq_level(p));
7190 eq_level(p):=cur_level; eq_type(p):=t; equiv(p):=e;
7191 assign_trace(p,"into")@;@/
7192 exit:end;
7193
7194 @ The counterpart of |eq_define| for the remaining (fullword) positions in
7195 |eqtb| is called |eq_word_define|. Since |xeq_level[p]>=level_one| for all
7196 |p|, a `|restore_zero|' will never be used in this case.
7197
7198 @p procedure eq_word_define(@!p:pointer;@!w:integer);
7199 label exit;
7200 begin if eTeX_ex and(eqtb[p].int=w) then
7201 begin assign_trace(p,"reassigning")@;@/
7202 return;
7203 end;
7204 assign_trace(p,"changing")@;@/
7205 if xeq_level[p]<>cur_level then
7206 begin eq_save(p,xeq_level[p]); xeq_level[p]:=cur_level;
7207 end;
7208 eqtb[p].int:=w;
7209 assign_trace(p,"into")@;@/
7210 exit:end;
7211
7212 @ The |eq_define| and |eq_word_define| routines take care of local definitions.
7213 @^global definitions@>
7214 Global definitions are done in almost the same way, but there is no need
7215 to save old values, and the new value is associated with |level_one|.
7216
7217 @p procedure geq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
7218 {global |eq_define|}
7219 begin assign_trace(p,"globally changing")@;@/
7220 begin eq_destroy(eqtb[p]);
7221 eq_level(p):=level_one; eq_type(p):=t; equiv(p):=e;
7222 end;
7223 assign_trace(p,"into")@;@/
7224 end;
7225 @#
7226 procedure geq_word_define(@!p:pointer;@!w:integer); {global |eq_word_define|}
7227 begin assign_trace(p,"globally changing")@;@/
7228 begin eqtb[p].int:=w; xeq_level[p]:=level_one;
7229 end;
7230 assign_trace(p,"into")@;@/
7231 end;
7232
7233 @ Subroutine |save_for_after| puts a token on the stack for save-keeping.
7234
7235 @p procedure save_for_after(@!t:halfword);
7236 begin if cur_level>level_one then
7237 begin check_full_save_stack;
7238 save_type(save_ptr):=insert_token; save_level(save_ptr):=level_zero;
7239 save_index(save_ptr):=t; incr(save_ptr);
7240 end;
7241 end;
7242
7243 @ The |unsave| routine goes the other way, taking items off of |save_stack|.
7244 This routine takes care of restoration when a level ends; everything
7245 belonging to the topmost group is cleared off of the save stack.
7246
7247 @p
7248 procedure@?back_input; forward; @t\2@>
7249 procedure unsave; {pops the top level off the save stack}
7250 label done;
7251 var p:pointer; {position to be restored}
7252 @!l:quarterword; {saved level, if in fullword regions of |eqtb|}
7253 @!t:halfword; {saved value of |cur_tok|}
7254 @!a:boolean; {have we already processed an \.{\\aftergroup} ?}
7255 begin a:=false;
7256 if cur_level>level_one then
7257 begin decr(cur_level);
7258 @<Clear off top level from |save_stack|@>;
7259 end
7260 else confusion("curlevel"); {|unsave| is not used when |cur_group=bottom_level|}
7261 @:this can't happen curlevel}{\quad curlevel@>
7262 end;
7263
7264 @ @<Clear off...@>=
7265 loop@+begin decr(save_ptr);
7266 if save_type(save_ptr)=level_boundary then goto done;
7267 p:=save_index(save_ptr);
7268 if save_type(save_ptr)=insert_token then
7269 @<Insert token |p| into \TeX's input@>
7270 else if save_type(save_ptr)=restore_sa then
7271 begin sa_restore; sa_chain:=p; sa_level:=save_level(save_ptr);
7272 end
7273 else begin if save_type(save_ptr)=restore_old_value then
7274 begin l:=save_level(save_ptr); decr(save_ptr);
7275 end
7276 else save_stack[save_ptr]:=eqtb[undefined_control_sequence];
7277 @<Store \(s)|save_stack[save_ptr]| in |eqtb[p]|, unless
7278 |eqtb[p]| holds a global value@>;
7279 end;
7280 end;
7281 done: @!stat if tracing_groups>0 then group_trace(true);@+tats@;@/
7282 if grp_stack[in_open]=cur_boundary then group_warning;
7283 {groups possibly not properly nested with files}
7284 cur_group:=save_level(save_ptr); cur_boundary:=save_index(save_ptr);
7285 if eTeX_ex then decr(save_ptr)
7286
7287 @ A global definition, which sets the level to |level_one|,
7288 @^global definitions@>
7289 will not be undone by |unsave|. If at least one global definition of
7290 |eqtb[p]| has been carried out within the group that just ended, the
7291 last such definition will therefore survive.
7292
7293 @<Store \(s)|save...@>=
7294 if p<int_base then
7295 if eq_level(p)=level_one then
7296 begin eq_destroy(save_stack[save_ptr]); {destroy the saved value}
7297 @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
7298 end
7299 else begin eq_destroy(eqtb[p]); {destroy the current value}
7300 eqtb[p]:=save_stack[save_ptr]; {restore the saved value}
7301 @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
7302 end
7303 else if xeq_level[p]<>level_one then
7304 begin eqtb[p]:=save_stack[save_ptr]; xeq_level[p]:=l;
7305 @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
7306 end
7307 else begin
7308 @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
7309 end
7310
7311 @ @<Declare \eTeX\ procedures for tr...@>=
7312 @!stat procedure restore_trace(@!p:pointer;@!s:str_number);
7313 {|eqtb[p]| has just been restored or retained}
7314 begin begin_diagnostic; print_char("{"); print(s); print_char(" ");
7315 show_eqtb(p); print_char("}");
7316 end_diagnostic(false);
7317 end;
7318 tats
7319
7320 @ When looking for possible pointers to a memory location, it is helpful
7321 to look for references from |eqtb| that might be waiting on the
7322 save stack. Of course, we might find spurious pointers too; but this
7323 routine is merely an aid when debugging, and at such times we are
7324 grateful for any scraps of information, even if they prove to be irrelevant.
7325 @^dirty \PASCAL@>
7326
7327 @<Search |save_stack| for equivalents that point to |p|@>=
7328 if save_ptr>0 then for q:=0 to save_ptr-1 do
7329 begin if equiv_field(save_stack[q])=p then
7330 begin print_nl("SAVE("); print_int(q); print_char(")");
7331 end;
7332 end
7333
7334 @ Most of the parameters kept in |eqtb| can be changed freely, but there's
7335 an exception: The magnification should not be used with two different
7336 values during any \TeX\ job, since a single magnification is applied to an
7337 entire run. The global variable |mag_set| is set to the current magnification
7338 whenever it becomes necessary to ``freeze'' it at a particular value.
7339
7340 @<Glob...@>=
7341 @!mag_set:integer; {if nonzero, this magnification should be used henceforth}
7342
7343 @ @<Set init...@>=
7344 mag_set:=0;
7345
7346 @ The |prepare_mag| subroutine is called whenever \TeX\ wants to use |mag|
7347 for magnification.
7348
7349 @p procedure prepare_mag;
7350 begin if (mag_set>0)and(mag<>mag_set) then
7351 begin print_err("Incompatible magnification ("); print_int(mag);
7352 @.Incompatible magnification@>
7353 print(");"); print_nl(" the previous value will be retained");
7354 help2("I can handle only one magnification ratio per job. So I've")@/
7355 ("reverted to the magnification you used earlier on this run.");@/
7356 int_error(mag_set);
7357 geq_word_define(int_base+mag_code,mag_set); {|mag:=mag_set|}
7358 end;
7359 if (mag<=0)or(mag>32768) then
7360 begin print_err("Illegal magnification has been changed to 1000");@/
7361 @.Illegal magnification...@>
7362 help1("The magnification ratio must be between 1 and 32768.");
7363 int_error(mag); geq_word_define(int_base+mag_code,1000);
7364 end;
7365 mag_set:=mag;
7366 end;
7367
7368 @* \[20] Token lists.
7369 A \TeX\ token is either a character or a control sequence, and it is
7370 @^token@>
7371 represented internally in one of two ways: (1)~A character whose ASCII
7372 code number is |c| and whose command code is |m| is represented as the
7373 number $2^8m+c$; the command code is in the range |1<=m<=14|. (2)~A control
7374 sequence whose |eqtb| address is |p| is represented as the number
7375 |cs_token_flag+p|. Here |cs_token_flag=@t$2^{12}-1$@>| is larger than
7376 $2^8m+c$, yet it is small enough that |cs_token_flag+p< max_halfword|;
7377 thus, a token fits comfortably in a halfword.
7378
7379 A token |t| represents a |left_brace| command if and only if
7380 |t<left_brace_limit|; it represents a |right_brace| command if and only if
7381 we have |left_brace_limit<=t<right_brace_limit|; and it represents a |match| or
7382 |end_match| command if and only if |match_token<=t<=end_match_token|.
7383 The following definitions take care of these token-oriented constants
7384 and a few others.
7385
7386 @d cs_token_flag==@'7777 {amount added to the |eqtb| location in a
7387 token that stands for a control sequence; is a multiple of~256, less~1}
7388 @d left_brace_token=@'0400 {$2^8\cdot|left_brace|$}
7389 @d left_brace_limit=@'1000 {$2^8\cdot(|left_brace|+1)$}
7390 @d right_brace_token=@'1000 {$2^8\cdot|right_brace|$}
7391 @d right_brace_limit=@'1400 {$2^8\cdot(|right_brace|+1)$}
7392 @d math_shift_token=@'1400 {$2^8\cdot|math_shift|$}
7393 @d tab_token=@'2000 {$2^8\cdot|tab_mark|$}
7394 @d out_param_token=@'2400 {$2^8\cdot|out_param|$}
7395 @d space_token=@'5040 {$2^8\cdot|spacer|+|" "|$}
7396 @d letter_token=@'5400 {$2^8\cdot|letter|$}
7397 @d other_token=@'6000 {$2^8\cdot|other_char|$}
7398 @d match_token=@'6400 {$2^8\cdot|match|$}
7399 @d end_match_token=@'7000 {$2^8\cdot|end_match|$}
7400 @d protected_token=@'7001 {$2^8\cdot|end_match|+1$}
7401
7402 @ @<Check the ``constant''...@>=
7403 if cs_token_flag+undefined_control_sequence>max_halfword then bad:=21;
7404
7405 @ A token list is a singly linked list of one-word nodes in |mem|, where
7406 each word contains a token and a link. Macro definitions, output-routine
7407 definitions, marks, \.{\\write} texts, and a few other things
7408 are remembered by \TeX\ in the form
7409 of token lists, usually preceded by a node with a reference count in its
7410 |token_ref_count| field. The token stored in location |p| is called
7411 |info(p)|.
7412
7413 Three special commands appear in the token lists of macro definitions.
7414 When |m=match|, it means that \TeX\ should scan a parameter
7415 for the current macro; when |m=end_match|, it means that parameter
7416 matching should end and \TeX\ should start reading the macro text; and
7417 when |m=out_param|, it means that \TeX\ should insert parameter
7418 number |c| into the text at this point.
7419
7420 The enclosing \.{\char'173} and \.{\char'175} characters of a macro
7421 definition are omitted, but an output routine
7422 will be enclosed in braces.
7423
7424 Here is an example macro definition that illustrates these conventions.
7425 After \TeX\ processes the text
7426 $$\.{\\def\\mac a\#1\#2 \\b \{\#1\\-a \#\#1\#2 \#2\}}$$
7427 the definition of \.{\\mac} is represented as a token list containing
7428 $$\def\,{\hskip2pt}
7429 \vbox{\halign{\hfil#\hfil\cr
7430 (reference count), |letter|\,\.a, |match|\,\#, |match|\,\#, |spacer|\,\.\ ,
7431 \.{\\b}, |end_match|,\cr
7432 |out_param|\,1, \.{\\-}, |letter|\,\.a, |spacer|\,\.\ , |mac_param|\,\#,
7433 |other_char|\,\.1,\cr
7434 |out_param|\,2, |spacer|\,\.\ , |out_param|\,2.\cr}}$$
7435 The procedure |scan_toks| builds such token lists, and |macro_call|
7436 does the parameter matching.
7437 @^reference counts@>
7438
7439 Examples such as
7440 $$\.{\\def\\m\{\\def\\m\{a\}\ b\}}$$
7441 explain why reference counts would be needed even if \TeX\ had no \.{\\let}
7442 operation: When the token list for \.{\\m} is being read, the redefinition of
7443 \.{\\m} changes the |eqtb| entry before the token list has been fully
7444 consumed, so we dare not simply destroy a token list when its
7445 control sequence is being redefined.
7446
7447 If the parameter-matching part of a definition ends with `\.{\#\{}',
7448 the corresponding token list will have `\.\{' just before the `|end_match|'
7449 and also at the very end. The first `\.\{' is used to delimit the parameter; the
7450 second one keeps the first from disappearing.
7451
7452 @ The procedure |show_token_list|, which prints a symbolic form of
7453 the token list that starts at a given node |p|, illustrates these
7454 conventions. The token list being displayed should not begin with a reference
7455 count. However, the procedure is intended to be robust, so that if the
7456 memory links are awry or if |p| is not really a pointer to a token list,
7457 nothing catastrophic will happen.
7458
7459 An additional parameter |q| is also given; this parameter is either null
7460 or it points to a node in the token list where a certain magic computation
7461 takes place that will be explained later. (Basically, |q| is non-null when
7462 we are printing the two-line context information at the time of an error
7463 message; |q| marks the place corresponding to where the second line
7464 should begin.)
7465
7466 For example, if |p| points to the node containing the first \.a in the
7467 token list above, then |show_token_list| will print the string
7468 $$\hbox{`\.{a\#1\#2\ \\b\ ->\#1\\-a\ \#\#1\#2\ \#2}';}$$
7469 and if |q| points to the node containing the second \.a,
7470 the magic computation will be performed just before the second \.a is printed.
7471
7472 The generation will stop, and `\.{\\ETC.}' will be printed, if the length
7473 of printing exceeds a given limit~|l|. Anomalous entries are printed in the
7474 form of control sequences that are not followed by a blank space, e.g.,
7475 `\.{\\BAD.}'; this cannot be confused with actual control sequences because
7476 a real control sequence named \.{BAD} would come out `\.{\\BAD\ }'.
7477
7478 @<Declare the procedure called |show_token_list|@>=
7479 procedure show_token_list(@!p,@!q:integer;@!l:integer);
7480 label exit;
7481 var m,@!c:integer; {pieces of a token}
7482 @!match_chr:ASCII_code; {character used in a `|match|'}
7483 @!n:ASCII_code; {the highest parameter number, as an ASCII digit}
7484 begin match_chr:="#"; n:="0"; tally:=0;
7485 while (p<>null) and (tally<l) do
7486 begin if p=q then @<Do magic computation@>;
7487 @<Display token |p|, and |return| if there are problems@>;
7488 p:=link(p);
7489 end;
7490 if p<>null then print_esc("ETC.");
7491 @.ETC@>
7492 exit:
7493 end;
7494
7495 @ @<Display token |p|...@>=
7496 if (p<hi_mem_min) or (p>mem_end) then
7497 begin print_esc("CLOBBERED."); return;
7498 @.CLOBBERED@>
7499 end;
7500 if info(p)>=cs_token_flag then print_cs(info(p)-cs_token_flag)
7501 else begin m:=info(p) div @'400; c:=info(p) mod @'400;
7502 if info(p)<0 then print_esc("BAD.")
7503 @.BAD@>
7504 else @<Display the token $(|m|,|c|)$@>;
7505 end
7506
7507 @ The procedure usually ``learns'' the character code used for macro
7508 parameters by seeing one in a |match| command before it runs into any
7509 |out_param| commands.
7510
7511 @<Display the token ...@>=
7512 case m of
7513 left_brace,right_brace,math_shift,tab_mark,sup_mark,sub_mark,spacer,
7514 letter,other_char: print(c);
7515 mac_param: begin print(c); print(c);
7516 end;
7517 out_param: begin print(match_chr);
7518 if c<=9 then print_char(c+"0")
7519 else begin print_char("!"); return;
7520 end;
7521 end;
7522 match: begin match_chr:=c; print(c); incr(n); print_char(n);
7523 if n>"9" then return;
7524 end;
7525 end_match: if c=0 then print("->");
7526 @.->@>
7527 othercases print_esc("BAD.")
7528 @.BAD@>
7529 endcases
7530
7531 @ Here's the way we sometimes want to display a token list, given a pointer
7532 to its reference count; the pointer may be null.
7533
7534 @p procedure token_show(@!p:pointer);
7535 begin if p<>null then show_token_list(link(p),null,10000000);
7536 end;
7537
7538 @ The |print_meaning| subroutine displays |cur_cmd| and |cur_chr| in
7539 symbolic form, including the expansion of a macro or mark.
7540
7541 @p procedure print_meaning;
7542 begin print_cmd_chr(cur_cmd,cur_chr);
7543 if cur_cmd>=call then
7544 begin print_char(":"); print_ln; token_show(cur_chr);
7545 end
7546 else if (cur_cmd=top_bot_mark)and(cur_chr<marks_code) then
7547 begin print_char(":"); print_ln;
7548 token_show(cur_mark[cur_chr]);
7549 end;
7550 end;
7551
7552 @* \[21] Introduction to the syntactic routines.
7553 Let's pause a moment now and try to look at the Big Picture.
7554 The \TeX\ program consists of three main parts: syntactic routines,
7555 semantic routines, and output routines. The chief purpose of the
7556 syntactic routines is to deliver the user's input to the semantic routines,
7557 one token at a time. The semantic routines act as an interpreter
7558 responding to these tokens, which may be regarded as commands. And the
7559 output routines are periodically called on to convert box-and-glue
7560 lists into a compact set of instructions that will be sent
7561 to a typesetter. We have discussed the basic data structures and utility
7562 routines of \TeX, so we are good and ready to plunge into the real activity by
7563 considering the syntactic routines.
7564
7565 Our current goal is to come to grips with the |get_next| procedure,
7566 which is the keystone of \TeX's input mechanism. Each call of |get_next|
7567 sets the value of three variables |cur_cmd|, |cur_chr|, and |cur_cs|,
7568 representing the next input token.
7569 $$\vbox{\halign{#\hfil\cr
7570 \hbox{|cur_cmd| denotes a command code from the long list of codes
7571 given above;}\cr
7572 \hbox{|cur_chr| denotes a character code or other modifier of the command
7573 code;}\cr
7574 \hbox{|cur_cs| is the |eqtb| location of the current control sequence,}\cr
7575 \hbox{\qquad if the current token was a control sequence,
7576 otherwise it's zero.}\cr}}$$
7577 Underlying this external behavior of |get_next| is all the machinery
7578 necessary to convert from character files to tokens. At a given time we
7579 may be only partially finished with the reading of several files (for
7580 which \.{\\input} was specified), and partially finished with the expansion
7581 of some user-defined macros and/or some macro parameters, and partially
7582 finished with the generation of some text in a template for \.{\\halign},
7583 and so on. When reading a character file, special characters must be
7584 classified as math delimiters, etc.; comments and extra blank spaces must
7585 be removed, paragraphs must be recognized, and control sequences must be
7586 found in the hash table. Furthermore there are occasions in which the
7587 scanning routines have looked ahead for a word like `\.{plus}' but only
7588 part of that word was found, hence a few characters must be put back
7589 into the input and scanned again.
7590
7591 To handle these situations, which might all be present simultaneously,
7592 \TeX\ uses various stacks that hold information about the incomplete
7593 activities, and there is a finite state control for each level of the
7594 input mechanism. These stacks record the current state of an implicitly
7595 recursive process, but the |get_next| procedure is not recursive.
7596 Therefore it will not be difficult to translate these algorithms into
7597 low-level languages that do not support recursion.
7598
7599 @<Glob...@>=
7600 @!cur_cmd: eight_bits; {current command set by |get_next|}
7601 @!cur_chr: halfword; {operand of current command}
7602 @!cur_cs: pointer; {control sequence found here, zero if none found}
7603 @!cur_tok: halfword; {packed representative of |cur_cmd| and |cur_chr|}
7604
7605 @ The |print_cmd_chr| routine prints a symbolic interpretation of a
7606 command code and its modifier. This is used in certain `\.{You can\'t}'
7607 error messages, and in the implementation of diagnostic routines like
7608 \.{\\show}.
7609
7610 The body of |print_cmd_chr| is a rather tedious listing of print
7611 commands, and most of it is essentially an inverse to the |primitive|
7612 routine that enters a \TeX\ primitive into |eqtb|. Therefore much of
7613 this procedure appears elsewhere in the program,
7614 together with the corresponding |primitive| calls.
7615
7616 @d chr_cmd(#)==begin print(#); print_ASCII(chr_code);
7617 end
7618
7619 @<Declare the procedure called |print_cmd_chr|@>=
7620 procedure print_cmd_chr(@!cmd:quarterword;@!chr_code:halfword);
7621 var n:integer; {temp variable}
7622 begin case cmd of
7623 left_brace: chr_cmd("begin-group character ");
7624 right_brace: chr_cmd("end-group character ");
7625 math_shift: chr_cmd("math shift character ");
7626 mac_param: chr_cmd("macro parameter character ");
7627 sup_mark: chr_cmd("superscript character ");
7628 sub_mark: chr_cmd("subscript character ");
7629 endv: print("end of alignment template");
7630 spacer: chr_cmd("blank space ");
7631 letter: chr_cmd("the letter ");
7632 other_char: chr_cmd("the character ");
7633 @t\4@>@<Cases of |print_cmd_chr| for symbolic printing of primitives@>@/
7634 othercases print("[unknown command code!]")
7635 endcases;
7636 end;
7637
7638 @ Here is a procedure that displays the current command.
7639
7640 @p procedure show_cur_cmd_chr;
7641 var n:integer; {level of \.{\\if...\\fi} nesting}
7642 @!l:integer; {line where \.{\\if} started}
7643 @!p:pointer;
7644 begin begin_diagnostic; print_nl("{");
7645 if mode<>shown_mode then
7646 begin print_mode(mode); print(": "); shown_mode:=mode;
7647 end;
7648 print_cmd_chr(cur_cmd,cur_chr);
7649 if tracing_ifs>0 then
7650 if cur_cmd>=if_test then if cur_cmd<=fi_or_else then
7651 begin print(": ");
7652 if cur_cmd=fi_or_else then
7653 begin print_cmd_chr(if_test,cur_if); print_char(" ");
7654 n:=0; l:=if_line;
7655 end
7656 else begin n:=1; l:=line;
7657 end;
7658 p:=cond_ptr;
7659 while p<>null do
7660 begin incr(n); p:=link(p);
7661 end;
7662 print("(level "); print_int(n); print_char(")"); print_if_line(l);
7663 end;
7664 print_char("}");
7665 end_diagnostic(false);
7666 end;
7667
7668 @* \[22] Input stacks and states.
7669 This implementation of
7670 \TeX\ uses two different conventions for representing sequential stacks.
7671 @^stack conventions@>@^conventions for representing stacks@>
7672
7673 \yskip\hangg 1) If there is frequent access to the top entry, and if the
7674 stack is essentially never empty, then the top entry is kept in a global
7675 variable (even better would be a machine register), and the other entries
7676 appear in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the
7677 semantic stack described above is handled this way, and so is the input
7678 stack that we are about to study.
7679
7680 \yskip\hangg 2) If there is infrequent top access, the entire stack contents
7681 are in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the |save_stack|
7682 is treated this way, as we have seen.
7683
7684 \yskip\noindent
7685 The state of \TeX's input mechanism appears in the input stack, whose
7686 entries are records with six fields, called |state|, |index|, |start|, |loc|,
7687 |limit|, and |name|. This stack is maintained with
7688 convention~(1), so it is declared in the following way:
7689
7690 @<Types...@>=
7691 @!in_state_record = record
7692 @!state_field, @!index_field: quarterword;
7693 @!start_field,@!loc_field, @!limit_field, @!name_field: halfword;
7694 end;
7695
7696 @ @<Glob...@>=
7697 @!input_stack : array[0..stack_size] of in_state_record;
7698 @!input_ptr : 0..stack_size; {first unused location of |input_stack|}
7699 @!max_in_stack: 0..stack_size; {largest value of |input_ptr| when pushing}
7700 @!cur_input : in_state_record;
7701 {the ``top'' input state, according to convention (1)}
7702
7703 @ We've already defined the special variable |loc==cur_input.loc_field|
7704 in our discussion of basic input-output routines. The other components of
7705 |cur_input| are defined in the same way:
7706
7707 @d state==cur_input.state_field {current scanner state}
7708 @d index==cur_input.index_field {reference for buffer information}
7709 @d start==cur_input.start_field {starting position in |buffer|}
7710 @d limit==cur_input.limit_field {end of current line in |buffer|}
7711 @d name==cur_input.name_field {name of the current file}
7712
7713 @ Let's look more closely now at the control variables
7714 (|state|,~|index|,~|start|,~|loc|,~|limit|,~|name|),
7715 assuming that \TeX\ is reading a line of characters that have been input
7716 from some file or from the user's terminal. There is an array called
7717 |buffer| that acts as a stack of all lines of characters that are
7718 currently being read from files, including all lines on subsidiary
7719 levels of the input stack that are not yet completed. \TeX\ will return to
7720 the other lines when it is finished with the present input file.
7721
7722 (Incidentally, on a machine with byte-oriented addressing, it might be
7723 appropriate to combine |buffer| with the |str_pool| array,
7724 letting the buffer entries grow downward from the top of the string pool
7725 and checking that these two tables don't bump into each other.)
7726
7727 The line we are currently working on begins in position |start| of the
7728 buffer; the next character we are about to read is |buffer[loc]|; and
7729 |limit| is the location of the last character present. If |loc>limit|,
7730 the line has been completely read. Usually |buffer[limit]| is the
7731 |end_line_char|, denoting the end of a line, but this is not
7732 true if the current line is an insertion that was entered on the user's
7733 terminal in response to an error message.
7734
7735 The |name| variable is a string number that designates the name of
7736 the current file, if we are reading a text file. It is zero if we
7737 are reading from the terminal; it is |n+1| if we are reading from
7738 input stream |n|, where |0<=n<=16|. (Input stream 16 stands for
7739 an invalid stream number; in such cases the input is actually from
7740 the terminal, under control of the procedure |read_toks|.)
7741 Finally |18<=name<=19| indicates that we are reading a pseudo file
7742 created by the \.{\\scantokens} command.
7743
7744 The |state| variable has one of three values, when we are scanning such
7745 files:
7746 $$\baselineskip 15pt\vbox{\halign{#\hfil\cr
7747 1) |state=mid_line| is the normal state.\cr
7748 2) |state=skip_blanks| is like |mid_line|, but blanks are ignored.\cr
7749 3) |state=new_line| is the state at the beginning of a line.\cr}}$$
7750 These state values are assigned numeric codes so that if we add the state
7751 code to the next character's command code, we get distinct values. For
7752 example, `|mid_line+spacer|' stands for the case that a blank
7753 space character occurs in the middle of a line when it is not being
7754 ignored; after this case is processed, the next value of |state| will
7755 be |skip_blanks|.
7756
7757 @d mid_line=1 {|state| code when scanning a line of characters}
7758 @d skip_blanks=2+max_char_code {|state| code when ignoring blanks}
7759 @d new_line=3+max_char_code+max_char_code {|state| code at start of line}
7760
7761 @ Additional information about the current line is available via the
7762 |index| variable, which counts how many lines of characters are present
7763 in the buffer below the current level. We have |index=0| when reading
7764 from the terminal and prompting the user for each line; then if the user types,
7765 e.g., `\.{\\input paper}', we will have |index=1| while reading
7766 the file \.{paper.tex}. However, it does not follow that |index| is the
7767 same as the input stack pointer, since many of the levels on the input
7768 stack may come from token lists. For example, the instruction `\.{\\input
7769 paper}' might occur in a token list.
7770
7771 The global variable |in_open| is equal to the |index|
7772 value of the highest non-token-list level. Thus, the number of partially read
7773 lines in the buffer is |in_open+1|, and we have |in_open=index|
7774 when we are not reading a token list.
7775
7776 If we are not currently reading from the terminal, or from an input
7777 stream, we are reading from the file variable |input_file[index]|. We use
7778 the notation |terminal_input| as a convenient abbreviation for |name=0|,
7779 and |cur_file| as an abbreviation for |input_file[index]|.
7780
7781 The global variable |line| contains the line number in the topmost
7782 open file, for use in error messages. If we are not reading from
7783 the terminal, |line_stack[index]| holds the line number for the
7784 enclosing level, so that |line| can be restored when the current
7785 file has been read. Line numbers should never be negative, since the
7786 negative of the current line number is used to identify the user's output
7787 routine in the |mode_line| field of the semantic nest entries.
7788
7789 If more information about the input state is needed, it can be
7790 included in small arrays like those shown here. For example,
7791 the current page or segment number in the input file might be
7792 put into a variable |@!page|, maintained for enclosing levels in
7793 `\ignorespaces|@!page_stack:array[1..max_in_open] of integer|\unskip'
7794 by analogy with |line_stack|.
7795 @^system dependencies@>
7796
7797 @d terminal_input==(name=0) {are we reading from the terminal?}
7798 @d cur_file==input_file[index] {the current |alpha_file| variable}
7799
7800 @<Glob...@>=
7801 @!in_open : 0..max_in_open; {the number of lines in the buffer, less one}
7802 @!open_parens : 0..max_in_open; {the number of open text files}
7803 @!input_file : array[1..max_in_open] of alpha_file;
7804 @!line : integer; {current line number in the current source file}
7805 @!line_stack : array[1..max_in_open] of integer;
7806
7807 @ Users of \TeX\ sometimes forget to balance left and right braces properly,
7808 and one of the ways \TeX\ tries to spot such errors is by considering an
7809 input file as broken into subfiles by control sequences that
7810 are declared to be \.{\\outer}.
7811
7812 A variable called |scanner_status| tells \TeX\ whether or not to complain
7813 when a subfile ends. This variable has six possible values:
7814
7815 \yskip\hang|normal|, means that a subfile can safely end here without incident.
7816
7817 \yskip\hang|skipping|, means that a subfile can safely end here, but not a file,
7818 because we're reading past some conditional text that was not selected.
7819
7820 \yskip\hang|defining|, means that a subfile shouldn't end now because a
7821 macro is being defined.
7822
7823 \yskip\hang|matching|, means that a subfile shouldn't end now because a
7824 macro is being used and we are searching for the end of its arguments.
7825
7826 \yskip\hang|aligning|, means that a subfile shouldn't end now because we are
7827 not finished with the preamble of an \.{\\halign} or \.{\\valign}.
7828
7829 \yskip\hang|absorbing|, means that a subfile shouldn't end now because we are
7830 reading a balanced token list for \.{\\message}, \.{\\write}, etc.
7831
7832 \yskip\noindent
7833 If the |scanner_status| is not |normal|, the variable |warning_index| points
7834 to the |eqtb| location for the relevant control sequence name to print
7835 in an error message.
7836
7837 @d skipping=1 {|scanner_status| when passing conditional text}
7838 @d defining=2 {|scanner_status| when reading a macro definition}
7839 @d matching=3 {|scanner_status| when reading macro arguments}
7840 @d aligning=4 {|scanner_status| when reading an alignment preamble}
7841 @d absorbing=5 {|scanner_status| when reading a balanced text}
7842
7843 @<Glob...@>=
7844 @!scanner_status : normal..absorbing; {can a subfile end now?}
7845 @!warning_index : pointer; {identifier relevant to non-|normal| scanner status}
7846 @!def_ref : pointer; {reference count of token list being defined}
7847
7848 @ Here is a procedure that uses |scanner_status| to print a warning message
7849 when a subfile has ended, and at certain other crucial times:
7850
7851 @<Declare the procedure called |runaway|@>=
7852 procedure runaway;
7853 var p:pointer; {head of runaway list}
7854 begin if scanner_status>skipping then
7855 begin print_nl("Runaway ");
7856 @.Runaway...@>
7857 case scanner_status of
7858 defining: begin print("definition"); p:=def_ref;
7859 end;
7860 matching: begin print("argument"); p:=temp_head;
7861 end;
7862 aligning: begin print("preamble"); p:=hold_head;
7863 end;
7864 absorbing: begin print("text"); p:=def_ref;
7865 end;
7866 end; {there are no other cases}
7867 print_char("?");print_ln; show_token_list(link(p),null,error_line-10);
7868 end;
7869 end;
7870
7871 @ However, all this discussion about input state really applies only to the
7872 case that we are inputting from a file. There is another important case,
7873 namely when we are currently getting input from a token list. In this case
7874 |state=token_list|, and the conventions about the other state variables
7875 are different:
7876
7877 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
7878 the node that will be read next. If |loc=null|, the token list has been
7879 fully read.
7880
7881 \yskip\hang|start| points to the first node of the token list; this node
7882 may or may not contain a reference count, depending on the type of token
7883 list involved.
7884
7885 \yskip\hang|token_type|, which takes the place of |index| in the
7886 discussion above, is a code number that explains what kind of token list
7887 is being scanned.
7888
7889 \yskip\hang|name| points to the |eqtb| address of the control sequence
7890 being expanded, if the current token list is a macro.
7891
7892 \yskip\hang|param_start|, which takes the place of |limit|, tells where
7893 the parameters of the current macro begin in the |param_stack|, if the
7894 current token list is a macro.
7895
7896 \yskip\noindent The |token_type| can take several values, depending on
7897 where the current token list came from:
7898
7899 \yskip\hang|parameter|, if a parameter is being scanned;
7900
7901 \hang|u_template|, if the \<u_j> part of an alignment
7902 template is being scanned;
7903
7904 \hang|v_template|, if the \<v_j> part of an alignment
7905 template is being scanned;
7906
7907 \hang|backed_up|, if the token list being scanned has been inserted as
7908 `to be read again';
7909
7910 \hang|inserted|, if the token list being scanned has been inserted as
7911 the text expansion of a \.{\\count} or similar variable;
7912
7913 \hang|macro|, if a user-defined control sequence is being scanned;
7914
7915 \hang|output_text|, if an \.{\\output} routine is being scanned;
7916
7917 \hang|every_par_text|, if the text of \.{\\everypar} is being scanned;
7918
7919 \hang|every_math_text|, if the text of \.{\\everymath} is being scanned;
7920
7921 \hang|every_display_text|, if the text of \.{\\everydisplay} is being scanned;
7922
7923 \hang|every_hbox_text|, if the text of \.{\\everyhbox} is being scanned;
7924
7925 \hang|every_vbox_text|, if the text of \.{\\everyvbox} is being scanned;
7926
7927 \hang|every_job_text|, if the text of \.{\\everyjob} is being scanned;
7928
7929 \hang|every_cr_text|, if the text of \.{\\everycr} is being scanned;
7930
7931 \hang|mark_text|, if the text of a \.{\\mark} is being scanned;
7932
7933 \hang|write_text|, if the text of a \.{\\write} is being scanned.
7934
7935 \yskip\noindent
7936 The codes for |output_text|, |every_par_text|, etc., are equal to a constant
7937 plus the corresponding codes for token list parameters |output_routine_loc|,
7938 |every_par_loc|, etc. The token list begins with a reference count if and
7939 only if |token_type>=macro|.
7940 @^reference counts@>
7941
7942 Since \eTeX's additional token list parameters precede |toks_base|, the
7943 corresponding token types must precede |write_text|.
7944
7945 @d token_list=0 {|state| code when scanning a token list}
7946 @d token_type==index {type of current token list}
7947 @d param_start==limit {base of macro parameters in |param_stack|}
7948 @d parameter=0 {|token_type| code for parameter}
7949 @d u_template=1 {|token_type| code for \<u_j> template}
7950 @d v_template=2 {|token_type| code for \<v_j> template}
7951 @d backed_up=3 {|token_type| code for text to be reread}
7952 @d inserted=4 {|token_type| code for inserted texts}
7953 @d macro=5 {|token_type| code for defined control sequences}
7954 @d output_text=6 {|token_type| code for output routines}
7955 @d every_par_text=7 {|token_type| code for \.{\\everypar}}
7956 @d every_math_text=8 {|token_type| code for \.{\\everymath}}
7957 @d every_display_text=9 {|token_type| code for \.{\\everydisplay}}
7958 @d every_hbox_text=10 {|token_type| code for \.{\\everyhbox}}
7959 @d every_vbox_text=11 {|token_type| code for \.{\\everyvbox}}
7960 @d every_job_text=12 {|token_type| code for \.{\\everyjob}}
7961 @d every_cr_text=13 {|token_type| code for \.{\\everycr}}
7962 @d mark_text=14 {|token_type| code for \.{\\topmark}, etc.}
7963 @#
7964 @d eTeX_text_offset=output_routine_loc-output_text
7965 @d every_eof_text=every_eof_loc-eTeX_text_offset
7966 {|token_type| code for \.{\\everyeof}}
7967 @#
7968 @d write_text=toks_base-eTeX_text_offset {|token_type| code for \.{\\write}}
7969
7970 @ The |param_stack| is an auxiliary array used to hold pointers to the token
7971 lists for parameters at the current level and subsidiary levels of input.
7972 This stack is maintained with convention (2), and it grows at a different
7973 rate from the others.
7974
7975 @<Glob...@>=
7976 @!param_stack:array [0..param_size] of pointer;
7977 {token list pointers for parameters}
7978 @!param_ptr:0..param_size; {first unused entry in |param_stack|}
7979 @!max_param_stack:integer;
7980 {largest value of |param_ptr|, will be |<=param_size+9|}
7981
7982 @ The input routines must also interact with the processing of
7983 \.{\\halign} and \.{\\valign}, since the appearance of tab marks and
7984 \.{\\cr} in certain places is supposed to trigger the beginning of special
7985 \<v_j> template text in the scanner. This magic is accomplished by an
7986 |align_state| variable that is increased by~1 when a `\.{\char'173}' is
7987 scanned and decreased by~1 when a `\.{\char'175}' is scanned. The |align_state|
7988 is nonzero during the \<u_j> template, after which it is set to zero; the
7989 \<v_j> template begins when a tab mark or \.{\\cr} occurs at a time that
7990 |align_state=0|.
7991
7992 @<Glob...@>=
7993 @!align_state:integer; {group level with respect to current alignment}
7994
7995 @ Thus, the ``current input state'' can be very complicated indeed; there
7996 can be many levels and each level can arise in a variety of ways. The
7997 |show_context| procedure, which is used by \TeX's error-reporting routine to
7998 print out the current input state on all levels down to the most recent
7999 line of characters from an input file, illustrates most of these conventions.
8000 The global variable |base_ptr| contains the lowest level that was
8001 displayed by this procedure.
8002
8003 @<Glob...@>=
8004 @!base_ptr:0..stack_size; {shallowest level shown by |show_context|}
8005
8006 @ The status at each level is indicated by printing two lines, where the first
8007 line indicates what was read so far and the second line shows what remains
8008 to be read. The context is cropped, if necessary, so that the first line
8009 contains at most |half_error_line| characters, and the second contains
8010 at most |error_line|. Non-current input levels whose |token_type| is
8011 `|backed_up|' are shown only if they have not been fully read.
8012
8013 @p procedure show_context; {prints where the scanner is}
8014 label done;
8015 var old_setting:0..max_selector; {saved |selector| setting}
8016 @!nn:integer; {number of contexts shown so far, less one}
8017 @!bottom_line:boolean; {have we reached the final context to be shown?}
8018 @<Local variables for formatting calculations@>@/
8019 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
8020 {store current state}
8021 nn:=-1; bottom_line:=false;
8022 loop@+begin cur_input:=input_stack[base_ptr]; {enter into the context}
8023 if (state<>token_list) then
8024 if (name>19) or (base_ptr=0) then bottom_line:=true;
8025 if (base_ptr=input_ptr)or bottom_line or(nn<error_context_lines) then
8026 @<Display the current context@>
8027 else if nn=error_context_lines then
8028 begin print_nl("..."); incr(nn); {omitted if |error_context_lines<0|}
8029 end;
8030 if bottom_line then goto done;
8031 decr(base_ptr);
8032 end;
8033 done: cur_input:=input_stack[input_ptr]; {restore original state}
8034 end;
8035
8036 @ @<Display the current context@>=
8037 begin if (base_ptr=input_ptr) or (state<>token_list) or
8038 (token_type<>backed_up) or (loc<>null) then
8039 {we omit backed-up token lists that have already been read}
8040 begin tally:=0; {get ready to count characters}
8041 old_setting:=selector;
8042 if state<>token_list then
8043 begin @<Print location of current line@>;
8044 @<Pseudoprint the line@>;
8045 end
8046 else begin @<Print type of token list@>;
8047 @<Pseudoprint the token list@>;
8048 end;
8049 selector:=old_setting; {stop pseudoprinting}
8050 @<Print two lines using the tricky pseudoprinted information@>;
8051 incr(nn);
8052 end;
8053 end
8054
8055 @ This routine should be changed, if necessary, to give the best possible
8056 indication of where the current line resides in the input file.
8057 For example, on some systems it is best to print both a page and line number.
8058 @^system dependencies@>
8059
8060 @<Print location of current line@>=
8061 if name<=17 then
8062 if terminal_input then
8063 if base_ptr=0 then print_nl("<*>") else print_nl("<insert> ")
8064 else begin print_nl("<read ");
8065 if name=17 then print_char("*")@+else print_int(name-1);
8066 @.*\relax@>
8067 print_char(">");
8068 end
8069 else begin print_nl("l.");
8070 if index=in_open then print_int(line)
8071 else print_int(line_stack[index+1]); {input from a pseudo file}
8072 end;
8073 print_char(" ")
8074
8075 @ @<Print type of token list@>=
8076 case token_type of
8077 parameter: print_nl("<argument> ");
8078 u_template,v_template: print_nl("<template> ");
8079 backed_up: if loc=null then print_nl("<recently read> ")
8080 else print_nl("<to be read again> ");
8081 inserted: print_nl("<inserted text> ");
8082 macro: begin print_ln; print_cs(name);
8083 end;
8084 output_text: print_nl("<output> ");
8085 every_par_text: print_nl("<everypar> ");
8086 every_math_text: print_nl("<everymath> ");
8087 every_display_text: print_nl("<everydisplay> ");
8088 every_hbox_text: print_nl("<everyhbox> ");
8089 every_vbox_text: print_nl("<everyvbox> ");
8090 every_job_text: print_nl("<everyjob> ");
8091 every_cr_text: print_nl("<everycr> ");
8092 mark_text: print_nl("<mark> ");
8093 every_eof_text: print_nl("<everyeof> ");
8094 write_text: print_nl("<write> ");
8095 othercases print_nl("?") {this should never happen}
8096 endcases
8097
8098 @ Here it is necessary to explain a little trick. We don't want to store a long
8099 string that corresponds to a token list, because that string might take up
8100 lots of memory; and we are printing during a time when an error message is
8101 being given, so we dare not do anything that might overflow one of \TeX's
8102 tables. So `pseudoprinting' is the answer: We enter a mode of printing
8103 that stores characters into a buffer of length |error_line|, where character
8104 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
8105 |k<trick_count|, otherwise character |k| is dropped. Initially we set
8106 |tally:=0| and |trick_count:=1000000|; then when we reach the
8107 point where transition from line 1 to line 2 should occur, we
8108 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
8109 tally+1+error_line-half_error_line)|. At the end of the
8110 pseudoprinting, the values of |first_count|, |tally|, and
8111 |trick_count| give us all the information we need to print the two lines,
8112 and all of the necessary text is in |trick_buf|.
8113
8114 Namely, let |l| be the length of the descriptive information that appears
8115 on the first line. The length of the context information gathered for that
8116 line is |k=first_count|, and the length of the context information
8117 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
8118 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
8119 descriptive information on line~1, and set |n:=l+k|; here |n| is the
8120 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
8121 and print `\.{...}' followed by
8122 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
8123 where subscripts of |trick_buf| are circular modulo |error_line|. The
8124 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
8125 unless |n+m>error_line|; in the latter case, further cropping is done.
8126 This is easier to program than to explain.
8127
8128 @<Local variables for formatting...@>=
8129 @!i:0..buf_size; {index into |buffer|}
8130 @!j:0..buf_size; {end of current line in |buffer|}
8131 @!l:0..half_error_line; {length of descriptive information on line 1}
8132 @!m:integer; {context information gathered for line 2}
8133 @!n:0..error_line; {length of line 1}
8134 @!p: integer; {starting or ending place in |trick_buf|}
8135 @!q: integer; {temporary index}
8136
8137 @ The following code sets up the print routines so that they will gather
8138 the desired information.
8139
8140 @d begin_pseudoprint==
8141 begin l:=tally; tally:=0; selector:=pseudo;
8142 trick_count:=1000000;
8143 end
8144 @d set_trick_count==
8145 begin first_count:=tally;
8146 trick_count:=tally+1+error_line-half_error_line;
8147 if trick_count<error_line then trick_count:=error_line;
8148 end
8149
8150 @ And the following code uses the information after it has been gathered.
8151
8152 @<Print two lines using the tricky pseudoprinted information@>=
8153 if trick_count=1000000 then set_trick_count;
8154 {|set_trick_count| must be performed}
8155 if tally<trick_count then m:=tally-first_count
8156 else m:=trick_count-first_count; {context on line 2}
8157 if l+first_count<=half_error_line then
8158 begin p:=0; n:=l+first_count;
8159 end
8160 else begin print("..."); p:=l+first_count-half_error_line+3;
8161 n:=half_error_line;
8162 end;
8163 for q:=p to first_count-1 do print_char(trick_buf[q mod error_line]);
8164 print_ln;
8165 for q:=1 to n do print_char(" "); {print |n| spaces to begin line~2}
8166 if m+n<=error_line then p:=first_count+m else p:=first_count+(error_line-n-3);
8167 for q:=first_count to p-1 do print_char(trick_buf[q mod error_line]);
8168 if m+n>error_line then print("...")
8169
8170 @ But the trick is distracting us from our current goal, which is to
8171 understand the input state. So let's concentrate on the data structures that
8172 are being pseudoprinted as we finish up the |show_context| procedure.
8173
8174 @<Pseudoprint the line@>=
8175 begin_pseudoprint;
8176 if buffer[limit]=end_line_char then j:=limit
8177 else j:=limit+1; {determine the effective end of the line}
8178 if j>0 then for i:=start to j-1 do
8179 begin if i=loc then set_trick_count;
8180 print(buffer[i]);
8181 end
8182
8183 @ @<Pseudoprint the token list@>=
8184 begin_pseudoprint;
8185 if token_type<macro then show_token_list(start,loc,100000)
8186 else show_token_list(link(start),loc,100000) {avoid reference count}
8187
8188 @ Here is the missing piece of |show_token_list| that is activated when the
8189 token beginning line~2 is about to be shown:
8190
8191 @<Do magic computation@>=set_trick_count
8192
8193 @* \[23] Maintaining the input stacks.
8194 The following subroutines change the input status in commonly needed ways.
8195
8196 First comes |push_input|, which stores the current state and creates a
8197 new level (having, initially, the same properties as the old).
8198
8199 @d push_input==@t@> {enter a new input level, save the old}
8200 begin if input_ptr>max_in_stack then
8201 begin max_in_stack:=input_ptr;
8202 if input_ptr=stack_size then overflow("input stack size",stack_size);
8203 @:TeX capacity exceeded input stack size}{\quad input stack size@>
8204 end;
8205 input_stack[input_ptr]:=cur_input; {stack the record}
8206 incr(input_ptr);
8207 end
8208
8209 @ And of course what goes up must come down.
8210
8211 @d pop_input==@t@> {leave an input level, re-enter the old}
8212 begin decr(input_ptr); cur_input:=input_stack[input_ptr];
8213 end
8214
8215 @ Here is a procedure that starts a new level of token-list input, given
8216 a token list |p| and its type |t|. If |t=macro|, the calling routine should
8217 set |name| and |loc|.
8218
8219 @d back_list(#)==begin_token_list(#,backed_up) {backs up a simple token list}
8220 @d ins_list(#)==begin_token_list(#,inserted) {inserts a simple token list}
8221
8222 @p procedure begin_token_list(@!p:pointer;@!t:quarterword);
8223 begin push_input; state:=token_list; start:=p; token_type:=t;
8224 if t>=macro then {the token list starts with a reference count}
8225 begin add_token_ref(p);
8226 if t=macro then param_start:=param_ptr
8227 else begin loc:=link(p);
8228 if tracing_macros>1 then
8229 begin begin_diagnostic; print_nl("");
8230 case t of
8231 mark_text:print_esc("mark");
8232 write_text:print_esc("write");
8233 othercases print_cmd_chr(assign_toks,t-output_text+output_routine_loc)
8234 endcases;@/
8235 print("->"); token_show(p); end_diagnostic(false);
8236 end;
8237 end;
8238 end
8239 else loc:=p;
8240 end;
8241
8242 @ When a token list has been fully scanned, the following computations
8243 should be done as we leave that level of input. The |token_type| tends
8244 to be equal to either |backed_up| or |inserted| about 2/3 of the time.
8245 @^inner loop@>
8246
8247 @p procedure end_token_list; {leave a token-list input level}
8248 begin if token_type>=backed_up then {token list to be deleted}
8249 begin if token_type<=inserted then flush_list(start)
8250 else begin delete_token_ref(start); {update reference count}
8251 if token_type=macro then {parameters must be flushed}
8252 while param_ptr>param_start do
8253 begin decr(param_ptr);
8254 flush_list(param_stack[param_ptr]);
8255 end;
8256 end;
8257 end
8258 else if token_type=u_template then
8259 if align_state>500000 then align_state:=0
8260 else fatal_error("(interwoven alignment preambles are not allowed)");
8261 @.interwoven alignment preambles...@>
8262 pop_input;
8263 check_interrupt;
8264 end;
8265
8266 @ Sometimes \TeX\ has read too far and wants to ``unscan'' what it has
8267 seen. The |back_input| procedure takes care of this by putting the token
8268 just scanned back into the input stream, ready to be read again. This
8269 procedure can be used only if |cur_tok| represents the token to be
8270 replaced. Some applications of \TeX\ use this procedure a lot,
8271 so it has been slightly optimized for speed.
8272 @^inner loop@>
8273
8274 @p procedure back_input; {undoes one token of input}
8275 var p:pointer; {a token list of length one}
8276 begin while (state=token_list)and(loc=null)and(token_type<>v_template) do
8277 end_token_list; {conserve stack space}
8278 p:=get_avail; info(p):=cur_tok;
8279 if cur_tok<right_brace_limit then
8280 if cur_tok<left_brace_limit then decr(align_state)
8281 else incr(align_state);
8282 push_input; state:=token_list; start:=p; token_type:=backed_up;
8283 loc:=p; {that was |back_list(p)|, without procedure overhead}
8284 end;
8285
8286 @ @<Insert token |p| into \TeX's input@>=
8287 begin t:=cur_tok; cur_tok:=p;
8288 if a then
8289 begin p:=get_avail; info(p):=cur_tok; link(p):=loc; loc:=p; start:=p;
8290 if cur_tok<right_brace_limit then
8291 if cur_tok<left_brace_limit then decr(align_state)
8292 else incr(align_state);
8293 end
8294 else begin back_input; a:=eTeX_ex;
8295 end;
8296 cur_tok:=t;
8297 end
8298
8299 @ The |back_error| routine is used when we want to replace an offending token
8300 just before issuing an error message. This routine, like |back_input|,
8301 requires that |cur_tok| has been set. We disable interrupts during the
8302 call of |back_input| so that the help message won't be lost.
8303
8304 @p procedure back_error; {back up one token and call |error|}
8305 begin OK_to_interrupt:=false; back_input; OK_to_interrupt:=true; error;
8306 end;
8307 @#
8308 procedure ins_error; {back up one inserted token and call |error|}
8309 begin OK_to_interrupt:=false; back_input; token_type:=inserted;
8310 OK_to_interrupt:=true; error;
8311 end;
8312
8313 @ The |begin_file_reading| procedure starts a new level of input for lines
8314 of characters to be read from a file, or as an insertion from the
8315 terminal. It does not take care of opening the file, nor does it set |loc|
8316 or |limit| or |line|.
8317 @^system dependencies@>
8318
8319 @p procedure begin_file_reading;
8320 begin if in_open=max_in_open then overflow("text input levels",max_in_open);
8321 @:TeX capacity exceeded text input levels}{\quad text input levels@>
8322 if first=buf_size then overflow("buffer size",buf_size);
8323 @:TeX capacity exceeded buffer size}{\quad buffer size@>
8324 incr(in_open); push_input; index:=in_open;
8325 eof_seen[index]:=false;
8326 grp_stack[index]:=cur_boundary; if_stack[index]:=cond_ptr;
8327 line_stack[index]:=line; start:=first; state:=mid_line;
8328 name:=0; {|terminal_input| is now |true|}
8329 end;
8330
8331 @ Conversely, the variables must be downdated when such a level of input
8332 is finished:
8333
8334 @p procedure end_file_reading;
8335 begin first:=start; line:=line_stack[index];
8336 if (name=18)or(name=19) then pseudo_close else
8337 if name>17 then a_close(cur_file); {forget it}
8338 pop_input; decr(in_open);
8339 end;
8340
8341 @ In order to keep the stack from overflowing during a long sequence of
8342 inserted `\.{\\show}' commands, the following routine removes completed
8343 error-inserted lines from memory.
8344
8345 @p procedure clear_for_error_prompt;
8346 begin while (state<>token_list)and terminal_input and@|
8347 (input_ptr>0)and(loc>limit) do end_file_reading;
8348 print_ln; clear_terminal;
8349 end;
8350
8351 @ To get \TeX's whole input mechanism going, we perform the following
8352 actions.
8353
8354 @<Initialize the input routines@>=
8355 begin input_ptr:=0; max_in_stack:=0;
8356 in_open:=0; open_parens:=0; max_buf_stack:=0;
8357 grp_stack[0]:=0; if_stack[0]:=null;
8358 param_ptr:=0; max_param_stack:=0;
8359 first:=buf_size; repeat buffer[first]:=0; decr(first); until first=0;
8360 scanner_status:=normal; warning_index:=null; first:=1;
8361 state:=new_line; start:=1; index:=0; line:=0; name:=0;
8362 force_eof:=false;
8363 align_state:=1000000;@/
8364 if not init_terminal then goto final_end;
8365 limit:=last; first:=last+1; {|init_terminal| has set |loc| and |last|}
8366 end
8367
8368 @* \[24] Getting the next token.
8369 The heart of \TeX's input mechanism is the |get_next| procedure, which
8370 we shall develop in the next few sections of the program. Perhaps we
8371 shouldn't actually call it the ``heart,'' however, because it really acts
8372 as \TeX's eyes and mouth, reading the source files and gobbling them up.
8373 And it also helps \TeX\ to regurgitate stored token lists that are to be
8374 processed again.
8375 @^eyes and mouth@>
8376
8377 The main duty of |get_next| is to input one token and to set |cur_cmd|
8378 and |cur_chr| to that token's command code and modifier. Furthermore, if
8379 the input token is a control sequence, the |eqtb| location of that control
8380 sequence is stored in |cur_cs|; otherwise |cur_cs| is set to zero.
8381
8382 Underlying this simple description is a certain amount of complexity
8383 because of all the cases that need to be handled.
8384 However, the inner loop of |get_next| is reasonably short and fast.
8385
8386 When |get_next| is asked to get the next token of a \.{\\read} line,
8387 it sets |cur_cmd=cur_chr=cur_cs=0| in the case that no more tokens
8388 appear on that line. (There might not be any tokens at all, if the
8389 |end_line_char| has |ignore| as its catcode.)
8390
8391 @ The value of |par_loc| is the |eqtb| address of `\.{\\par}'. This quantity
8392 is needed because a blank line of input is supposed to be exactly equivalent
8393 to the appearance of \.{\\par}; we must set |cur_cs:=par_loc|
8394 when detecting a blank line.
8395
8396 @<Glob...@>=
8397 @!par_loc:pointer; {location of `\.{\\par}' in |eqtb|}
8398 @!par_token:halfword; {token representing `\.{\\par}'}
8399
8400 @ @<Put each...@>=
8401 primitive("par",par_end,256); {cf.\ |scan_file_name|}
8402 @!@:par_}{\.{\\par} primitive@>
8403 par_loc:=cur_val; par_token:=cs_token_flag+par_loc;
8404
8405 @ @<Cases of |print_cmd_chr|...@>=
8406 par_end:print_esc("par");
8407
8408 @ Before getting into |get_next|, let's consider the subroutine that
8409 is called when an `\.{\\outer}' control sequence has been scanned or
8410 when the end of a file has been reached. These two cases are distinguished
8411 by |cur_cs|, which is zero at the end of a file.
8412
8413 @p procedure check_outer_validity;
8414 var p:pointer; {points to inserted token list}
8415 @!q:pointer; {auxiliary pointer}
8416 begin if scanner_status<>normal then
8417 begin deletions_allowed:=false;
8418 @<Back up an outer control sequence so that it can be reread@>;
8419 if scanner_status>skipping then
8420 @<Tell the user what has run away and try to recover@>
8421 else begin print_err("Incomplete "); print_cmd_chr(if_test,cur_if);
8422 @.Incomplete \\if...@>
8423 print("; all text was ignored after line "); print_int(skip_line);
8424 help3("A forbidden control sequence occurred in skipped text.")@/
8425 ("This kind of error happens when you say `\if...' and forget")@/
8426 ("the matching `\fi'. I've inserted a `\fi'; this might work.");
8427 if cur_cs<>0 then cur_cs:=0
8428 else help_line[2]:=@|
8429 "The file ended while I was skipping conditional text.";
8430 cur_tok:=cs_token_flag+frozen_fi; ins_error;
8431 end;
8432 deletions_allowed:=true;
8433 end;
8434 end;
8435
8436 @ An outer control sequence that occurs in a \.{\\read} will not be reread,
8437 since the error recovery for \.{\\read} is not very powerful.
8438
8439 @<Back up an outer control sequence so that it can be reread@>=
8440 if cur_cs<>0 then
8441 begin if (state=token_list)or(name<1)or(name>17) then
8442 begin p:=get_avail; info(p):=cs_token_flag+cur_cs;
8443 back_list(p); {prepare to read the control sequence again}
8444 end;
8445 cur_cmd:=spacer; cur_chr:=" "; {replace it by a space}
8446 end
8447
8448 @ @<Tell the user what has run away...@>=
8449 begin runaway; {print a definition, argument, or preamble}
8450 if cur_cs=0 then print_err("File ended")
8451 @.File ended while scanning...@>
8452 else begin cur_cs:=0; print_err("Forbidden control sequence found");
8453 @.Forbidden control sequence...@>
8454 end;
8455 print(" while scanning ");
8456 @<Print either `\.{definition}' or `\.{use}' or `\.{preamble}' or `\.{text}',
8457 and insert tokens that should lead to recovery@>;
8458 print(" of "); sprint_cs(warning_index);
8459 help4("I suspect you have forgotten a `}', causing me")@/
8460 ("to read past where you wanted me to stop.")@/
8461 ("I'll try to recover; but if the error is serious,")@/
8462 ("you'd better type `E' or `X' now and fix your file.");@/
8463 error;
8464 end
8465
8466 @ The recovery procedure can't be fully understood without knowing more
8467 about the \TeX\ routines that should be aborted, but we can sketch the
8468 ideas here: For a runaway definition or a runaway balanced text
8469 we will insert a right brace; for a
8470 runaway preamble, we will insert a special \.{\\cr} token and a right
8471 brace; and for a runaway argument, we will set |long_state| to
8472 |outer_call| and insert \.{\\par}.
8473
8474 @<Print either `\.{definition}' or ...@>=
8475 p:=get_avail;
8476 case scanner_status of
8477 defining:begin print("definition"); info(p):=right_brace_token+"}";
8478 end;
8479 matching:begin print("use"); info(p):=par_token; long_state:=outer_call;
8480 end;
8481 aligning:begin print("preamble"); info(p):=right_brace_token+"}"; q:=p;
8482 p:=get_avail; link(p):=q; info(p):=cs_token_flag+frozen_cr;
8483 align_state:=-1000000;
8484 end;
8485 absorbing:begin print("text"); info(p):=right_brace_token+"}";
8486 end;
8487 end; {there are no other cases}
8488 ins_list(p)
8489
8490 @ We need to mention a procedure here that may be called by |get_next|.
8491
8492 @p procedure@?firm_up_the_line; forward;
8493
8494 @ Now we're ready to take the plunge into |get_next| itself. Parts of
8495 this routine are executed more often than any other instructions of \TeX.
8496 @^mastication@>@^inner loop@>
8497
8498 @d switch=25 {a label in |get_next|}
8499 @d start_cs=26 {another}
8500
8501 @p procedure get_next; {sets |cur_cmd|, |cur_chr|, |cur_cs| to next token}
8502 label restart, {go here to get the next input token}
8503 switch, {go here to eat the next character from a file}
8504 reswitch, {go here to digest it again}
8505 start_cs, {go here to start looking for a control sequence}
8506 found, {go here when a control sequence has been found}
8507 exit; {go here when the next input token has been got}
8508 var k:0..buf_size; {an index into |buffer|}
8509 @!t:halfword; {a token}
8510 @!cat:0..max_char_code; {|cat_code(cur_chr)|, usually}
8511 @!c,@!cc:ASCII_code; {constituents of a possible expanded code}
8512 @!d:2..3; {number of excess characters in an expanded code}
8513 begin restart: cur_cs:=0;
8514 if state<>token_list then
8515 @<Input from external file, |goto restart| if no input found@>
8516 else @<Input from token list, |goto restart| if end of list or
8517 if a parameter needs to be expanded@>;
8518 @<If an alignment entry has just ended, take appropriate action@>;
8519 exit:end;
8520
8521 @ An alignment entry ends when a tab or \.{\\cr} occurs, provided that the
8522 current level of braces is the same as the level that was present at the
8523 beginning of that alignment entry; i.e., provided that |align_state| has
8524 returned to the value it had after the \<u_j> template for that entry.
8525 @^inner loop@>
8526
8527 @<If an alignment entry has just ended, take appropriate action@>=
8528 if cur_cmd<=car_ret then if cur_cmd>=tab_mark then if align_state=0 then
8529 @<Insert the \(v)\<v_j> template and |goto restart|@>
8530
8531 @ @<Input from external file, |goto restart| if no input found@>=
8532 @^inner loop@>
8533 begin switch: if loc<=limit then {current line not yet finished}
8534 begin cur_chr:=buffer[loc]; incr(loc);
8535 reswitch: cur_cmd:=cat_code(cur_chr);
8536 @<Change state if necessary, and |goto switch| if the
8537 current character should be ignored,
8538 or |goto reswitch| if the current character
8539 changes to another@>;
8540 end
8541 else begin state:=new_line;@/
8542 @<Move to next line of file,
8543 or |goto restart| if there is no next line,
8544 or |return| if a \.{\\read} line has finished@>;
8545 check_interrupt;
8546 goto switch;
8547 end;
8548 end
8549
8550 @ The following 48-way switch accomplishes the scanning quickly, assuming
8551 that a decent \PASCAL\ compiler has translated the code. Note that the numeric
8552 values for |mid_line|, |skip_blanks|, and |new_line| are spaced
8553 apart from each other by |max_char_code+1|, so we can add a character's
8554 command code to the state to get a single number that characterizes both.
8555
8556 @d any_state_plus(#) == mid_line+#,skip_blanks+#,new_line+#
8557
8558 @<Change state if necessary...@>=
8559 case state+cur_cmd of
8560 @<Cases where character is ignored@>: goto switch;
8561 any_state_plus(escape): @<Scan a control sequence
8562 and set |state:=skip_blanks| or |mid_line|@>;
8563 any_state_plus(active_char): @<Process an active-character control sequence
8564 and set |state:=mid_line|@>;
8565 any_state_plus(sup_mark): @<If this |sup_mark| starts an expanded character
8566 like~\.{\^\^A} or~\.{\^\^df}, then |goto reswitch|,
8567 otherwise set |state:=mid_line|@>;
8568 any_state_plus(invalid_char): @<Decry the invalid character and
8569 |goto restart|@>;
8570 @t\4@>@<Handle situations involving spaces, braces, changes of state@>@;
8571 othercases do_nothing
8572 endcases
8573
8574 @ @<Cases where character is ignored@>=
8575 any_state_plus(ignore),skip_blanks+spacer,new_line+spacer
8576
8577 @ We go to |restart| instead of to |switch|, because |state| might equal
8578 |token_list| after the error has been dealt with
8579 (cf.\ |clear_for_error_prompt|).
8580
8581 @<Decry the invalid...@>=
8582 begin print_err("Text line contains an invalid character");
8583 @.Text line contains...@>
8584 help2("A funny symbol that I can't read has just been input.")@/
8585 ("Continue, and I'll forget that it ever happened.");@/
8586 deletions_allowed:=false; error; deletions_allowed:=true;
8587 goto restart;
8588 end
8589
8590 @ @d add_delims_to(#)==#+math_shift,#+tab_mark,#+mac_param,
8591 #+sub_mark,#+letter,#+other_char
8592
8593 @<Handle situations involving spaces, braces, changes of state@>=
8594 mid_line+spacer:@<Enter |skip_blanks| state, emit a space@>;
8595 mid_line+car_ret:@<Finish line, emit a space@>;
8596 skip_blanks+car_ret,any_state_plus(comment):
8597 @<Finish line, |goto switch|@>;
8598 new_line+car_ret:@<Finish line, emit a \.{\\par}@>;
8599 mid_line+left_brace: incr(align_state);
8600 skip_blanks+left_brace,new_line+left_brace: begin
8601 state:=mid_line; incr(align_state);
8602 end;
8603 mid_line+right_brace: decr(align_state);
8604 skip_blanks+right_brace,new_line+right_brace: begin
8605 state:=mid_line; decr(align_state);
8606 end;
8607 add_delims_to(skip_blanks),add_delims_to(new_line): state:=mid_line;
8608
8609 @ When a character of type |spacer| gets through, its character code is
8610 changed to $\.{"\ "}=@'40$. This means that the ASCII codes for tab and space,
8611 and for the space inserted at the end of a line, will
8612 be treated alike when macro parameters are being matched. We do this
8613 since such characters are indistinguishable on most computer terminal displays.
8614
8615 @<Finish line, emit a space@>=
8616 begin loc:=limit+1; cur_cmd:=spacer; cur_chr:=" ";
8617 end
8618
8619 @ The following code is performed only when |cur_cmd=spacer|.
8620
8621 @<Enter |skip_blanks| state, emit a space@>=
8622 begin state:=skip_blanks; cur_chr:=" ";
8623 end
8624
8625 @ @<Finish line, |goto switch|@>=
8626 begin loc:=limit+1; goto switch;
8627 end
8628
8629 @ @<Finish line, emit a \.{\\par}@>=
8630 begin loc:=limit+1; cur_cs:=par_loc; cur_cmd:=eq_type(cur_cs);
8631 cur_chr:=equiv(cur_cs);
8632 if cur_cmd>=outer_call then check_outer_validity;
8633 end
8634
8635 @ Notice that a code like \.{\^\^8} becomes \.x if not followed by a hex digit.
8636
8637 @d is_hex(#)==(((#>="0")and(#<="9"))or((#>="a")and(#<="f")))
8638 @d hex_to_cur_chr==
8639 if c<="9" then cur_chr:=c-"0" @+else cur_chr:=c-"a"+10;
8640 if cc<="9" then cur_chr:=16*cur_chr+cc-"0"
8641 else cur_chr:=16*cur_chr+cc-"a"+10
8642
8643 @<If this |sup_mark| starts an expanded character...@>=
8644 begin if cur_chr=buffer[loc] then if loc<limit then
8645 begin c:=buffer[loc+1]; @+if c<@'200 then {yes we have an expanded char}
8646 begin loc:=loc+2;
8647 if is_hex(c) then if loc<=limit then
8648 begin cc:=buffer[loc]; @+if is_hex(cc) then
8649 begin incr(loc); hex_to_cur_chr; goto reswitch;
8650 end;
8651 end;
8652 if c<@'100 then cur_chr:=c+@'100 @+else cur_chr:=c-@'100;
8653 goto reswitch;
8654 end;
8655 end;
8656 state:=mid_line;
8657 end
8658
8659 @ @<Process an active-character...@>=
8660 begin cur_cs:=cur_chr+active_base;
8661 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs); state:=mid_line;
8662 if cur_cmd>=outer_call then check_outer_validity;
8663 end
8664
8665 @ Control sequence names are scanned only when they appear in some line of
8666 a file; once they have been scanned the first time, their |eqtb| location
8667 serves as a unique identification, so \TeX\ doesn't need to refer to the
8668 original name any more except when it prints the equivalent in symbolic form.
8669
8670 The program that scans a control sequence has been written carefully
8671 in order to avoid the blowups that might otherwise occur if a malicious
8672 user tried something like `\.{\\catcode\'15=0}'. The algorithm might
8673 look at |buffer[limit+1]|, but it never looks at |buffer[limit+2]|.
8674
8675 If expanded characters like `\.{\^\^A}' or `\.{\^\^df}'
8676 appear in or just following
8677 a control sequence name, they are converted to single characters in the
8678 buffer and the process is repeated, slowly but surely.
8679
8680 @<Scan a control...@>=
8681 begin if loc>limit then cur_cs:=null_cs {|state| is irrelevant in this case}
8682 else begin start_cs: k:=loc; cur_chr:=buffer[k]; cat:=cat_code(cur_chr);
8683 incr(k);
8684 if cat=letter then state:=skip_blanks
8685 else if cat=spacer then state:=skip_blanks
8686 else state:=mid_line;
8687 if (cat=letter)and(k<=limit) then
8688 @<Scan ahead in the buffer until finding a nonletter;
8689 if an expanded code is encountered, reduce it
8690 and |goto start_cs|; otherwise if a multiletter control
8691 sequence is found, adjust |cur_cs| and |loc|, and
8692 |goto found|@>
8693 else @<If an expanded code is present, reduce it and |goto start_cs|@>;
8694 cur_cs:=single_base+buffer[loc]; incr(loc);
8695 end;
8696 found: cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
8697 if cur_cmd>=outer_call then check_outer_validity;
8698 end
8699
8700 @ Whenever we reach the following piece of code, we will have
8701 |cur_chr=buffer[k-1]| and |k<=limit+1| and |cat=cat_code(cur_chr)|. If an
8702 expanded code like \.{\^\^A} or \.{\^\^df} appears in |buffer[(k-1)..(k+1)]|
8703 or |buffer[(k-1)..(k+2)]|, we
8704 will store the corresponding code in |buffer[k-1]| and shift the rest of
8705 the buffer left two or three places.
8706
8707 @<If an expanded...@>=
8708 begin if buffer[k]=cur_chr then @+if cat=sup_mark then @+if k<limit then
8709 begin c:=buffer[k+1]; @+if c<@'200 then {yes, one is indeed present}
8710 begin d:=2;
8711 if is_hex(c) then @+if k+2<=limit then
8712 begin cc:=buffer[k+2]; @+if is_hex(cc) then incr(d);
8713 end;
8714 if d>2 then
8715 begin hex_to_cur_chr; buffer[k-1]:=cur_chr;
8716 end
8717 else if c<@'100 then buffer[k-1]:=c+@'100
8718 else buffer[k-1]:=c-@'100;
8719 limit:=limit-d; first:=first-d;
8720 while k<=limit do
8721 begin buffer[k]:=buffer[k+d]; incr(k);
8722 end;
8723 goto start_cs;
8724 end;
8725 end;
8726 end
8727
8728 @ @<Scan ahead in the buffer...@>=
8729 begin repeat cur_chr:=buffer[k]; cat:=cat_code(cur_chr); incr(k);
8730 until (cat<>letter)or(k>limit);
8731 @<If an expanded...@>;
8732 if cat<>letter then decr(k);
8733 {now |k| points to first nonletter}
8734 if k>loc+1 then {multiletter control sequence has been scanned}
8735 begin cur_cs:=id_lookup(loc,k-loc); loc:=k; goto found;
8736 end;
8737 end
8738
8739 @ Let's consider now what happens when |get_next| is looking at a token list.
8740
8741 @<Input from token list, |goto restart| if end of list or
8742 if a parameter needs to be expanded@>=
8743 if loc<>null then {list not exhausted}
8744 @^inner loop@>
8745 begin t:=info(loc); loc:=link(loc); {move to next}
8746 if t>=cs_token_flag then {a control sequence token}
8747 begin cur_cs:=t-cs_token_flag;
8748 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
8749 if cur_cmd>=outer_call then
8750 if cur_cmd=dont_expand then
8751 @<Get the next token, suppressing expansion@>
8752 else check_outer_validity;
8753 end
8754 else begin cur_cmd:=t div @'400; cur_chr:=t mod @'400;
8755 case cur_cmd of
8756 left_brace: incr(align_state);
8757 right_brace: decr(align_state);
8758 out_param: @<Insert macro parameter and |goto restart|@>;
8759 othercases do_nothing
8760 endcases;
8761 end;
8762 end
8763 else begin {we are done with this token list}
8764 end_token_list; goto restart; {resume previous level}
8765 end
8766
8767 @ The present point in the program is reached only when the |expand|
8768 routine has inserted a special marker into the input. In this special
8769 case, |info(loc)| is known to be a control sequence token, and |link(loc)=null|.
8770
8771 @d no_expand_flag=257 {this characterizes a special variant of |relax|}
8772
8773 @<Get the next token, suppressing expansion@>=
8774 begin cur_cs:=info(loc)-cs_token_flag; loc:=null;@/
8775 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
8776 if cur_cmd>max_command then
8777 begin cur_cmd:=relax; cur_chr:=no_expand_flag;
8778 end;
8779 end
8780
8781 @ @<Insert macro parameter...@>=
8782 begin begin_token_list(param_stack[param_start+cur_chr-1],parameter);
8783 goto restart;
8784 end
8785
8786 @ All of the easy branches of |get_next| have now been taken care of.
8787 There is one more branch.
8788
8789 @d end_line_char_inactive == (end_line_char<0)or(end_line_char>255)
8790
8791 @<Move to next line of file, or |goto restart|...@>=
8792 if name>17 then @<Read next line of file into |buffer|, or
8793 |goto restart| if the file has ended@>
8794 else begin if not terminal_input then {\.{\\read} line has ended}
8795 begin cur_cmd:=0; cur_chr:=0; return;
8796 end;
8797 if input_ptr>0 then {text was inserted during error recovery}
8798 begin end_file_reading; goto restart; {resume previous level}
8799 end;
8800 if selector<log_only then open_log_file;
8801 if interaction>nonstop_mode then
8802 begin if end_line_char_inactive then incr(limit);
8803 if limit=start then {previous line was empty}
8804 print_nl("(Please type a command or say `\end')");
8805 @.Please type...@>
8806 print_ln; first:=start;
8807 prompt_input("*"); {input on-line into |buffer|}
8808 @.*\relax@>
8809 limit:=last;
8810 if end_line_char_inactive then decr(limit)
8811 else buffer[limit]:=end_line_char;
8812 first:=limit+1;
8813 loc:=start;
8814 end
8815 else fatal_error("*** (job aborted, no legal \end found)");
8816 @.job aborted@>
8817 {nonstop mode, which is intended for overnight batch processing,
8818 never waits for on-line input}
8819 end
8820
8821 @ The global variable |force_eof| is normally |false|; it is set |true|
8822 by an \.{\\endinput} command.
8823
8824 @<Glob...@>=
8825 @!force_eof:boolean; {should the next \.{\\input} be aborted early?}
8826
8827 @ @<Read next line of file into |buffer|, or
8828 |goto restart| if the file has ended@>=
8829 begin incr(line); first:=start;
8830 if not force_eof then
8831 if name<=19 then
8832 begin if pseudo_input then {not end of file}
8833 firm_up_the_line {this sets |limit|}
8834 else if (every_eof<>null)and not eof_seen[index] then
8835 begin limit:=first-1; eof_seen[index]:=true; {fake one empty line}
8836 begin_token_list(every_eof,every_eof_text); goto restart;
8837 end
8838 else force_eof:=true;
8839 end
8840 else
8841 begin if input_ln(cur_file,true) then {not end of file}
8842 firm_up_the_line {this sets |limit|}
8843 else if (every_eof<>null)and not eof_seen[index] then
8844 begin limit:=first-1; eof_seen[index]:=true; {fake one empty line}
8845 begin_token_list(every_eof,every_eof_text); goto restart;
8846 end
8847 else force_eof:=true;
8848 end;
8849 if force_eof then
8850 begin if tracing_nesting>0 then
8851 if (grp_stack[in_open]<>cur_boundary)or@|
8852 (if_stack[in_open]<>cond_ptr) then file_warning;
8853 {give warning for some unfinished groups and/or conditionals}
8854 if name>=19 then
8855 begin print_char(")"); decr(open_parens);
8856 update_terminal; {show user that file has been read}
8857 end;
8858 force_eof:=false;
8859 end_file_reading; {resume previous level}
8860 check_outer_validity; goto restart;
8861 end;
8862 if end_line_char_inactive then decr(limit)
8863 else buffer[limit]:=end_line_char;
8864 first:=limit+1; loc:=start; {ready to read}
8865 end
8866
8867 @ If the user has set the |pausing| parameter to some positive value,
8868 and if nonstop mode has not been selected, each line of input is displayed
8869 on the terminal and the transcript file, followed by `\.{=>}'.
8870 \TeX\ waits for a response. If the response is simply |carriage_return|, the
8871 line is accepted as it stands, otherwise the line typed is
8872 used instead of the line in the file.
8873
8874 @p procedure firm_up_the_line;
8875 var k:0..buf_size; {an index into |buffer|}
8876 begin limit:=last;
8877 if pausing>0 then if interaction>nonstop_mode then
8878 begin wake_up_terminal; print_ln;
8879 if start<limit then for k:=start to limit-1 do print(buffer[k]);
8880 first:=limit; prompt_input("=>"); {wait for user response}
8881 @.=>@>
8882 if last>first then
8883 begin for k:=first to last-1 do {move line down in buffer}
8884 buffer[k+start-first]:=buffer[k];
8885 limit:=start+last-first;
8886 end;
8887 end;
8888 end;
8889
8890 @ Since |get_next| is used so frequently in \TeX, it is convenient
8891 to define three related procedures that do a little more:
8892
8893 \yskip\hang|get_token| not only sets |cur_cmd| and |cur_chr|, it
8894 also sets |cur_tok|, a packed halfword version of the current token.
8895
8896 \yskip\hang|get_x_token|, meaning ``get an expanded token,'' is like
8897 |get_token|, but if the current token turns out to be a user-defined
8898 control sequence (i.e., a macro call), or a conditional,
8899 or something like \.{\\topmark} or \.{\\expandafter} or \.{\\csname},
8900 it is eliminated from the input by beginning the expansion of the macro
8901 or the evaluation of the conditional.
8902
8903 \yskip\hang|x_token| is like |get_x_token| except that it assumes that
8904 |get_next| has already been called.
8905
8906 \yskip\noindent
8907 In fact, these three procedures account for almost every use of |get_next|.
8908
8909 @ No new control sequences will be defined except during a call of
8910 |get_token|, or when \.{\\csname} compresses a token list, because
8911 |no_new_control_sequence| is always |true| at other times.
8912
8913 @p procedure get_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|}
8914 begin no_new_control_sequence:=false; get_next; no_new_control_sequence:=true;
8915 @^inner loop@>
8916 if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
8917 else cur_tok:=cs_token_flag+cur_cs;
8918 end;
8919
8920 @* \[25] Expanding the next token.
8921 Only a dozen or so command codes |>max_command| can possibly be returned by
8922 |get_next|; in increasing order, they are |undefined_cs|, |expand_after|,
8923 |no_expand|, |input|, |if_test|, |fi_or_else|, |cs_name|, |convert|, |the|,
8924 |top_bot_mark|, |call|, |long_call|, |outer_call|, |long_outer_call|, and
8925 |end_template|.{\emergencystretch=40pt\par}
8926
8927 The |expand| subroutine is used when |cur_cmd>max_command|. It removes a
8928 ``call'' or a conditional or one of the other special operations just
8929 listed. It follows that |expand| might invoke itself recursively. In all
8930 cases, |expand| destroys the current token, but it sets things up so that
8931 the next |get_next| will deliver the appropriate next token. The value of
8932 |cur_tok| need not be known when |expand| is called.
8933
8934 Since several of the basic scanning routines communicate via global variables,
8935 their values are saved as local variables of |expand| so that
8936 recursive calls don't invalidate them.
8937 @^recursion@>
8938
8939 @p@t\4@>@<Declare the procedure called |macro_call|@>@;@/
8940 @t\4@>@<Declare the procedure called |insert_relax|@>@;@/
8941 @t\4@>@<Declare \eTeX\ procedures for expanding@>@;@/
8942 procedure@?pass_text; forward;@t\2@>
8943 procedure@?start_input; forward;@t\2@>
8944 procedure@?conditional; forward;@t\2@>
8945 procedure@?get_x_token; forward;@t\2@>
8946 procedure@?conv_toks; forward;@t\2@>
8947 procedure@?ins_the_toks; forward;@t\2@>
8948 procedure expand;
8949 label reswitch;
8950 var t:halfword; {token that is being ``expanded after''}
8951 @!b:boolean; {keep track of nested csnames}
8952 @!p,@!q,@!r:pointer; {for list manipulation}
8953 @!j:0..buf_size; {index into |buffer|}
8954 @!cv_backup:integer; {to save the global quantity |cur_val|}
8955 @!cvl_backup,@!radix_backup,@!co_backup:small_number;
8956 {to save |cur_val_level|, etc.}
8957 @!backup_backup:pointer; {to save |link(backup_head)|}
8958 @!save_scanner_status:small_number; {temporary storage of |scanner_status|}
8959 begin cv_backup:=cur_val; cvl_backup:=cur_val_level; radix_backup:=radix;
8960 co_backup:=cur_order; backup_backup:=link(backup_head);
8961 reswitch:
8962 if cur_cmd<call then @<Expand a nonmacro@>
8963 else if cur_cmd<end_template then macro_call
8964 else @<Insert a token containing |frozen_endv|@>;
8965 cur_val:=cv_backup; cur_val_level:=cvl_backup; radix:=radix_backup;
8966 cur_order:=co_backup; link(backup_head):=backup_backup;
8967 end;
8968
8969 @ @<Glob...@>=
8970 @!is_in_csname: boolean;
8971
8972 @ @<Set init...@>=
8973 is_in_csname := false;
8974
8975 @ @<Expand a nonmacro@>=
8976 begin if tracing_commands>1 then show_cur_cmd_chr;
8977 case cur_cmd of
8978 top_bot_mark:@<Insert the \(a)appropriate mark text into the scanner@>;
8979 expand_after:if cur_chr=0 then @<Expand the token after the next token@>
8980 else @<Negate a boolean conditional and |goto reswitch|@>;
8981 no_expand: if cur_chr=0 then @<Suppress expansion of the next token@>
8982 else @<Implement \.{\\pdfprimitive}@>;
8983 cs_name:@<Manufacture a control sequence name@>;
8984 convert:conv_toks; {this procedure is discussed in Part 27 below}
8985 the:ins_the_toks; {this procedure is discussed in Part 27 below}
8986 if_test:conditional; {this procedure is discussed in Part 28 below}
8987 fi_or_else:@<Terminate the current conditional and skip to \.{\\fi}@>;
8988 input:@<Initiate or terminate input from a file@>;
8989 othercases @<Complain about an undefined macro@>
8990 endcases;
8991 end
8992
8993 @ It takes only a little shuffling to do what \TeX\ calls \.{\\expandafter}.
8994
8995 @<Expand the token after...@>=
8996 begin get_token; t:=cur_tok; get_token;
8997 if cur_cmd>max_command then expand@+else back_input;
8998 cur_tok:=t; back_input;
8999 end
9000
9001 @ The implementation of \.{\\noexpand} is a bit trickier, because it is
9002 necessary to insert a special `|dont_expand|' marker into \TeX's reading
9003 mechanism. This special marker is processed by |get_next|, but it does
9004 not slow down the inner loop.
9005
9006 Since \.{\\outer} macros might arise here, we must also
9007 clear the |scanner_status| temporarily.
9008
9009 @<Suppress expansion...@>=
9010 begin save_scanner_status:=scanner_status; scanner_status:=normal;
9011 get_token; scanner_status:=save_scanner_status; t:=cur_tok;
9012 back_input; {now |start| and |loc| point to the backed-up token |t|}
9013 if t>=cs_token_flag then
9014 begin p:=get_avail; info(p):=cs_token_flag+frozen_dont_expand;
9015 link(p):=loc; start:=p; loc:=p;
9016 end;
9017 end
9018
9019 @ The \.{\\pdfprimitive} handling. If the primitive meaning of the next
9020 token is an expandable command, it suffices to replace the current
9021 token with the primitive one and restart |expand|.
9022
9023 Otherwise, the token we just read has to be pushed back, as well
9024 as a token matching the internal form of \.{\\pdfprimitive}, that is
9025 sneaked in as an alternate form of |ignore_spaces|.
9026 @!@:pdfprimitive_}{\.{\\pdfprimitive} primitive (internalized)@>
9027
9028 Simply pushing back a token that matches the correct internal command
9029 does not work, because approach would not survive roundtripping to a
9030 temporary file.
9031
9032 @<Implement \.{\\pdfprimitive}@>=
9033 begin save_scanner_status := scanner_status; scanner_status:=normal;
9034 get_token; scanner_status:=save_scanner_status;
9035 if cur_cs < hash_base then
9036 cur_cs := prim_lookup(cur_cs-single_base)
9037 else
9038 cur_cs := prim_lookup(text(cur_cs));
9039 if cur_cs<>undefined_primitive then begin
9040 t := prim_eq_type(cur_cs);
9041 if t>max_command then begin
9042 cur_cmd := t;
9043 cur_chr := prim_equiv(cur_cs);
9044 cur_tok := (cur_cmd*@'400)+cur_chr;
9045 cur_cs := 0;
9046 goto reswitch;
9047 end
9048 else begin
9049 back_input; { now |loc| and |start| point to a one-item list }
9050 p:=get_avail; info(p):=cs_token_flag+frozen_primitive;
9051 link(p):=loc; loc:=p; start:=p;
9052 end;
9053 end;
9054 end
9055
9056 @ This block deals with unexpandable \.{\\primitive} appearing at a spot where
9057 an integer or an internal values should have been found. It fetches the
9058 next token then resets |cur_cmd|, |cur_cs|, and |cur_tok|, based on the
9059 primitive value of that token. No expansion takes place, because the
9060 next token may be all sorts of things. This could trigger further
9061 expansion creating new errors.
9062
9063 @<Reset |cur_tok| for unexpandable primitives, goto restart @>=
9064 begin
9065 get_token;
9066 if cur_cs < hash_base then
9067 cur_cs := prim_lookup(cur_cs-single_base)
9068 else
9069 cur_cs := prim_lookup(text(cur_cs));
9070 if cur_cs<>undefined_primitive then begin
9071 cur_cmd := prim_eq_type(cur_cs);
9072 cur_chr := prim_equiv(cur_cs);
9073 cur_cs := prim_eqtb_base+cur_cs;
9074 cur_tok := cs_token_flag+cur_cs;
9075 end
9076 else begin
9077 cur_cmd := relax;
9078 cur_chr := 0;
9079 cur_tok := cs_token_flag+frozen_relax;
9080 cur_cs := frozen_relax;
9081 end;
9082 goto restart;
9083 end
9084
9085 @ @<Complain about an undefined macro@>=
9086 begin print_err("Undefined control sequence");
9087 @.Undefined control sequence@>
9088 help5("The control sequence at the end of the top line")@/
9089 ("of your error message was never \def'ed. If you have")@/
9090 ("misspelled it (e.g., `\hobx'), type `I' and the correct")@/
9091 ("spelling (e.g., `I\hbox'). Otherwise just continue,")@/
9092 ("and I'll forget about whatever was undefined.");
9093 error;
9094 end
9095
9096 @ The |expand| procedure and some other routines that construct token
9097 lists find it convenient to use the following macros, which are valid only if
9098 the variables |p| and |q| are reserved for token-list building.
9099
9100 @d store_new_token(#)==begin q:=get_avail; link(p):=q; info(q):=#;
9101 p:=q; {|link(p)| is |null|}
9102 end
9103 @d fast_store_new_token(#)==begin fast_get_avail(q); link(p):=q; info(q):=#;
9104 p:=q; {|link(p)| is |null|}
9105 end
9106
9107 @ @<Manufacture a control...@>=
9108 begin r:=get_avail; p:=r; {head of the list of characters}
9109 b := is_in_csname; is_in_csname := true;
9110 repeat get_x_token;
9111 if cur_cs=0 then store_new_token(cur_tok);
9112 until cur_cs<>0;
9113 if cur_cmd<>end_cs_name then @<Complain about missing \.{\\endcsname}@>;
9114 is_in_csname := b;
9115 @<Look up the characters of list |r| in the hash table, and set |cur_cs|@>;
9116 flush_list(r);
9117 if eq_type(cur_cs)=undefined_cs then
9118 begin eq_define(cur_cs,relax,256); {N.B.: The |save_stack| might change}
9119 end; {the control sequence will now match `\.{\\relax}'}
9120 cur_tok:=cur_cs+cs_token_flag; back_input;
9121 end
9122
9123 @ @<Complain about missing \.{\\endcsname}@>=
9124 begin print_err("Missing "); print_esc("endcsname"); print(" inserted");
9125 @.Missing \\endcsname...@>
9126 help2("The control sequence marked <to be read again> should")@/
9127 ("not appear between \csname and \endcsname.");
9128 back_error;
9129 end
9130
9131 @ @<Look up the characters of list |r| in the hash table...@>=
9132 j:=first; p:=link(r);
9133 while p<>null do
9134 begin if j>=max_buf_stack then
9135 begin max_buf_stack:=j+1;
9136 if max_buf_stack=buf_size then
9137 overflow("buffer size",buf_size);
9138 @:TeX capacity exceeded buffer size}{\quad buffer size@>
9139 end;
9140 buffer[j]:=info(p) mod @'400; incr(j); p:=link(p);
9141 end;
9142 if j>first+1 then
9143 begin no_new_control_sequence:=false; cur_cs:=id_lookup(first,j-first);
9144 no_new_control_sequence:=true;
9145 end
9146 else if j=first then cur_cs:=null_cs {the list is empty}
9147 else cur_cs:=single_base+buffer[first] {the list has length one}
9148
9149 @ An |end_template| command is effectively changed to an |endv| command
9150 by the following code. (The reason for this is discussed below; the
9151 |frozen_end_template| at the end of the template has passed the
9152 |check_outer_validity| test, so its mission of error detection has been
9153 accomplished.)
9154
9155 @<Insert a token containing |frozen_endv|@>=
9156 begin cur_tok:=cs_token_flag+frozen_endv; back_input;
9157 end
9158
9159 @ The processing of \.{\\input} involves the |start_input| subroutine,
9160 which will be declared later; the processing of \.{\\endinput} is trivial.
9161
9162 @<Put each...@>=
9163 primitive("input",input,0);@/
9164 @!@:input_}{\.{\\input} primitive@>
9165 primitive("endinput",input,1);@/
9166 @!@:end_input_}{\.{\\endinput} primitive@>
9167
9168 @ @<Cases of |print_cmd_chr|...@>=
9169 input: if chr_code=0 then print_esc("input")
9170 @/@<Cases of |input| for |print_cmd_chr|@>@/
9171 else print_esc("endinput");
9172
9173 @ @<Initiate or terminate input...@>=
9174 if cur_chr=1 then force_eof:=true
9175 @/@<Cases for |input|@>@/
9176 else if name_in_progress then insert_relax
9177 else start_input
9178
9179 @ Sometimes the expansion looks too far ahead, so we want to insert
9180 a harmless \.{\\relax} into the user's input.
9181
9182 @<Declare the procedure called |insert_relax|@>=
9183 procedure insert_relax;
9184 begin cur_tok:=cs_token_flag+cur_cs; back_input;
9185 cur_tok:=cs_token_flag+frozen_relax; back_input; token_type:=inserted;
9186 end;
9187
9188 @ Here is a recursive procedure that is \TeX's usual way to get the
9189 next token of input. It has been slightly optimized to take account of
9190 common cases.
9191
9192 @p procedure get_x_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|,
9193 and expands macros}
9194 label restart,done;
9195 begin restart: get_next;
9196 @^inner loop@>
9197 if cur_cmd<=max_command then goto done;
9198 if cur_cmd>=call then
9199 if cur_cmd<end_template then macro_call
9200 else begin cur_cs:=frozen_endv; cur_cmd:=endv;
9201 goto done; {|cur_chr=null_list|}
9202 end
9203 else expand;
9204 goto restart;
9205 done: if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
9206 else cur_tok:=cs_token_flag+cur_cs;
9207 end;
9208
9209 @ The |get_x_token| procedure is essentially equivalent to two consecutive
9210 procedure calls: |get_next; x_token|.
9211
9212 @p procedure x_token; {|get_x_token| without the initial |get_next|}
9213 begin while cur_cmd>max_command do
9214 begin expand;
9215 get_next;
9216 end;
9217 if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
9218 else cur_tok:=cs_token_flag+cur_cs;
9219 end;
9220
9221 @ A control sequence that has been \.{\\def}'ed by the user is expanded by
9222 \TeX's |macro_call| procedure.
9223
9224 Before we get into the details of |macro_call|, however, let's consider the
9225 treatment of primitives like \.{\\topmark}, since they are essentially
9226 macros without parameters. The token lists for such marks are kept in a
9227 global array of five pointers; we refer to the individual entries of this
9228 array by symbolic names |top_mark|, etc. The value of |top_mark| is either
9229 |null| or a pointer to the reference count of a token list.
9230
9231 @d marks_code==5 {add this for \.{\\topmarks} etc.}
9232 @#
9233 @d top_mark_code=0 {the mark in effect at the previous page break}
9234 @d first_mark_code=1 {the first mark between |top_mark| and |bot_mark|}
9235 @d bot_mark_code=2 {the mark in effect at the current page break}
9236 @d split_first_mark_code=3 {the first mark found by \.{\\vsplit}}
9237 @d split_bot_mark_code=4 {the last mark found by \.{\\vsplit}}
9238 @d top_mark==cur_mark[top_mark_code]
9239 @d first_mark==cur_mark[first_mark_code]
9240 @d bot_mark==cur_mark[bot_mark_code]
9241 @d split_first_mark==cur_mark[split_first_mark_code]
9242 @d split_bot_mark==cur_mark[split_bot_mark_code]
9243
9244 @<Glob...@>=
9245 @!cur_mark:array[top_mark_code..split_bot_mark_code] of pointer;
9246 {token lists for marks}
9247
9248 @ @<Set init...@>=
9249 top_mark:=null; first_mark:=null; bot_mark:=null;
9250 split_first_mark:=null; split_bot_mark:=null;
9251
9252 @ @<Put each...@>=
9253 primitive("topmark",top_bot_mark,top_mark_code);
9254 @!@:top_mark_}{\.{\\topmark} primitive@>
9255 primitive("firstmark",top_bot_mark,first_mark_code);
9256 @!@:first_mark_}{\.{\\firstmark} primitive@>
9257 primitive("botmark",top_bot_mark,bot_mark_code);
9258 @!@:bot_mark_}{\.{\\botmark} primitive@>
9259 primitive("splitfirstmark",top_bot_mark,split_first_mark_code);
9260 @!@:split_first_mark_}{\.{\\splitfirstmark} primitive@>
9261 primitive("splitbotmark",top_bot_mark,split_bot_mark_code);
9262 @!@:split_bot_mark_}{\.{\\splitbotmark} primitive@>
9263
9264 @ @<Cases of |print_cmd_chr|...@>=
9265 top_bot_mark: begin case (chr_code mod marks_code) of
9266 first_mark_code: print_esc("firstmark");
9267 bot_mark_code: print_esc("botmark");
9268 split_first_mark_code: print_esc("splitfirstmark");
9269 split_bot_mark_code: print_esc("splitbotmark");
9270 othercases print_esc("topmark")
9271 endcases;
9272 if chr_code>=marks_code then print_char("s");
9273 end;
9274
9275 @ The following code is activated when |cur_cmd=top_bot_mark| and
9276 when |cur_chr| is a code like |top_mark_code|.
9277
9278 @<Insert the \(a)appropriate mark text into the scanner@>=
9279 begin t:=cur_chr mod marks_code;
9280 if cur_chr>=marks_code then scan_register_num@+else cur_val:=0;
9281 if cur_val=0 then cur_ptr:=cur_mark[t]
9282 else @<Compute the mark pointer for mark type |t| and class |cur_val|@>;
9283 if cur_ptr<>null then begin_token_list(cur_ptr,mark_text);
9284 end
9285
9286 @ Now let's consider |macro_call| itself, which is invoked when \TeX\ is
9287 scanning a control sequence whose |cur_cmd| is either |call|, |long_call|,
9288 |outer_call|, or |long_outer_call|. The control sequence definition
9289 appears in the token list whose reference count is in location |cur_chr|
9290 of |mem|.
9291
9292 The global variable |long_state| will be set to |call| or to |long_call|,
9293 depending on whether or not the control sequence disallows \.{\\par}
9294 in its parameters. The |get_next| routine will set |long_state| to
9295 |outer_call| and emit \.{\\par}, if a file ends or if an \.{\\outer}
9296 control sequence occurs in the midst of an argument.
9297
9298 @<Glob...@>=
9299 @!long_state:call..long_outer_call; {governs the acceptance of \.{\\par}}
9300
9301 @ The parameters, if any, must be scanned before the macro is expanded.
9302 Parameters are token lists without reference counts. They are placed on
9303 an auxiliary stack called |pstack| while they are being scanned, since
9304 the |param_stack| may be losing entries during the matching process.
9305 (Note that |param_stack| can't be gaining entries, since |macro_call| is
9306 the only routine that puts anything onto |param_stack|, and it
9307 is not recursive.)
9308
9309 @<Glob...@>=
9310 @!pstack:array[0..8] of pointer; {arguments supplied to a macro}
9311
9312 @ After parameter scanning is complete, the parameters are moved to the
9313 |param_stack|. Then the macro body is fed to the scanner; in other words,
9314 |macro_call| places the defined text of the control sequence at the
9315 top of\/ \TeX's input stack, so that |get_next| will proceed to read it
9316 next.
9317
9318 The global variable |cur_cs| contains the |eqtb| address of the control sequence
9319 being expanded, when |macro_call| begins. If this control sequence has not been
9320 declared \.{\\long}, i.e., if its command code in the |eq_type| field is
9321 not |long_call| or |long_outer_call|, its parameters are not allowed to contain
9322 the control sequence \.{\\par}. If an illegal \.{\\par} appears, the macro
9323 call is aborted, and the \.{\\par} will be rescanned.
9324
9325 @<Declare the procedure called |macro_call|@>=
9326 procedure macro_call; {invokes a user-defined control sequence}
9327 label exit, continue, done, done1, found;
9328 var r:pointer; {current node in the macro's token list}
9329 @!p:pointer; {current node in parameter token list being built}
9330 @!q:pointer; {new node being put into the token list}
9331 @!s:pointer; {backup pointer for parameter matching}
9332 @!t:pointer; {cycle pointer for backup recovery}
9333 @!u,@!v:pointer; {auxiliary pointers for backup recovery}
9334 @!rbrace_ptr:pointer; {one step before the last |right_brace| token}
9335 @!n:small_number; {the number of parameters scanned}
9336 @!unbalance:halfword; {unmatched left braces in current parameter}
9337 @!m:halfword; {the number of tokens or groups (usually)}
9338 @!ref_count:pointer; {start of the token list}
9339 @!save_scanner_status:small_number; {|scanner_status| upon entry}
9340 @!save_warning_index:pointer; {|warning_index| upon entry}
9341 @!match_chr:ASCII_code; {character used in parameter}
9342 begin save_scanner_status:=scanner_status; save_warning_index:=warning_index;
9343 warning_index:=cur_cs; ref_count:=cur_chr; r:=link(ref_count); n:=0;
9344 if tracing_macros>0 then @<Show the text of the macro being expanded@>;
9345 if info(r)=protected_token then r:=link(r);
9346 if info(r)<>end_match_token then
9347 @<Scan the parameters and make |link(r)| point to the macro body; but
9348 |return| if an illegal \.{\\par} is detected@>;
9349 @<Feed the macro body and its parameters to the scanner@>;
9350 exit:scanner_status:=save_scanner_status; warning_index:=save_warning_index;
9351 end;
9352
9353 @ Before we put a new token list on the input stack, it is wise to clean off
9354 all token lists that have recently been depleted. Then a user macro that ends
9355 with a call to itself will not require unbounded stack space.
9356
9357 @<Feed the macro body and its parameters to the scanner@>=
9358 while (state=token_list)and(loc=null)and(token_type<>v_template) do
9359 end_token_list; {conserve stack space}
9360 begin_token_list(ref_count,macro); name:=warning_index; loc:=link(r);
9361 if n>0 then
9362 begin if param_ptr+n>max_param_stack then
9363 begin max_param_stack:=param_ptr+n;
9364 if max_param_stack>param_size then
9365 overflow("parameter stack size",param_size);
9366 @:TeX capacity exceeded parameter stack size}{\quad parameter stack size@>
9367 end;
9368 for m:=0 to n-1 do param_stack[param_ptr+m]:=pstack[m];
9369 param_ptr:=param_ptr+n;
9370 end
9371
9372 @ At this point, the reader will find it advisable to review the explanation
9373 of token list format that was presented earlier, since many aspects of that
9374 format are of importance chiefly in the |macro_call| routine.
9375
9376 The token list might begin with a string of compulsory tokens before the
9377 first |match| or |end_match|. In that case the macro name is supposed to be
9378 followed by those tokens; the following program will set |s=null| to
9379 represent this restriction. Otherwise |s| will be set to the first token of
9380 a string that will delimit the next parameter.
9381
9382 @<Scan the parameters and make |link(r)| point to the macro body...@>=
9383 begin scanner_status:=matching; unbalance:=0;
9384 long_state:=eq_type(cur_cs);
9385 if long_state>=outer_call then long_state:=long_state-2;
9386 repeat link(temp_head):=null;
9387 if (info(r)>match_token+255)or(info(r)<match_token) then s:=null
9388 else begin match_chr:=info(r)-match_token; s:=link(r); r:=s;
9389 p:=temp_head; m:=0;
9390 end;
9391 @<Scan a parameter until its delimiter string has been found; or, if |s=null|,
9392 simply scan the delimiter string@>;@/
9393 {now |info(r)| is a token whose command code is either |match| or |end_match|}
9394 until info(r)=end_match_token;
9395 end
9396
9397 @ If |info(r)| is a |match| or |end_match| command, it cannot be equal to
9398 any token found by |get_token|. Therefore an undelimited parameter---i.e.,
9399 a |match| that is immediately followed by |match| or |end_match|---will
9400 always fail the test `|cur_tok=info(r)|' in the following algorithm.
9401
9402 @<Scan a parameter until its delimiter string has been found; or, ...@>=
9403 continue: get_token; {set |cur_tok| to the next token of input}
9404 if cur_tok=info(r) then
9405 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been
9406 fully matched, otherwise |goto continue|@>;
9407 @<Contribute the recently matched tokens to the current parameter, and
9408 |goto continue| if a partial match is still in effect;
9409 but abort if |s=null|@>;
9410 if cur_tok=par_token then if long_state<>long_call then
9411 @<Report a runaway argument and abort@>;
9412 if cur_tok<right_brace_limit then
9413 if cur_tok<left_brace_limit then
9414 @<Contribute an entire group to the current parameter@>
9415 else @<Report an extra right brace and |goto continue|@>
9416 else @<Store the current token, but |goto continue| if it is
9417 a blank space that would become an undelimited parameter@>;
9418 incr(m);
9419 if info(r)>end_match_token then goto continue;
9420 if info(r)<match_token then goto continue;
9421 found: if s<>null then @<Tidy up the parameter just scanned, and tuck it away@>
9422
9423 @ @<Store the current token, but |goto continue| if it is...@>=
9424 begin if cur_tok=space_token then
9425 if info(r)<=end_match_token then
9426 if info(r)>=match_token then goto continue;
9427 store_new_token(cur_tok);
9428 end
9429
9430 @ A slightly subtle point arises here: When the parameter delimiter ends
9431 with `\.{\#\{}', the token list will have a left brace both before and
9432 after the |end_match|\kern-.4pt. Only one of these should affect the
9433 |align_state|, but both will be scanned, so we must make a correction.
9434
9435 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully...@>=
9436 begin r:=link(r);
9437 if (info(r)>=match_token)and(info(r)<=end_match_token) then
9438 begin if cur_tok<left_brace_limit then decr(align_state);
9439 goto found;
9440 end
9441 else goto continue;
9442 end
9443
9444 @ @<Report an extra right brace and |goto continue|@>=
9445 begin back_input; print_err("Argument of "); sprint_cs(warning_index);
9446 @.Argument of \\x has...@>
9447 print(" has an extra }");
9448 help6("I've run across a `}' that doesn't seem to match anything.")@/
9449 ("For example, `\def\a#1{...}' and `\a}' would produce")@/
9450 ("this error. If you simply proceed now, the `\par' that")@/
9451 ("I've just inserted will cause me to report a runaway")@/
9452 ("argument that might be the root of the problem. But if")@/
9453 ("your `}' was spurious, just type `2' and it will go away.");
9454 incr(align_state); long_state:=call; cur_tok:=par_token; ins_error;
9455 goto continue;
9456 end {a white lie; the \.{\\par} won't always trigger a runaway}
9457
9458 @ If |long_state=outer_call|, a runaway argument has already been reported.
9459
9460 @<Report a runaway argument and abort@>=
9461 begin if long_state=call then
9462 begin runaway; print_err("Paragraph ended before ");
9463 @.Paragraph ended before...@>
9464 sprint_cs(warning_index); print(" was complete");
9465 help3("I suspect you've forgotten a `}', causing me to apply this")@/
9466 ("control sequence to too much text. How can we recover?")@/
9467 ("My plan is to forget the whole thing and hope for the best.");
9468 back_error;
9469 end;
9470 pstack[n]:=link(temp_head); align_state:=align_state-unbalance;
9471 for m:=0 to n do flush_list(pstack[m]);
9472 return;
9473 end
9474
9475 @ When the following code becomes active, we have matched tokens from |s| to
9476 the predecessor of |r|, and we have found that |cur_tok<>info(r)|. An
9477 interesting situation now presents itself: If the parameter is to be
9478 delimited by a string such as `\.{ab}', and if we have scanned `\.{aa}',
9479 we want to contribute one `\.a' to the current parameter and resume
9480 looking for a `\.b'. The program must account for such partial matches and
9481 for others that can be quite complex. But most of the time we have |s=r|
9482 and nothing needs to be done.
9483
9484 Incidentally, it is possible for \.{\\par} tokens to sneak in to certain
9485 parameters of non-\.{\\long} macros. For example, consider a case like
9486 `\.{\\def\\a\#1\\par!\{...\}}' where the first \.{\\par} is not followed
9487 by an exclamation point. In such situations it does not seem appropriate
9488 to prohibit the \.{\\par}, so \TeX\ keeps quiet about this bending of
9489 the rules.
9490
9491 @<Contribute the recently matched tokens to the current parameter...@>=
9492 if s<>r then
9493 if s=null then @<Report an improper use of the macro and abort@>
9494 else begin t:=s;
9495 repeat store_new_token(info(t)); incr(m); u:=link(t); v:=s;
9496 loop@+ begin if u=r then
9497 if cur_tok<>info(v) then goto done
9498 else begin r:=link(v); goto continue;
9499 end;
9500 if info(u)<>info(v) then goto done;
9501 u:=link(u); v:=link(v);
9502 end;
9503 done: t:=link(t);
9504 until t=r;
9505 r:=s; {at this point, no tokens are recently matched}
9506 end
9507
9508 @ @<Report an improper use...@>=
9509 begin print_err("Use of "); sprint_cs(warning_index);
9510 @.Use of x doesn't match...@>
9511 print(" doesn't match its definition");
9512 help4("If you say, e.g., `\def\a1{...}', then you must always")@/
9513 ("put `1' after `\a', since control sequence names are")@/
9514 ("made up of letters only. The macro here has not been")@/
9515 ("followed by the required stuff, so I'm ignoring it.");
9516 error; return;
9517 end
9518
9519 @ @<Contribute an entire group to the current parameter@>=
9520 begin unbalance:=1;
9521 @^inner loop@>
9522 loop@+ begin fast_store_new_token(cur_tok); get_token;
9523 if cur_tok=par_token then if long_state<>long_call then
9524 @<Report a runaway argument and abort@>;
9525 if cur_tok<right_brace_limit then
9526 if cur_tok<left_brace_limit then incr(unbalance)
9527 else begin decr(unbalance);
9528 if unbalance=0 then goto done1;
9529 end;
9530 end;
9531 done1: rbrace_ptr:=p; store_new_token(cur_tok);
9532 end
9533
9534 @ If the parameter consists of a single group enclosed in braces, we must
9535 strip off the enclosing braces. That's why |rbrace_ptr| was introduced.
9536
9537 @<Tidy up the parameter just scanned, and tuck it away@>=
9538 begin if (m=1)and(info(p)<right_brace_limit) then
9539 begin link(rbrace_ptr):=null; free_avail(p);
9540 p:=link(temp_head); pstack[n]:=link(p); free_avail(p);
9541 end
9542 else pstack[n]:=link(temp_head);
9543 incr(n);
9544 if tracing_macros>0 then
9545 begin begin_diagnostic; print_nl(match_chr); print_int(n);
9546 print("<-"); show_token_list(pstack[n-1],null,1000);
9547 end_diagnostic(false);
9548 end;
9549 end
9550
9551 @ @<Show the text of the macro being expanded@>=
9552 begin begin_diagnostic; print_ln; print_cs(warning_index);
9553 token_show(ref_count); end_diagnostic(false);
9554 end
9555
9556 @* \[26] Basic scanning subroutines.
9557 Let's turn now to some procedures that \TeX\ calls upon frequently to digest
9558 certain kinds of patterns in the input. Most of these are quite simple;
9559 some are quite elaborate. Almost all of the routines call |get_x_token|,
9560 which can cause them to be invoked recursively.
9561 @^stomach@>
9562 @^recursion@>
9563
9564 @ The |scan_left_brace| routine is called when a left brace is supposed to be
9565 the next non-blank token. (The term ``left brace'' means, more precisely,
9566 a character whose catcode is |left_brace|.) \TeX\ allows \.{\\relax} to
9567 appear before the |left_brace|.
9568
9569 @p procedure scan_left_brace; {reads a mandatory |left_brace|}
9570 begin @<Get the next non-blank non-relax non-call token@>;
9571 if cur_cmd<>left_brace then
9572 begin print_err("Missing { inserted");
9573 @.Missing \{ inserted@>
9574 help4("A left brace was mandatory here, so I've put one in.")@/
9575 ("You might want to delete and/or insert some corrections")@/
9576 ("so that I will find a matching right brace soon.")@/
9577 ("(If you're confused by all this, try typing `I}' now.)");
9578 back_error; cur_tok:=left_brace_token+"{"; cur_cmd:=left_brace;
9579 cur_chr:="{"; incr(align_state);
9580 end;
9581 end;
9582
9583 @ @<Get the next non-blank non-relax non-call token@>=
9584 repeat get_x_token;
9585 until (cur_cmd<>spacer)and(cur_cmd<>relax)
9586
9587 @ The |scan_optional_equals| routine looks for an optional `\.=' sign preceded
9588 by optional spaces; `\.{\\relax}' is not ignored here.
9589
9590 @p procedure scan_optional_equals;
9591 begin @<Get the next non-blank non-call token@>;
9592 if cur_tok<>other_token+"=" then back_input;
9593 end;
9594
9595 @ @<Get the next non-blank non-call token@>=
9596 repeat get_x_token;
9597 until cur_cmd<>spacer
9598
9599 @ In case you are getting bored, here is a slightly less trivial routine:
9600 Given a string of lowercase letters, like `\.{pt}' or `\.{plus}' or
9601 `\.{width}', the |scan_keyword| routine checks to see whether the next
9602 tokens of input match this string. The match must be exact, except that
9603 uppercase letters will match their lowercase counterparts; uppercase
9604 equivalents are determined by subtracting |"a"-"A"|, rather than using the
9605 |uc_code| table, since \TeX\ uses this routine only for its own limited
9606 set of keywords.
9607
9608 If a match is found, the characters are effectively removed from the input
9609 and |true| is returned. Otherwise |false| is returned, and the input
9610 is left essentially unchanged (except for the fact that some macros
9611 may have been expanded, etc.).
9612 @^inner loop@>
9613
9614 @p function scan_keyword(@!s:str_number):boolean; {look for a given string}
9615 label exit;
9616 var p:pointer; {tail of the backup list}
9617 @!q:pointer; {new node being added to the token list via |store_new_token|}
9618 @!k:pool_pointer; {index into |str_pool|}
9619 @!save_cur_cs:pointer; {to save |cur_cs|}
9620 begin p:=backup_head; link(p):=null; k:=str_start[s];
9621 save_cur_cs:=cur_cs;
9622 while k<str_start[s+1] do
9623 begin get_x_token; {recursion is possible here}
9624 @^recursion@>
9625 if (cur_cs=0)and@|
9626 ((cur_chr=so(str_pool[k]))or(cur_chr=so(str_pool[k])-"a"+"A")) then
9627 begin store_new_token(cur_tok); incr(k);
9628 end
9629 else if (cur_cmd<>spacer)or(p<>backup_head) then
9630 begin back_input;
9631 if p<>backup_head then back_list(link(backup_head));
9632 cur_cs:=save_cur_cs;
9633 scan_keyword:=false; return;
9634 end;
9635 end;
9636 flush_list(link(backup_head)); scan_keyword:=true;
9637 exit:end;
9638
9639 @ Here is a procedure that sounds an alarm when mu and non-mu units
9640 are being switched.
9641
9642 @p procedure mu_error;
9643 begin print_err("Incompatible glue units");
9644 @.Incompatible glue units@>
9645 help1("I'm going to assume that 1mu=1pt when they're mixed.");
9646 error;
9647 end;
9648
9649 @ The next routine `|scan_something_internal|' is used to fetch internal
9650 numeric quantities like `\.{\\hsize}', and also to handle the `\.{\\the}'
9651 when expanding constructions like `\.{\\the\\toks0}' and
9652 `\.{\\the\\baselineskip}'. Soon we will be considering the |scan_int|
9653 procedure, which calls |scan_something_internal|; on the other hand,
9654 |scan_something_internal| also calls |scan_int|, for constructions like
9655 `\.{\\catcode\`\\\$}' or `\.{\\fontdimen} \.3 \.{\\ff}'. So we
9656 have to declare |scan_int| as a |forward| procedure. A few other
9657 procedures are also declared at this point.
9658
9659 @p procedure@?scan_int; forward; {scans an integer value}
9660 @t\4\4@>@<Declare procedures that scan restricted classes of integers@>@;
9661 @t\4\4@>@<Declare \eTeX\ procedures for scanning@>@;
9662 @t\4\4@>@<Declare procedures that scan font-related stuff@>
9663
9664 @ \TeX\ doesn't know exactly what to expect when |scan_something_internal|
9665 begins. For example, an integer or dimension or glue value could occur
9666 immediately after `\.{\\hskip}'; and one can even say \.{\\the} with
9667 respect to token lists in constructions like
9668 `\.{\\xdef\\o\{\\the\\output\}}'. On the other hand, only integers are
9669 allowed after a construction like `\.{\\count}'. To handle the various
9670 possibilities, |scan_something_internal| has a |level| parameter, which
9671 tells the ``highest'' kind of quantity that |scan_something_internal| is
9672 allowed to produce. Six levels are distinguished, namely |int_val|,
9673 |dimen_val|, |glue_val|, |mu_val|, |ident_val|, and |tok_val|.
9674
9675 The output of |scan_something_internal| (and of the other routines
9676 |scan_int|, |scan_dimen|, and |scan_glue| below) is put into the global
9677 variable |cur_val|, and its level is put into |cur_val_level|. The highest
9678 values of |cur_val_level| are special: |mu_val| is used only when
9679 |cur_val| points to something in a ``muskip'' register, or to one of the
9680 three parameters \.{\\thinmuskip}, \.{\\medmuskip}, \.{\\thickmuskip};
9681 |ident_val| is used only when |cur_val| points to a font identifier;
9682 |tok_val| is used only when |cur_val| points to |null| or to the reference
9683 count of a token list. The last two cases are allowed only when
9684 |scan_something_internal| is called with |level=tok_val|.
9685
9686 If the output is glue, |cur_val| will point to a glue specification, and
9687 the reference count of that glue will have been updated to reflect this
9688 reference; if the output is a nonempty token list, |cur_val| will point to
9689 its reference count, but in this case the count will not have been updated.
9690 Otherwise |cur_val| will contain the integer or scaled value in question.
9691
9692 @d int_val=0 {integer values}
9693 @d dimen_val=1 {dimension values}
9694 @d glue_val=2 {glue specifications}
9695 @d mu_val=3 {math glue specifications}
9696 @d ident_val=4 {font identifier}
9697 @d tok_val=5 {token lists}
9698
9699 @<Glob...@>=
9700 @!cur_val:integer; {value returned by numeric scanners}
9701 @!cur_val_level:int_val..tok_val; {the ``level'' of this value}
9702
9703 @ The hash table is initialized with `\.{\\count}', `\.{\\dimen}', `\.{\\skip}',
9704 and `\.{\\muskip}' all having |register| as their command code; they are
9705 distinguished by the |chr_code|, which is either |int_val|, |dimen_val|,
9706 |glue_val|, or |mu_val| more than |mem_bot| (dynamic variable-size nodes
9707 cannot have these values)
9708
9709 @<Put each...@>=
9710 primitive("count",register,mem_bot+int_val);
9711 @!@:count_}{\.{\\count} primitive@>
9712 primitive("dimen",register,mem_bot+dimen_val);
9713 @!@:dimen_}{\.{\\dimen} primitive@>
9714 primitive("skip",register,mem_bot+glue_val);
9715 @!@:skip_}{\.{\\skip} primitive@>
9716 primitive("muskip",register,mem_bot+mu_val);
9717 @!@:mu_skip_}{\.{\\muskip} primitive@>
9718
9719 @ @<Cases of |print_cmd_chr|...@>=
9720 register: @<Cases of |register| for |print_cmd_chr|@>;
9721
9722 @ OK, we're ready for |scan_something_internal| itself. A second parameter,
9723 |negative|, is set |true| if the value that is found should be negated.
9724 It is assumed that |cur_cmd| and |cur_chr| represent the first token of
9725 the internal quantity to be scanned; an error will be signalled if
9726 |cur_cmd<min_internal| or |cur_cmd>max_internal|.
9727
9728 @d scanned_result_end(#)==cur_val_level:=#;@+end
9729 @d scanned_result(#)==@+begin cur_val:=#;scanned_result_end
9730
9731 @p procedure scan_something_internal(@!level:small_number;@!negative:boolean);
9732 {fetch an internal parameter}
9733 label exit, restart;
9734 var m:halfword; {|chr_code| part of the operand token}
9735 n, k: integer; {accumulators}
9736 @!q,@!r:pointer; {general purpose indices}
9737 @!tx:pointer; {effective tail node}
9738 @!i:four_quarters; {character info}
9739 @!p:0..nest_size; {index into |nest|}
9740 begin restart: m:=cur_chr;
9741 case cur_cmd of
9742 def_code: @<Fetch a character code from some table@>;
9743 toks_register,assign_toks,def_family,set_font,def_font,letterspace_font,pdf_copy_font: @<Fetch a token list or
9744 font identifier, provided that |level=tok_val|@>;
9745 assign_int: scanned_result(eqtb[m].int)(int_val);
9746 assign_dimen: scanned_result(eqtb[m].sc)(dimen_val);
9747 assign_glue: scanned_result(equiv(m))(glue_val);
9748 assign_mu_glue: scanned_result(equiv(m))(mu_val);
9749 set_aux: @<Fetch the |space_factor| or the |prev_depth|@>;
9750 set_prev_graf: @<Fetch the |prev_graf|@>;
9751 set_page_int:@<Fetch the |dead_cycles| or the |insert_penalties|@>;
9752 set_page_dimen: @<Fetch something on the |page_so_far|@>;
9753 set_shape: @<Fetch the |par_shape| size@>;
9754 set_box_dimen: @<Fetch a box dimension@>;
9755 char_given,math_given: scanned_result(cur_chr)(int_val);
9756 assign_font_dimen: @<Fetch a font dimension@>;
9757 assign_font_int: @<Fetch a font integer@>;
9758 register: @<Fetch a register@>;
9759 last_item: @<Fetch an item in the current node, if appropriate@>;
9760 ignore_spaces: {trap unexpandable primitives}
9761 if cur_chr=1 then @<Reset |cur_tok| for unexpandable primitives, goto restart@>;
9762 othercases @<Complain that \.{\\the} can't do this; give zero result@>
9763 endcases;@/
9764 while cur_val_level>level do @<Convert \(c)|cur_val| to a lower level@>;
9765 @<Fix the reference count, if any, and negate |cur_val| if |negative|@>;
9766 exit:end;
9767
9768 @ @<Fetch a character code from some table@>=
9769 begin scan_char_num;
9770 if m=math_code_base then scanned_result(ho(math_code(cur_val)))(int_val)
9771 else if m<math_code_base then scanned_result(equiv(m+cur_val))(int_val)
9772 else scanned_result(eqtb[m+cur_val].int)(int_val);
9773 end
9774
9775 @ @<Fetch a token list...@>=
9776 if level<>tok_val then
9777 begin print_err("Missing number, treated as zero");
9778 @.Missing number...@>
9779 help3("A number should have been here; I inserted `0'.")@/
9780 ("(If you can't figure out why I needed to see a number,")@/
9781 ("look up `weird error' in the index to The TeXbook.)");
9782 @:TeXbook}{\sl The \TeX book@>
9783 back_error; scanned_result(0)(dimen_val);
9784 end
9785 else if cur_cmd<=assign_toks then
9786 begin if cur_cmd<assign_toks then {|cur_cmd=toks_register|}
9787 if m=mem_bot then
9788 begin scan_register_num;
9789 if cur_val<256 then cur_val:=equiv(toks_base+cur_val)
9790 else begin find_sa_element(tok_val,cur_val,false);
9791 if cur_ptr=null then cur_val:=null
9792 else cur_val:=sa_ptr(cur_ptr);
9793 end;
9794 end
9795 else cur_val:=sa_ptr(m)
9796 else cur_val:=equiv(m);
9797 cur_val_level:=tok_val;
9798 end
9799 else begin back_input; scan_font_ident;
9800 scanned_result(font_id_base+cur_val)(ident_val);
9801 end
9802
9803 @ Users refer to `\.{\\the\\spacefactor}' only in horizontal
9804 mode, and to `\.{\\the\\prevdepth}' only in vertical mode; so we put the
9805 associated mode in the modifier part of the |set_aux| command.
9806 The |set_page_int| command has modifier 0 or 1, for `\.{\\deadcycles}' and
9807 `\.{\\insertpenalties}', respectively. The |set_box_dimen| command is
9808 modified by either |width_offset|, |height_offset|, or |depth_offset|.
9809 And the |last_item| command is modified by either |int_val|, |dimen_val|,
9810 |glue_val|, |input_line_no_code|, or |badness_code|.
9811 \pdfTeX\ adds the codes for its extensions: |pdftex_version_code|, \dots.
9812 \eTeX\ inserts |last_node_type_code| after |glue_val| and adds
9813 the codes for its extensions: |eTeX_version_code|, \dots.
9814
9815 @d last_node_type_code=glue_val+1 {code for \.{\\lastnodetype}}
9816 @d input_line_no_code=glue_val+2 {code for \.{\\inputlineno}}
9817 @d badness_code=input_line_no_code+1 {code for \.{\\badness}}
9818 @#
9819 @d pdftex_first_rint_code = badness_code + 1 {base for \pdfTeX's command codes}
9820 @d pdftex_version_code = pdftex_first_rint_code + 0 {code for \.{\\pdftexversion}}
9821 @d pdf_last_obj_code = pdftex_first_rint_code + 1 {code for \.{\\pdflastobj}}
9822 @d pdf_last_xform_code = pdftex_first_rint_code + 2 {code for \.{\\pdflastxform}}
9823 @d pdf_last_ximage_code = pdftex_first_rint_code + 3 {code for \.{\\pdflastximage}}
9824 @d pdf_last_ximage_pages_code = pdftex_first_rint_code + 4 {code for \.{\\pdflastximagepages}}
9825 @d pdf_last_annot_code = pdftex_first_rint_code + 5 {code for \.{\\pdflastannot}}
9826 @d pdf_last_x_pos_code = pdftex_first_rint_code + 6 {code for \.{\\pdflastxpos}}
9827 @d pdf_last_y_pos_code = pdftex_first_rint_code + 7 {code for \.{\\pdflastypos}}
9828 @d pdf_retval_code = pdftex_first_rint_code + 8 {global multi-purpose return value}
9829 @d pdf_last_ximage_colordepth_code = pdftex_first_rint_code + 9 {code for \.{\\pdflastximagecolordepth}}
9830 @d elapsed_time_code = pdftex_first_rint_code + 10 {code for \.{\\pdfelapsedtime}}
9831 @d pdf_shell_escape_code = pdftex_first_rint_code + 11 {code for \.{\\pdfshellescape}}
9832 @d random_seed_code = pdftex_first_rint_code + 12 {code for \.{\\pdfrandomseed}}
9833 @d pdf_last_link_code = pdftex_first_rint_code + 13 {code for \.{\\pdflastlink}}
9834 @d pdftex_last_item_codes = pdftex_first_rint_code + 13 {end of \pdfTeX's command codes}
9835 @#
9836 @d eTeX_int=pdftex_last_item_codes+1 {first of \eTeX\ codes for integers}
9837 @d eTeX_dim=eTeX_int+8 {first of \eTeX\ codes for dimensions}
9838 @d eTeX_glue=eTeX_dim+9 {first of \eTeX\ codes for glue}
9839 @d eTeX_mu=eTeX_glue+1 {first of \eTeX\ codes for muglue}
9840 @d eTeX_expr=eTeX_mu+1 {first of \eTeX\ codes for expressions}
9841
9842 @<Put each...@>=
9843 primitive("spacefactor",set_aux,hmode);
9844 @!@:space_factor_}{\.{\\spacefactor} primitive@>
9845 primitive("prevdepth",set_aux,vmode);@/
9846 @!@:prev_depth_}{\.{\\prevdepth} primitive@>
9847 primitive("deadcycles",set_page_int,0);
9848 @!@:dead_cycles_}{\.{\\deadcycles} primitive@>
9849 primitive("insertpenalties",set_page_int,1);
9850 @!@:insert_penalties_}{\.{\\insertpenalties} primitive@>
9851 primitive("wd",set_box_dimen,width_offset);
9852 @!@:wd_}{\.{\\wd} primitive@>
9853 primitive("ht",set_box_dimen,height_offset);
9854 @!@:ht_}{\.{\\ht} primitive@>
9855 primitive("dp",set_box_dimen,depth_offset);
9856 @!@:dp_}{\.{\\dp} primitive@>
9857 primitive("lastpenalty",last_item,int_val);
9858 @!@:last_penalty_}{\.{\\lastpenalty} primitive@>
9859 primitive("lastkern",last_item,dimen_val);
9860 @!@:last_kern_}{\.{\\lastkern} primitive@>
9861 primitive("lastskip",last_item,glue_val);
9862 @!@:last_skip_}{\.{\\lastskip} primitive@>
9863 primitive("inputlineno",last_item,input_line_no_code);
9864 @!@:input_line_no_}{\.{\\inputlineno} primitive@>
9865 primitive("badness",last_item,badness_code);
9866 @!@:badness_}{\.{\\badness} primitive@>
9867 primitive("pdftexversion",last_item,pdftex_version_code);@/
9868 @!@:pdftex_version_}{\.{\\pdftexversion} primitive@>
9869 primitive("pdflastobj",last_item,pdf_last_obj_code);@/
9870 @!@:pdf_last_obj_}{\.{\\pdflastobj} primitive@>
9871 primitive("pdflastxform",last_item,pdf_last_xform_code);@/
9872 @!@:pdf_last_xform_}{\.{\\pdflastxform} primitive@>
9873 primitive("pdflastximage",last_item,pdf_last_ximage_code);@/
9874 @!@:pdf_last_ximage_}{\.{\\pdflastximage} primitive@>
9875 primitive("pdflastximagepages",last_item,pdf_last_ximage_pages_code);@/
9876 @!@:pdf_last_ximage_pages_}{\.{\\pdflastximagepages} primitive@>
9877 primitive("pdflastannot",last_item,pdf_last_annot_code);@/
9878 @!@:pdf_last_annot_}{\.{\\pdflastannot} primitive@>
9879 primitive("pdflastxpos",last_item,pdf_last_x_pos_code);@/
9880 @!@:pdf_last_x_pos_}{\.{\\pdflastxpos} primitive@>
9881 primitive("pdflastypos",last_item,pdf_last_y_pos_code);@/
9882 @!@:pdf_last_y_pos_}{\.{\\pdflastypos} primitive@>
9883 primitive("pdfretval",last_item,pdf_retval_code);@/
9884 @!@:pdf_retval_}{\.{\\pdfretval} primitive@>
9885 primitive("pdflastximagecolordepth",last_item,pdf_last_ximage_colordepth_code);@/
9886 @!@:pdf_last_ximage_colordepth_}{\.{\\pdflastximagecolordepth} primitive@>
9887 primitive("pdfelapsedtime",last_item,elapsed_time_code);
9888 @!@:elapsed_time_}{\.{\\pdfelapsedtime} primitive@>
9889 primitive("pdfshellescape",last_item,pdf_shell_escape_code);
9890 @!@:pdf_shell_escape_}{\.{\\pdfshellescape} primitive@>
9891 primitive("pdfrandomseed",last_item,random_seed_code);
9892 @!@:random_seed_}{\.{\\pdfrandomseed} primitive@>
9893 primitive("pdflastlink",last_item,pdf_last_link_code);@/
9894 @!@:pdf_last_link_}{\.{\\pdflastlink} primitive@>
9895
9896 @ @<Cases of |print_cmd_chr|...@>=
9897 set_aux: if chr_code=vmode then print_esc("prevdepth")
9898 @+else print_esc("spacefactor");
9899 set_page_int: if chr_code=0 then print_esc("deadcycles")
9900 @/@<Cases of |set_page_int| for |print_cmd_chr|@>@/
9901 @+else print_esc("insertpenalties");
9902 set_box_dimen: if chr_code=width_offset then print_esc("wd")
9903 else if chr_code=height_offset then print_esc("ht")
9904 else print_esc("dp");
9905 last_item: case chr_code of
9906 int_val: print_esc("lastpenalty");
9907 dimen_val: print_esc("lastkern");
9908 glue_val: print_esc("lastskip");
9909 input_line_no_code: print_esc("inputlineno");
9910 @/@<Cases of |last_item| for |print_cmd_chr|@>@/
9911 pdftex_version_code: print_esc("pdftexversion");
9912 pdf_last_obj_code: print_esc("pdflastobj");
9913 pdf_last_xform_code: print_esc("pdflastxform");
9914 pdf_last_ximage_code: print_esc("pdflastximage");
9915 pdf_last_ximage_pages_code: print_esc("pdflastximagepages");
9916 pdf_last_annot_code: print_esc("pdflastannot");
9917 pdf_last_x_pos_code: print_esc("pdflastxpos");
9918 pdf_last_y_pos_code: print_esc("pdflastypos");
9919 pdf_retval_code: print_esc("pdfretval");
9920 pdf_last_ximage_colordepth_code: print_esc("pdflastximagecolordepth");
9921 elapsed_time_code: print_esc("pdfelapsedtime");
9922 pdf_shell_escape_code: print_esc("pdfshellescape");
9923 random_seed_code: print_esc("pdfrandomseed");
9924 pdf_last_link_code: print_esc("pdflastlink");
9925 othercases print_esc("badness")
9926 endcases;
9927
9928 @ @<Fetch the |space_factor| or the |prev_depth|@>=
9929 if abs(mode)<>m then
9930 begin print_err("Improper "); print_cmd_chr(set_aux,m);
9931 @.Improper \\spacefactor@>
9932 @.Improper \\prevdepth@>
9933 help4("You can refer to \spacefactor only in horizontal mode;")@/
9934 ("you can refer to \prevdepth only in vertical mode; and")@/
9935 ("neither of these is meaningful inside \write. So")@/
9936 ("I'm forgetting what you said and using zero instead.");
9937 error;
9938 if level<>tok_val then scanned_result(0)(dimen_val)
9939 else scanned_result(0)(int_val);
9940 end
9941 else if m=vmode then scanned_result(prev_depth)(dimen_val)
9942 else scanned_result(space_factor)(int_val)
9943
9944 @ @<Fetch the |dead_cycles| or the |insert_penalties|@>=
9945 begin if m=0 then cur_val:=dead_cycles
9946 @/@<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>@/
9947 else cur_val:=insert_penalties;
9948 cur_val_level:=int_val;
9949 end
9950
9951 @ @<Fetch a box dimension@>=
9952 begin scan_register_num; fetch_box(q);
9953 if q=null then cur_val:=0 @+else cur_val:=mem[q+m].sc;
9954 cur_val_level:=dimen_val;
9955 end
9956
9957 @ Inside an \.{\\output} routine, a user may wish to look at the page totals
9958 that were present at the moment when output was triggered.
9959
9960 @d max_dimen==@'7777777777 {$2^{30}-1$}
9961
9962 @<Fetch something on the |page_so_far|@>=
9963 begin if (page_contents=empty) and (not output_active) then
9964 if m=0 then cur_val:=max_dimen@+else cur_val:=0
9965 else cur_val:=page_so_far[m];
9966 cur_val_level:=dimen_val;
9967 end
9968
9969 @ @<Fetch the |prev_graf|@>=
9970 if mode=0 then scanned_result(0)(int_val) {|prev_graf=0| within \.{\\write}}
9971 else begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
9972 while abs(nest[p].mode_field)<>vmode do decr(p);
9973 scanned_result(nest[p].pg_field)(int_val);
9974 end
9975
9976 @ @<Fetch the |par_shape| size@>=
9977 begin if m>par_shape_loc then @<Fetch a penalties array element@>
9978 else if par_shape_ptr=null then cur_val:=0
9979 else cur_val:=info(par_shape_ptr);
9980 cur_val_level:=int_val;
9981 end
9982
9983 @ Here is where \.{\\lastpenalty}, \.{\\lastkern}, \.{\\lastskip}, and
9984 \.{\\lastnodetype} are
9985 implemented. The reference count for \.{\\lastskip} will be updated later.
9986
9987 We also handle \.{\\inputlineno} and \.{\\badness} here, because they are
9988 legal in similar contexts.
9989
9990 The macro |find_effective_tail_eTeX| sets |tx| to the last non-\.{\\endM}
9991 node of the current list.
9992
9993 @d find_effective_tail_eTeX==
9994 tx:=tail;
9995 if not is_char_node(tx) then
9996 if (type(tx)=math_node)and(subtype(tx)=end_M_code) then
9997 begin r:=head;
9998 repeat q:=r; r:=link(q);
9999 until r=tx;
10000 tx:=q;
10001 end
10002 @#
10003 @d find_effective_tail==find_effective_tail_eTeX
10004
10005 @<Fetch an item in the current node...@>=
10006 if m>=input_line_no_code then
10007 if m>=eTeX_glue then @<Process an expression and |return|@>@;
10008 else if m>=eTeX_dim then
10009 begin case m of
10010 @/@<Cases for fetching a dimension value@>@/
10011 end; {there are no other cases}
10012 cur_val_level:=dimen_val;
10013 end
10014 else begin case m of
10015 input_line_no_code: cur_val:=line;
10016 badness_code: cur_val:=last_badness;
10017 pdftex_version_code: cur_val := pdftex_version;
10018 pdf_last_obj_code: cur_val := pdf_last_obj;
10019 pdf_last_xform_code: cur_val := pdf_last_xform;
10020 pdf_last_ximage_code: cur_val := pdf_last_ximage;
10021 pdf_last_ximage_pages_code: cur_val := pdf_last_ximage_pages;
10022 pdf_last_annot_code: cur_val := pdf_last_annot;
10023 pdf_last_x_pos_code: cur_val := pdf_last_x_pos;
10024 pdf_last_y_pos_code: cur_val := pdf_last_y_pos;
10025 pdf_retval_code: cur_val := pdf_retval;
10026 pdf_last_ximage_colordepth_code: cur_val := pdf_last_ximage_colordepth;
10027 elapsed_time_code: cur_val := get_microinterval;
10028 random_seed_code: cur_val := random_seed;
10029 pdf_shell_escape_code:
10030 begin
10031 if shellenabledp then begin
10032 if restrictedshell then cur_val :=2
10033 else cur_val := 1;
10034 end
10035 else cur_val := 0;
10036 end;
10037 pdf_last_link_code: cur_val := pdf_last_link;
10038 @/@<Cases for fetching an integer value@>@/
10039 end; {there are no other cases}
10040 cur_val_level:=int_val;
10041 end
10042 else begin if cur_chr=glue_val then cur_val:=zero_glue@+else cur_val:=0;
10043 find_effective_tail;
10044 if cur_chr=last_node_type_code then
10045 begin cur_val_level:=int_val;
10046 if (tx=head)or(mode=0) then cur_val:=-1;
10047 end
10048 else cur_val_level:=cur_chr;
10049 if not is_char_node(tx)and(mode<>0) then
10050 case cur_chr of
10051 int_val: if type(tx)=penalty_node then cur_val:=penalty(tx);
10052 dimen_val: if type(tx)=kern_node then cur_val:=width(tx);
10053 glue_val: if type(tx)=glue_node then
10054 begin cur_val:=glue_ptr(tx);
10055 if subtype(tx)=mu_glue then cur_val_level:=mu_val;
10056 end;
10057 last_node_type_code: if type(tx)<=unset_node then cur_val:=type(tx)+1
10058 else cur_val:=unset_node+2;
10059 end {there are no other cases}
10060 else if (mode=vmode)and(tx=head) then
10061 case cur_chr of
10062 int_val: cur_val:=last_penalty;
10063 dimen_val: cur_val:=last_kern;
10064 glue_val: if last_glue<>max_halfword then cur_val:=last_glue;
10065 last_node_type_code: cur_val:=last_node_type;
10066 end; {there are no other cases}
10067 end
10068
10069 @ @<Fetch a font dimension@>=
10070 begin find_font_dimen(false); font_info[fmem_ptr].sc:=0;
10071 scanned_result(font_info[cur_val].sc)(dimen_val);
10072 end
10073
10074 @ @<Fetch a font integer@>=
10075 begin scan_font_ident;
10076 if m=0 then scanned_result(hyphen_char[cur_val])(int_val)
10077 else if m=1 then scanned_result(skew_char[cur_val])(int_val)
10078 else if m=no_lig_code then scanned_result(test_no_ligatures(cur_val))(int_val)
10079 else begin
10080 n := cur_val;
10081 scan_char_num;
10082 k := cur_val;
10083 case m of
10084 lp_code_base: scanned_result(get_lp_code(n, k))(int_val);
10085 rp_code_base: scanned_result(get_rp_code(n, k))(int_val);
10086 ef_code_base: scanned_result(get_ef_code(n, k))(int_val);
10087 tag_code: scanned_result(get_tag_code(n, k))(int_val);
10088 kn_bs_code_base: scanned_result(get_kn_bs_code(n, k))(int_val);
10089 st_bs_code_base: scanned_result(get_st_bs_code(n, k))(int_val);
10090 sh_bs_code_base: scanned_result(get_sh_bs_code(n, k))(int_val);
10091 kn_bc_code_base: scanned_result(get_kn_bc_code(n, k))(int_val);
10092 kn_ac_code_base: scanned_result(get_kn_ac_code(n, k))(int_val);
10093 end;
10094 end;
10095 end
10096
10097 @ @<Fetch a register@>=
10098 begin if (m<mem_bot)or(m>lo_mem_stat_max) then
10099 begin cur_val_level:=sa_type(m);
10100 if cur_val_level<glue_val then cur_val:=sa_int(m)
10101 else cur_val:=sa_ptr(m);
10102 end
10103 else begin scan_register_num; cur_val_level:=m-mem_bot;
10104 if cur_val>255 then
10105 begin find_sa_element(cur_val_level,cur_val,false);
10106 if cur_ptr=null then
10107 if cur_val_level<glue_val then cur_val:=0
10108 else cur_val:=zero_glue
10109 else if cur_val_level<glue_val then cur_val:=sa_int(cur_ptr)
10110 else cur_val:=sa_ptr(cur_ptr);
10111 end
10112 else
10113 case cur_val_level of
10114 int_val:cur_val:=count(cur_val);
10115 dimen_val:cur_val:=dimen(cur_val);
10116 glue_val: cur_val:=skip(cur_val);
10117 mu_val: cur_val:=mu_skip(cur_val);
10118 end; {there are no other cases}
10119 end;
10120 end
10121
10122 @ @<Complain that \.{\\the} can't do this; give zero result@>=
10123 begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
10124 @.You can't use x after ...@>
10125 print("' after "); print_esc("the");
10126 help1("I'm forgetting what you said and using zero instead.");
10127 error;
10128 if level<>tok_val then scanned_result(0)(dimen_val)
10129 else scanned_result(0)(int_val);
10130 end
10131
10132 @ When a |glue_val| changes to a |dimen_val|, we use the width component
10133 of the glue; there is no need to decrease the reference count, since it
10134 has not yet been increased. When a |dimen_val| changes to an |int_val|,
10135 we use scaled points so that the value doesn't actually change. And when a
10136 |mu_val| changes to a |glue_val|, the value doesn't change either.
10137
10138 @<Convert \(c)|cur_val| to a lower level@>=
10139 begin if cur_val_level=glue_val then cur_val:=width(cur_val)
10140 else if cur_val_level=mu_val then mu_error;
10141 decr(cur_val_level);
10142 end
10143
10144 @ If |cur_val| points to a glue specification at this point, the reference
10145 count for the glue does not yet include the reference by |cur_val|.
10146 If |negative| is |true|, |cur_val_level| is known to be |<=mu_val|.
10147
10148 @<Fix the reference count, if any, ...@>=
10149 if negative then
10150 if cur_val_level>=glue_val then
10151 begin cur_val:=new_spec(cur_val);
10152 @<Negate all three glue components of |cur_val|@>;
10153 end
10154 else negate(cur_val)
10155 else if (cur_val_level>=glue_val)and(cur_val_level<=mu_val) then
10156 add_glue_ref(cur_val)
10157
10158 @ @<Negate all three...@>=
10159 begin negate(width(cur_val));
10160 negate(stretch(cur_val));
10161 negate(shrink(cur_val));
10162 end
10163
10164 @ Our next goal is to write the |scan_int| procedure, which scans anything that
10165 \TeX\ treats as an integer. But first we might as well look at some simple
10166 applications of |scan_int| that have already been made inside of
10167 |scan_something_internal|.
10168
10169 @ @<Declare procedures that scan restricted classes of integers@>=
10170 procedure scan_eight_bit_int;
10171 begin scan_int;
10172 if (cur_val<0)or(cur_val>255) then
10173 begin print_err("Bad register code");
10174 @.Bad register code@>
10175 help2("A register number must be between 0 and 255.")@/
10176 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10177 end;
10178 end;
10179
10180 @ @<Declare procedures that scan restricted classes of integers@>=
10181 procedure scan_char_num;
10182 begin scan_int;
10183 if (cur_val<0)or(cur_val>255) then
10184 begin print_err("Bad character code");
10185 @.Bad character code@>
10186 help2("A character number must be between 0 and 255.")@/
10187 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10188 end;
10189 end;
10190
10191 @ While we're at it, we might as well deal with similar routines that
10192 will be needed later.
10193
10194 @<Declare procedures that scan restricted classes of integers@>=
10195 procedure scan_four_bit_int;
10196 begin scan_int;
10197 if (cur_val<0)or(cur_val>15) then
10198 begin print_err("Bad number");
10199 @.Bad number@>
10200 help2("Since I expected to read a number between 0 and 15,")@/
10201 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10202 end;
10203 end;
10204
10205 @ @<Declare procedures that scan restricted classes of integers@>=
10206 procedure scan_fifteen_bit_int;
10207 begin scan_int;
10208 if (cur_val<0)or(cur_val>@'77777) then
10209 begin print_err("Bad mathchar");
10210 @.Bad mathchar@>
10211 help2("A mathchar number must be between 0 and 32767.")@/
10212 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10213 end;
10214 end;
10215
10216 @ @<Declare procedures that scan restricted classes of integers@>=
10217 procedure scan_twenty_seven_bit_int;
10218 begin scan_int;
10219 if (cur_val<0)or(cur_val>@'777777777) then
10220 begin print_err("Bad delimiter code");
10221 @.Bad delimiter code@>
10222 help2("A numeric delimiter code must be between 0 and 2^{27}-1.")@/
10223 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10224 end;
10225 end;
10226
10227 @ An integer number can be preceded by any number of spaces and `\.+' or
10228 `\.-' signs. Then comes either a decimal constant (i.e., radix 10), an
10229 octal constant (i.e., radix 8, preceded by~\.\'), a hexadecimal constant
10230 (radix 16, preceded by~\."), an alphabetic constant (preceded by~\.\`), or
10231 an internal variable. After scanning is complete,
10232 |cur_val| will contain the answer, which must be at most
10233 $2^{31}-1=2147483647$ in absolute value. The value of |radix| is set to
10234 10, 8, or 16 in the cases of decimal, octal, or hexadecimal constants,
10235 otherwise |radix| is set to zero. An optional space follows a constant.
10236
10237 @d octal_token=other_token+"'" {apostrophe, indicates an octal constant}
10238 @d hex_token=other_token+"""" {double quote, indicates a hex constant}
10239 @d alpha_token=other_token+"`" {reverse apostrophe, precedes alpha constants}
10240 @d point_token=other_token+"." {decimal point}
10241 @d continental_point_token=other_token+"," {decimal point, Eurostyle}
10242
10243 @<Glob...@>=
10244 @!radix:small_number; {|scan_int| sets this to 8, 10, 16, or zero}
10245
10246 @ We initialize the following global variables just in case |expand|
10247 comes into action before any of the basic scanning routines has assigned
10248 them a value.
10249
10250 @<Set init...@>=
10251 cur_val:=0; cur_val_level:=int_val; radix:=0; cur_order:=normal;
10252
10253 @ The |scan_int| routine is used also to scan the integer part of a
10254 fraction; for example, the `\.3' in `\.{3.14159}' will be found by
10255 |scan_int|. The |scan_dimen| routine assumes that |cur_tok=point_token|
10256 after the integer part of such a fraction has been scanned by |scan_int|,
10257 and that the decimal point has been backed up to be scanned again.
10258
10259 @p procedure scan_int; {sets |cur_val| to an integer}
10260 label done, restart;
10261 var negative:boolean; {should the answer be negated?}
10262 @!m:integer; {|@t$2^{31}$@> div radix|, the threshold of danger}
10263 @!d:small_number; {the digit just scanned}
10264 @!vacuous:boolean; {have no digits appeared?}
10265 @!OK_so_far:boolean; {has an error message been issued?}
10266 begin radix:=0; OK_so_far:=true;@/
10267 @<Get the next non-blank non-sign token; set |negative| appropriately@>;
10268 restart:
10269 if cur_tok=alpha_token then @<Scan an alphabetic character code into |cur_val|@>
10270 else if cur_tok=cs_token_flag+frozen_primitive then
10271 @<Reset |cur_tok| for unexpandable primitives, goto restart@>
10272 else if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
10273 scan_something_internal(int_val,false)
10274 else @<Scan a numeric constant@>;
10275 if negative then negate(cur_val);
10276 end;
10277
10278 @ @<Get the next non-blank non-sign token...@>=
10279 negative:=false;
10280 repeat @<Get the next non-blank non-call token@>;
10281 if cur_tok=other_token+"-" then
10282 begin negative := not negative; cur_tok:=other_token+"+";
10283 end;
10284 until cur_tok<>other_token+"+"
10285
10286 @ A space is ignored after an alphabetic character constant, so that
10287 such constants behave like numeric ones.
10288
10289 @<Scan an alphabetic character code into |cur_val|@>=
10290 begin get_token; {suppress macro expansion}
10291 if cur_tok<cs_token_flag then
10292 begin cur_val:=cur_chr;
10293 if cur_cmd<=right_brace then
10294 if cur_cmd=right_brace then incr(align_state)
10295 else decr(align_state);
10296 end
10297 else if cur_tok<cs_token_flag+single_base then
10298 cur_val:=cur_tok-cs_token_flag-active_base
10299 else cur_val:=cur_tok-cs_token_flag-single_base;
10300 if cur_val>255 then
10301 begin print_err("Improper alphabetic constant");
10302 @.Improper alphabetic constant@>
10303 help2("A one-character control sequence belongs after a ` mark.")@/
10304 ("So I'm essentially inserting \0 here.");
10305 cur_val:="0"; back_error;
10306 end
10307 else @<Scan an optional space@>;
10308 end
10309
10310 @ @<Scan an optional space@>=
10311 begin get_x_token; if cur_cmd<>spacer then back_input;
10312 end
10313
10314 @ @<Scan a numeric constant@>=
10315 begin radix:=10; m:=214748364;
10316 if cur_tok=octal_token then
10317 begin radix:=8; m:=@'2000000000; get_x_token;
10318 end
10319 else if cur_tok=hex_token then
10320 begin radix:=16; m:=@'1000000000; get_x_token;
10321 end;
10322 vacuous:=true; cur_val:=0;@/
10323 @<Accumulate the constant until |cur_tok| is not a suitable digit@>;
10324 if vacuous then @<Express astonishment that no number was here@>
10325 else if cur_cmd<>spacer then back_input;
10326 end
10327
10328 @ @d infinity==@'17777777777 {the largest positive value that \TeX\ knows}
10329 @d zero_token=other_token+"0" {zero, the smallest digit}
10330 @d A_token=letter_token+"A" {the smallest special hex digit}
10331 @d other_A_token=other_token+"A" {special hex digit of type |other_char|}
10332
10333 @<Accumulate the constant...@>=
10334 loop@+ begin if (cur_tok<zero_token+radix)and(cur_tok>=zero_token)and
10335 (cur_tok<=zero_token+9) then d:=cur_tok-zero_token
10336 else if radix=16 then
10337 if (cur_tok<=A_token+5)and(cur_tok>=A_token) then d:=cur_tok-A_token+10
10338 else if (cur_tok<=other_A_token+5)and(cur_tok>=other_A_token) then
10339 d:=cur_tok-other_A_token+10
10340 else goto done
10341 else goto done;
10342 vacuous:=false;
10343 if (cur_val>=m)and((cur_val>m)or(d>7)or(radix<>10)) then
10344 begin if OK_so_far then
10345 begin print_err("Number too big");
10346 @.Number too big@>
10347 help2("I can only go up to 2147483647='17777777777=""7FFFFFFF,")@/
10348 ("so I'm using that number instead of yours.");
10349 error; cur_val:=infinity; OK_so_far:=false;
10350 end;
10351 end
10352 else cur_val:=cur_val*radix+d;
10353 get_x_token;
10354 end;
10355 done:
10356
10357 @ @<Express astonishment...@>=
10358 begin print_err("Missing number, treated as zero");
10359 @.Missing number...@>
10360 help3("A number should have been here; I inserted `0'.")@/
10361 ("(If you can't figure out why I needed to see a number,")@/
10362 ("look up `weird error' in the index to The TeXbook.)");
10363 @:TeXbook}{\sl The \TeX book@>
10364 back_error;
10365 end
10366
10367 @ The |scan_dimen| routine is similar to |scan_int|, but it sets |cur_val| to
10368 a |scaled| value, i.e., an integral number of sp. One of its main tasks
10369 is therefore to interpret the abbreviations for various kinds of units and
10370 to convert measurements to scaled points.
10371
10372 There are three parameters: |mu| is |true| if the finite units must be
10373 `\.{mu}', while |mu| is |false| if `\.{mu}' units are disallowed;
10374 |inf| is |true| if the infinite units `\.{fil}', `\.{fill}', `\.{filll}'
10375 are permitted; and |shortcut| is |true| if |cur_val| already contains
10376 an integer and only the units need to be considered.
10377
10378 The order of infinity that was found in the case of infinite glue is returned
10379 in the global variable |cur_order|.
10380
10381 @<Glob...@>=
10382 @!cur_order:glue_ord; {order of infinity found by |scan_dimen|}
10383
10384 @ Constructions like `\.{-\'77 pt}' are legal dimensions, so |scan_dimen|
10385 may begin with |scan_int|. This explains why it is convenient to use
10386 |scan_int| also for the integer part of a decimal fraction.
10387
10388 Several branches of |scan_dimen| work with |cur_val| as an integer and
10389 with an auxiliary fraction |f|, so that the actual quantity of interest is
10390 $|cur_val|+|f|/2^{16}$. At the end of the routine, this ``unpacked''
10391 representation is put into the single word |cur_val|, which suddenly
10392 switches significance from |integer| to |scaled|.
10393
10394 @d attach_fraction=88 {go here to pack |cur_val| and |f| into |cur_val|}
10395 @d attach_sign=89 {go here when |cur_val| is correct except perhaps for sign}
10396 @d scan_normal_dimen==scan_dimen(false,false,false)
10397
10398 @p procedure scan_dimen(@!mu,@!inf,@!shortcut:boolean);
10399 {sets |cur_val| to a dimension}
10400 label done, done1, done2, found, not_found, attach_fraction, attach_sign;
10401 var negative:boolean; {should the answer be negated?}
10402 @!f:integer; {numerator of a fraction whose denominator is $2^{16}$}
10403 @<Local variables for dimension calculations@>@;
10404 begin f:=0; arith_error:=false; cur_order:=normal; negative:=false;
10405 if not shortcut then
10406 begin @<Get the next non-blank non-sign...@>;
10407 if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
10408 @<Fetch an internal dimension and |goto attach_sign|,
10409 or fetch an internal integer@>
10410 else begin back_input;
10411 if cur_tok=continental_point_token then cur_tok:=point_token;
10412 if cur_tok<>point_token then scan_int
10413 else begin radix:=10; cur_val:=0;
10414 end;
10415 if cur_tok=continental_point_token then cur_tok:=point_token;
10416 if (radix=10)and(cur_tok=point_token) then @<Scan decimal fraction@>;
10417 end;
10418 end;
10419 if cur_val<0 then {in this case |f=0|}
10420 begin negative := not negative; negate(cur_val);
10421 end;
10422 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$, where there
10423 are |x| sp per unit; |goto attach_sign| if the units are internal@>;
10424 @<Scan an optional space@>;
10425 attach_sign: if arith_error or(abs(cur_val)>=@'10000000000) then
10426 @<Report that this dimension is out of range@>;
10427 if negative then negate(cur_val);
10428 end;
10429
10430 @ @<Fetch an internal dimension and |goto attach_sign|...@>=
10431 if mu then
10432 begin scan_something_internal(mu_val,false);
10433 @<Coerce glue to a dimension@>;
10434 if cur_val_level=mu_val then goto attach_sign;
10435 if cur_val_level<>int_val then mu_error;
10436 end
10437 else begin scan_something_internal(dimen_val,false);
10438 if cur_val_level=dimen_val then goto attach_sign;
10439 end
10440
10441 @ @<Local variables for dimension calculations@>=
10442 @!num,@!denom:1..65536; {conversion ratio for the scanned units}
10443 @!k,@!kk:small_number; {number of digits in a decimal fraction}
10444 @!p,@!q:pointer; {top of decimal digit stack}
10445 @!v:scaled; {an internal dimension}
10446 @!save_cur_val:integer; {temporary storage of |cur_val|}
10447
10448 @ The following code is executed when |scan_something_internal| was
10449 called asking for |mu_val|, when we really wanted a ``mudimen'' instead
10450 of ``muglue.''
10451
10452 @<Coerce glue to a dimension@>=
10453 if cur_val_level>=glue_val then
10454 begin v:=width(cur_val); delete_glue_ref(cur_val); cur_val:=v;
10455 end
10456
10457 @ When the following code is executed, we have |cur_tok=point_token|, but this
10458 token has been backed up using |back_input|; we must first discard it.
10459
10460 It turns out that a decimal point all by itself is equivalent to `\.{0.0}'.
10461 Let's hope people don't use that fact.
10462
10463 @<Scan decimal fraction@>=
10464 begin k:=0; p:=null; get_token; {|point_token| is being re-scanned}
10465 loop@+ begin get_x_token;
10466 if (cur_tok>zero_token+9)or(cur_tok<zero_token) then goto done1;
10467 if k<17 then {digits for |k>=17| cannot affect the result}
10468 begin q:=get_avail; link(q):=p; info(q):=cur_tok-zero_token;
10469 p:=q; incr(k);
10470 end;
10471 end;
10472 done1: for kk:=k downto 1 do
10473 begin dig[kk-1]:=info(p); q:=p; p:=link(p); free_avail(q);
10474 end;
10475 f:=round_decimals(k);
10476 if cur_cmd<>spacer then back_input;
10477 end
10478
10479 @ Now comes the harder part: At this point in the program, |cur_val| is a
10480 nonnegative integer and $f/2^{16}$ is a nonnegative fraction less than 1;
10481 we want to multiply the sum of these two quantities by the appropriate
10482 factor, based on the specified units, in order to produce a |scaled|
10483 result, and we want to do the calculation with fixed point arithmetic that
10484 does not overflow.
10485
10486 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$...@>=
10487 if inf then @<Scan for \(f)\.{fil} units; |goto attach_fraction| if found@>;
10488 @<Scan for \(u)units that are internal dimensions;
10489 |goto attach_sign| with |cur_val| set if found@>;
10490 if mu then @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>;
10491 if scan_keyword("true") then @<Adjust \(f)for the magnification ratio@>;
10492 @.true@>
10493 if scan_keyword("pt") then goto attach_fraction; {the easy case}
10494 @.pt@>
10495 @<Scan for \(a)all other units and adjust |cur_val| and |f| accordingly;
10496 |goto done| in the case of scaled points@>;
10497 attach_fraction: if cur_val>=@'40000 then arith_error:=true
10498 else cur_val:=cur_val*unity+f;
10499 done:
10500
10501 @ A specification like `\.{filllll}' or `\.{fill L L L}' will lead to two
10502 error messages (one for each additional keyword \.{"l"}).
10503
10504 @<Scan for \(f)\.{fil} units...@>=
10505 if scan_keyword("fil") then
10506 @.fil@>
10507 begin cur_order:=fil;
10508 while scan_keyword("l") do
10509 begin if cur_order=filll then
10510 begin print_err("Illegal unit of measure (");
10511 @.Illegal unit of measure@>
10512 print("replaced by filll)");
10513 help1("I dddon't go any higher than filll."); error;
10514 end
10515 else incr(cur_order);
10516 end;
10517 goto attach_fraction;
10518 end
10519
10520 @ @<Scan for \(u)units that are internal dimensions...@>=
10521 save_cur_val:=cur_val;
10522 @<Get the next non-blank non-call...@>;
10523 if (cur_cmd<min_internal)or(cur_cmd>max_internal) then back_input
10524 else begin if mu then
10525 begin scan_something_internal(mu_val,false); @<Coerce glue...@>;
10526 if cur_val_level<>mu_val then mu_error;
10527 end
10528 else scan_something_internal(dimen_val,false);
10529 v:=cur_val; goto found;
10530 end;
10531 if mu then goto not_found;
10532 if scan_keyword("em") then v:=(@<The em width for |cur_font|@>)
10533 @.em@>
10534 else if scan_keyword("ex") then v:=(@<The x-height for |cur_font|@>)
10535 @.ex@>
10536 else if scan_keyword("px") then v:=pdf_px_dimen
10537 @.px@>
10538 else goto not_found;
10539 @<Scan an optional space@>;
10540 found:cur_val:=nx_plus_y(save_cur_val,v,xn_over_d(v,f,@'200000));
10541 goto attach_sign;
10542 not_found:
10543
10544 @ @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>=
10545 if scan_keyword("mu") then goto attach_fraction
10546 @.mu@>
10547 else begin print_err("Illegal unit of measure ("); print("mu inserted)");
10548 @.Illegal unit of measure@>
10549 help4("The unit of measurement in math glue must be mu.")@/
10550 ("To recover gracefully from this error, it's best to")@/
10551 ("delete the erroneous units; e.g., type `2' to delete")@/
10552 ("two letters. (See Chapter 27 of The TeXbook.)");
10553 @:TeXbook}{\sl The \TeX book@>
10554 error; goto attach_fraction;
10555 end
10556
10557 @ @<Adjust \(f)for the magnification ratio@>=
10558 begin prepare_mag;
10559 if mag<>1000 then
10560 begin cur_val:=xn_over_d(cur_val,1000,mag);
10561 f:=(1000*f+@'200000*remainder) div mag;
10562 cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
10563 end;
10564 end
10565
10566 @ The necessary conversion factors can all be specified exactly as
10567 fractions whose numerator and denominator sum to 32768 or less.
10568 According to the definitions here, $\rm2660\,dd\approx1000.33297\,mm$;
10569 this agrees well with the value $\rm1000.333\,mm$ cited by Bosshard
10570 @^Bosshard, Hans Rudolf@>
10571 in {\sl Technische Grundlagen zur Satzherstellung\/} (Bern, 1980).
10572 The Didot point has been newly standardized in 1978;
10573 it's now exactly $\rm 1\,nd=0.375\,mm$.
10574 Conversion uses the equation $0.375=21681/20320/72.27\cdot25.4$.
10575 The new Cicero follows the new Didot point; $\rm 1\,nc=12\,nd$.
10576 These would lead to the ratios $21681/20320$ and $65043/5080$,
10577 respectively.
10578 The closest approximations supported by the algorithm would be
10579 $11183/10481$ and $1370/107$. In order to maintain the
10580 relation $\rm 1\,nc=12\,nd$, we pick the ratio $685/642$ for
10581 $\rm nd$, however.
10582
10583 @d set_conversion_end(#)== denom:=#; end
10584 @d set_conversion(#)==@+begin num:=#; set_conversion_end
10585
10586 @<Scan for \(a)all other units and adjust |cur_val| and |f|...@>=
10587 if scan_keyword("in") then set_conversion(7227)(100)
10588 @.in@>
10589 else if scan_keyword("pc") then set_conversion(12)(1)
10590 @.pc@>
10591 else if scan_keyword("cm") then set_conversion(7227)(254)
10592 @.cm@>
10593 else if scan_keyword("mm") then set_conversion(7227)(2540)
10594 @.mm@>
10595 else if scan_keyword("bp") then set_conversion(7227)(7200)
10596 @.bp@>
10597 else if scan_keyword("dd") then set_conversion(1238)(1157)
10598 @.dd@>
10599 else if scan_keyword("cc") then set_conversion(14856)(1157)
10600 @.cc@>
10601 else if scan_keyword("nd") then set_conversion(685)(642)
10602 @.nd@>
10603 else if scan_keyword("nc") then set_conversion(1370)(107)
10604 @.nc@>
10605 else if scan_keyword("sp") then goto done
10606 @.sp@>
10607 else @<Complain about unknown unit and |goto done2|@>;
10608 cur_val:=xn_over_d(cur_val,num,denom);
10609 f:=(num*f+@'200000*remainder) div denom;@/
10610 cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
10611 done2:
10612
10613 @ @<Complain about unknown unit...@>=
10614 begin print_err("Illegal unit of measure ("); print("pt inserted)");
10615 @.Illegal unit of measure@>
10616 help6("Dimensions can be in units of em, ex, in, pt, pc,")@/
10617 ("cm, mm, dd, cc, nd, nc, bp, or sp; but yours is a new one!")@/
10618 ("I'll assume that you meant to say pt, for printer's points.")@/
10619 ("To recover gracefully from this error, it's best to")@/
10620 ("delete the erroneous units; e.g., type `2' to delete")@/
10621 ("two letters. (See Chapter 27 of The TeXbook.)");
10622 @:TeXbook}{\sl The \TeX book@>
10623 error; goto done2;
10624 end
10625
10626
10627 @ @<Report that this dimension is out of range@>=
10628 begin print_err("Dimension too large");
10629 @.Dimension too large@>
10630 help2("I can't work with sizes bigger than about 19 feet.")@/
10631 ("Continue and I'll use the largest value I can.");@/
10632 error; cur_val:=max_dimen; arith_error:=false;
10633 end
10634
10635 @ The final member of \TeX's value-scanning trio is |scan_glue|, which
10636 makes |cur_val| point to a glue specification. The reference count of that
10637 glue spec will take account of the fact that |cur_val| is pointing to~it.
10638
10639 The |level| parameter should be either |glue_val| or |mu_val|.
10640
10641 Since |scan_dimen| was so much more complex than |scan_int|, we might expect
10642 |scan_glue| to be even worse. But fortunately, it is very simple, since
10643 most of the work has already been done.
10644
10645 @p procedure scan_glue(@!level:small_number);
10646 {sets |cur_val| to a glue spec pointer}
10647 label exit;
10648 var negative:boolean; {should the answer be negated?}
10649 @!q:pointer; {new glue specification}
10650 @!mu:boolean; {does |level=mu_val|?}
10651 begin mu:=(level=mu_val); @<Get the next non-blank non-sign...@>;
10652 if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
10653 begin scan_something_internal(level,negative);
10654 if cur_val_level>=glue_val then
10655 begin if cur_val_level<>level then mu_error;
10656 return;
10657 end;
10658 if cur_val_level=int_val then scan_dimen(mu,false,true)
10659 else if level=mu_val then mu_error;
10660 end
10661 else begin back_input; scan_dimen(mu,false,false);
10662 if negative then negate(cur_val);
10663 end;
10664 @<Create a new glue specification whose width is |cur_val|; scan for its
10665 stretch and shrink components@>;
10666 exit:end;
10667 @#
10668 @<Declare procedures needed for expressions@>@;
10669
10670 @ @<Create a new glue specification whose width is |cur_val|...@>=
10671 q:=new_spec(zero_glue); width(q):=cur_val;
10672 if scan_keyword("plus") then
10673 @.plus@>
10674 begin scan_dimen(mu,true,false);
10675 stretch(q):=cur_val; stretch_order(q):=cur_order;
10676 end;
10677 if scan_keyword("minus") then
10678 @.minus@>
10679 begin scan_dimen(mu,true,false);
10680 shrink(q):=cur_val; shrink_order(q):=cur_order;
10681 end;
10682 cur_val:=q
10683
10684 @ Here's a similar procedure that returns a pointer to a rule node. This
10685 routine is called just after \TeX\ has seen \.{\\hrule} or \.{\\vrule};
10686 therefore |cur_cmd| will be either |hrule| or |vrule|. The idea is to store
10687 the default rule dimensions in the node, then to override them if
10688 `\.{height}' or `\.{width}' or `\.{depth}' specifications are
10689 found (in any order).
10690
10691 @d default_rule=26214 {0.4\thinspace pt}
10692
10693 @p function scan_rule_spec:pointer;
10694 label reswitch;
10695 var q:pointer; {the rule node being created}
10696 begin q:=new_rule; {|width|, |depth|, and |height| all equal |null_flag| now}
10697 if cur_cmd=vrule then width(q):=default_rule
10698 else begin height(q):=default_rule; depth(q):=0;
10699 end;
10700 reswitch: if scan_keyword("width") then
10701 @.width@>
10702 begin scan_normal_dimen; width(q):=cur_val; goto reswitch;
10703 end;
10704 if scan_keyword("height") then
10705 @.height@>
10706 begin scan_normal_dimen; height(q):=cur_val; goto reswitch;
10707 end;
10708 if scan_keyword("depth") then
10709 @.depth@>
10710 begin scan_normal_dimen; depth(q):=cur_val; goto reswitch;
10711 end;
10712 scan_rule_spec:=q;
10713 end;
10714
10715 @* \[27] Building token lists.
10716 The token lists for macros and for other things like \.{\\mark} and \.{\\output}
10717 and \.{\\write} are produced by a procedure called |scan_toks|.
10718
10719 Before we get into the details of |scan_toks|, let's consider a much
10720 simpler task, that of converting the current string into a token list.
10721 The |str_toks| function does this; it classifies spaces as type |spacer|
10722 and everything else as type |other_char|.
10723
10724 The token list created by |str_toks| begins at |link(temp_head)| and ends
10725 at the value |p| that is returned. (If |p=temp_head|, the list is empty.)
10726
10727 @p @t\4@>@<Declare \eTeX\ procedures for token lists@>@;@/
10728 function str_toks(@!b:pool_pointer):pointer;
10729 {converts |str_pool[b..pool_ptr-1]| to a token list}
10730 var p:pointer; {tail of the token list}
10731 @!q:pointer; {new node being added to the token list via |store_new_token|}
10732 @!t:halfword; {token being appended}
10733 @!k:pool_pointer; {index into |str_pool|}
10734 begin str_room(1);
10735 p:=temp_head; link(p):=null; k:=b;
10736 while k<pool_ptr do
10737 begin t:=so(str_pool[k]);
10738 if t=" " then t:=space_token
10739 else t:=other_token+t;
10740 fast_store_new_token(t);
10741 incr(k);
10742 end;
10743 pool_ptr:=b; str_toks:=p;
10744 end;
10745
10746 @ The main reason for wanting |str_toks| is the next function,
10747 |the_toks|, which has similar input/output characteristics.
10748
10749 This procedure is supposed to scan something like `\.{\\skip\\count12}',
10750 i.e., whatever can follow `\.{\\the}', and it constructs a token list
10751 containing something like `\.{-3.0pt minus 0.5fill}'.
10752
10753 @p function the_toks:pointer;
10754 label exit;
10755 var old_setting:0..max_selector; {holds |selector| setting}
10756 @!p,@!q,@!r:pointer; {used for copying a token list}
10757 @!b:pool_pointer; {base of temporary string}
10758 @!c:small_number; {value of |cur_chr|}
10759 begin @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>;@/
10760 get_x_token; scan_something_internal(tok_val,false);
10761 if cur_val_level>=ident_val then @<Copy the token list@>
10762 else begin old_setting:=selector; selector:=new_string; b:=pool_ptr;
10763 case cur_val_level of
10764 int_val:print_int(cur_val);
10765 dimen_val:begin print_scaled(cur_val); print("pt");
10766 end;
10767 glue_val: begin print_spec(cur_val,"pt"); delete_glue_ref(cur_val);
10768 end;
10769 mu_val: begin print_spec(cur_val,"mu"); delete_glue_ref(cur_val);
10770 end;
10771 end; {there are no other cases}
10772 selector:=old_setting; the_toks:=str_toks(b);
10773 end;
10774 exit:end;
10775
10776 @ @<Copy the token list@>=
10777 begin p:=temp_head; link(p):=null;
10778 if cur_val_level=ident_val then store_new_token(cs_token_flag+cur_val)
10779 else if cur_val<>null then
10780 begin r:=link(cur_val); {do not copy the reference count}
10781 while r<>null do
10782 begin fast_store_new_token(info(r)); r:=link(r);
10783 end;
10784 end;
10785 the_toks:=p;
10786 end
10787
10788 @ Here's part of the |expand| subroutine that we are now ready to complete:
10789
10790 @p procedure ins_the_toks;
10791 begin link(garbage):=the_toks; ins_list(link(temp_head));
10792 end;
10793
10794 @ The primitives \.{\\number}, \.{\\romannumeral}, \.{\\string}, \.{\\meaning},
10795 \.{\\fontname}, and \.{\\jobname} are defined as follows.
10796
10797 \eTeX\ adds \.{\\eTeXrevision} such that |job_name_code| remains last.
10798
10799 \pdfTeX\ adds \.{\\pdftexrevision}, \.{\\pdftexbanner}, \.{\\pdffontname},
10800 \.{\\pdffontobjnum}, \.{\\pdffontsize}, and \.{\\pdfpageref} such that
10801 |job_name_code| remains last.
10802
10803 @d number_code=0 {command code for \.{\\number}}
10804 @d roman_numeral_code=1 {command code for \.{\\romannumeral}}
10805 @d string_code=2 {command code for \.{\\string}}
10806 @d meaning_code=3 {command code for \.{\\meaning}}
10807 @d font_name_code=4 {command code for \.{\\fontname}}
10808 @d etex_convert_base=5 {base for \eTeX's command codes}
10809 @d eTeX_revision_code=etex_convert_base {command code for \.{\\eTeXrevision}}
10810 @d etex_convert_codes=etex_convert_base+1 {end of \eTeX's command codes}
10811 @d expanded_code = etex_convert_codes {command code for \.{\\expanded}}
10812 @d pdftex_first_expand_code = expanded_code + 1 {base for \pdfTeX's command codes}
10813 @d pdftex_revision_code = pdftex_first_expand_code + 0 {command code for \.{\\pdftexrevision}}
10814 @d pdftex_banner_code = pdftex_first_expand_code + 1 {command code for \.{\\pdftexbanner}}
10815 @d pdf_font_name_code = pdftex_first_expand_code + 2 {command code for \.{\\pdffontname}}
10816 @d pdf_font_objnum_code = pdftex_first_expand_code + 3 {command code for \.{\\pdffontobjnum}}
10817 @d pdf_font_size_code = pdftex_first_expand_code + 4 {command code for \.{\\pdffontsize}}
10818 @d pdf_page_ref_code = pdftex_first_expand_code + 5 {command code for \.{\\pdfpageref}}
10819 @d pdf_xform_name_code = pdftex_first_expand_code + 6 {command code for \.{\\pdfxformname}}
10820 @d pdf_escape_string_code = pdftex_first_expand_code + 7 {command code for \.{\\pdfescapestring}}
10821 @d pdf_escape_name_code = pdftex_first_expand_code + 8 {command code for \.{\\pdfescapename}}
10822 @d left_margin_kern_code = pdftex_first_expand_code + 9 {command code for \.{\\leftmarginkern}}
10823 @d right_margin_kern_code = pdftex_first_expand_code + 10 {command code for \.{\\rightmarginkern}}
10824 @d pdf_strcmp_code = pdftex_first_expand_code + 11 {command code for \.{\\pdfstrcmp}}
10825 @d pdf_colorstack_init_code = pdftex_first_expand_code + 12 {command code for \.{\\pdfcolorstackinit}}
10826 @d pdf_escape_hex_code = pdftex_first_expand_code + 13 {command code for \.{\\pdfescapehex}}
10827 @d pdf_unescape_hex_code = pdftex_first_expand_code + 14 {command code for \.{\\pdfunescapehex}}
10828 @d pdf_creation_date_code = pdftex_first_expand_code + 15 {command code for \.{\\pdfcreationdate}}
10829 @d pdf_file_mod_date_code = pdftex_first_expand_code + 16 {command code for \.{\\pdffilemoddate}}
10830 @d pdf_file_size_code = pdftex_first_expand_code + 17 {command code for \.{\\pdffilesize}}
10831 @d pdf_mdfive_sum_code = pdftex_first_expand_code + 18 {command code for \.{\\pdfmdfivesum}}
10832 @d pdf_file_dump_code = pdftex_first_expand_code + 19 {command code for \.{\\pdffiledump}}
10833 @d pdf_match_code = pdftex_first_expand_code + 20 {command code for \.{\\pdfmatch}}
10834 @d pdf_last_match_code = pdftex_first_expand_code + 21 {command code for \.{\\pdflastmatch}}
10835 @d uniform_deviate_code = pdftex_first_expand_code + 22 {end of \pdfTeX's command codes}
10836 @d normal_deviate_code = pdftex_first_expand_code + 23 {end of \pdfTeX's command codes}
10837 @d pdf_insert_ht_code = pdftex_first_expand_code + 24 {command code for \.{\\pdfinsertht}}
10838 @d pdf_ximage_bbox_code = pdftex_first_expand_code + 25 {command code for \.{\\pdfximagebbox}}
10839 @d pdftex_convert_codes = pdftex_first_expand_code + 26 {end of \pdfTeX's command codes}
10840 @d job_name_code=pdftex_convert_codes {command code for \.{\\jobname}}
10841
10842 @<Put each...@>=
10843 primitive("number",convert,number_code);@/
10844 @!@:number_}{\.{\\number} primitive@>
10845 primitive("romannumeral",convert,roman_numeral_code);@/
10846 @!@:roman_numeral_}{\.{\\romannumeral} primitive@>
10847 primitive("string",convert,string_code);@/
10848 @!@:string_}{\.{\\string} primitive@>
10849 primitive("meaning",convert,meaning_code);@/
10850 @!@:meaning_}{\.{\\meaning} primitive@>
10851 primitive("fontname",convert,font_name_code);@/
10852 @!@:font_name_}{\.{\\fontname} primitive@>
10853 @#
10854 primitive("expanded",convert,expanded_code);@/
10855 @!@:expanded_}{\.{\\expanded} primitive@>
10856 @#
10857 primitive("pdftexrevision",convert,pdftex_revision_code);@/
10858 @!@:pdftex_revision_}{\.{\\pdftexrevision} primitive@>
10859 primitive("pdftexbanner",convert,pdftex_banner_code);@/
10860 @!@:pdftex_banner_}{\.{\\pdftexbanner} primitive@>
10861 primitive("pdffontname",convert,pdf_font_name_code);@/
10862 @!@:pdf_font_name_}{\.{\\pdffontname} primitive@>
10863 primitive("pdffontobjnum",convert,pdf_font_objnum_code);@/
10864 @!@:pdf_font_objnum_}{\.{\\pdffontobjnum} primitive@>
10865 primitive("pdffontsize",convert,pdf_font_size_code);@/
10866 @!@:pdf_font_size_}{\.{\\pdffontsize} primitive@>
10867 primitive("pdfpageref",convert,pdf_page_ref_code);@/
10868 @!@:pdf_page_ref_}{\.{\\pdfpageref} primitive@>
10869 primitive("leftmarginkern",convert,left_margin_kern_code);@/
10870 @!@:left_margin_kern_}{\.{\\leftmarginkern} primitive@>
10871 primitive("rightmarginkern",convert,right_margin_kern_code);@/
10872 @!@:right_margin_kern_}{\.{\\rightmarginkern} primitive@>
10873 primitive("pdfxformname",convert,pdf_xform_name_code);@/
10874 @!@:pdf_xform_name_}{\.{\\pdfxformname} primitive@>
10875 primitive("pdfescapestring",convert,pdf_escape_string_code);@/
10876 @!@:pdf_escape_string_}{\.{\\pdfescapestring} primitive@>
10877 primitive("pdfescapename",convert,pdf_escape_name_code);@/
10878 @!@:pdf_escape_name_}{\.{\\pdfescapename} primitive@>
10879 primitive("pdfescapehex",convert,pdf_escape_hex_code);@/
10880 @!@:pdf_escape_hex_}{\.{\\pdfescapehex} primitive@>
10881 primitive("pdfunescapehex",convert,pdf_unescape_hex_code);@/
10882 @!@:pdf_unescape_hex_}{\.{\\pdfunescapehex} primitive@>
10883 primitive("pdfcreationdate",convert,pdf_creation_date_code);@/
10884 @!@:pdf_creation_date_}{\.{\\pdfcreationdate} primitive@>
10885 primitive("pdffilemoddate",convert,pdf_file_mod_date_code);@/
10886 @!@:pdf_file_mod_date_}{\.{\\pdffilemoddate} primitive@>
10887 primitive("pdffilesize",convert,pdf_file_size_code);@/
10888 @!@:pdf_file_size_}{\.{\\pdffilesize} primitive@>
10889 primitive("pdfmdfivesum",convert,pdf_mdfive_sum_code);@/
10890 @!@:pdf_mdfive_sum_}{\.{\\pdfmdfivesum} primitive@>
10891 primitive("pdffiledump",convert,pdf_file_dump_code);@/
10892 @!@:pdf_file_dump_}{\.{\\pdffiledump} primitive@>
10893 primitive("pdfmatch",convert,pdf_match_code);@/
10894 @!@:pdf_match_}{\.{\\pdfmatch} primitive@>
10895 primitive("pdflastmatch",convert,pdf_last_match_code);@/
10896 @!@:pdf_last_match_}{\.{\\pdflastmatch} primitive@>
10897 primitive("pdfstrcmp",convert,pdf_strcmp_code);@/
10898 @!@:pdf_strcmp_}{\.{\\pdfstrcmp} primitive@>
10899 primitive("pdfcolorstackinit",convert,pdf_colorstack_init_code);@/
10900 @!@:pdf_colorstack_init_}{\.{\\pdfcolorstackinit} primitive@>
10901 primitive("pdfuniformdeviate",convert,uniform_deviate_code);@/
10902 @!@:uniform_deviate_}{\.{\\pdfuniformdeviate} primitive@>
10903 primitive("pdfnormaldeviate",convert,normal_deviate_code);@/
10904 @!@:normal_deviate_}{\.{\\pdfnormaldeviate} primitive@>
10905 @#
10906 primitive("jobname",convert,job_name_code);@/
10907 @!@:job_name_}{\.{\\jobname} primitive@>
10908 primitive("pdfinsertht",convert,pdf_insert_ht_code);@/
10909 @!@:pdf_insert_ht_}{\.{\\pdfinsertht} primitive@>
10910 primitive("pdfximagebbox",convert,pdf_ximage_bbox_code);@/
10911 @!@:pdf_ximage_bbox_}{\.{\\pdfximagebbox} primitive@>
10912
10913 @ @<Cases of |print_cmd_chr|...@>=
10914 convert: case chr_code of
10915 number_code: print_esc("number");
10916 roman_numeral_code: print_esc("romannumeral");
10917 string_code: print_esc("string");
10918 meaning_code: print_esc("meaning");
10919 font_name_code: print_esc("fontname");
10920 eTeX_revision_code: print_esc("eTeXrevision");
10921 expanded_code: print_esc("expanded");
10922 pdftex_revision_code: print_esc("pdftexrevision");
10923 pdftex_banner_code: print_esc("pdftexbanner");
10924 pdf_font_name_code: print_esc("pdffontname");
10925 pdf_font_objnum_code: print_esc("pdffontobjnum");
10926 pdf_font_size_code: print_esc("pdffontsize");
10927 pdf_page_ref_code: print_esc("pdfpageref");
10928 left_margin_kern_code: print_esc("leftmarginkern");
10929 right_margin_kern_code: print_esc("rightmarginkern");
10930 pdf_xform_name_code: print_esc("pdfxformname");
10931 pdf_escape_string_code: print_esc("pdfescapestring");
10932 pdf_escape_name_code: print_esc("pdfescapename");
10933 pdf_escape_hex_code: print_esc("pdfescapehex");
10934 pdf_unescape_hex_code: print_esc("pdfunescapehex");
10935 pdf_creation_date_code: print_esc("pdfcreationdate");
10936 pdf_file_mod_date_code: print_esc("pdffilemoddate");
10937 pdf_file_size_code: print_esc("pdffilesize");
10938 pdf_mdfive_sum_code: print_esc("pdfmdfivesum");
10939 pdf_file_dump_code: print_esc("pdffiledump");
10940 pdf_match_code: print_esc("pdfmatch");
10941 pdf_last_match_code: print_esc("pdflastmatch");
10942 pdf_strcmp_code: print_esc("pdfstrcmp");
10943 pdf_colorstack_init_code: print_esc("pdfcolorstackinit");
10944 uniform_deviate_code: print_esc("pdfuniformdeviate");
10945 normal_deviate_code: print_esc("pdfnormaldeviate");
10946 pdf_insert_ht_code: print_esc("pdfinsertht");
10947 pdf_ximage_bbox_code: print_esc("pdfximagebbox");
10948 othercases print_esc("jobname")
10949 endcases;
10950
10951 @ The procedure |conv_toks| uses |str_toks| to insert the token list
10952 for |convert| functions into the scanner; `\.{\\outer}' control sequences
10953 are allowed to follow `\.{\\string}' and `\.{\\meaning}'.
10954
10955 The extra temp string |u| is needed because |pdf_scan_ext_toks| incorporates
10956 any pending string in its output. In order to save such a pending string,
10957 we have to create a temporary string that is destroyed immediately after.
10958
10959 @d save_cur_string==if str_start[str_ptr]<pool_ptr then u:=make_string
10960 @d restore_cur_string==if u<>0 then begin decr(str_ptr); u:=0; end
10961
10962 @p procedure conv_toks;
10963 label exit;
10964 var old_setting:0..max_selector; {holds |selector| setting}
10965 p, q: pointer;
10966 @!c:number_code..job_name_code; {desired type of conversion}
10967 @!save_scanner_status:small_number; {|scanner_status| upon entry}
10968 @!save_def_ref: pointer; {|def_ref| upon entry, important if inside `\.{\\message}'}
10969 @!save_warning_index: pointer;
10970 @!booltemp: boolean; {temp boolean}
10971 @!i: integer; {first temp integer}
10972 @!j: integer; {second temp integer}
10973 @!b:pool_pointer; {base of temporary string}
10974 @!s: str_number; {first temp string}
10975 @!t: str_number; {second temp string}
10976 @!u: str_number; {saved current string string}
10977 begin
10978 c:=cur_chr;
10979 u:=0; { will become non-nil if a string is already being built}
10980 @<Scan the argument for command |c|@>;
10981 old_setting:=selector; selector:=new_string; b:=pool_ptr;
10982 @<Print the result of command |c|@>;
10983 selector:=old_setting; link(garbage):=str_toks(b); ins_list(link(temp_head));
10984 exit:end;
10985
10986 @ @<Scan the argument for command |c|@>=
10987 case c of
10988 number_code,roman_numeral_code: scan_int;
10989 string_code, meaning_code: begin save_scanner_status:=scanner_status;
10990 scanner_status:=normal; get_token; scanner_status:=save_scanner_status;
10991 end;
10992 font_name_code: scan_font_ident;
10993 eTeX_revision_code: do_nothing;
10994 expanded_code:
10995 begin
10996 save_scanner_status := scanner_status;
10997 save_warning_index := warning_index;
10998 save_def_ref := def_ref;
10999 save_cur_string;
11000 scan_pdf_ext_toks;
11001 warning_index := save_warning_index;
11002 scanner_status := save_scanner_status;
11003 ins_list(link(def_ref));
11004 free_avail(def_ref);
11005 def_ref := save_def_ref;
11006 restore_cur_string;
11007 return;
11008 end;
11009 pdftex_revision_code: do_nothing;
11010 pdftex_banner_code: do_nothing;
11011 pdf_font_name_code, pdf_font_objnum_code, pdf_font_size_code: begin
11012 scan_font_ident;
11013 if cur_val = null_font then
11014 pdf_error("font", "invalid font identifier");
11015 if c <> pdf_font_size_code then begin
11016 pdf_check_vf_cur_val;
11017 if not font_used[cur_val] then
11018 pdf_init_font_cur_val;
11019 end;
11020 end;
11021 pdf_page_ref_code: begin
11022 scan_int;
11023 if cur_val <= 0 then
11024 pdf_error("pageref", "invalid page number");
11025 end;
11026 left_margin_kern_code, right_margin_kern_code: begin
11027 scan_register_num;
11028 fetch_box(p);
11029 if (p = null) or (type(p) <> hlist_node) then
11030 pdf_error("marginkern", "a non-empty hbox expected")
11031 end;
11032 pdf_xform_name_code: begin
11033 scan_int;
11034 pdf_check_obj(obj_type_xform, cur_val);
11035 end;
11036 pdf_escape_string_code:
11037 begin
11038 save_scanner_status := scanner_status;
11039 save_warning_index := warning_index;
11040 save_def_ref := def_ref;
11041 save_cur_string;
11042 scan_pdf_ext_toks;
11043 s := tokens_to_string(def_ref);
11044 delete_token_ref(def_ref);
11045 def_ref := save_def_ref;
11046 warning_index := save_warning_index;
11047 scanner_status := save_scanner_status;
11048 b := pool_ptr;
11049 escapestring(str_start[s]);
11050 link(garbage) := str_toks(b);
11051 flush_str(s);
11052 ins_list(link(temp_head));
11053 restore_cur_string;
11054 return;
11055 end;
11056 pdf_escape_name_code:
11057 begin
11058 save_scanner_status := scanner_status;
11059 save_warning_index := warning_index;
11060 save_def_ref := def_ref;
11061 save_cur_string;
11062 scan_pdf_ext_toks;
11063 s := tokens_to_string(def_ref);
11064 delete_token_ref(def_ref);
11065 def_ref := save_def_ref;
11066 warning_index := save_warning_index;
11067 scanner_status := save_scanner_status;
11068 b := pool_ptr;
11069 escapename(str_start[s]);
11070 link(garbage) := str_toks(b);
11071 flush_str(s);
11072 ins_list(link(temp_head));
11073 restore_cur_string;
11074 return;
11075 end;
11076 pdf_escape_hex_code:
11077 begin
11078 save_scanner_status := scanner_status;
11079 save_warning_index := warning_index;
11080 save_def_ref := def_ref;
11081 save_cur_string;
11082 scan_pdf_ext_toks;
11083 s := tokens_to_string(def_ref);
11084 delete_token_ref(def_ref);
11085 def_ref := save_def_ref;
11086 warning_index := save_warning_index;
11087 scanner_status := save_scanner_status;
11088 b := pool_ptr;
11089 escapehex(str_start[s]);
11090 link(garbage) := str_toks(b);
11091 flush_str(s);
11092 ins_list(link(temp_head));
11093 restore_cur_string;
11094 return;
11095 end;
11096 pdf_unescape_hex_code:
11097 begin
11098 save_scanner_status := scanner_status;
11099 save_warning_index := warning_index;
11100 save_def_ref := def_ref;
11101 save_cur_string;
11102 scan_pdf_ext_toks;
11103 s := tokens_to_string(def_ref);
11104 delete_token_ref(def_ref);
11105 def_ref := save_def_ref;
11106 warning_index := save_warning_index;
11107 scanner_status := save_scanner_status;
11108 b := pool_ptr;
11109 unescapehex(str_start[s]);
11110 link(garbage) := str_toks(b);
11111 flush_str(s);
11112 ins_list(link(temp_head));
11113 restore_cur_string;
11114 return;
11115 end;
11116 pdf_creation_date_code:
11117 begin
11118 b := pool_ptr;
11119 getcreationdate;
11120 link(garbage) := str_toks(b);
11121 ins_list(link(temp_head));
11122 return;
11123 end;
11124 pdf_file_mod_date_code:
11125 begin
11126 save_scanner_status := scanner_status;
11127 save_warning_index := warning_index;
11128 save_def_ref := def_ref;
11129 save_cur_string;
11130 scan_pdf_ext_toks;
11131 s := tokens_to_string(def_ref);
11132 delete_token_ref(def_ref);
11133 def_ref := save_def_ref;
11134 warning_index := save_warning_index;
11135 scanner_status := save_scanner_status;
11136 b := pool_ptr;
11137 getfilemoddate(s);
11138 link(garbage) := str_toks(b);
11139 flush_str(s);
11140 ins_list(link(temp_head));
11141 restore_cur_string;
11142 return;
11143 end;
11144 pdf_file_size_code:
11145 begin
11146 save_scanner_status := scanner_status;
11147 save_warning_index := warning_index;
11148 save_def_ref := def_ref;
11149 save_cur_string;
11150 scan_pdf_ext_toks;
11151 s := tokens_to_string(def_ref);
11152 delete_token_ref(def_ref);
11153 def_ref := save_def_ref;
11154 warning_index := save_warning_index;
11155 scanner_status := save_scanner_status;
11156 b := pool_ptr;
11157 getfilesize(s);
11158 link(garbage) := str_toks(b);
11159 flush_str(s);
11160 ins_list(link(temp_head));
11161 restore_cur_string;
11162 return;
11163 end;
11164 pdf_mdfive_sum_code:
11165 begin
11166 save_scanner_status := scanner_status;
11167 save_warning_index := warning_index;
11168 save_def_ref := def_ref;
11169 save_cur_string;
11170 booltemp := scan_keyword("file");
11171 scan_pdf_ext_toks;
11172 s := tokens_to_string(def_ref);
11173 delete_token_ref(def_ref);
11174 def_ref := save_def_ref;
11175 warning_index := save_warning_index;
11176 scanner_status := save_scanner_status;
11177 b := pool_ptr;
11178 getmd5sum(s, booltemp);
11179 link(garbage) := str_toks(b);
11180 flush_str(s);
11181 ins_list(link(temp_head));
11182 restore_cur_string;
11183 return;
11184 end;
11185 pdf_file_dump_code:
11186 begin
11187 save_scanner_status := scanner_status;
11188 save_warning_index := warning_index;
11189 save_def_ref := def_ref;
11190 save_cur_string;
11191 {scan offset}
11192 cur_val := 0;
11193 if (scan_keyword("offset")) then begin
11194 scan_int;
11195 if (cur_val < 0) then begin
11196 print_err("Bad file offset");
11197 @.Bad file offset@>
11198 help2("A file offset must be between 0 and 2^{31}-1,")@/
11199 ("I changed this one to zero.");
11200 int_error(cur_val);
11201 cur_val := 0;
11202 end;
11203 end;
11204 i := cur_val;
11205 {scan length}
11206 cur_val := 0;
11207 if (scan_keyword("length")) then begin
11208 scan_int;
11209 if (cur_val < 0) then begin
11210 print_err("Bad dump length");
11211 @.Bad dump length@>
11212 help2("A dump length must be between 0 and 2^{31}-1,")@/
11213 ("I changed this one to zero.");
11214 int_error(cur_val);
11215 cur_val := 0;
11216 end;
11217 end;
11218 j := cur_val;
11219 {scan file name}
11220 scan_pdf_ext_toks;
11221 s := tokens_to_string(def_ref);
11222 delete_token_ref(def_ref);
11223 def_ref := save_def_ref;
11224 warning_index := save_warning_index;
11225 scanner_status := save_scanner_status;
11226 b := pool_ptr;
11227 getfiledump(s, i, j);
11228 link(garbage) := str_toks(b);
11229 flush_str(s);
11230 ins_list(link(temp_head));
11231 restore_cur_string;
11232 return;
11233 end;
11234 pdf_match_code:
11235 begin
11236 save_scanner_status := scanner_status;
11237 save_warning_index := warning_index;
11238 save_def_ref := def_ref;
11239 save_cur_string;
11240 {scan for icase}
11241 booltemp := scan_keyword("icase");
11242 {scan for subcount}
11243 i := -1; {default for subcount}
11244 if scan_keyword("subcount") then begin
11245 scan_int;
11246 i := cur_val;
11247 end;
11248 scan_pdf_ext_toks;
11249 s := tokens_to_string(def_ref);
11250 delete_token_ref(def_ref);
11251 scan_pdf_ext_toks;
11252 t := tokens_to_string(def_ref);
11253 delete_token_ref(def_ref);
11254 def_ref := save_def_ref;
11255 warning_index := save_warning_index;
11256 scanner_status := save_scanner_status;
11257 b := pool_ptr;
11258 matchstrings(s, t, i, booltemp);
11259 link(garbage) := str_toks(b);
11260 flush_str(t);
11261 flush_str(s);
11262 ins_list(link(temp_head));
11263 restore_cur_string;
11264 return;
11265 end;
11266 pdf_last_match_code:
11267 begin
11268 scan_int;
11269 if cur_val < 0 then begin
11270 print_err("Bad match number");
11271 @.Bad match number@>
11272 help2("Since I expected zero or a positive number,")@/
11273 ("I changed this one to zero.");
11274 int_error(cur_val);
11275 cur_val := 0;
11276 end;
11277 b := pool_ptr;
11278 getmatch(cur_val);
11279 link(garbage) := str_toks(b);
11280 ins_list(link(temp_head));
11281 return;
11282 end;
11283 pdf_strcmp_code:
11284 begin
11285 save_scanner_status := scanner_status;
11286 save_warning_index := warning_index;
11287 save_def_ref := def_ref;
11288 save_cur_string;
11289 compare_strings;
11290 def_ref := save_def_ref;
11291 warning_index := save_warning_index;
11292 scanner_status := save_scanner_status;
11293 restore_cur_string;
11294 end;
11295 pdf_colorstack_init_code:
11296 begin
11297 booltemp := scan_keyword("page");
11298 if scan_keyword("direct") then
11299 cur_val := direct_always
11300 else
11301 if scan_keyword("page") then
11302 cur_val := direct_page
11303 else
11304 cur_val := set_origin;
11305 save_scanner_status := scanner_status;
11306 save_warning_index := warning_index;
11307 save_def_ref := def_ref;
11308 save_cur_string;
11309 scan_pdf_ext_toks;
11310 s := tokens_to_string(def_ref);
11311 delete_token_ref(def_ref);
11312 def_ref := save_def_ref;
11313 warning_index := save_warning_index;
11314 scanner_status := save_scanner_status;
11315 cur_val := newcolorstack(s, cur_val, booltemp);
11316 flush_str(s);
11317 cur_val_level := int_val;
11318 if cur_val < 0 then begin
11319 print_err("Too many color stacks");
11320 @.Too many color stacks@>
11321 help2("The number of color stacks is limited to 32768.")@/
11322 ("I'll use the default color stack 0 here.");
11323 error;
11324 cur_val := 0;
11325 restore_cur_string;
11326 end;
11327 end;
11328 job_name_code: if job_name=0 then open_log_file;
11329 uniform_deviate_code: scan_int;
11330 normal_deviate_code: do_nothing;
11331 pdf_insert_ht_code: scan_register_num;
11332 pdf_ximage_bbox_code: begin
11333 scan_int;
11334 pdf_check_obj(obj_type_ximage, cur_val);
11335 i := obj_ximage_data(cur_val);
11336 scan_int;
11337 j := cur_val;
11338 if (j < 1) or (j > 4) then
11339 pdf_error("pdfximagebbox", "invalid parameter");
11340 end;
11341 end {there are no other cases}
11342
11343 @ @<Print the result of command |c|@>=
11344 case c of
11345 number_code: print_int(cur_val);
11346 roman_numeral_code: print_roman_int(cur_val);
11347 string_code:if cur_cs<>0 then sprint_cs(cur_cs)
11348 else print_char(cur_chr);
11349 meaning_code: print_meaning;
11350 font_name_code: begin print(font_name[cur_val]);
11351 if font_size[cur_val]<>font_dsize[cur_val] then
11352 begin print(" at "); print_scaled(font_size[cur_val]);
11353 print("pt");
11354 end;
11355 end;
11356 eTeX_revision_code: print(eTeX_revision);
11357 pdftex_revision_code: print(pdftex_revision);
11358 pdftex_banner_code: print(pdftex_banner);
11359 pdf_font_name_code, pdf_font_objnum_code: begin
11360 set_ff(cur_val);
11361 if c = pdf_font_name_code then
11362 print_int(obj_info(pdf_font_num[ff]))
11363 else
11364 print_int(pdf_font_num[ff]);
11365 end;
11366 pdf_font_size_code: begin
11367 print_scaled(font_size[cur_val]);
11368 print("pt");
11369 end;
11370 pdf_page_ref_code: print_int(get_obj(obj_type_page, cur_val, false));
11371 left_margin_kern_code: begin
11372 p := list_ptr(p);
11373 while (p <> null) and
11374 (cp_skipable(p) or
11375 ((not is_char_node(p)) and (type(p) = glue_node) and (subtype(p) = left_skip_code + 1)))
11376 do
11377 p := link(p);
11378 if (p <> null) and (not is_char_node(p)) and
11379 (type(p) = margin_kern_node) and (subtype(p) = left_side) then
11380 print_scaled(width(p))
11381 else
11382 print("0");
11383 print("pt");
11384 end;
11385 right_margin_kern_code: begin
11386 q := list_ptr(p);
11387 p := prev_rightmost(q, null);
11388 while (p <> null) and
11389 (cp_skipable(p) or
11390 ((not is_char_node(p)) and (type(p) = glue_node) and (subtype(p) = right_skip_code + 1)))
11391 do
11392 p := prev_rightmost(q, p);
11393 if (p <> null) and (not is_char_node(p)) and
11394 (type(p) = margin_kern_node) and (subtype(p) = right_side) then
11395 print_scaled(width(p))
11396 else
11397 print("0");
11398 print("pt");
11399 end;
11400 pdf_xform_name_code: print_int(obj_info(cur_val));
11401 pdf_strcmp_code: print_int(cur_val);
11402 pdf_colorstack_init_code: print_int(cur_val);
11403 uniform_deviate_code: print_int(unif_rand(cur_val));
11404 normal_deviate_code: print_int(norm_rand);
11405 pdf_insert_ht_code: begin
11406 i := qi(cur_val);
11407 p := page_ins_head;
11408 while i >= subtype(link(p)) do
11409 p := link(p);
11410 if subtype(p) = i then
11411 print_scaled(height(p))
11412 else
11413 print("0");
11414 print("pt");
11415 end;
11416 pdf_ximage_bbox_code: begin
11417 if is_pdf_image(i) then begin
11418 case j of
11419 1: print_scaled(epdf_orig_x(i));
11420 2: print_scaled(epdf_orig_y(i));
11421 3: print_scaled(epdf_orig_x(i) + image_width(i));
11422 4: print_scaled(epdf_orig_y(i) + image_height(i));
11423 endcases;
11424 end else
11425 print_scaled(0);
11426 print("pt");
11427 end;
11428 job_name_code: print(job_name);
11429 end {there are no other cases}
11430
11431 @ Now we can't postpone the difficulties any longer; we must bravely tackle
11432 |scan_toks|. This function returns a pointer to the tail of a new token
11433 list, and it also makes |def_ref| point to the reference count at the
11434 head of that list.
11435
11436 There are two boolean parameters, |macro_def| and |xpand|. If |macro_def|
11437 is true, the goal is to create the token list for a macro definition;
11438 otherwise the goal is to create the token list for some other \TeX\
11439 primitive: \.{\\mark}, \.{\\output}, \.{\\everypar}, \.{\\lowercase},
11440 \.{\\uppercase}, \.{\\message}, \.{\\errmessage}, \.{\\write}, or
11441 \.{\\special}. In the latter cases a left brace must be scanned next; this
11442 left brace will not be part of the token list, nor will the matching right
11443 brace that comes at the end. If |xpand| is false, the token list will
11444 simply be copied from the input using |get_token|. Otherwise all expandable
11445 tokens will be expanded until unexpandable tokens are left, except that
11446 the results of expanding `\.{\\the}' are not expanded further.
11447 If both |macro_def| and |xpand| are true, the expansion applies
11448 only to the macro body (i.e., to the material following the first
11449 |left_brace| character).
11450
11451 The value of |cur_cs| when |scan_toks| begins should be the |eqtb|
11452 address of the control sequence to display in ``runaway'' error
11453 messages.
11454
11455 @p function scan_toks(@!macro_def,@!xpand:boolean):pointer;
11456 label found,continue,done,done1,done2;
11457 var t:halfword; {token representing the highest parameter number}
11458 @!s:halfword; {saved token}
11459 @!p:pointer; {tail of the token list being built}
11460 @!q:pointer; {new node being added to the token list via |store_new_token|}
11461 @!unbalance:halfword; {number of unmatched left braces}
11462 @!hash_brace:halfword; {possible `\.{\#\{}' token}
11463 begin if macro_def then scanner_status:=defining
11464 @+else scanner_status:=absorbing;
11465 warning_index:=cur_cs; def_ref:=get_avail; token_ref_count(def_ref):=null;
11466 p:=def_ref; hash_brace:=0; t:=zero_token;
11467 if macro_def then @<Scan and build the parameter part of the macro definition@>
11468 else scan_left_brace; {remove the compulsory left brace}
11469 @<Scan and build the body of the token list; |goto found| when finished@>;
11470 found: scanner_status:=normal;
11471 if hash_brace<>0 then store_new_token(hash_brace);
11472 scan_toks:=p;
11473 end;
11474
11475 @ @<Scan and build the parameter part...@>=
11476 begin loop begin continue: get_token; {set |cur_cmd|, |cur_chr|, |cur_tok|}
11477 if cur_tok<right_brace_limit then goto done1;
11478 if cur_cmd=mac_param then
11479 @<If the next character is a parameter number, make |cur_tok|
11480 a |match| token; but if it is a left brace, store
11481 `|left_brace|, |end_match|', set |hash_brace|, and |goto done|@>;
11482 store_new_token(cur_tok);
11483 end;
11484 done1: store_new_token(end_match_token);
11485 if cur_cmd=right_brace then
11486 @<Express shock at the missing left brace; |goto found|@>;
11487 done: end
11488
11489 @ @<Express shock...@>=
11490 begin print_err("Missing { inserted"); incr(align_state);
11491 @.Missing \{ inserted@>
11492 help2("Where was the left brace? You said something like `\def\a}',")@/
11493 ("which I'm going to interpret as `\def\a{}'."); error; goto found;
11494 end
11495
11496 @ @<If the next character is a parameter number...@>=
11497 begin s:=match_token+cur_chr; get_token;
11498 if cur_tok<left_brace_limit then
11499 begin hash_brace:=cur_tok;
11500 store_new_token(cur_tok); store_new_token(end_match_token);
11501 goto done;
11502 end;
11503 if t=zero_token+9 then
11504 begin print_err("You already have nine parameters");
11505 @.You already have nine...@>
11506 help2("I'm going to ignore the # sign you just used,")@/
11507 ("as well as the token that followed it."); error; goto continue;
11508 end
11509 else begin incr(t);
11510 if cur_tok<>t then
11511 begin print_err("Parameters must be numbered consecutively");
11512 @.Parameters...consecutively@>
11513 help2("I've inserted the digit you should have used after the #.")@/
11514 ("Type `1' to delete what you did use."); back_error;
11515 end;
11516 cur_tok:=s;
11517 end;
11518 end
11519
11520 @ @<Scan and build the body of the token list; |goto found| when finished@>=
11521 unbalance:=1;
11522 loop@+ begin if xpand then @<Expand the next part of the input@>
11523 else get_token;
11524 if cur_tok<right_brace_limit then
11525 if cur_cmd<right_brace then incr(unbalance)
11526 else begin decr(unbalance);
11527 if unbalance=0 then goto found;
11528 end
11529 else if cur_cmd=mac_param then
11530 if macro_def then @<Look for parameter number or \.{\#\#}@>;
11531 store_new_token(cur_tok);
11532 end
11533
11534 @ Here we insert an entire token list created by |the_toks| without
11535 expanding it further.
11536
11537 @<Expand the next part of the input@>=
11538 begin loop begin get_next;
11539 if cur_cmd>=call then
11540 if info(link(cur_chr))=protected_token then
11541 begin cur_cmd:=relax; cur_chr:=no_expand_flag;
11542 end;
11543 if cur_cmd<=max_command then goto done2;
11544 if cur_cmd<>the then expand
11545 else begin q:=the_toks;
11546 if link(temp_head)<>null then
11547 begin link(p):=link(temp_head); p:=q;
11548 end;
11549 end;
11550 end;
11551 done2: x_token
11552 end
11553
11554 @ @<Look for parameter number...@>=
11555 begin s:=cur_tok;
11556 if xpand then get_x_token else get_token;
11557 if cur_cmd<>mac_param then
11558 if (cur_tok<=zero_token)or(cur_tok>t) then
11559 begin print_err("Illegal parameter number in definition of ");
11560 @.Illegal parameter number...@>
11561 sprint_cs(warning_index);
11562 help3("You meant to type ## instead of #, right?")@/
11563 ("Or maybe a } was forgotten somewhere earlier, and things")@/
11564 ("are all screwed up? I'm going to assume that you meant ##.");
11565 back_error; cur_tok:=s;
11566 end
11567 else cur_tok:=out_param_token-"0"+cur_chr;
11568 end
11569
11570 @ Another way to create a token list is via the \.{\\read} command. The
11571 sixteen files potentially usable for reading appear in the following
11572 global variables. The value of |read_open[n]| will be |closed| if
11573 stream number |n| has not been opened or if it has been fully read;
11574 |just_open| if an \.{\\openin} but not a \.{\\read} has been done;
11575 and |normal| if it is open and ready to read the next line.
11576
11577 @d closed=2 {not open, or at end of file}
11578 @d just_open=1 {newly opened, first line not yet read}
11579
11580 @<Glob...@>=
11581 @!read_file:array[0..15] of alpha_file; {used for \.{\\read}}
11582 @!read_open:array[0..16] of normal..closed; {state of |read_file[n]|}
11583
11584 @ @<Set init...@>=
11585 for k:=0 to 16 do read_open[k]:=closed;
11586
11587 @ The |read_toks| procedure constructs a token list like that for any
11588 macro definition, and makes |cur_val| point to it. Parameter |r| points
11589 to the control sequence that will receive this token list.
11590
11591 @p procedure read_toks(@!n:integer;@!r:pointer;@!j:halfword);
11592 label done;
11593 var p:pointer; {tail of the token list}
11594 @!q:pointer; {new node being added to the token list via |store_new_token|}
11595 @!s:integer; {saved value of |align_state|}
11596 @!m:small_number; {stream number}
11597 begin scanner_status:=defining; warning_index:=r;
11598 def_ref:=get_avail; token_ref_count(def_ref):=null;
11599 p:=def_ref; {the reference count}
11600 store_new_token(end_match_token);
11601 if (n<0)or(n>15) then m:=16@+else m:=n;
11602 s:=align_state; align_state:=1000000; {disable tab marks, etc.}
11603 repeat @<Input and store tokens from the next line of the file@>;
11604 until align_state=1000000;
11605 cur_val:=def_ref; scanner_status:=normal; align_state:=s;
11606 end;
11607
11608 @ @<Input and store tokens from the next line of the file@>=
11609 begin_file_reading; name:=m+1;
11610 if read_open[m]=closed then @<Input for \.{\\read} from the terminal@>
11611 else if read_open[m]=just_open then @<Input the first line of |read_file[m]|@>
11612 else @<Input the next line of |read_file[m]|@>;
11613 limit:=last;
11614 if end_line_char_inactive then decr(limit)
11615 else buffer[limit]:=end_line_char;
11616 first:=limit+1; loc:=start; state:=new_line;@/
11617 @<Handle \.{\\readline} and |goto done|@>;@/
11618 loop@+ begin get_token;
11619 if cur_tok=0 then goto done;
11620 {|cur_cmd=cur_chr=0| will occur at the end of the line}
11621 if align_state<1000000 then {unmatched `\.\}' aborts the line}
11622 begin repeat get_token; until cur_tok=0;
11623 align_state:=1000000; goto done;
11624 end;
11625 store_new_token(cur_tok);
11626 end;
11627 done: end_file_reading
11628
11629 @ Here we input on-line into the |buffer| array, prompting the user explicitly
11630 if |n>=0|. The value of |n| is set negative so that additional prompts
11631 will not be given in the case of multi-line input.
11632
11633 @<Input for \.{\\read} from the terminal@>=
11634 if interaction>nonstop_mode then
11635 if n<0 then prompt_input("")
11636 else begin wake_up_terminal;
11637 print_ln; sprint_cs(r); prompt_input("="); n:=-1;
11638 end
11639 else fatal_error("*** (cannot \read from terminal in nonstop modes)")
11640 @.cannot \\read@>
11641
11642 @ The first line of a file must be treated specially, since |input_ln|
11643 must be told not to start with |get|.
11644 @^system dependencies@>
11645
11646 @<Input the first line of |read_file[m]|@>=
11647 if input_ln(read_file[m],false) then read_open[m]:=normal
11648 else begin a_close(read_file[m]); read_open[m]:=closed;
11649 end
11650
11651 @ An empty line is appended at the end of a |read_file|.
11652 @^empty line at end of file@>
11653
11654 @<Input the next line of |read_file[m]|@>=
11655 begin if not input_ln(read_file[m],true) then
11656 begin a_close(read_file[m]); read_open[m]:=closed;
11657 if align_state<>1000000 then
11658 begin runaway;
11659 print_err("File ended within "); print_esc("read");
11660 @.File ended within \\read@>
11661 help1("This \read has unbalanced braces.");
11662 align_state:=1000000; limit:=0; error;
11663 end;
11664 end;
11665 end
11666
11667 @* \[28] Conditional processing.
11668 We consider now the way \TeX\ handles various kinds of \.{\\if} commands.
11669
11670 @d unless_code=32 {amount added for `\.{\\unless}' prefix}
11671 @#
11672 @d if_char_code=0 { `\.{\\if}' }
11673 @d if_cat_code=1 { `\.{\\ifcat}' }
11674 @d if_int_code=2 { `\.{\\ifnum}' }
11675 @d if_dim_code=3 { `\.{\\ifdim}' }
11676 @d if_odd_code=4 { `\.{\\ifodd}' }
11677 @d if_vmode_code=5 { `\.{\\ifvmode}' }
11678 @d if_hmode_code=6 { `\.{\\ifhmode}' }
11679 @d if_mmode_code=7 { `\.{\\ifmmode}' }
11680 @d if_inner_code=8 { `\.{\\ifinner}' }
11681 @d if_void_code=9 { `\.{\\ifvoid}' }
11682 @d if_hbox_code=10 { `\.{\\ifhbox}' }
11683 @d if_vbox_code=11 { `\.{\\ifvbox}' }
11684 @d ifx_code=12 { `\.{\\ifx}' }
11685 @d if_eof_code=13 { `\.{\\ifeof}' }
11686 @d if_true_code=14 { `\.{\\iftrue}' }
11687 @d if_false_code=15 { `\.{\\iffalse}' }
11688 @d if_case_code=16 { `\.{\\ifcase}' }
11689 @d if_pdfprimitive_code=21 { `\.{\\ifpdfprimitive}' }
11690
11691 @<Put each...@>=
11692 primitive("if",if_test,if_char_code);
11693 @!@:if_char_}{\.{\\if} primitive@>
11694 primitive("ifcat",if_test,if_cat_code);
11695 @!@:if_cat_code_}{\.{\\ifcat} primitive@>
11696 primitive("ifnum",if_test,if_int_code);
11697 @!@:if_int_}{\.{\\ifnum} primitive@>
11698 primitive("ifdim",if_test,if_dim_code);
11699 @!@:if_dim_}{\.{\\ifdim} primitive@>
11700 primitive("ifodd",if_test,if_odd_code);
11701 @!@:if_odd_}{\.{\\ifodd} primitive@>
11702 primitive("ifvmode",if_test,if_vmode_code);
11703 @!@:if_vmode_}{\.{\\ifvmode} primitive@>
11704 primitive("ifhmode",if_test,if_hmode_code);
11705 @!@:if_hmode_}{\.{\\ifhmode} primitive@>
11706 primitive("ifmmode",if_test,if_mmode_code);
11707 @!@:if_mmode_}{\.{\\ifmmode} primitive@>
11708 primitive("ifinner",if_test,if_inner_code);
11709 @!@:if_inner_}{\.{\\ifinner} primitive@>
11710 primitive("ifvoid",if_test,if_void_code);
11711 @!@:if_void_}{\.{\\ifvoid} primitive@>
11712 primitive("ifhbox",if_test,if_hbox_code);
11713 @!@:if_hbox_}{\.{\\ifhbox} primitive@>
11714 primitive("ifvbox",if_test,if_vbox_code);
11715 @!@:if_vbox_}{\.{\\ifvbox} primitive@>
11716 primitive("ifx",if_test,ifx_code);
11717 @!@:ifx_}{\.{\\ifx} primitive@>
11718 primitive("ifeof",if_test,if_eof_code);
11719 @!@:if_eof_}{\.{\\ifeof} primitive@>
11720 primitive("iftrue",if_test,if_true_code);
11721 @!@:if_true_}{\.{\\iftrue} primitive@>
11722 primitive("iffalse",if_test,if_false_code);
11723 @!@:if_false_}{\.{\\iffalse} primitive@>
11724 primitive("ifcase",if_test,if_case_code);
11725 @!@:if_case_}{\.{\\ifcase} primitive@>
11726 primitive("ifpdfprimitive",if_test,if_pdfprimitive_code);
11727 @!@:if_pdfprimitive_}{\.{\\ifpdfprimitive} primitive@>
11728
11729 @ @<Cases of |print_cmd_chr|...@>=
11730 if_test: begin if chr_code>=unless_code then print_esc("unless");
11731 case chr_code mod unless_code of
11732 if_cat_code:print_esc("ifcat");
11733 if_int_code:print_esc("ifnum");
11734 if_dim_code:print_esc("ifdim");
11735 if_odd_code:print_esc("ifodd");
11736 if_vmode_code:print_esc("ifvmode");
11737 if_hmode_code:print_esc("ifhmode");
11738 if_mmode_code:print_esc("ifmmode");
11739 if_inner_code:print_esc("ifinner");
11740 if_void_code:print_esc("ifvoid");
11741 if_hbox_code:print_esc("ifhbox");
11742 if_vbox_code:print_esc("ifvbox");
11743 ifx_code:print_esc("ifx");
11744 if_eof_code:print_esc("ifeof");
11745 if_true_code:print_esc("iftrue");
11746 if_false_code:print_esc("iffalse");
11747 if_case_code:print_esc("ifcase");
11748 if_pdfprimitive_code:print_esc("ifpdfprimitive");
11749 @/@<Cases of |if_test| for |print_cmd_chr|@>@/
11750 othercases print_esc("if")
11751 endcases;
11752 end;
11753
11754 @ Conditions can be inside conditions, and this nesting has a stack
11755 that is independent of the |save_stack|.
11756
11757 Four global variables represent the top of the condition stack:
11758 |cond_ptr| points to pushed-down entries, if any; |if_limit| specifies
11759 the largest code of a |fi_or_else| command that is syntactically legal;
11760 |cur_if| is the name of the current type of conditional; and |if_line|
11761 is the line number at which it began.
11762
11763 If no conditions are currently in progress, the condition stack has the
11764 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
11765 Otherwise |cond_ptr| points to a two-word node; the |type|, |subtype|, and
11766 |link| fields of the first word contain |if_limit|, |cur_if|, and
11767 |cond_ptr| at the next level, and the second word contains the
11768 corresponding |if_line|.
11769
11770 @d if_node_size=2 {number of words in stack entry for conditionals}
11771 @d if_line_field(#)==mem[#+1].int
11772 @d if_code=1 {code for \.{\\if...} being evaluated}
11773 @d fi_code=2 {code for \.{\\fi}}
11774 @d else_code=3 {code for \.{\\else}}
11775 @d or_code=4 {code for \.{\\or}}
11776
11777 @<Glob...@>=
11778 @!cond_ptr:pointer; {top of the condition stack}
11779 @!if_limit:normal..or_code; {upper bound on |fi_or_else| codes}
11780 @!cur_if:small_number; {type of conditional being worked on}
11781 @!if_line:integer; {line where that conditional began}
11782
11783 @ @<Set init...@>=
11784 cond_ptr:=null; if_limit:=normal; cur_if:=0; if_line:=0;
11785
11786 @ @<Put each...@>=
11787 primitive("fi",fi_or_else,fi_code);
11788 @!@:fi_}{\.{\\fi} primitive@>
11789 text(frozen_fi):="fi"; eqtb[frozen_fi]:=eqtb[cur_val];
11790 primitive("or",fi_or_else,or_code);
11791 @!@:or_}{\.{\\or} primitive@>
11792 primitive("else",fi_or_else,else_code);
11793 @!@:else_}{\.{\\else} primitive@>
11794
11795 @ @<Cases of |print_cmd_chr|...@>=
11796 fi_or_else: if chr_code=fi_code then print_esc("fi")
11797 else if chr_code=or_code then print_esc("or")
11798 else print_esc("else");
11799
11800 @ When we skip conditional text, we keep track of the line number
11801 where skipping began, for use in error messages.
11802
11803 @<Glob...@>=
11804 @!skip_line:integer; {skipping began here}
11805
11806 @ Here is a procedure that ignores text until coming to an \.{\\or},
11807 \.{\\else}, or \.{\\fi} at the current level of $\.{\\if}\ldots\.{\\fi}$
11808 nesting. After it has acted, |cur_chr| will indicate the token that
11809 was found, but |cur_tok| will not be set (because this makes the
11810 procedure run faster).
11811
11812 @p procedure pass_text;
11813 label done;
11814 var l:integer; {level of $\.{\\if}\ldots\.{\\fi}$ nesting}
11815 @!save_scanner_status:small_number; {|scanner_status| upon entry}
11816 begin save_scanner_status:=scanner_status; scanner_status:=skipping; l:=0;
11817 skip_line:=line;
11818 loop@+ begin get_next;
11819 if cur_cmd=fi_or_else then
11820 begin if l=0 then goto done;
11821 if cur_chr=fi_code then decr(l);
11822 end
11823 else if cur_cmd=if_test then incr(l);
11824 end;
11825 done: scanner_status:=save_scanner_status;
11826 if tracing_ifs>0 then show_cur_cmd_chr;
11827 end;
11828
11829 @ When we begin to process a new \.{\\if}, we set |if_limit:=if_code|; then
11830 if\/ \.{\\or} or \.{\\else} or \.{\\fi} occurs before the current \.{\\if}
11831 condition has been evaluated, \.{\\relax} will be inserted.
11832 For example, a sequence of commands like `\.{\\ifvoid1\\else...\\fi}'
11833 would otherwise require something after the `\.1'.
11834
11835 @<Push the condition stack@>=
11836 begin p:=get_node(if_node_size); link(p):=cond_ptr; type(p):=if_limit;
11837 subtype(p):=cur_if; if_line_field(p):=if_line;
11838 cond_ptr:=p; cur_if:=cur_chr; if_limit:=if_code; if_line:=line;
11839 end
11840
11841 @ @<Pop the condition stack@>=
11842 begin if if_stack[in_open]=cond_ptr then if_warning;
11843 {conditionals possibly not properly nested with files}
11844 p:=cond_ptr; if_line:=if_line_field(p);
11845 cur_if:=subtype(p); if_limit:=type(p); cond_ptr:=link(p);
11846 free_node(p,if_node_size);
11847 end
11848
11849 @ Here's a procedure that changes the |if_limit| code corresponding to
11850 a given value of |cond_ptr|.
11851
11852 @p procedure change_if_limit(@!l:small_number;@!p:pointer);
11853 label exit;
11854 var q:pointer;
11855 begin if p=cond_ptr then if_limit:=l {that's the easy case}
11856 else begin q:=cond_ptr;
11857 loop@+ begin if q=null then confusion("if");
11858 @:this can't happen if}{\quad if@>
11859 if link(q)=p then
11860 begin type(q):=l; return;
11861 end;
11862 q:=link(q);
11863 end;
11864 end;
11865 exit:end;
11866
11867 @ A condition is started when the |expand| procedure encounters
11868 an |if_test| command; in that case |expand| reduces to |conditional|,
11869 which is a recursive procedure.
11870 @^recursion@>
11871
11872 @p procedure conditional;
11873 label exit,common_ending;
11874 var b:boolean; {is the condition true?}
11875 @!e:boolean; {keep track of nested csnames}
11876 @!r:"<"..">"; {relation to be evaluated}
11877 @!m,@!n:integer; {to be tested against the second operand}
11878 @!p,@!q:pointer; {for traversing token lists in \.{\\ifx} tests}
11879 @!save_scanner_status:small_number; {|scanner_status| upon entry}
11880 @!save_cond_ptr:pointer; {|cond_ptr| corresponding to this conditional}
11881 @!this_if:small_number; {type of this conditional}
11882 @!is_unless:boolean; {was this if preceded by `\.{\\unless}' ?}
11883 begin if tracing_ifs>0 then if tracing_commands<=1 then show_cur_cmd_chr;
11884 @<Push the condition stack@>;@+save_cond_ptr:=cond_ptr;
11885 is_unless:=(cur_chr>=unless_code); this_if:=cur_chr mod unless_code;@/
11886 @<Either process \.{\\ifcase} or set |b| to the value of a boolean condition@>;
11887 if is_unless then b:=not b;
11888 if tracing_commands>1 then @<Display the value of |b|@>;
11889 if b then
11890 begin change_if_limit(else_code,save_cond_ptr);
11891 return; {wait for \.{\\else} or \.{\\fi}}
11892 end;
11893 @<Skip to \.{\\else} or \.{\\fi}, then |goto common_ending|@>;
11894 common_ending: if cur_chr=fi_code then @<Pop the condition stack@>
11895 else if_limit:=fi_code; {wait for \.{\\fi}}
11896 exit:end;
11897
11898 @ In a construction like `\.{\\if\\iftrue abc\\else d\\fi}', the first
11899 \.{\\else} that we come to after learning that the \.{\\if} is false is
11900 not the \.{\\else} we're looking for. Hence the following curious
11901 logic is needed.
11902
11903 @ @<Skip to \.{\\else} or \.{\\fi}...@>=
11904 loop@+ begin pass_text;
11905 if cond_ptr=save_cond_ptr then
11906 begin if cur_chr<>or_code then goto common_ending;
11907 print_err("Extra "); print_esc("or");
11908 @.Extra \\or@>
11909 help1("I'm ignoring this; it doesn't match any \if.");
11910 error;
11911 end
11912 else if cur_chr=fi_code then @<Pop the condition stack@>;
11913 end
11914
11915 @ @<Either process \.{\\ifcase} or set |b|...@>=
11916 case this_if of
11917 if_char_code, if_cat_code: @<Test if two characters match@>;
11918 if_int_code, if_dim_code: @<Test relation between integers or dimensions@>;
11919 if_odd_code: @<Test if an integer is odd@>;
11920 if_vmode_code: b:=(abs(mode)=vmode);
11921 if_hmode_code: b:=(abs(mode)=hmode);
11922 if_mmode_code: b:=(abs(mode)=mmode);
11923 if_inner_code: b:=(mode<0);
11924 if_void_code, if_hbox_code, if_vbox_code: @<Test box register status@>;
11925 ifx_code: @<Test if two tokens match@>;
11926 if_eof_code: begin scan_four_bit_int; b:=(read_open[cur_val]=closed);
11927 end;
11928 if_true_code: b:=true;
11929 if_false_code: b:=false;
11930 @/@<Cases for |conditional|@>@/
11931 if_case_code: @<Select the appropriate case
11932 and |return| or |goto common_ending|@>;
11933 if_pdfprimitive_code: begin
11934 save_scanner_status:=scanner_status;
11935 scanner_status:=normal;
11936 get_next;
11937 scanner_status:=save_scanner_status;
11938 if cur_cs < hash_base then
11939 m := prim_lookup(cur_cs-single_base)
11940 else
11941 m := prim_lookup(text(cur_cs));
11942 b :=((cur_cmd<>undefined_cs) and
11943 (m<>undefined_primitive) and
11944 (cur_cmd=prim_eq_type(m)) and
11945 (cur_chr=prim_equiv(m)));
11946 end;
11947 end {there are no other cases}
11948
11949 @ @<Display the value of |b|@>=
11950 begin begin_diagnostic;
11951 if b then print("{true}")@+else print("{false}");
11952 end_diagnostic(false);
11953 end
11954
11955 @ Here we use the fact that |"<"|, |"="|, and |">"| are consecutive ASCII
11956 codes.
11957 @^ASCII code@>
11958
11959 @<Test relation between integers or dimensions@>=
11960 begin if this_if=if_int_code then scan_int@+else scan_normal_dimen;
11961 n:=cur_val; @<Get the next non-blank non-call...@>;
11962 if (cur_tok>=other_token+"<")and(cur_tok<=other_token+">") then
11963 r:=cur_tok-other_token
11964 else begin print_err("Missing = inserted for ");
11965 @.Missing = inserted@>
11966 print_cmd_chr(if_test,this_if);
11967 help1("I was expecting to see `<', `=', or `>'. Didn't.");
11968 back_error; r:="=";
11969 end;
11970 if this_if=if_int_code then scan_int@+else scan_normal_dimen;
11971 case r of
11972 "<": b:=(n<cur_val);
11973 "=": b:=(n=cur_val);
11974 ">": b:=(n>cur_val);
11975 end;
11976 end
11977
11978 @ @<Test if an integer is odd@>=
11979 begin scan_int; b:=odd(cur_val);
11980 end
11981
11982 @ @<Test box register status@>=
11983 begin scan_register_num; fetch_box(p);
11984 if this_if=if_void_code then b:=(p=null)
11985 else if p=null then b:=false
11986 else if this_if=if_hbox_code then b:=(type(p)=hlist_node)
11987 else b:=(type(p)=vlist_node);
11988 end
11989
11990 @ An active character will be treated as category 13 following
11991 \.{\\if\\noexpand} or following \.{\\ifcat\\noexpand}. We use the fact that
11992 active characters have the smallest tokens, among all control sequences.
11993
11994 @d get_x_token_or_active_char==@t@>@;
11995 begin get_x_token;
11996 if cur_cmd=relax then if cur_chr=no_expand_flag then
11997 begin cur_cmd:=active_char;
11998 cur_chr:=cur_tok-cs_token_flag-active_base;
11999 end;
12000 end
12001
12002 @<Test if two characters match@>=
12003 begin get_x_token_or_active_char;
12004 if (cur_cmd>active_char)or(cur_chr>255) then {not a character}
12005 begin m:=relax; n:=256;
12006 end
12007 else begin m:=cur_cmd; n:=cur_chr;
12008 end;
12009 get_x_token_or_active_char;
12010 if (cur_cmd>active_char)or(cur_chr>255) then
12011 begin cur_cmd:=relax; cur_chr:=256;
12012 end;
12013 if this_if=if_char_code then b:=(n=cur_chr)@+else b:=(m=cur_cmd);
12014 end
12015
12016 @ Note that `\.{\\ifx}' will declare two macros different if one is \\{long}
12017 or \\{outer} and the other isn't, even though the texts of the macros are
12018 the same.
12019
12020 We need to reset |scanner_status|, since \.{\\outer} control sequences
12021 are allowed, but we might be scanning a macro definition or preamble.
12022
12023 @<Test if two tokens match@>=
12024 begin save_scanner_status:=scanner_status; scanner_status:=normal;
12025 get_next; n:=cur_cs; p:=cur_cmd; q:=cur_chr;
12026 get_next; if cur_cmd<>p then b:=false
12027 else if cur_cmd<call then b:=(cur_chr=q)
12028 else @<Test if two macro texts match@>;
12029 scanner_status:=save_scanner_status;
12030 end
12031
12032 @ Note also that `\.{\\ifx}' decides that macros \.{\\a} and \.{\\b} are
12033 different in examples like this:
12034 $$\vbox{\halign{\.{#}\hfil&\qquad\.{#}\hfil\cr
12035 {}\\def\\a\{\\c\}&
12036 {}\\def\\c\{\}\cr
12037 {}\\def\\b\{\\d\}&
12038 {}\\def\\d\{\}\cr}}$$
12039
12040 @<Test if two macro texts match@>=
12041 begin p:=link(cur_chr); q:=link(equiv(n)); {omit reference counts}
12042 if p=q then b:=true
12043 else begin while (p<>null)and(q<>null) do
12044 if info(p)<>info(q) then p:=null
12045 else begin p:=link(p); q:=link(q);
12046 end;
12047 b:=((p=null)and(q=null));
12048 end;
12049 end
12050
12051 @ @<Select the appropriate case and |return| or |goto common_ending|@>=
12052 begin scan_int; n:=cur_val; {|n| is the number of cases to pass}
12053 if tracing_commands>1 then
12054 begin begin_diagnostic; print("{case "); print_int(n); print_char("}");
12055 end_diagnostic(false);
12056 end;
12057 while n<>0 do
12058 begin pass_text;
12059 if cond_ptr=save_cond_ptr then
12060 if cur_chr=or_code then decr(n)
12061 else goto common_ending
12062 else if cur_chr=fi_code then @<Pop the condition stack@>;
12063 end;
12064 change_if_limit(or_code,save_cond_ptr);
12065 return; {wait for \.{\\or}, \.{\\else}, or \.{\\fi}}
12066 end
12067
12068 @ The processing of conditionals is complete except for the following
12069 code, which is actually part of |expand|. It comes into play when
12070 \.{\\or}, \.{\\else}, or \.{\\fi} is scanned.
12071
12072 @<Terminate the current conditional and skip to \.{\\fi}@>=
12073 begin if tracing_ifs>0 then if tracing_commands<=1 then show_cur_cmd_chr;
12074 if cur_chr>if_limit then
12075 if if_limit=if_code then insert_relax {condition not yet evaluated}
12076 else begin print_err("Extra "); print_cmd_chr(fi_or_else,cur_chr);
12077 @.Extra \\or@>
12078 @.Extra \\else@>
12079 @.Extra \\fi@>
12080 help1("I'm ignoring this; it doesn't match any \if.");
12081 error;
12082 end
12083 else begin while cur_chr<>fi_code do pass_text; {skip to \.{\\fi}}
12084 @<Pop the condition stack@>;
12085 end;
12086 end
12087
12088 @* \[29] File names.
12089 It's time now to fret about file names. Besides the fact that different
12090 operating systems treat files in different ways, we must cope with the
12091 fact that completely different naming conventions are used by different
12092 groups of people. The following programs show what is required for one
12093 particular operating system; similar routines for other systems are not
12094 difficult to devise.
12095 @^fingers@>
12096 @^system dependencies@>
12097
12098 \TeX\ assumes that a file name has three parts: the name proper; its
12099 ``extension''; and a ``file area'' where it is found in an external file
12100 system. The extension of an input file or a write file is assumed to be
12101 `\.{.tex}' unless otherwise specified; it is `\.{.log}' on the
12102 transcript file that records each run of \TeX; it is `\.{.tfm}' on the font
12103 metric files that describe characters in the fonts \TeX\ uses; it is
12104 `\.{.dvi}' on the output files that specify typesetting information; and it
12105 is `\.{.fmt}' on the format files written by \.{INITEX} to initialize \TeX.
12106 The file area can be arbitrary on input files, but files are usually
12107 output to the user's current area. If an input file cannot be
12108 found on the specified area, \TeX\ will look for it on a special system
12109 area; this special area is intended for commonly used input files like
12110 \.{webmac.tex}.
12111
12112 Simple uses of \TeX\ refer only to file names that have no explicit
12113 extension or area. For example, a person usually says `\.{\\input} \.{paper}'
12114 or `\.{\\font\\tenrm} \.= \.{helvetica}' instead of `\.{\\input}
12115 \.{paper.new}' or `\.{\\font\\tenrm} \.= \.{<csd.knuth>test}'. Simple file
12116 names are best, because they make the \TeX\ source files portable;
12117 whenever a file name consists entirely of letters and digits, it should be
12118 treated in the same way by all implementations of \TeX. However, users
12119 need the ability to refer to other files in their environment, especially
12120 when responding to error messages concerning unopenable files; therefore
12121 we want to let them use the syntax that appears in their favorite
12122 operating system.
12123
12124 The following procedures don't allow spaces to be part of
12125 file names; but some users seem to like names that are spaced-out.
12126 System-dependent changes to allow such things should probably
12127 be made with reluctance, and only when an entire file name that
12128 includes spaces is ``quoted'' somehow.
12129
12130 @ In order to isolate the system-dependent aspects of file names, the
12131 @^system dependencies@>
12132 system-independent parts of \TeX\ are expressed in terms
12133 of three system-dependent
12134 procedures called |begin_name|, |more_name|, and |end_name|. In
12135 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
12136 the system-independent driver program does the operations
12137 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
12138 \,|end_name|.$$
12139 These three procedures communicate with each other via global variables.
12140 Afterwards the file name will appear in the string pool as three strings
12141 called |cur_name|\penalty10000\hskip-.05em,
12142 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
12143 |""|), unless they were explicitly specified by the user.
12144
12145 Actually the situation is slightly more complicated, because \TeX\ needs
12146 to know when the file name ends. The |more_name| routine is a function
12147 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
12148 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
12149 returns |false|; or, it returns |true| and the token following $c_n$ is
12150 something like `\.{\\hbox}' (i.e., not a character). In other words,
12151 |more_name| is supposed to return |true| unless it is sure that the
12152 file name has been completely scanned; and |end_name| is supposed to be able
12153 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
12154 whether $|more_name|(c_n)$ returned |true| or |false|.
12155
12156 @<Glob...@>=
12157 @!cur_name:str_number; {name of file just scanned}
12158 @!cur_area:str_number; {file area just scanned, or \.{""}}
12159 @!cur_ext:str_number; {file extension just scanned, or \.{""}}
12160
12161 @ The file names we shall deal with for illustrative purposes have the
12162 following structure: If the name contains `\.>' or `\.:', the file area
12163 consists of all characters up to and including the final such character;
12164 otherwise the file area is null. If the remaining file name contains
12165 `\..', the file extension consists of all such characters from the first
12166 remaining `\..' to the end, otherwise the file extension is null.
12167 @^system dependencies@>
12168
12169 We can scan such file names easily by using two global variables that keep track
12170 of the occurrences of area and extension delimiters:
12171
12172 @<Glob...@>=
12173 @!area_delimiter:pool_pointer; {the most recent `\.>' or `\.:', if any}
12174 @!ext_delimiter:pool_pointer; {the relevant `\..', if any}
12175
12176 @ Input files that can't be found in the user's area may appear in a standard
12177 system area called |TEX_area|. Font metric files whose areas are not given
12178 explicitly are assumed to appear in a standard system area called
12179 |TEX_font_area|. These system area names will, of course, vary from place
12180 to place.
12181 @^system dependencies@>
12182
12183 @d TEX_area=="TeXinputs:"
12184 @.TeXinputs@>
12185 @d TEX_font_area=="TeXfonts:"
12186 @.TeXfonts@>
12187
12188 @ Here now is the first of the system-dependent routines for file name scanning.
12189 @^system dependencies@>
12190
12191 @p procedure begin_name;
12192 begin area_delimiter:=0; ext_delimiter:=0;
12193 end;
12194
12195 @ And here's the second. The string pool might change as the file name is
12196 being scanned, since a new \.{\\csname} might be entered; therefore we keep
12197 |area_delimiter| and |ext_delimiter| relative to the beginning of the current
12198 string, instead of assigning an absolute address like |pool_ptr| to them.
12199 @^system dependencies@>
12200
12201 @p function more_name(@!c:ASCII_code):boolean;
12202 begin if c=" " then more_name:=false
12203 else begin str_room(1); append_char(c); {contribute |c| to the current string}
12204 if (c=">")or(c=":") then
12205 begin area_delimiter:=cur_length; ext_delimiter:=0;
12206 end
12207 else if (c=".")and(ext_delimiter=0) then ext_delimiter:=cur_length;
12208 more_name:=true;
12209 end;
12210 end;
12211
12212 @ The third.
12213 @^system dependencies@>
12214
12215 @p procedure end_name;
12216 begin if str_ptr+3>max_strings then
12217 overflow("number of strings",max_strings-init_str_ptr);
12218 @:TeX capacity exceeded number of strings}{\quad number of strings@>
12219 if area_delimiter=0 then cur_area:=""
12220 else begin cur_area:=str_ptr;
12221 str_start[str_ptr+1]:=str_start[str_ptr]+area_delimiter; incr(str_ptr);
12222 end;
12223 if ext_delimiter=0 then
12224 begin cur_ext:=""; cur_name:=make_string;
12225 end
12226 else begin cur_name:=str_ptr;
12227 str_start[str_ptr+1]:=str_start[str_ptr]+ext_delimiter-area_delimiter-1;
12228 incr(str_ptr); cur_ext:=make_string;
12229 end;
12230 end;
12231
12232 @ Conversely, here is a routine that takes three strings and prints a file
12233 name that might have produced them. (The routine is system dependent, because
12234 some operating systems put the file area last instead of first.)
12235 @^system dependencies@>
12236
12237 @<Basic printing...@>=
12238 procedure print_file_name(@!n,@!a,@!e:integer);
12239 begin slow_print(a); slow_print(n); slow_print(e);
12240 end;
12241
12242 @ Another system-dependent routine is needed to convert three internal
12243 \TeX\ strings
12244 into the |name_of_file| value that is used to open files. The present code
12245 allows both lowercase and uppercase letters in the file name.
12246 @^system dependencies@>
12247
12248 @d append_to_name(#)==begin c:=#; incr(k);
12249 if k<=file_name_size then name_of_file[k]:=xchr[c];
12250 end
12251
12252 @p procedure pack_file_name(@!n,@!a,@!e:str_number);
12253 var k:integer; {number of positions filled in |name_of_file|}
12254 @!c: ASCII_code; {character being packed}
12255 @!j:pool_pointer; {index into |str_pool|}
12256 begin k:=0;
12257 for j:=str_start[a] to str_start[a+1]-1 do append_to_name(so(str_pool[j]));
12258 for j:=str_start[n] to str_start[n+1]-1 do append_to_name(so(str_pool[j]));
12259 for j:=str_start[e] to str_start[e+1]-1 do append_to_name(so(str_pool[j]));
12260 if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
12261 for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
12262 end;
12263
12264 @ A messier routine is also needed, since format file names must be scanned
12265 before \TeX's string mechanism has been initialized. We shall use the
12266 global variable |TEX_format_default| to supply the text for default system areas
12267 and extensions related to format files.
12268 @^system dependencies@>
12269
12270 @d format_default_length=20 {length of the |TEX_format_default| string}
12271 @d format_area_length=11 {length of its area part}
12272 @d format_ext_length=4 {length of its `\.{.fmt}' part}
12273 @d format_extension=".fmt" {the extension, as a \.{WEB} constant}
12274
12275 @<Glob...@>=
12276 @!TEX_format_default:packed array[1..format_default_length] of char;
12277
12278 @ @<Set init...@>=
12279 TEX_format_default:='TeXformats:plain.fmt';
12280 @.TeXformats@>
12281 @.plain@>
12282 @^system dependencies@>
12283
12284 @ @<Check the ``constant'' values for consistency@>=
12285 if format_default_length>file_name_size then bad:=31;
12286
12287 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
12288 from the first |n| characters of |TEX_format_default|, followed by
12289 |buffer[a..b]|, followed by the last |format_ext_length| characters of
12290 |TEX_format_default|.
12291
12292 We dare not give error messages here, since \TeX\ calls this routine before
12293 the |error| routine is ready to roll. Instead, we simply drop excess characters,
12294 since the error will be detected in another way when a strange file name
12295 isn't found.
12296 @^system dependencies@>
12297
12298 @p procedure pack_buffered_name(@!n:small_number;@!a,@!b:integer);
12299 var k:integer; {number of positions filled in |name_of_file|}
12300 @!c: ASCII_code; {character being packed}
12301 @!j:integer; {index into |buffer| or |TEX_format_default|}
12302 begin if n+b-a+1+format_ext_length>file_name_size then
12303 b:=a+file_name_size-n-1-format_ext_length;
12304 k:=0;
12305 for j:=1 to n do append_to_name(xord[TEX_format_default[j]]);
12306 for j:=a to b do append_to_name(buffer[j]);
12307 for j:=format_default_length-format_ext_length+1 to format_default_length do
12308 append_to_name(xord[TEX_format_default[j]]);
12309 if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
12310 for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
12311 end;
12312
12313 @ Here is the only place we use |pack_buffered_name|. This part of the program
12314 becomes active when a ``virgin'' \TeX\ is trying to get going, just after
12315 the preliminary initialization, or when the user is substituting another
12316 format file by typing `\.\&' after the initial `\.{**}' prompt. The buffer
12317 contains the first line of input in |buffer[loc..(last-1)]|, where
12318 |loc<last| and |buffer[loc]<>" "|.
12319
12320 @<Declare the function called |open_fmt_file|@>=
12321 function open_fmt_file:boolean;
12322 label found,exit;
12323 var j:0..buf_size; {the first space after the format file name}
12324 begin j:=loc;
12325 if buffer[loc]="&" then
12326 begin incr(loc); j:=loc; buffer[last]:=" ";
12327 while buffer[j]<>" " do incr(j);
12328 pack_buffered_name(0,loc,j-1); {try first without the system file area}
12329 if w_open_in(fmt_file) then goto found;
12330 pack_buffered_name(format_area_length,loc,j-1);
12331 {now try the system format file area}
12332 if w_open_in(fmt_file) then goto found;
12333 wake_up_terminal;
12334 wterm_ln('Sorry, I can''t find that format;',' will try PLAIN.');
12335 @.Sorry, I can't find...@>
12336 update_terminal;
12337 end;
12338 {now pull out all the stops: try for the system \.{plain} file}
12339 pack_buffered_name(format_default_length-format_ext_length,1,0);
12340 if not w_open_in(fmt_file) then
12341 begin wake_up_terminal;
12342 wterm_ln('I can''t find the PLAIN format file!');
12343 @.I can't find PLAIN...@>
12344 @.plain@>
12345 open_fmt_file:=false; return;
12346 end;
12347 found:loc:=j; open_fmt_file:=true;
12348 exit:end;
12349
12350 @ Operating systems often make it possible to determine the exact name (and
12351 possible version number) of a file that has been opened. The following routine,
12352 which simply makes a \TeX\ string from the value of |name_of_file|, should
12353 ideally be changed to deduce the full name of file~|f|, which is the file
12354 most recently opened, if it is possible to do this in a \PASCAL\ program.
12355 @^system dependencies@>
12356
12357 This routine might be called after string memory has overflowed, hence
12358 we dare not use `|str_room|'.
12359
12360 @p function make_name_string:str_number;
12361 var k:1..file_name_size; {index into |name_of_file|}
12362 begin if (pool_ptr+name_length>pool_size)or(str_ptr=max_strings)or
12363 (cur_length>0) then
12364 make_name_string:="?"
12365 else begin for k:=1 to name_length do append_char(xord[name_of_file[k]]);
12366 make_name_string:=make_string;
12367 end;
12368 end;
12369 function a_make_name_string(var f:alpha_file):str_number;
12370 begin a_make_name_string:=make_name_string;
12371 end;
12372 function b_make_name_string(var f:byte_file):str_number;
12373 begin b_make_name_string:=make_name_string;
12374 end;
12375 function w_make_name_string(var f:word_file):str_number;
12376 begin w_make_name_string:=make_name_string;
12377 end;
12378
12379 @ Now let's consider the ``driver''
12380 routines by which \TeX\ deals with file names
12381 in a system-independent manner. First comes a procedure that looks for a
12382 file name in the input by calling |get_x_token| for the information.
12383
12384 @p procedure scan_file_name;
12385 label done;
12386 begin name_in_progress:=true; begin_name;
12387 @<Get the next non-blank non-call...@>;
12388 loop@+begin if (cur_cmd>other_char)or(cur_chr>255) then {not a character}
12389 begin back_input; goto done;
12390 end;
12391 if not more_name(cur_chr) then goto done;
12392 get_x_token;
12393 end;
12394 done: end_name; name_in_progress:=false;
12395 end;
12396
12397 @ The global variable |name_in_progress| is used to prevent recursive
12398 use of |scan_file_name|, since the |begin_name| and other procedures
12399 communicate via global variables. Recursion would arise only by
12400 devious tricks like `\.{\\input\\input f}'; such attempts at sabotage
12401 must be thwarted. Furthermore, |name_in_progress| prevents \.{\\input}
12402 @^recursion@>
12403 from being initiated when a font size specification is being scanned.
12404
12405 Another global variable, |job_name|, contains the file name that was first
12406 \.{\\input} by the user. This name is extended by `\.{.log}' and `\.{.dvi}'
12407 and `\.{.fmt}' in the names of \TeX's output files.
12408
12409 @<Glob...@>=
12410 @!name_in_progress:boolean; {is a file name being scanned?}
12411 @!job_name:str_number; {principal file name}
12412 @!log_opened:boolean; {has the transcript file been opened?}
12413
12414 @ Initially |job_name=0|; it becomes nonzero as soon as the true name is known.
12415 We have |job_name=0| if and only if the `\.{log}' file has not been opened,
12416 except of course for a short time just after |job_name| has become nonzero.
12417
12418 @<Initialize the output...@>=
12419 job_name:=0; name_in_progress:=false; log_opened:=false;
12420
12421 @ Here is a routine that manufactures the output file names, assuming that
12422 |job_name<>0|. It ignores and changes the current settings of |cur_area|
12423 and |cur_ext|.
12424
12425 @d pack_cur_name==pack_file_name(cur_name,cur_area,cur_ext)
12426
12427 @p procedure pack_job_name(@!s:str_number); {|s = ".log"|, |".dvi"|, or
12428 |format_extension|}
12429 begin cur_area:=""; cur_ext:=s;
12430 cur_name:=job_name; pack_cur_name;
12431 end;
12432
12433 @ If some trouble arises when \TeX\ tries to open a file, the following
12434 routine calls upon the user to supply another file name. Parameter~|s|
12435 is used in the error message to identify the type of file; parameter~|e|
12436 is the default extension if none is given. Upon exit from the routine,
12437 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
12438 ready for another attempt at file opening.
12439
12440 @p procedure prompt_file_name(@!s,@!e:str_number);
12441 label done;
12442 var k:0..buf_size; {index into |buffer|}
12443 begin if interaction=scroll_mode then wake_up_terminal;
12444 if s="input file name" then print_err("I can't find file `")
12445 @.I can't find file x@>
12446 else print_err("I can't write on file `");
12447 @.I can't write on file x@>
12448 print_file_name(cur_name,cur_area,cur_ext); print("'.");
12449 if e=".tex" then show_context;
12450 print_nl("Please type another "); print(s);
12451 @.Please type...@>
12452 if interaction<scroll_mode then
12453 fatal_error("*** (job aborted, file error in nonstop mode)");
12454 @.job aborted, file error...@>
12455 clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
12456 if cur_ext="" then cur_ext:=e;
12457 pack_cur_name;
12458 end;
12459
12460 @ @<Scan file name in the buffer@>=
12461 begin begin_name; k:=first;
12462 while (buffer[k]=" ")and(k<last) do incr(k);
12463 loop@+ begin if k=last then goto done;
12464 if not more_name(buffer[k]) then goto done;
12465 incr(k);
12466 end;
12467 done:end_name;
12468 end
12469
12470 @ Here's an example of how these conventions are used. Whenever it is time to
12471 ship out a box of stuff, we shall use the macro |ensure_dvi_open|.
12472
12473 @d ensure_dvi_open==if output_file_name=0 then
12474 begin if job_name=0 then open_log_file;
12475 pack_job_name(".dvi");
12476 while not b_open_out(dvi_file) do
12477 prompt_file_name("file name for output",".dvi");
12478 output_file_name:=b_make_name_string(dvi_file);
12479 end
12480
12481 @<Glob...@>=
12482 @!dvi_file: byte_file; {the device-independent output goes here}
12483 @!output_file_name: str_number; {full name of the output file}
12484 @!log_name:str_number; {full name of the log file}
12485
12486 @ @<Initialize the output...@>=output_file_name:=0;
12487
12488 @ The |open_log_file| routine is used to open the transcript file and to help
12489 it catch up to what has previously been printed on the terminal.
12490
12491 @p procedure open_log_file;
12492 var old_setting:0..max_selector; {previous |selector| setting}
12493 @!k:0..buf_size; {index into |months| and |buffer|}
12494 @!l:0..buf_size; {end of first input line}
12495 @!months:packed array [1..36] of char; {abbreviations of month names}
12496 begin old_setting:=selector;
12497 if job_name=0 then job_name:="texput";
12498 @.texput@>
12499 pack_job_name(".log");
12500 while not a_open_out(log_file) do @<Try to get a different log file name@>;
12501 log_name:=a_make_name_string(log_file);
12502 selector:=log_only; log_opened:=true;
12503 @<Print the banner line, including the date and time@>;
12504 input_stack[input_ptr]:=cur_input; {make sure bottom level is in memory}
12505 print_nl("**");
12506 @.**@>
12507 l:=input_stack[0].limit_field; {last position of first line}
12508 if buffer[l]=end_line_char then decr(l);
12509 for k:=1 to l do print(buffer[k]);
12510 print_ln; {now the transcript file contains the first line of input}
12511 selector:=old_setting+2; {|log_only| or |term_and_log|}
12512 end;
12513
12514 @ Sometimes |open_log_file| is called at awkward moments when \TeX\ is
12515 unable to print error messages or even to |show_context|.
12516 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
12517 routine will not be invoked because |log_opened| will be false.
12518
12519 The normal idea of |batch_mode| is that nothing at all should be written
12520 on the terminal. However, in the unusual case that
12521 no log file could be opened, we make an exception and allow
12522 an explanatory message to be seen.
12523
12524 Incidentally, the program always refers to the log file as a `\.{transcript
12525 file}', because some systems cannot use the extension `\.{.log}' for
12526 this file.
12527
12528 @<Try to get a different log file name@>=
12529 begin selector:=term_only;
12530 prompt_file_name("transcript file name",".log");
12531 end
12532
12533 @ @<Print the banner...@>=
12534 begin wlog(banner);
12535 slow_print(format_ident); print(" ");
12536 print_int(sys_day); print_char(" ");
12537 months:='JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC';
12538 for k:=3*sys_month-2 to 3*sys_month do wlog(months[k]);
12539 print_char(" "); print_int(sys_year); print_char(" ");
12540 print_two(sys_time div 60); print_char(":"); print_two(sys_time mod 60);
12541 if eTeX_ex then
12542 begin; wlog_cr; wlog('entering extended mode');
12543 end;
12544 end
12545
12546 @ Let's turn now to the procedure that is used to initiate file reading
12547 when an `\.{\\input}' command is being processed.
12548 Beware: For historic reasons, this code foolishly conserves a tiny bit
12549 of string pool space; but that can confuse the interactive `\.E' option.
12550 @^system dependencies@>
12551
12552 @p procedure start_input; {\TeX\ will \.{\\input} something}
12553 label done;
12554 begin scan_file_name; {set |cur_name| to desired file name}
12555 if cur_ext="" then cur_ext:=".tex";
12556 pack_cur_name;
12557 loop@+ begin begin_file_reading; {set up |cur_file| and new level of input}
12558 if a_open_in(cur_file) then goto done;
12559 if cur_area="" then
12560 begin pack_file_name(cur_name,TEX_area,cur_ext);
12561 if a_open_in(cur_file) then goto done;
12562 end;
12563 end_file_reading; {remove the level that didn't work}
12564 prompt_file_name("input file name",".tex");
12565 end;
12566 done: name:=a_make_name_string(cur_file);
12567 if job_name=0 then
12568 begin job_name:=cur_name; open_log_file;
12569 end; {|open_log_file| doesn't |show_context|, so |limit|
12570 and |loc| needn't be set to meaningful values yet}
12571 if term_offset+length(name)>max_print_line-2 then print_ln
12572 else if (term_offset>0)or(file_offset>0) then print_char(" ");
12573 print_char("("); incr(open_parens); slow_print(name); update_terminal;
12574 state:=new_line;
12575 if name=str_ptr-1 then {conserve string pool space (but see note above)}
12576 begin flush_string; name:=cur_name;
12577 end;
12578 @<Read the first line of the new file@>;
12579 end;
12580
12581 @ Here we have to remember to tell the |input_ln| routine not to
12582 start with a |get|. If the file is empty, it is considered to
12583 contain a single blank line.
12584 @^system dependencies@>
12585 @^empty line at end of file@>
12586
12587 @<Read the first line...@>=
12588 begin line:=1;
12589 if input_ln(cur_file,false) then do_nothing;
12590 firm_up_the_line;
12591 if end_line_char_inactive then decr(limit)
12592 else buffer[limit]:=end_line_char;
12593 first:=limit+1; loc:=start;
12594 end
12595
12596 @* \[30] Font metric data.
12597 \TeX\ gets its knowledge about fonts from font metric files, also called
12598 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
12599 but other programs know about them too.
12600 @:TFM files}{\.{TFM} files@>
12601 @^font metric files@>
12602
12603 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
12604 Since the number of bytes is always a multiple of 4, we could
12605 also regard the file as a sequence of 32-bit words, but \TeX\ uses the
12606 byte interpretation. The format of \.{TFM} files was designed by
12607 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
12608 @^Ramshaw, Lyle Harold@>
12609 of information in a compact but useful form.
12610
12611 @<Glob...@>=
12612 @!tfm_file:byte_file;
12613
12614 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
12615 integers that give the lengths of the various subsequent portions
12616 of the file. These twelve integers are, in order:
12617 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
12618 |lf|&length of the entire file, in words;\cr
12619 |lh|&length of the header data, in words;\cr
12620 |bc|&smallest character code in the font;\cr
12621 |ec|&largest character code in the font;\cr
12622 |nw|&number of words in the width table;\cr
12623 |nh|&number of words in the height table;\cr
12624 |nd|&number of words in the depth table;\cr
12625 |ni|&number of words in the italic correction table;\cr
12626 |nl|&number of words in the lig/kern table;\cr
12627 |nk|&number of words in the kern table;\cr
12628 |ne|&number of words in the extensible character table;\cr
12629 |np|&number of font parameter words.\cr}}$$
12630 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
12631 and
12632 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
12633 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
12634 and as few as 0 characters (if |bc=ec+1|).
12635
12636 Incidentally, when two or more 8-bit bytes are combined to form an integer of
12637 16 or more bits, the most significant bytes appear first in the file.
12638 This is called BigEndian order.
12639 @!@^BigEndian order@>
12640
12641 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
12642 arrays having the informal specification
12643 $$\def\arr$[#1]#2${\&{array} $[#1]$ \&{of} #2}
12644 \vbox{\halign{\hfil\\{#}&$\,:\,$\arr#\hfil\cr
12645 header&|[0..lh-1]@t\\{stuff}@>|\cr
12646 char\_info&|[bc..ec]char_info_word|\cr
12647 width&|[0..nw-1]fix_word|\cr
12648 height&|[0..nh-1]fix_word|\cr
12649 depth&|[0..nd-1]fix_word|\cr
12650 italic&|[0..ni-1]fix_word|\cr
12651 lig\_kern&|[0..nl-1]lig_kern_command|\cr
12652 kern&|[0..nk-1]fix_word|\cr
12653 exten&|[0..ne-1]extensible_recipe|\cr
12654 param&|[1..np]fix_word|\cr}}$$
12655 The most important data type used here is a |@!fix_word|, which is
12656 a 32-bit representation of a binary fraction. A |fix_word| is a signed
12657 quantity, with the two's complement of the entire word used to represent
12658 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
12659 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
12660 the smallest is $-2048$. We will see below, however, that all but two of
12661 the |fix_word| values must lie between $-16$ and $+16$.
12662
12663 @ The first data array is a block of header information, which contains
12664 general facts about the font. The header must contain at least two words,
12665 |header[0]| and |header[1]|, whose meaning is explained below.
12666 Additional header information of use to other software routines might
12667 also be included, but \TeX82 does not need to know about such details.
12668 For example, 16 more words of header information are in use at the Xerox
12669 Palo Alto Research Center; the first ten specify the character coding
12670 scheme used (e.g., `\.{XEROX text}' or `\.{TeX math symbols}'), the next five
12671 give the font identifier (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
12672 last gives the ``face byte.'' The program that converts \.{DVI} files
12673 to Xerox printing format gets this information by looking at the \.{TFM}
12674 file, which it needs to read anyway because of other information that
12675 is not explicitly repeated in \.{DVI}~format.
12676
12677 \yskip\hang|header[0]| is a 32-bit check sum that \TeX\ will copy into
12678 the \.{DVI} output file. Later on when the \.{DVI} file is printed,
12679 possibly on another computer, the actual font that gets used is supposed
12680 to have a check sum that agrees with the one in the \.{TFM} file used by
12681 \TeX. In this way, users will be warned about potential incompatibilities.
12682 (However, if the check sum is zero in either the font file or the \.{TFM}
12683 file, no check is made.) The actual relation between this check sum and
12684 the rest of the \.{TFM} file is not important; the check sum is simply an
12685 identification number with the property that incompatible fonts almost
12686 always have distinct check sums.
12687 @^check sum@>
12688
12689 \yskip\hang|header[1]| is a |fix_word| containing the design size of
12690 the font, in units of \TeX\ points. This number must be at least 1.0; it is
12691 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
12692 font, i.e., a font that was designed to look best at a 10-point size,
12693 whatever that really means. When a \TeX\ user asks for a font
12694 `\.{at} $\delta$ \.{pt}', the effect is to override the design size
12695 and replace it by $\delta$, and to multiply the $x$ and~$y$ coordinates
12696 of the points in the font image by a factor of $\delta$ divided by the
12697 design size. {\sl All other dimensions in the\/ \.{TFM} file are
12698 |fix_word|\kern-1pt\ numbers in design-size units}, with the exception of
12699 |param[1]| (which denotes the slant ratio). Thus, for example, the value
12700 of |param[6]|, which defines the \.{em} unit, is often the |fix_word| value
12701 $2^{20}=1.0$, since many fonts have a design size equal to one em.
12702 The other dimensions must be less than 16 design-size units in absolute
12703 value; thus, |header[1]| and |param[1]| are the only |fix_word|
12704 entries in the whole \.{TFM} file whose first byte might be something
12705 besides 0 or 255.
12706
12707 @ Next comes the |char_info| array, which contains one |@!char_info_word|
12708 per character. Each word in this part of the file contains six fields
12709 packed into four bytes as follows.
12710
12711 \yskip\hang first byte: |@!width_index| (8 bits)\par
12712 \hang second byte: |@!height_index| (4 bits) times 16, plus |@!depth_index|
12713 (4~bits)\par
12714 \hang third byte: |@!italic_index| (6 bits) times 4, plus |@!tag|
12715 (2~bits)\par
12716 \hang fourth byte: |@!remainder| (8 bits)\par
12717 \yskip\noindent
12718 The actual width of a character is \\{width}|[width_index]|, in design-size
12719 units; this is a device for compressing information, since many characters
12720 have the same width. Since it is quite common for many characters
12721 to have the same height, depth, or italic correction, the \.{TFM} format
12722 imposes a limit of 16 different heights, 16 different depths, and
12723 64 different italic corrections.
12724
12725 @!@^italic correction@>
12726 The italic correction of a character has two different uses.
12727 (a)~In ordinary text, the italic correction is added to the width only if
12728 the \TeX\ user specifies `\.{\\/}' after the character.
12729 (b)~In math formulas, the italic correction is always added to the width,
12730 except with respect to the positioning of subscripts.
12731
12732 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
12733 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
12734 value of zero. The |width_index| should never be zero unless the
12735 character does not exist in the font, since a character is valid if and
12736 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
12737
12738 @ The |tag| field in a |char_info_word| has four values that explain how to
12739 interpret the |remainder| field.
12740
12741 \yskip\hangg|tag=0| (|no_tag|) means that |remainder| is unused.\par
12742 \hangg|tag=1| (|lig_tag|) means that this character has a ligature/kerning
12743 program starting at position |remainder| in the |lig_kern| array.\par
12744 \hangg|tag=2| (|list_tag|) means that this character is part of a chain of
12745 characters of ascending sizes, and not the largest in the chain. The
12746 |remainder| field gives the character code of the next larger character.\par
12747 \hangg|tag=3| (|ext_tag|) means that this character code represents an
12748 extensible character, i.e., a character that is built up of smaller pieces
12749 so that it can be made arbitrarily large. The pieces are specified in
12750 |@!exten[remainder]|.\par
12751 \yskip\noindent
12752 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
12753 unless they are used in special circumstances in math formulas. For example,
12754 the \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
12755 operation looks for both |list_tag| and |ext_tag|.
12756
12757 @d no_tag=0 {vanilla character}
12758 @d lig_tag=1 {character has a ligature/kerning program}
12759 @d list_tag=2 {character has a successor in a charlist}
12760 @d ext_tag=3 {character is extensible}
12761
12762 @ The |lig_kern| array contains instructions in a simple programming language
12763 that explains what to do for special letter pairs. Each word in this array is a
12764 |@!lig_kern_command| of four bytes.
12765
12766 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
12767 step if the byte is 128 or more, otherwise the next step is obtained by
12768 skipping this number of intervening steps.\par
12769 \hang second byte: |next_char|, ``if |next_char| follows the current character,
12770 then perform the operation and stop, otherwise continue.''\par
12771 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
12772 a kern step otherwise.\par
12773 \hang fourth byte: |remainder|.\par
12774 \yskip\noindent
12775 In a kern step, an
12776 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
12777 between the current character and |next_char|. This amount is
12778 often negative, so that the characters are brought closer together
12779 by kerning; but it might be positive.
12780
12781 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
12782 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
12783 |remainder| is inserted between the current character and |next_char|;
12784 then the current character is deleted if $b=0$, and |next_char| is
12785 deleted if $c=0$; then we pass over $a$~characters to reach the next
12786 current character (which may have a ligature/kerning program of its own).
12787
12788 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
12789 the |next_char| byte is the so-called boundary character of this font;
12790 the value of |next_char| need not lie between |bc| and~|ec|.
12791 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
12792 there is a special ligature/kerning program for a boundary character at the
12793 left, beginning at location |256*op_byte+remainder|.
12794 The interpretation is that \TeX\ puts implicit boundary characters
12795 before and after each consecutive string of characters from the same font.
12796 These implicit characters do not appear in the output, but they can affect
12797 ligatures and kerning.
12798
12799 If the very first instruction of a character's |lig_kern| program has
12800 |skip_byte>128|, the program actually begins in location
12801 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
12802 arrays, because the first instruction must otherwise
12803 appear in a location |<=255|.
12804
12805 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
12806 the condition
12807 $$\hbox{|256*op_byte+remainder<nl|.}$$
12808 If such an instruction is encountered during
12809 normal program execution, it denotes an unconditional halt; no ligature
12810 or kerning command is performed.
12811
12812 @d stop_flag==qi(128) {value indicating `\.{STOP}' in a lig/kern program}
12813 @d kern_flag==qi(128) {op code for a kern step}
12814 @d skip_byte(#)==#.b0
12815 @d next_char(#)==#.b1
12816 @d op_byte(#)==#.b2
12817 @d rem_byte(#)==#.b3
12818
12819 @ Extensible characters are specified by an |@!extensible_recipe|, which
12820 consists of four bytes called |@!top|, |@!mid|, |@!bot|, and |@!rep| (in this
12821 order). These bytes are the character codes of individual pieces used to
12822 build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
12823 present in the built-up result. For example, an extensible vertical line is
12824 like an extensible bracket, except that the top and bottom pieces are missing.
12825
12826 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
12827 if the piece isn't present. Then the extensible characters have the form
12828 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
12829 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
12830 The width of the extensible character is the width of $R$; and the
12831 height-plus-depth is the sum of the individual height-plus-depths of the
12832 components used, since the pieces are butted together in a vertical list.
12833
12834 @d ext_top(#)==#.b0 {|top| piece in a recipe}
12835 @d ext_mid(#)==#.b1 {|mid| piece in a recipe}
12836 @d ext_bot(#)==#.b2 {|bot| piece in a recipe}
12837 @d ext_rep(#)==#.b3 {|rep| piece in a recipe}
12838
12839 @ The final portion of a \.{TFM} file is the |param| array, which is another
12840 sequence of |fix_word| values.
12841
12842 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
12843 to help position accents. For example, |slant=.25| means that when you go
12844 up one unit, you also go .25 units to the right. The |slant| is a pure
12845 number; it's the only |fix_word| other than the design size itself that is
12846 not scaled by the design size.
12847
12848 \hang|param[2]=space| is the normal spacing between words in text.
12849 Note that character |" "| in the font need not have anything to do with
12850 blank spaces.
12851
12852 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
12853
12854 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
12855
12856 \hang|param[5]=x_height| is the size of one ex in the font; it is also
12857 the height of letters for which accents don't have to be raised or lowered.
12858
12859 \hang|param[6]=quad| is the size of one em in the font.
12860
12861 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
12862 ends of sentences.
12863
12864 \yskip\noindent
12865 If fewer than seven parameters are present, \TeX\ sets the missing parameters
12866 to zero. Fonts used for math symbols are required to have
12867 additional parameter information, which is explained later.
12868
12869 @d slant_code=1
12870 @d space_code=2
12871 @d space_stretch_code=3
12872 @d space_shrink_code=4
12873 @d x_height_code=5
12874 @d quad_code=6
12875 @d extra_space_code=7
12876
12877 @ So that is what \.{TFM} files hold. Since \TeX\ has to absorb such information
12878 about lots of fonts, it stores most of the data in a large array called
12879 |font_info|. Each item of |font_info| is a |memory_word|; the |fix_word|
12880 data gets converted into |scaled| entries, while everything else goes into
12881 words of type |four_quarters|.
12882
12883 When the user defines \.{\\font\\f}, say, \TeX\ assigns an internal number
12884 to the user's font~\.{\\f}. Adding this number to |font_id_base| gives the
12885 |eqtb| location of a ``frozen'' control sequence that will always select
12886 the font.
12887
12888 @<Types...@>=
12889 @!internal_font_number=font_base..font_max; {|font| in a |char_node|}
12890 @!font_index=0..font_mem_size; {index into |font_info|}
12891
12892 @ Here now is the (rather formidable) array of font arrays.
12893
12894 @d non_char==qi(256) {a |halfword| code that can't match a real character}
12895 @d non_address=0 {a spurious |bchar_label|}
12896
12897 @<Glob...@>=
12898 @!font_info:array[font_index] of memory_word;
12899 {the big collection of font data}
12900 @!fmem_ptr:font_index; {first unused word of |font_info|}
12901 @!font_ptr:internal_font_number; {largest internal font number in use}
12902 @!font_check:array[internal_font_number] of four_quarters; {check sum}
12903 @!font_size:array[internal_font_number] of scaled; {``at'' size}
12904 @!font_dsize:array[internal_font_number] of scaled; {``design'' size}
12905 @!font_params:array[internal_font_number] of font_index; {how many font
12906 parameters are present}
12907 @!font_name:array[internal_font_number] of str_number; {name of the font}
12908 @!font_area:array[internal_font_number] of str_number; {area of the font}
12909 @!font_bc:array[internal_font_number] of eight_bits;
12910 {beginning (smallest) character code}
12911 @!font_ec:array[internal_font_number] of eight_bits;
12912 {ending (largest) character code}
12913 @!font_glue:array[internal_font_number] of pointer;
12914 {glue specification for interword space, |null| if not allocated}
12915 @!font_used:array[internal_font_number] of boolean;
12916 {has a character from this font actually appeared in the output?}
12917 @!hyphen_char:array[internal_font_number] of integer;
12918 {current \.{\\hyphenchar} values}
12919 @!skew_char:array[internal_font_number] of integer;
12920 {current \.{\\skewchar} values}
12921 @!bchar_label:array[internal_font_number] of font_index;
12922 {start of |lig_kern| program for left boundary character,
12923 |non_address| if there is none}
12924 @!font_bchar:array[internal_font_number] of min_quarterword..non_char;
12925 {boundary character, |non_char| if there is none}
12926 @!font_false_bchar:array[internal_font_number] of min_quarterword..non_char;
12927 {|font_bchar| if it doesn't exist in the font, otherwise |non_char|}
12928
12929 @ Besides the arrays just enumerated, we have directory arrays that make it
12930 easy to get at the individual entries in |font_info|. For example, the
12931 |char_info| data for character |c| in font |f| will be in
12932 |font_info[char_base[f]+c].qqqq|; and if |w| is the |width_index|
12933 part of this word (the |b0| field), the width of the character is
12934 |font_info[width_base[f]+w].sc|. (These formulas assume that
12935 |min_quarterword| has already been added to |c| and to |w|, since \TeX\
12936 stores its quarterwords that way.)
12937
12938 @<Glob...@>=
12939 @!char_base:array[internal_font_number] of integer;
12940 {base addresses for |char_info|}
12941 @!width_base:array[internal_font_number] of integer;
12942 {base addresses for widths}
12943 @!height_base:array[internal_font_number] of integer;
12944 {base addresses for heights}
12945 @!depth_base:array[internal_font_number] of integer;
12946 {base addresses for depths}
12947 @!italic_base:array[internal_font_number] of integer;
12948 {base addresses for italic corrections}
12949 @!lig_kern_base:array[internal_font_number] of integer;
12950 {base addresses for ligature/kerning programs}
12951 @!kern_base:array[internal_font_number] of integer;
12952 {base addresses for kerns}
12953 @!exten_base:array[internal_font_number] of integer;
12954 {base addresses for extensible recipes}
12955 @!param_base:array[internal_font_number] of integer;
12956 {base addresses for font parameters}
12957
12958 @ @<Set init...@>=
12959 for k:=font_base to font_max do font_used[k]:=false;
12960
12961 @ \TeX\ always knows at least one font, namely the null font. It has no
12962 characters, and its seven parameters are all equal to zero.
12963
12964 @<Initialize table...@>=
12965 font_ptr:=null_font; fmem_ptr:=7;
12966 font_name[null_font]:="nullfont"; font_area[null_font]:="";
12967 hyphen_char[null_font]:="-"; skew_char[null_font]:=-1;
12968 bchar_label[null_font]:=non_address;
12969 font_bchar[null_font]:=non_char; font_false_bchar[null_font]:=non_char;
12970 font_bc[null_font]:=1; font_ec[null_font]:=0;
12971 font_size[null_font]:=0; font_dsize[null_font]:=0;
12972 char_base[null_font]:=0; width_base[null_font]:=0;
12973 height_base[null_font]:=0; depth_base[null_font]:=0;
12974 italic_base[null_font]:=0; lig_kern_base[null_font]:=0;
12975 kern_base[null_font]:=0; exten_base[null_font]:=0;
12976 font_glue[null_font]:=null; font_params[null_font]:=7;
12977 param_base[null_font]:=-1;
12978 for k:=0 to 6 do font_info[k].sc:=0;
12979
12980 @ @<Put each...@>=
12981 primitive("nullfont",set_font,null_font);
12982 @!@:null_font_}{\.{\\nullfont} primitive@>
12983 text(frozen_null_font):="nullfont"; eqtb[frozen_null_font]:=eqtb[cur_val];
12984
12985 @ Of course we want to define macros that suppress the detail of how font
12986 information is actually packed, so that we don't have to write things like
12987 $$\hbox{|font_info[width_base[f]+font_info[char_base[f]+c].qqqq.b0].sc|}$$
12988 too often. The \.{WEB} definitions here make |char_info(f)(c)| the
12989 |four_quarters| word of font information corresponding to character
12990 |c| of font |f|. If |q| is such a word, |char_width(f)(q)| will be
12991 the character's width; hence the long formula above is at least
12992 abbreviated to
12993 $$\hbox{|char_width(f)(char_info(f)(c))|.}$$
12994 Usually, of course, we will fetch |q| first and look at several of its
12995 fields at the same time.
12996
12997 The italic correction of a character will be denoted by
12998 |char_italic(f)(q)|, so it is analogous to |char_width|. But we will get
12999 at the height and depth in a slightly different way, since we usually want
13000 to compute both height and depth if we want either one. The value of
13001 |height_depth(q)| will be the 8-bit quantity
13002 $$b=|height_index|\times16+|depth_index|,$$ and if |b| is such a byte we
13003 will write |char_height(f)(b)| and |char_depth(f)(b)| for the height and
13004 depth of the character |c| for which |q=char_info(f)(c)|. Got that?
13005
13006 The tag field will be called |char_tag(q)|; the remainder byte will be
13007 called |rem_byte(q)|, using a macro that we have already defined above.
13008
13009 Access to a character's |width|, |height|, |depth|, and |tag| fields is
13010 part of \TeX's inner loop, so we want these macros to produce code that is
13011 as fast as possible under the circumstances.
13012 @^inner loop@>
13013
13014 @d char_info_end(#)==#].qqqq
13015 @d char_info(#)==font_info[char_base[#]+char_info_end
13016 @d char_width_end(#)==#.b0].sc
13017 @d char_width(#)==font_info[width_base[#]+char_width_end
13018 @d char_exists(#)==(#.b0>min_quarterword)
13019 @d char_italic_end(#)==(qo(#.b2)) div 4].sc
13020 @d char_italic(#)==font_info[italic_base[#]+char_italic_end
13021 @d height_depth(#)==qo(#.b1)
13022 @d char_height_end(#)==(#) div 16].sc
13023 @d char_height(#)==font_info[height_base[#]+char_height_end
13024 @d char_depth_end(#)==(#) mod 16].sc
13025 @d char_depth(#)==font_info[depth_base[#]+char_depth_end
13026 @d char_tag(#)==((qo(#.b2)) mod 4)
13027
13028 @ The global variable |null_character| is set up to be a word of
13029 |char_info| for a character that doesn't exist. Such a word provides a
13030 convenient way to deal with erroneous situations.
13031
13032 @<Glob...@>=
13033 @!null_character:four_quarters; {nonexistent character information}
13034
13035 @ @<Set init...@>=
13036 null_character.b0:=min_quarterword; null_character.b1:=min_quarterword;
13037 null_character.b2:=min_quarterword; null_character.b3:=min_quarterword;
13038
13039 @ Here are some macros that help process ligatures and kerns.
13040 We write |char_kern(f)(j)| to find the amount of kerning specified by
13041 kerning command~|j| in font~|f|. If |j| is the |char_info| for a character
13042 with a ligature/kern program, the first instruction of that program is either
13043 |i=font_info[lig_kern_start(f)(j)]| or |font_info[lig_kern_restart(f)(i)]|,
13044 depending on whether or not |skip_byte(i)<=stop_flag|.
13045
13046 The constant |kern_base_offset| should be simplified, for \PASCAL\ compilers
13047 that do not do local optimization.
13048 @^system dependencies@>
13049
13050 @d char_kern_end(#)==256*op_byte(#)+rem_byte(#)].sc
13051 @d char_kern(#)==font_info[kern_base[#]+char_kern_end
13052 @d kern_base_offset==256*(128+min_quarterword)
13053 @d lig_kern_start(#)==lig_kern_base[#]+rem_byte {beginning of lig/kern program}
13054 @d lig_kern_restart_end(#)==256*op_byte(#)+rem_byte(#)+32768-kern_base_offset
13055 @d lig_kern_restart(#)==lig_kern_base[#]+lig_kern_restart_end
13056
13057 @ Font parameters are referred to as |slant(f)|, |space(f)|, etc.
13058
13059 @d param_end(#)==param_base[#]].sc
13060 @d param(#)==font_info[#+param_end
13061 @d slant==param(slant_code) {slant to the right, per unit distance upward}
13062 @d space==param(space_code) {normal space between words}
13063 @d space_stretch==param(space_stretch_code) {stretch between words}
13064 @d space_shrink==param(space_shrink_code) {shrink between words}
13065 @d x_height==param(x_height_code) {one ex}
13066 @d quad==param(quad_code) {one em}
13067 @d extra_space==param(extra_space_code) {additional space at end of sentence}
13068
13069 @<The em width for |cur_font|@>=quad(cur_font)
13070
13071 @ @<The x-height for |cur_font|@>=x_height(cur_font)
13072
13073 @ \TeX\ checks the information of a \.{TFM} file for validity as the
13074 file is being read in, so that no further checks will be needed when
13075 typesetting is going on. The somewhat tedious subroutine that does this
13076 is called |read_font_info|. It has four parameters: the user font
13077 identifier~|u|, the file name and area strings |nom| and |aire|, and the
13078 ``at'' size~|s|. If |s|~is negative, it's the negative of a scale factor
13079 to be applied to the design size; |s=-1000| is the normal case.
13080 Otherwise |s| will be substituted for the design size; in this
13081 case, |s| must be positive and less than $2048\rm\,pt$
13082 (i.e., it must be less than $2^{27}$ when considered as an integer).
13083
13084 The subroutine opens and closes a global file variable called |tfm_file|.
13085 It returns the value of the internal font number that was just loaded.
13086 If an error is detected, an error message is issued and no font
13087 information is stored; |null_font| is returned in this case.
13088
13089 @d bad_tfm=11 {label for |read_font_info|}
13090 @d abort==goto bad_tfm {do this when the \.{TFM} data is wrong}
13091
13092 @p function read_font_info(@!u:pointer;@!nom,@!aire:str_number;
13093 @!s:scaled):internal_font_number; {input a \.{TFM} file}
13094 label done,bad_tfm,not_found;
13095 var k:font_index; {index into |font_info|}
13096 @!file_opened:boolean; {was |tfm_file| successfully opened?}
13097 @!lf,@!lh,@!bc,@!ec,@!nw,@!nh,@!nd,@!ni,@!nl,@!nk,@!ne,@!np:halfword;
13098 {sizes of subfiles}
13099 @!f:internal_font_number; {the new font's number}
13100 @!g:internal_font_number; {the number to return}
13101 @!a,@!b,@!c,@!d:eight_bits; {byte variables}
13102 @!qw:four_quarters;@!sw:scaled; {accumulators}
13103 @!bch_label:integer; {left boundary start location, or infinity}
13104 @!bchar:0..256; {boundary character, or 256}
13105 @!z:scaled; {the design size or the ``at'' size}
13106 @!alpha:integer;@!beta:1..16;
13107 {auxiliary quantities used in fixed-point multiplication}
13108 begin g:=null_font;@/
13109 @<Read and check the font data; |abort| if the \.{TFM} file is
13110 malformed; if there's no room for this font, say so and |goto
13111 done|; otherwise |incr(font_ptr)| and |goto done|@>;
13112 bad_tfm: @<Report that the font won't be loaded@>;
13113 done: if file_opened then b_close(tfm_file);
13114 read_font_info:=g;
13115 end;
13116
13117 @ There are programs called \.{TFtoPL} and \.{PLtoTF} that convert
13118 between the \.{TFM} format and a symbolic property-list format
13119 that can be easily edited. These programs contain extensive
13120 diagnostic information, so \TeX\ does not have to bother giving
13121 precise details about why it rejects a particular \.{TFM} file.
13122 @.TFtoPL@> @.PLtoTF@>
13123
13124 @d start_font_error_message==print_err("Font "); sprint_cs(u);
13125 print_char("="); print_file_name(nom,aire,"");
13126 if s>=0 then
13127 begin print(" at "); print_scaled(s); print("pt");
13128 end
13129 else if s<>-1000 then
13130 begin print(" scaled "); print_int(-s);
13131 end
13132
13133 @<Report that the font won't be loaded@>=
13134 start_font_error_message;
13135 @.Font x=xx not loadable...@>
13136 if file_opened then print(" not loadable: Bad metric (TFM) file")
13137 else print(" not loadable: Metric (TFM) file not found");
13138 help5("I wasn't able to read the size data for this font,")@/
13139 ("so I will ignore the font specification.")@/
13140 ("[Wizards can fix TFM files using TFtoPL/PLtoTF.]")@/
13141 ("You might try inserting a different font spec;")@/
13142 ("e.g., type `I\font<same font id>=<substitute font name>'.");
13143 error
13144
13145 @ @<Read and check...@>=
13146 @<Open |tfm_file| for input@>;
13147 @<Read the {\.{TFM}} size fields@>;
13148 @<Use size fields to allocate font information@>;
13149 @<Read the {\.{TFM}} header@>;
13150 @<Read character data@>;
13151 @<Read box dimensions@>;
13152 @<Read ligature/kern program@>;
13153 @<Read extensible character recipes@>;
13154 @<Read font parameters@>;
13155 @<Make final adjustments and |goto done|@>
13156
13157 @ @<Open |tfm_file| for input@>=
13158 file_opened:=false;
13159 if aire="" then pack_file_name(nom,TEX_font_area,".tfm")
13160 else pack_file_name(nom,aire,".tfm");
13161 if not b_open_in(tfm_file) then abort;
13162 file_opened:=true
13163
13164 @ Note: A malformed \.{TFM} file might be shorter than it claims to be;
13165 thus |eof(tfm_file)| might be true when |read_font_info| refers to
13166 |tfm_file^| or when it says |get(tfm_file)|. If such circumstances
13167 cause system error messages, you will have to defeat them somehow,
13168 for example by defining |fget| to be `\ignorespaces|begin get(tfm_file);|
13169 |if eof(tfm_file) then abort; end|\unskip'.
13170 @^system dependencies@>
13171
13172 @d fget==get(tfm_file)
13173 @d fbyte==tfm_file^
13174 @d read_sixteen(#)==begin #:=fbyte;
13175 if #>127 then abort;
13176 fget; #:=#*@'400+fbyte;
13177 end
13178 @d store_four_quarters(#)==begin fget; a:=fbyte; qw.b0:=qi(a);
13179 fget; b:=fbyte; qw.b1:=qi(b);
13180 fget; c:=fbyte; qw.b2:=qi(c);
13181 fget; d:=fbyte; qw.b3:=qi(d);
13182 #:=qw;
13183 end
13184
13185 @ @<Read the {\.{TFM}} size fields@>=
13186 begin read_sixteen(lf);
13187 fget; read_sixteen(lh);
13188 fget; read_sixteen(bc);
13189 fget; read_sixteen(ec);
13190 if (bc>ec+1)or(ec>255) then abort;
13191 if bc>255 then {|bc=256| and |ec=255|}
13192 begin bc:=1; ec:=0;
13193 end;
13194 fget; read_sixteen(nw);
13195 fget; read_sixteen(nh);
13196 fget; read_sixteen(nd);
13197 fget; read_sixteen(ni);
13198 fget; read_sixteen(nl);
13199 fget; read_sixteen(nk);
13200 fget; read_sixteen(ne);
13201 fget; read_sixteen(np);
13202 if lf<>6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np then abort;
13203 if (nw=0)or(nh=0)or(nd=0)or(ni=0) then abort;
13204 end
13205
13206 @ The preliminary settings of the index-offset variables |char_base|,
13207 |width_base|, |lig_kern_base|, |kern_base|, and |exten_base| will be
13208 corrected later by subtracting |min_quarterword| from them; and we will
13209 subtract 1 from |param_base| too. It's best to forget about such anomalies
13210 until later.
13211
13212 @<Use size fields to allocate font information@>=
13213 lf:=lf-6-lh; {|lf| words should be loaded into |font_info|}
13214 if np<7 then lf:=lf+7-np; {at least seven parameters will appear}
13215 if (font_ptr=font_max)or(fmem_ptr+lf>font_mem_size) then
13216 @<Apologize for not loading the font, |goto done|@>;
13217 f:=font_ptr+1;
13218 char_base[f]:=fmem_ptr-bc;
13219 width_base[f]:=char_base[f]+ec+1;
13220 height_base[f]:=width_base[f]+nw;
13221 depth_base[f]:=height_base[f]+nh;
13222 italic_base[f]:=depth_base[f]+nd;
13223 lig_kern_base[f]:=italic_base[f]+ni;
13224 kern_base[f]:=lig_kern_base[f]+nl-kern_base_offset;
13225 exten_base[f]:=kern_base[f]+kern_base_offset+nk;
13226 param_base[f]:=exten_base[f]+ne
13227
13228 @ @<Apologize for not loading...@>=
13229 begin start_font_error_message;
13230 print(" not loaded: Not enough room left");
13231 @.Font x=xx not loaded...@>
13232 help4("I'm afraid I won't be able to make use of this font,")@/
13233 ("because my memory for character-size data is too small.")@/
13234 ("If you're really stuck, ask a wizard to enlarge me.")@/
13235 ("Or maybe try `I\font<same font id>=<name of loaded font>'.");
13236 error; goto done;
13237 end
13238
13239 @ Only the first two words of the header are needed by \TeX82.
13240
13241 @<Read the {\.{TFM}} header@>=
13242 begin if lh<2 then abort;
13243 store_four_quarters(font_check[f]);
13244 fget; read_sixteen(z); {this rejects a negative design size}
13245 fget; z:=z*@'400+fbyte; fget; z:=(z*@'20)+(fbyte div@'20);
13246 if z<unity then abort;
13247 while lh>2 do
13248 begin fget;fget;fget;fget;decr(lh); {ignore the rest of the header}
13249 end;
13250 font_dsize[f]:=z;
13251 if s<>-1000 then
13252 if s>=0 then z:=s
13253 else z:=xn_over_d(z,-s,1000);
13254 font_size[f]:=z;
13255 end
13256
13257 @ @<Read character data@>=
13258 for k:=fmem_ptr to width_base[f]-1 do
13259 begin store_four_quarters(font_info[k].qqqq);
13260 if (a>=nw)or(b div @'20>=nh)or(b mod @'20>=nd)or
13261 (c div 4>=ni) then abort;
13262 case c mod 4 of
13263 lig_tag: if d>=nl then abort;
13264 ext_tag: if d>=ne then abort;
13265 list_tag: @<Check for charlist cycle@>;
13266 othercases do_nothing {|no_tag|}
13267 endcases;
13268 end
13269
13270 @ We want to make sure that there is no cycle of characters linked together
13271 by |list_tag| entries, since such a cycle would get \TeX\ into an endless
13272 loop. If such a cycle exists, the routine here detects it when processing
13273 the largest character code in the cycle.
13274
13275 @d check_byte_range(#)==begin if (#<bc)or(#>ec) then abort@+end
13276 @d current_character_being_worked_on==k+bc-fmem_ptr
13277
13278 @<Check for charlist cycle@>=
13279 begin check_byte_range(d);
13280 while d<current_character_being_worked_on do
13281 begin qw:=char_info(f)(d);
13282 {N.B.: not |qi(d)|, since |char_base[f]| hasn't been adjusted yet}
13283 if char_tag(qw)<>list_tag then goto not_found;
13284 d:=qo(rem_byte(qw)); {next character on the list}
13285 end;
13286 if d=current_character_being_worked_on then abort; {yes, there's a cycle}
13287 not_found:end
13288
13289 @ A |fix_word| whose four bytes are $(a,b,c,d)$ from left to right represents
13290 the number
13291 $$x=\left\{\vcenter{\halign{$#$,\hfil\qquad&if $#$\hfil\cr
13292 b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=0;\cr
13293 -16+b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=255.\cr}}\right.$$
13294 (No other choices of |a| are allowed, since the magnitude of a number in
13295 design-size units must be less than 16.) We want to multiply this
13296 quantity by the integer~|z|, which is known to be less than $2^{27}$.
13297 If $|z|<2^{23}$, the individual multiplications $b\cdot z$,
13298 $c\cdot z$, $d\cdot z$ cannot overflow; otherwise we will divide |z| by 2,
13299 4, 8, or 16, to obtain a multiplier less than $2^{23}$, and we can
13300 compensate for this later. If |z| has thereby been replaced by
13301 $|z|^\prime=|z|/2^e$, let $\beta=2^{4-e}$; we shall compute
13302 $$\lfloor(b+c\cdot2^{-8}+d\cdot2^{-16})\,z^\prime/\beta\rfloor$$
13303 if $a=0$, or the same quantity minus $\alpha=2^{4+e}z^\prime$ if $a=255$.
13304 This calculation must be done exactly, in order to guarantee portability
13305 of \TeX\ between computers.
13306
13307 @d store_scaled(#)==begin fget; a:=fbyte; fget; b:=fbyte;
13308 fget; c:=fbyte; fget; d:=fbyte;@/
13309 sw:=(((((d*z)div@'400)+(c*z))div@'400)+(b*z))div beta;
13310 if a=0 then #:=sw@+else if a=255 then #:=sw-alpha@+else abort;
13311 end
13312
13313 @p function store_scaled_f(sq, z: scaled): scaled;
13314 var a,b,c,d:eight_bits; sw:scaled;
13315 alpha:integer;
13316 beta:1..16;
13317 begin
13318 alpha:=16;
13319 if z>=@'1000000000 then pdf_error("font", "size is too large");
13320 while z>=@'40000000 do
13321 begin z:=z div 2; alpha:=alpha+alpha;
13322 end;
13323 beta:=256 div alpha; alpha:=alpha*z;
13324 if sq >= 0 then begin
13325 d:=sq mod 256; sq:=sq div 256; {any "mod 256" not really needed, would typecast alone be safe?}
13326 c:=sq mod 256; sq:=sq div 256;
13327 b:=sq mod 256; sq:=sq div 256;
13328 a:=sq mod 256;
13329 end else begin
13330 sq:=(sq+1073741824)+1073741824; {braces for optimizing compiler}
13331 d:=sq mod 256; sq:=sq div 256;
13332 c:=sq mod 256; sq:=sq div 256;
13333 b:=sq mod 256; sq:=sq div 256;
13334 a:=(sq+128) mod 256;
13335 end;
13336 sw:=(((((d*z)div@'400)+(c*z))div@'400)+(b*z))div beta;
13337 if a=0 then store_scaled_f:=sw@+else if a=255 then store_scaled_f:=sw-alpha@+else pdf_error("store_scaled_f", "vf scaling");
13338 end;
13339
13340
13341 @ @<Read box dimensions@>=
13342 begin @<Replace |z| by $|z|^\prime$ and compute $\alpha,\beta$@>;
13343 for k:=width_base[f] to lig_kern_base[f]-1 do
13344 store_scaled(font_info[k].sc);
13345 if font_info[width_base[f]].sc<>0 then abort; {\\{width}[0] must be zero}
13346 if font_info[height_base[f]].sc<>0 then abort; {\\{height}[0] must be zero}
13347 if font_info[depth_base[f]].sc<>0 then abort; {\\{depth}[0] must be zero}
13348 if font_info[italic_base[f]].sc<>0 then abort; {\\{italic}[0] must be zero}
13349 end
13350
13351 @ @<Replace |z|...@>=
13352 begin alpha:=16;
13353 if z>=@'1000000000 then pdf_error("font", "size is too large");
13354 while z>=@'40000000 do
13355 begin z:=z div 2; alpha:=alpha+alpha;
13356 end;
13357 beta:=256 div alpha; alpha:=alpha*z;
13358 end
13359
13360 @ @d check_existence(#)==@t@>@;@/
13361 begin check_byte_range(#);
13362 qw:=char_info(f)(#); {N.B.: not |qi(#)|}
13363 if not char_exists(qw) then abort;
13364 end
13365
13366 @<Read ligature/kern program@>=
13367 bch_label:=@'77777; bchar:=256;
13368 if nl>0 then
13369 begin for k:=lig_kern_base[f] to kern_base[f]+kern_base_offset-1 do
13370 begin store_four_quarters(font_info[k].qqqq);
13371 if a>128 then
13372 begin if 256*c+d>=nl then abort;
13373 if a=255 then if k=lig_kern_base[f] then bchar:=b;
13374 end
13375 else begin if b<>bchar then check_existence(b);
13376 if c<128 then check_existence(d) {check ligature}
13377 else if 256*(c-128)+d>=nk then abort; {check kern}
13378 if a<128 then if k-lig_kern_base[f]+a+1>=nl then abort;
13379 end;
13380 end;
13381 if a=255 then bch_label:=256*c+d;
13382 end;
13383 for k:=kern_base[f]+kern_base_offset to exten_base[f]-1 do
13384 store_scaled(font_info[k].sc);
13385
13386 @ @<Read extensible character recipes@>=
13387 for k:=exten_base[f] to param_base[f]-1 do
13388 begin store_four_quarters(font_info[k].qqqq);
13389 if a<>0 then check_existence(a);
13390 if b<>0 then check_existence(b);
13391 if c<>0 then check_existence(c);
13392 check_existence(d);
13393 end
13394
13395 @ We check to see that the \.{TFM} file doesn't end prematurely; but
13396 no error message is given for files having more than |lf| words.
13397
13398 @<Read font parameters@>=
13399 begin for k:=1 to np do
13400 if k=1 then {the |slant| parameter is a pure number}
13401 begin fget; sw:=fbyte; if sw>127 then sw:=sw-256;
13402 fget; sw:=sw*@'400+fbyte; fget; sw:=sw*@'400+fbyte;
13403 fget; font_info[param_base[f]].sc:=
13404 (sw*@'20)+(fbyte div@'20);
13405 end
13406 else store_scaled(font_info[param_base[f]+k-1].sc);
13407 if eof(tfm_file) then abort;
13408 for k:=np+1 to 7 do font_info[param_base[f]+k-1].sc:=0;
13409 end
13410
13411 @ Now to wrap it up, we have checked all the necessary things about the \.{TFM}
13412 file, and all we need to do is put the finishing touches on the data for
13413 the new font.
13414
13415 @d adjust(#)==#[f]:=qo(#[f])
13416 {correct for the excess |min_quarterword| that was added}
13417
13418 @<Make final adjustments...@>=
13419 if np>=7 then font_params[f]:=np@+else font_params[f]:=7;
13420 hyphen_char[f]:=default_hyphen_char; skew_char[f]:=default_skew_char;
13421 if bch_label<nl then bchar_label[f]:=bch_label+lig_kern_base[f]
13422 else bchar_label[f]:=non_address;
13423 font_bchar[f]:=qi(bchar);
13424 font_false_bchar[f]:=qi(bchar);
13425 if bchar<=ec then if bchar>=bc then
13426 begin qw:=char_info(f)(bchar); {N.B.: not |qi(bchar)|}
13427 if char_exists(qw) then font_false_bchar[f]:=non_char;
13428 end;
13429 font_name[f]:=nom;
13430 font_area[f]:=aire;
13431 font_bc[f]:=bc; font_ec[f]:=ec; font_glue[f]:=null;
13432 adjust(char_base); adjust(width_base); adjust(lig_kern_base);
13433 adjust(kern_base); adjust(exten_base);
13434 decr(param_base[f]);
13435 fmem_ptr:=fmem_ptr+lf; font_ptr:=f; g:=f; goto done
13436
13437 @ Before we forget about the format of these tables, let's deal with two
13438 of \TeX's basic scanning routines related to font information.
13439
13440 @<Declare procedures that scan font-related stuff@>=
13441 function test_no_ligatures(f: internal_font_number): integer;
13442 label exit;
13443 var c:integer;
13444 begin
13445 test_no_ligatures:= 1;
13446 for c := font_bc[f] to font_ec[f] do
13447 if char_exists(orig_char_info(f)(c)) then
13448 if odd(char_tag(orig_char_info(f)(c))) then begin
13449 test_no_ligatures:= 0;
13450 return;
13451 end;
13452 exit:
13453 end;
13454
13455 function get_tag_code(f: internal_font_number; c: eight_bits): integer;
13456 var i:small_number;
13457 begin
13458 if is_valid_char(c) then
13459 begin i := char_tag(char_info(f)(c));
13460 if i = lig_tag then
13461 get_tag_code := 1
13462 else if i = list_tag then
13463 get_tag_code := 2
13464 else if i = ext_tag then
13465 get_tag_code := 4
13466 else
13467 get_tag_code := 0;
13468 end
13469 else
13470 get_tag_code := -1;
13471 end;
13472 procedure scan_font_ident;
13473 var f:internal_font_number;
13474 @!m:halfword;
13475 begin @<Get the next non-blank non-call...@>;
13476 if (cur_cmd=def_font) or (cur_cmd=letterspace_font) or (cur_cmd=pdf_copy_font) then f:=cur_font
13477 else if cur_cmd=set_font then f:=cur_chr
13478 else if cur_cmd=def_family then
13479 begin m:=cur_chr; scan_four_bit_int; f:=equiv(m+cur_val);
13480 end
13481 else begin print_err("Missing font identifier");
13482 @.Missing font identifier@>
13483 help2("I was looking for a control sequence whose")@/
13484 ("current meaning has been defined by \font.");
13485 back_error; f:=null_font;
13486 end;
13487 cur_val:=f;
13488 end;
13489
13490 @ The following routine is used to implement `\.{\\fontdimen} |n| |f|'.
13491 The boolean parameter |writing| is set |true| if the calling program
13492 intends to change the parameter value.
13493
13494 @<Declare procedures that scan font-related stuff@>=
13495 procedure find_font_dimen(@!writing:boolean);
13496 {sets |cur_val| to |font_info| location}
13497 var f:internal_font_number;
13498 @!n:integer; {the parameter number}
13499 begin scan_int; n:=cur_val; scan_font_ident; f:=cur_val;
13500 if n<=0 then cur_val:=fmem_ptr
13501 else begin if writing and(n<=space_shrink_code)and@|
13502 (n>=space_code)and(font_glue[f]<>null) then
13503 begin delete_glue_ref(font_glue[f]);
13504 font_glue[f]:=null;
13505 end;
13506 if n>font_params[f] then
13507 if f<font_ptr then cur_val:=fmem_ptr
13508 else @<Increase the number of parameters in the last font@>
13509 else cur_val:=n+param_base[f];
13510 end;
13511 @<Issue an error message if |cur_val=fmem_ptr|@>;
13512 end;
13513
13514 @ @<Issue an error message if |cur_val=fmem_ptr|@>=
13515 if cur_val=fmem_ptr then
13516 begin print_err("Font "); print_esc(font_id_text(f));
13517 print(" has only "); print_int(font_params[f]);
13518 print(" fontdimen parameters");
13519 @.Font x has only...@>
13520 help2("To increase the number of font parameters, you must")@/
13521 ("use \fontdimen immediately after the \font is loaded.");
13522 error;
13523 end
13524
13525 @ @<Increase the number of parameters...@>=
13526 begin repeat if fmem_ptr=font_mem_size then
13527 overflow("font memory",font_mem_size);
13528 @:TeX capacity exceeded font memory}{\quad font memory@>
13529 font_info[fmem_ptr].sc:=0; incr(fmem_ptr); incr(font_params[f]);
13530 until n=font_params[f];
13531 cur_val:=fmem_ptr-1; {this equals |param_base[f]+font_params[f]|}
13532 end
13533
13534 @ When \TeX\ wants to typeset a character that doesn't exist, the
13535 character node is not created; thus the output routine can assume
13536 that characters exist when it sees them. The following procedure
13537 prints a warning message unless the user has suppressed it.
13538
13539 @p procedure char_warning(@!f:internal_font_number;@!c:eight_bits);
13540 var old_setting: integer; {saved value of |tracing_online|}
13541 begin if tracing_lost_chars>0 then
13542 begin old_setting:=tracing_online;
13543 if eTeX_ex and(tracing_lost_chars>1) then tracing_online:=1;
13544 begin begin_diagnostic;
13545 print_nl("Missing character: There is no ");
13546 @.Missing character@>
13547 print_ASCII(c); print(" in font ");
13548 slow_print(font_name[f]); print_char("!"); end_diagnostic(false);
13549 end;
13550 tracing_online:=old_setting;
13551 end;
13552 end;
13553
13554 @ Here is a function that returns a pointer to a character node for a
13555 given character in a given font. If that character doesn't exist,
13556 |null| is returned instead.
13557
13558 @p function new_character(@!f:internal_font_number;@!c:eight_bits):pointer;
13559 label exit;
13560 var p:pointer; {newly allocated node}
13561 begin if font_bc[f]<=c then if font_ec[f]>=c then
13562 if char_exists(char_info(f)(qi(c))) then
13563 begin p:=get_avail; font(p):=f; character(p):=qi(c);
13564 new_character:=p; return;
13565 end;
13566 char_warning(f,c);
13567 new_character:=null;
13568 exit:end;
13569
13570 @* \[31] Device-independent file format.
13571 The most important output produced by a run of \TeX\ is the ``device
13572 independent'' (\.{DVI}) file that specifies where characters and rules
13573 are to appear on printed pages. The form of these files was designed by
13574 David R. Fuchs in 1979. Almost any reasonable typesetting device can be
13575 @^Fuchs, David Raymond@>
13576 @:DVI_files}{\.{DVI} files@>
13577 driven by a program that takes \.{DVI} files as input, and dozens of such
13578 \.{DVI}-to-whatever programs have been written. Thus, it is possible to
13579 print the output of \TeX\ on many different kinds of equipment, using \TeX\
13580 as a device-independent ``front end.''
13581
13582 A \.{DVI} file is a stream of 8-bit bytes, which may be regarded as a
13583 series of commands in a machine-like language. The first byte of each command
13584 is the operation code, and this code is followed by zero or more bytes
13585 that provide parameters to the command. The parameters themselves may consist
13586 of several consecutive bytes; for example, the `|set_rule|' command has two
13587 parameters, each of which is four bytes long. Parameters are usually
13588 regarded as nonnegative integers; but four-byte-long parameters,
13589 and shorter parameters that denote distances, can be
13590 either positive or negative. Such parameters are given in two's complement
13591 notation. For example, a two-byte-long distance parameter has a value between
13592 $-2^{15}$ and $2^{15}-1$. As in \.{TFM} files, numbers that occupy
13593 more than one byte position appear in BigEndian order.
13594
13595 A \.{DVI} file consists of a ``preamble,'' followed by a sequence of one
13596 or more ``pages,'' followed by a ``postamble.'' The preamble is simply a
13597 |pre| command, with its parameters that define the dimensions used in the
13598 file; this must come first. Each ``page'' consists of a |bop| command,
13599 followed by any number of other commands that tell where characters are to
13600 be placed on a physical page, followed by an |eop| command. The pages
13601 appear in the order that \TeX\ generated them. If we ignore |nop| commands
13602 and \\{fnt\_def} commands (which are allowed between any two commands in
13603 the file), each |eop| command is immediately followed by a |bop| command,
13604 or by a |post| command; in the latter case, there are no more pages in the
13605 file, and the remaining bytes form the postamble. Further details about
13606 the postamble will be explained later.
13607
13608 Some parameters in \.{DVI} commands are ``pointers.'' These are four-byte
13609 quantities that give the location number of some other byte in the file;
13610 the first byte is number~0, then comes number~1, and so on. For example,
13611 one of the parameters of a |bop| command points to the previous |bop|;
13612 this makes it feasible to read the pages in backwards order, in case the
13613 results are being directed to a device that stacks its output face up.
13614 Suppose the preamble of a \.{DVI} file occupies bytes 0 to 99. Now if the
13615 first page occupies bytes 100 to 999, say, and if the second
13616 page occupies bytes 1000 to 1999, then the |bop| that starts in byte 1000
13617 points to 100 and the |bop| that starts in byte 2000 points to 1000. (The
13618 very first |bop|, i.e., the one starting in byte 100, has a pointer of~$-1$.)
13619
13620 @ The \.{DVI} format is intended to be both compact and easily interpreted
13621 by a machine. Compactness is achieved by making most of the information
13622 implicit instead of explicit. When a \.{DVI}-reading program reads the
13623 commands for a page, it keeps track of several quantities: (a)~The current
13624 font |f| is an integer; this value is changed only
13625 by \\{fnt} and \\{fnt\_num} commands. (b)~The current position on the page
13626 is given by two numbers called the horizontal and vertical coordinates,
13627 |h| and |v|. Both coordinates are zero at the upper left corner of the page;
13628 moving to the right corresponds to increasing the horizontal coordinate, and
13629 moving down corresponds to increasing the vertical coordinate. Thus, the
13630 coordinates are essentially Cartesian, except that vertical directions are
13631 flipped; the Cartesian version of |(h,v)| would be |(h,-v)|. (c)~The
13632 current spacing amounts are given by four numbers |w|, |x|, |y|, and |z|,
13633 where |w| and~|x| are used for horizontal spacing and where |y| and~|z|
13634 are used for vertical spacing. (d)~There is a stack containing
13635 |(h,v,w,x,y,z)| values; the \.{DVI} commands |push| and |pop| are used to
13636 change the current level of operation. Note that the current font~|f| is
13637 not pushed and popped; the stack contains only information about
13638 positioning.
13639
13640 The values of |h|, |v|, |w|, |x|, |y|, and |z| are signed integers having up
13641 to 32 bits, including the sign. Since they represent physical distances,
13642 there is a small unit of measurement such that increasing |h| by~1 means
13643 moving a certain tiny distance to the right. The actual unit of
13644 measurement is variable, as explained below; \TeX\ sets things up so that
13645 its \.{DVI} output is in sp units, i.e., scaled points, in agreement with
13646 all the |scaled| dimensions in \TeX's data structures.
13647
13648 @ Here is a list of all the commands that may appear in a \.{DVI} file. Each
13649 command is specified by its symbolic name (e.g., |bop|), its opcode byte
13650 (e.g., 139), and its parameters (if any). The parameters are followed
13651 by a bracketed number telling how many bytes they occupy; for example,
13652 `|p[4]|' means that parameter |p| is four bytes long.
13653
13654 \yskip\hang|set_char_0| 0. Typeset character number~0 from font~|f|
13655 such that the reference point of the character is at |(h,v)|. Then
13656 increase |h| by the width of that character. Note that a character may
13657 have zero or negative width, so one cannot be sure that |h| will advance
13658 after this command; but |h| usually does increase.
13659
13660 \yskip\hang\\{set\_char\_1} through \\{set\_char\_127} (opcodes 1 to 127).
13661 Do the operations of |set_char_0|; but use the character whose number
13662 matches the opcode, instead of character~0.
13663
13664 \yskip\hang|set1| 128 |c[1]|. Same as |set_char_0|, except that character
13665 number~|c| is typeset. \TeX82 uses this command for characters in the
13666 range |128<=c<256|.
13667
13668 \yskip\hang|@!set2| 129 |c[2]|. Same as |set1|, except that |c|~is two
13669 bytes long, so it is in the range |0<=c<65536|. \TeX82 never uses this
13670 command, but it should come in handy for extensions of \TeX\ that deal
13671 with oriental languages.
13672 @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
13673
13674 \yskip\hang|@!set3| 130 |c[3]|. Same as |set1|, except that |c|~is three
13675 bytes long, so it can be as large as $2^{24}-1$. Not even the Chinese
13676 language has this many characters, but this command might prove useful
13677 in some yet unforeseen extension.
13678
13679 \yskip\hang|@!set4| 131 |c[4]|. Same as |set1|, except that |c|~is four
13680 bytes long. Imagine that.
13681
13682 \yskip\hang|set_rule| 132 |a[4]| |b[4]|. Typeset a solid black rectangle
13683 of height~|a| and width~|b|, with its bottom left corner at |(h,v)|. Then
13684 set |h:=h+b|. If either |a<=0| or |b<=0|, nothing should be typeset. Note
13685 that if |b<0|, the value of |h| will decrease even though nothing else happens.
13686 See below for details about how to typeset rules so that consistency with
13687 \MF\ is guaranteed.
13688
13689 \yskip\hang|@!put1| 133 |c[1]|. Typeset character number~|c| from font~|f|
13690 such that the reference point of the character is at |(h,v)|. (The `put'
13691 commands are exactly like the `set' commands, except that they simply put out a
13692 character or a rule without moving the reference point afterwards.)
13693
13694 \yskip\hang|@!put2| 134 |c[2]|. Same as |set2|, except that |h| is not changed.
13695
13696 \yskip\hang|@!put3| 135 |c[3]|. Same as |set3|, except that |h| is not changed.
13697
13698 \yskip\hang|@!put4| 136 |c[4]|. Same as |set4|, except that |h| is not changed.
13699
13700 \yskip\hang|put_rule| 137 |a[4]| |b[4]|. Same as |set_rule|, except that
13701 |h| is not changed.
13702
13703 \yskip\hang|nop| 138. No operation, do nothing. Any number of |nop|'s
13704 may occur between \.{DVI} commands, but a |nop| cannot be inserted between
13705 a command and its parameters or between two parameters.
13706
13707 \yskip\hang|bop| 139 $c_0[4]$ $c_1[4]$ $\ldots$ $c_9[4]$ $p[4]$. Beginning
13708 of a page: Set |(h,v,w,x,y,z):=(0,0,0,0,0,0)| and set the stack empty. Set
13709 the current font |f| to an undefined value. The ten $c_i$ parameters hold
13710 the values of \.{\\count0} $\ldots$ \.{\\count9} in \TeX\ at the time
13711 \.{\\shipout} was invoked for this page; they can be used to identify
13712 pages, if a user wants to print only part of a \.{DVI} file. The parameter
13713 |p| points to the previous |bop| in the file; the first
13714 |bop| has $p=-1$.
13715
13716 \yskip\hang|eop| 140. End of page: Print what you have read since the
13717 previous |bop|. At this point the stack should be empty. (The \.{DVI}-reading
13718 programs that drive most output devices will have kept a buffer of the
13719 material that appears on the page that has just ended. This material is
13720 largely, but not entirely, in order by |v| coordinate and (for fixed |v|) by
13721 |h|~coordinate; so it usually needs to be sorted into some order that is
13722 appropriate for the device in question.)
13723
13724 \yskip\hang|push| 141. Push the current values of |(h,v,w,x,y,z)| onto the
13725 top of the stack; do not change any of these values. Note that |f| is
13726 not pushed.
13727
13728 \yskip\hang|pop| 142. Pop the top six values off of the stack and assign
13729 them respectively to |(h,v,w,x,y,z)|. The number of pops should never
13730 exceed the number of pushes, since it would be highly embarrassing if the
13731 stack were empty at the time of a |pop| command.
13732
13733 \yskip\hang|right1| 143 |b[1]|. Set |h:=h+b|, i.e., move right |b| units.
13734 The parameter is a signed number in two's complement notation, |-128<=b<128|;
13735 if |b<0|, the reference point moves left.
13736
13737 \yskip\hang|@!right2| 144 |b[2]|. Same as |right1|, except that |b| is a
13738 two-byte quantity in the range |-32768<=b<32768|.
13739
13740 \yskip\hang|@!right3| 145 |b[3]|. Same as |right1|, except that |b| is a
13741 three-byte quantity in the range |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
13742
13743 \yskip\hang|@!right4| 146 |b[4]|. Same as |right1|, except that |b| is a
13744 four-byte quantity in the range |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
13745
13746 \yskip\hang|w0| 147. Set |h:=h+w|; i.e., move right |w| units. With luck,
13747 this parameterless command will usually suffice, because the same kind of motion
13748 will occur several times in succession; the following commands explain how
13749 |w| gets particular values.
13750
13751 \yskip\hang|w1| 148 |b[1]|. Set |w:=b| and |h:=h+b|. The value of |b| is a
13752 signed quantity in two's complement notation, |-128<=b<128|. This command
13753 changes the current |w|~spacing and moves right by |b|.
13754
13755 \yskip\hang|@!w2| 149 |b[2]|. Same as |w1|, but |b| is two bytes long,
13756 |-32768<=b<32768|.
13757
13758 \yskip\hang|@!w3| 150 |b[3]|. Same as |w1|, but |b| is three bytes long,
13759 |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
13760
13761 \yskip\hang|@!w4| 151 |b[4]|. Same as |w1|, but |b| is four bytes long,
13762 |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
13763
13764 \yskip\hang|x0| 152. Set |h:=h+x|; i.e., move right |x| units. The `|x|'
13765 commands are like the `|w|' commands except that they involve |x| instead
13766 of |w|.
13767
13768 \yskip\hang|x1| 153 |b[1]|. Set |x:=b| and |h:=h+b|. The value of |b| is a
13769 signed quantity in two's complement notation, |-128<=b<128|. This command
13770 changes the current |x|~spacing and moves right by |b|.
13771
13772 \yskip\hang|@!x2| 154 |b[2]|. Same as |x1|, but |b| is two bytes long,
13773 |-32768<=b<32768|.
13774
13775 \yskip\hang|@!x3| 155 |b[3]|. Same as |x1|, but |b| is three bytes long,
13776 |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
13777
13778 \yskip\hang|@!x4| 156 |b[4]|. Same as |x1|, but |b| is four bytes long,
13779 |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
13780
13781 \yskip\hang|down1| 157 |a[1]|. Set |v:=v+a|, i.e., move down |a| units.
13782 The parameter is a signed number in two's complement notation, |-128<=a<128|;
13783 if |a<0|, the reference point moves up.
13784
13785 \yskip\hang|@!down2| 158 |a[2]|. Same as |down1|, except that |a| is a
13786 two-byte quantity in the range |-32768<=a<32768|.
13787
13788 \yskip\hang|@!down3| 159 |a[3]|. Same as |down1|, except that |a| is a
13789 three-byte quantity in the range |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
13790
13791 \yskip\hang|@!down4| 160 |a[4]|. Same as |down1|, except that |a| is a
13792 four-byte quantity in the range |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
13793
13794 \yskip\hang|y0| 161. Set |v:=v+y|; i.e., move down |y| units. With luck,
13795 this parameterless command will usually suffice, because the same kind of motion
13796 will occur several times in succession; the following commands explain how
13797 |y| gets particular values.
13798
13799 \yskip\hang|y1| 162 |a[1]|. Set |y:=a| and |v:=v+a|. The value of |a| is a
13800 signed quantity in two's complement notation, |-128<=a<128|. This command
13801 changes the current |y|~spacing and moves down by |a|.
13802
13803 \yskip\hang|@!y2| 163 |a[2]|. Same as |y1|, but |a| is two bytes long,
13804 |-32768<=a<32768|.
13805
13806 \yskip\hang|@!y3| 164 |a[3]|. Same as |y1|, but |a| is three bytes long,
13807 |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
13808
13809 \yskip\hang|@!y4| 165 |a[4]|. Same as |y1|, but |a| is four bytes long,
13810 |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
13811
13812 \yskip\hang|z0| 166. Set |v:=v+z|; i.e., move down |z| units. The `|z|' commands
13813 are like the `|y|' commands except that they involve |z| instead of |y|.
13814
13815 \yskip\hang|z1| 167 |a[1]|. Set |z:=a| and |v:=v+a|. The value of |a| is a
13816 signed quantity in two's complement notation, |-128<=a<128|. This command
13817 changes the current |z|~spacing and moves down by |a|.
13818
13819 \yskip\hang|@!z2| 168 |a[2]|. Same as |z1|, but |a| is two bytes long,
13820 |-32768<=a<32768|.
13821
13822 \yskip\hang|@!z3| 169 |a[3]|. Same as |z1|, but |a| is three bytes long,
13823 |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
13824
13825 \yskip\hang|@!z4| 170 |a[4]|. Same as |z1|, but |a| is four bytes long,
13826 |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
13827
13828 \yskip\hang|fnt_num_0| 171. Set |f:=0|. Font 0 must previously have been
13829 defined by a \\{fnt\_def} instruction, as explained below.
13830
13831 \yskip\hang\\{fnt\_num\_1} through \\{fnt\_num\_63} (opcodes 172 to 234). Set
13832 |f:=1|, \dots, \hbox{|f:=63|}, respectively.
13833
13834 \yskip\hang|fnt1| 235 |k[1]|. Set |f:=k|. \TeX82 uses this command for font
13835 numbers in the range |64<=k<256|.
13836
13837 \yskip\hang|@!fnt2| 236 |k[2]|. Same as |fnt1|, except that |k|~is two
13838 bytes long, so it is in the range |0<=k<65536|. \TeX82 never generates this
13839 command, but large font numbers may prove useful for specifications of
13840 color or texture, or they may be used for special fonts that have fixed
13841 numbers in some external coding scheme.
13842
13843 \yskip\hang|@!fnt3| 237 |k[3]|. Same as |fnt1|, except that |k|~is three
13844 bytes long, so it can be as large as $2^{24}-1$.
13845
13846 \yskip\hang|@!fnt4| 238 |k[4]|. Same as |fnt1|, except that |k|~is four
13847 bytes long; this is for the really big font numbers (and for the negative ones).
13848
13849 \yskip\hang|xxx1| 239 |k[1]| |x[k]|. This command is undefined in
13850 general; it functions as a $(k+2)$-byte |nop| unless special \.{DVI}-reading
13851 programs are being used. \TeX82 generates |xxx1| when a short enough
13852 \.{\\special} appears, setting |k| to the number of bytes being sent. It
13853 is recommended that |x| be a string having the form of a keyword followed
13854 by possible parameters relevant to that keyword.
13855
13856 \yskip\hang|@!xxx2| 240 |k[2]| |x[k]|. Like |xxx1|, but |0<=k<65536|.
13857
13858 \yskip\hang|@!xxx3| 241 |k[3]| |x[k]|. Like |xxx1|, but |0<=k<@t$2^{24}$@>|.
13859
13860 \yskip\hang|xxx4| 242 |k[4]| |x[k]|. Like |xxx1|, but |k| can be ridiculously
13861 large. \TeX82 uses |xxx4| when sending a string of length 256 or more.
13862
13863 \yskip\hang|fnt_def1| 243 |k[1]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13864 Define font |k|, where |0<=k<256|; font definitions will be explained shortly.
13865
13866 \yskip\hang|@!fnt_def2| 244 |k[2]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13867 Define font |k|, where |0<=k<65536|.
13868
13869 \yskip\hang|@!fnt_def3| 245 |k[3]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13870 Define font |k|, where |0<=k<@t$2^{24}$@>|.
13871
13872 \yskip\hang|@!fnt_def4| 246 |k[4]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13873 Define font |k|, where |@t$-2^{31}$@><=k<@t$2^{31}$@>|.
13874
13875 \yskip\hang|pre| 247 |i[1]| |num[4]| |den[4]| |mag[4]| |k[1]| |x[k]|.
13876 Beginning of the preamble; this must come at the very beginning of the
13877 file. Parameters |i|, |num|, |den|, |mag|, |k|, and |x| are explained below.
13878
13879 \yskip\hang|post| 248. Beginning of the postamble, see below.
13880
13881 \yskip\hang|post_post| 249. Ending of the postamble, see below.
13882
13883 \yskip\noindent Commands 250--255 are undefined at the present time.
13884
13885 @ @d set_char_0=0 {typeset character 0 and move right}
13886 @d set1=128 {typeset a character and move right}
13887 @d set_rule=132 {typeset a rule and move right}
13888 @d put_rule=137 {typeset a rule}
13889 @d nop=138 {no operation}
13890 @d bop=139 {beginning of page}
13891 @d eop=140 {ending of page}
13892 @d push=141 {save the current positions}
13893 @d pop=142 {restore previous positions}
13894 @d right1=143 {move right}
13895 @d w0=147 {move right by |w|}
13896 @d w1=148 {move right and set |w|}
13897 @d x0=152 {move right by |x|}
13898 @d x1=153 {move right and set |x|}
13899 @d down1=157 {move down}
13900 @d y0=161 {move down by |y|}
13901 @d y1=162 {move down and set |y|}
13902 @d z0=166 {move down by |z|}
13903 @d z1=167 {move down and set |z|}
13904 @d fnt_num_0=171 {set current font to 0}
13905 @d fnt1=235 {set current font}
13906 @d xxx1=239 {extension to \.{DVI} primitives}
13907 @d xxx4=242 {potentially long extension to \.{DVI} primitives}
13908 @d fnt_def1=243 {define the meaning of a font number}
13909 @d pre=247 {preamble}
13910 @d post=248 {postamble beginning}
13911 @d post_post=249 {postamble ending}
13912
13913 @ The preamble contains basic information about the file as a whole. As
13914 stated above, there are six parameters:
13915 $$\hbox{|@!i[1]| |@!num[4]| |@!den[4]| |@!mag[4]| |@!k[1]| |@!x[k]|.}$$
13916 The |i| byte identifies \.{DVI} format; currently this byte is always set
13917 to~2. (The value |i=3| is currently used for an extended format that
13918 allows a mixture of right-to-left and left-to-right typesetting.
13919 Some day we will set |i=4|, when \.{DVI} format makes another
13920 incompatible change---perhaps in the year 2048.)
13921
13922 The next two parameters, |num| and |den|, are positive integers that define
13923 the units of measurement; they are the numerator and denominator of a
13924 fraction by which all dimensions in the \.{DVI} file could be multiplied
13925 in order to get lengths in units of $10^{-7}$ meters. Since $\rm 7227{pt} =
13926 254{cm}$, and since \TeX\ works with scaled points where there are $2^{16}$
13927 sp in a point, \TeX\ sets
13928 $|num|/|den|=(254\cdot10^5)/(7227\cdot2^{16})=25400000/473628672$.
13929 @^sp@>
13930
13931 The |mag| parameter is what \TeX\ calls \.{\\mag}, i.e., 1000 times the
13932 desired magnification. The actual fraction by which dimensions are
13933 multiplied is therefore $|mag|\cdot|num|/1000|den|$. Note that if a \TeX\
13934 source document does not call for any `\.{true}' dimensions, and if you
13935 change it only by specifying a different \.{\\mag} setting, the \.{DVI}
13936 file that \TeX\ creates will be completely unchanged except for the value
13937 of |mag| in the preamble and postamble. (Fancy \.{DVI}-reading programs allow
13938 users to override the |mag|~setting when a \.{DVI} file is being printed.)
13939
13940 Finally, |k| and |x| allow the \.{DVI} writer to include a comment, which is not
13941 interpreted further. The length of comment |x| is |k|, where |0<=k<256|.
13942
13943 @d id_byte=2 {identifies the kind of \.{DVI} files described here}
13944
13945 @ Font definitions for a given font number |k| contain further parameters
13946 $$\hbox{|c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.}$$
13947 The four-byte value |c| is the check sum that \TeX\ found in the \.{TFM}
13948 file for this font; |c| should match the check sum of the font found by
13949 programs that read this \.{DVI} file.
13950 @^check sum@>
13951
13952 Parameter |s| contains a fixed-point scale factor that is applied to
13953 the character widths in font |k|; font dimensions in \.{TFM} files and
13954 other font files are relative to this quantity, which is called the
13955 ``at size'' elsewhere in this documentation. The value of |s| is
13956 always positive and less than $2^{27}$. It is given in the same units
13957 as the other \.{DVI} dimensions, i.e., in sp when \TeX82 has made the
13958 file. Parameter |d| is similar to |s|; it is the ``design size,'' and
13959 (like~|s|) it is given in \.{DVI} units. Thus, font |k| is to be used
13960 at $|mag|\cdot s/1000d$ times its normal size.
13961
13962 The remaining part of a font definition gives the external name of the font,
13963 which is an ASCII string of length |a+l|. The number |a| is the length
13964 of the ``area'' or directory, and |l| is the length of the font name itself;
13965 the standard local system font area is supposed to be used when |a=0|.
13966 The |n| field contains the area in its first |a| bytes.
13967
13968 Font definitions must appear before the first use of a particular font number.
13969 Once font |k| is defined, it must not be defined again; however, we
13970 shall see below that font definitions appear in the postamble as well as
13971 in the pages, so in this sense each font number is defined exactly twice,
13972 if at all. Like |nop| commands, font definitions can
13973 appear before the first |bop|, or between an |eop| and a |bop|.
13974
13975 @ Sometimes it is desirable to make horizontal or vertical rules line up
13976 precisely with certain features in characters of a font. It is possible to
13977 guarantee the correct matching between \.{DVI} output and the characters
13978 generated by \MF\ by adhering to the following principles: (1)~The \MF\
13979 characters should be positioned so that a bottom edge or left edge that is
13980 supposed to line up with the bottom or left edge of a rule appears at the
13981 reference point, i.e., in row~0 and column~0 of the \MF\ raster. This
13982 ensures that the position of the rule will not be rounded differently when
13983 the pixel size is not a perfect multiple of the units of measurement in
13984 the \.{DVI} file. (2)~A typeset rule of height $a>0$ and width $b>0$
13985 should be equivalent to a \MF-generated character having black pixels in
13986 precisely those raster positions whose \MF\ coordinates satisfy
13987 |0<=x<@t$\alpha$@>b| and |0<=y<@t$\alpha$@>a|, where $\alpha$ is the number
13988 of pixels per \.{DVI} unit.
13989 @:METAFONT}{\MF@>
13990 @^alignment of rules with characters@>
13991 @^rules aligning with characters@>
13992
13993 @ The last page in a \.{DVI} file is followed by `|post|'; this command
13994 introduces the postamble, which summarizes important facts that \TeX\ has
13995 accumulated about the file, making it possible to print subsets of the data
13996 with reasonable efficiency. The postamble has the form
13997 $$\vbox{\halign{\hbox{#\hfil}\cr
13998 |post| |p[4]| |num[4]| |den[4]| |mag[4]| |l[4]| |u[4]| |s[2]| |t[2]|\cr
13999 $\langle\,$font definitions$\,\rangle$\cr
14000 |post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
14001 Here |p| is a pointer to the final |bop| in the file. The next three
14002 parameters, |num|, |den|, and |mag|, are duplicates of the quantities that
14003 appeared in the preamble.
14004
14005 Parameters |l| and |u| give respectively the height-plus-depth of the tallest
14006 page and the width of the widest page, in the same units as other dimensions
14007 of the file. These numbers might be used by a \.{DVI}-reading program to
14008 position individual ``pages'' on large sheets of film or paper; however,
14009 the standard convention for output on normal size paper is to position each
14010 page so that the upper left-hand corner is exactly one inch from the left
14011 and the top. Experience has shown that it is unwise to design \.{DVI}-to-printer
14012 software that attempts cleverly to center the output; a fixed position of
14013 the upper left corner is easiest for users to understand and to work with.
14014 Therefore |l| and~|u| are often ignored.
14015
14016 Parameter |s| is the maximum stack depth (i.e., the largest excess of
14017 |push| commands over |pop| commands) needed to process this file. Then
14018 comes |t|, the total number of pages (|bop| commands) present.
14019
14020 The postamble continues with font definitions, which are any number of
14021 \\{fnt\_def} commands as described above, possibly interspersed with |nop|
14022 commands. Each font number that is used in the \.{DVI} file must be defined
14023 exactly twice: Once before it is first selected by a \\{fnt} command, and once
14024 in the postamble.
14025
14026 @ The last part of the postamble, following the |post_post| byte that
14027 signifies the end of the font definitions, contains |q|, a pointer to the
14028 |post| command that started the postamble. An identification byte, |i|,
14029 comes next; this currently equals~2, as in the preamble.
14030
14031 The |i| byte is followed by four or more bytes that are all equal to
14032 the decimal number 223 (i.e., @'337 in octal). \TeX\ puts out four to seven of
14033 these trailing bytes, until the total length of the file is a multiple of
14034 four bytes, since this works out best on machines that pack four bytes per
14035 word; but any number of 223's is allowed, as long as there are at least four
14036 of them. In effect, 223 is a sort of signature that is added at the very end.
14037 @^Fuchs, David Raymond@>
14038
14039 This curious way to finish off a \.{DVI} file makes it feasible for
14040 \.{DVI}-reading programs to find the postamble first, on most computers,
14041 even though \TeX\ wants to write the postamble last. Most operating
14042 systems permit random access to individual words or bytes of a file, so
14043 the \.{DVI} reader can start at the end and skip backwards over the 223's
14044 until finding the identification byte. Then it can back up four bytes, read
14045 |q|, and move to byte |q| of the file. This byte should, of course,
14046 contain the value 248 (|post|); now the postamble can be read, so the
14047 \.{DVI} reader can discover all the information needed for typesetting the
14048 pages. Note that it is also possible to skip through the \.{DVI} file at
14049 reasonably high speed to locate a particular page, if that proves
14050 desirable. This saves a lot of time, since \.{DVI} files used in production
14051 jobs tend to be large.
14052
14053 Unfortunately, however, standard \PASCAL\ does not include the ability to
14054 @^system dependencies@>
14055 access a random position in a file, or even to determine the length of a file.
14056 Almost all systems nowadays provide the necessary capabilities, so \.{DVI}
14057 format has been designed to work most efficiently with modern operating systems.
14058 But if \.{DVI} files have to be processed under the restrictions of standard
14059 \PASCAL, one can simply read them from front to back, since the necessary
14060 header information is present in the preamble and in the font definitions.
14061 (The |l| and |u| and |s| and |t| parameters, which appear only in the
14062 postamble, are ``frills'' that are handy but not absolutely necessary.)
14063
14064 @* \[32] Shipping pages out.
14065 After considering \TeX's eyes and stomach, we come now to the bowels.
14066 @^bowels@>
14067
14068 The |ship_out| procedure is given a pointer to a box; its mission is
14069 to describe that box in \.{DVI} form, outputting a ``page'' to |dvi_file|.
14070 The \.{DVI} coordinates $(h,v)=(0,0)$ should correspond to the upper left
14071 corner of the box being shipped.
14072
14073 Since boxes can be inside of boxes inside of boxes, the main work of
14074 |ship_out| is done by two mutually recursive routines, |hlist_out|
14075 and |vlist_out|, which traverse the hlists and vlists inside of horizontal
14076 and vertical boxes.
14077
14078 As individual pages are being processed, we need to accumulate
14079 information about the entire set of pages, since such statistics must be
14080 reported in the postamble. The global variables |total_pages|, |max_v|,
14081 |max_h|, |max_push|, and |last_bop| are used to record this information.
14082
14083 The variable |doing_leaders| is |true| while leaders are being output.
14084 The variable |dead_cycles| contains the number of times an output routine
14085 has been initiated since the last |ship_out|.
14086
14087 A few additional global variables are also defined here for use in
14088 |vlist_out| and |hlist_out|. They could have been local variables, but
14089 that would waste stack space when boxes are deeply nested, since the
14090 values of these variables are not needed during recursive calls.
14091 @^recursion@>
14092
14093 @<Glob...@>=
14094 @!total_pages:integer; {the number of pages that have been shipped out}
14095 @!max_v:scaled; {maximum height-plus-depth of pages shipped so far}
14096 @!max_h:scaled; {maximum width of pages shipped so far}
14097 @!max_push:integer; {deepest nesting of |push| commands encountered so far}
14098 @!last_bop:integer; {location of previous |bop| in the \.{DVI} output}
14099 @!dead_cycles:integer; {recent outputs that didn't ship anything out}
14100 @!doing_leaders:boolean; {are we inside a leader box?}
14101 @#
14102 @!c,@!f:quarterword; {character and font in current |char_node|}
14103 @!rule_ht,@!rule_dp,@!rule_wd:scaled; {size of current rule being output}
14104 @!g:pointer; {current glue specification}
14105 @!lq,@!lr:integer; {quantities used in calculations for leaders}
14106
14107 @ @<Set init...@>=
14108 total_pages:=0; max_v:=0; max_h:=0; max_push:=0; last_bop:=-1;
14109 doing_leaders:=false; dead_cycles:=0; cur_s:=-1;
14110
14111 @ The \.{DVI} bytes are output to a buffer instead of being written directly
14112 to the output file. This makes it possible to reduce the overhead of
14113 subroutine calls, thereby measurably speeding up the computation, since
14114 output of \.{DVI} bytes is part of \TeX's inner loop. And it has another
14115 advantage as well, since we can change instructions in the buffer in order to
14116 make the output more compact. For example, a `|down2|' command can be
14117 changed to a `|y2|', thereby making a subsequent `|y0|' command possible,
14118 saving two bytes.
14119
14120 The output buffer is divided into two parts of equal size; the bytes found
14121 in |dvi_buf[0..half_buf-1]| constitute the first half, and those in
14122 |dvi_buf[half_buf..dvi_buf_size-1]| constitute the second. The global
14123 variable |dvi_ptr| points to the position that will receive the next
14124 output byte. When |dvi_ptr| reaches |dvi_limit|, which is always equal
14125 to one of the two values |half_buf| or |dvi_buf_size|, the half buffer that
14126 is about to be invaded next is sent to the output and |dvi_limit| is
14127 changed to its other value. Thus, there is always at least a half buffer's
14128 worth of information present, except at the very beginning of the job.
14129
14130 Bytes of the \.{DVI} file are numbered sequentially starting with 0;
14131 the next byte to be generated will be number |dvi_offset+dvi_ptr|.
14132 A byte is present in the buffer only if its number is |>=dvi_gone|.
14133
14134 @<Types...@>=
14135 @!dvi_index=0..dvi_buf_size; {an index into the output buffer}
14136
14137 @ Some systems may find it more efficient to make |dvi_buf| a |packed|
14138 array, since output of four bytes at once may be facilitated.
14139 @^system dependencies@>
14140
14141 @<Glob...@>=
14142 @!dvi_buf:array[dvi_index] of eight_bits; {buffer for \.{DVI} output}
14143 @!half_buf:dvi_index; {half of |dvi_buf_size|}
14144 @!dvi_limit:dvi_index; {end of the current half buffer}
14145 @!dvi_ptr:dvi_index; {the next available buffer address}
14146 @!dvi_offset:integer; {|dvi_buf_size| times the number of times the
14147 output buffer has been fully emptied}
14148 @!dvi_gone:integer; {the number of bytes already output to |dvi_file|}
14149
14150 @ Initially the buffer is all in one piece; we will output half of it only
14151 after it first fills up.
14152
14153 @<Set init...@>=
14154 half_buf:=dvi_buf_size div 2; dvi_limit:=dvi_buf_size; dvi_ptr:=0;
14155 dvi_offset:=0; dvi_gone:=0;
14156
14157 @ The actual output of |dvi_buf[a..b]| to |dvi_file| is performed by calling
14158 |write_dvi(a,b)|. For best results, this procedure should be optimized to
14159 run as fast as possible on each particular system, since it is part of
14160 \TeX's inner loop. It is safe to assume that |a| and |b+1| will both be
14161 multiples of 4 when |write_dvi(a,b)| is called; therefore it is possible on
14162 many machines to use efficient methods to pack four bytes per word and to
14163 output an array of words with one system call.
14164 @^system dependencies@>
14165 @^inner loop@>
14166 @^defecation@>
14167
14168 @p procedure write_dvi(@!a,@!b:dvi_index);
14169 var k:dvi_index;
14170 begin for k:=a to b do write(dvi_file,dvi_buf[k]);
14171 end;
14172
14173 @ To put a byte in the buffer without paying the cost of invoking a procedure
14174 each time, we use the macro |dvi_out|.
14175
14176 @d dvi_out(#)==@+begin dvi_buf[dvi_ptr]:=#; incr(dvi_ptr);
14177 if dvi_ptr=dvi_limit then dvi_swap;
14178 end
14179
14180 @p procedure dvi_swap; {outputs half of the buffer}
14181 begin if dvi_limit=dvi_buf_size then
14182 begin write_dvi(0,half_buf-1); dvi_limit:=half_buf;
14183 dvi_offset:=dvi_offset+dvi_buf_size; dvi_ptr:=0;
14184 end
14185 else begin write_dvi(half_buf,dvi_buf_size-1); dvi_limit:=dvi_buf_size;
14186 end;
14187 dvi_gone:=dvi_gone+half_buf;
14188 end;
14189
14190 @ Here is how we clean out the buffer when \TeX\ is all through; |dvi_ptr|
14191 will be a multiple of~4.
14192
14193 @<Empty the last bytes out of |dvi_buf|@>=
14194 if dvi_limit=half_buf then write_dvi(half_buf,dvi_buf_size-1);
14195 if dvi_ptr>0 then write_dvi(0,dvi_ptr-1)
14196
14197 @ The |dvi_four| procedure outputs four bytes in two's complement notation,
14198 without risking arithmetic overflow.
14199
14200 @p procedure dvi_four(@!x:integer);
14201 begin if x>=0 then dvi_out(x div @'100000000)
14202 else begin x:=x+@'10000000000;
14203 x:=x+@'10000000000;
14204 dvi_out((x div @'100000000) + 128);
14205 end;
14206 x:=x mod @'100000000; dvi_out(x div @'200000);
14207 x:=x mod @'200000; dvi_out(x div @'400);
14208 dvi_out(x mod @'400);
14209 end;
14210
14211 @ A mild optimization of the output is performed by the |dvi_pop|
14212 routine, which issues a |pop| unless it is possible to cancel a
14213 `|push| |pop|' pair. The parameter to |dvi_pop| is the byte address
14214 following the old |push| that matches the new |pop|.
14215
14216 @p procedure dvi_pop(@!l:integer);
14217 begin if (l=dvi_offset+dvi_ptr)and(dvi_ptr>0) then decr(dvi_ptr)
14218 else dvi_out(pop);
14219 end;
14220
14221 @ Here's a procedure that outputs a font definition. Since \TeX82 uses at
14222 most 256 different fonts per job, |fnt_def1| is always used as the command code.
14223
14224 @p procedure dvi_font_def(@!f:internal_font_number);
14225 var k:pool_pointer; {index into |str_pool|}
14226 begin dvi_out(fnt_def1);
14227 dvi_out(f-font_base-1);@/
14228 dvi_out(qo(font_check[f].b0));
14229 dvi_out(qo(font_check[f].b1));
14230 dvi_out(qo(font_check[f].b2));
14231 dvi_out(qo(font_check[f].b3));@/
14232 dvi_four(font_size[f]);
14233 dvi_four(font_dsize[f]);@/
14234 dvi_out(length(font_area[f]));
14235 dvi_out(length(font_name[f]));
14236 @<Output the font name whose internal number is |f|@>;
14237 end;
14238
14239 @ @<Output the font name whose internal number is |f|@>=
14240 for k:=str_start[font_area[f]] to str_start[font_area[f]+1]-1 do
14241 dvi_out(so(str_pool[k]));
14242 for k:=str_start[font_name[f]] to str_start[font_name[f]+1]-1 do
14243 dvi_out(so(str_pool[k]))
14244
14245 @ Versions of \TeX\ intended for small computers might well choose to omit
14246 the ideas in the next few parts of this program, since it is not really
14247 necessary to optimize the \.{DVI} code by making use of the |w0|, |x0|,
14248 |y0|, and |z0| commands. Furthermore, the algorithm that we are about to
14249 describe does not pretend to give an optimum reduction in the length
14250 of the \.{DVI} code; after all, speed is more important than compactness.
14251 But the method is surprisingly effective, and it takes comparatively little
14252 time.
14253
14254 We can best understand the basic idea by first considering a simpler problem
14255 that has the same essential characteristics. Given a sequence of digits,
14256 say $3\,1\,4\,1\,5\,9\,2\,6\,5\,3\,5\,8\,9$, we want to assign subscripts
14257 $d$, $y$, or $z$ to each digit so as to maximize the number of ``$y$-hits''
14258 and ``$z$-hits''; a $y$-hit is an instance of two appearances of the same
14259 digit with the subscript $y$, where no $y$'s intervene between the two
14260 appearances, and a $z$-hit is defined similarly. For example, the sequence
14261 above could be decorated with subscripts as follows:
14262 $$3_z\,1_y\,4_d\,1_y\,5_y\,9_d\,2_d\,6_d\,5_y\,3_z\,5_y\,8_d\,9_d.$$
14263 There are three $y$-hits ($1_y\ldots1_y$ and $5_y\ldots5_y\ldots5_y$) and
14264 one $z$-hit ($3_z\ldots3_z$); there are no $d$-hits, since the two appearances
14265 of $9_d$ have $d$'s between them, but we don't count $d$-hits so it doesn't
14266 matter how many there are. These subscripts are analogous to the \.{DVI}
14267 commands called \\{down}, $y$, and $z$, and the digits are analogous to
14268 different amounts of vertical motion; a $y$-hit or $z$-hit corresponds to
14269 the opportunity to use the one-byte commands |y0| or |z0| in a \.{DVI} file.
14270
14271 \TeX's method of assigning subscripts works like this: Append a new digit,
14272 say $\delta$, to the right of the sequence. Now look back through the
14273 sequence until one of the following things happens: (a)~You see
14274 $\delta_y$ or $\delta_z$, and this was the first time you encountered a
14275 $y$ or $z$ subscript, respectively. Then assign $y$ or $z$ to the new
14276 $\delta$; you have scored a hit. (b)~You see $\delta_d$, and no $y$
14277 subscripts have been encountered so far during this search. Then change
14278 the previous $\delta_d$ to $\delta_y$ (this corresponds to changing a
14279 command in the output buffer), and assign $y$ to the new $\delta$; it's
14280 another hit. (c)~You see $\delta_d$, and a $y$ subscript has been seen
14281 but not a $z$. Change the previous $\delta_d$ to $\delta_z$ and assign
14282 $z$ to the new $\delta$. (d)~You encounter both $y$ and $z$ subscripts
14283 before encountering a suitable $\delta$, or you scan all the way to the
14284 front of the sequence. Assign $d$ to the new $\delta$; this assignment may
14285 be changed later.
14286
14287 The subscripts $3_z\,1_y\,4_d\ldots\,$ in the example above were, in fact,
14288 produced by this procedure, as the reader can verify. (Go ahead and try it.)
14289
14290 @ In order to implement such an idea, \TeX\ maintains a stack of pointers
14291 to the \\{down}, $y$, and $z$ commands that have been generated for the
14292 current page. And there is a similar stack for \\{right}, |w|, and |x|
14293 commands. These stacks are called the down stack and right stack, and their
14294 top elements are maintained in the variables |down_ptr| and |right_ptr|.
14295
14296 Each entry in these stacks contains four fields: The |width| field is
14297 the amount of motion down or to the right; the |location| field is the
14298 byte number of the \.{DVI} command in question (including the appropriate
14299 |dvi_offset|); the |link| field points to the next item below this one
14300 on the stack; and the |info| field encodes the options for possible change
14301 in the \.{DVI} command.
14302
14303 @d movement_node_size=3 {number of words per entry in the down and right stacks}
14304 @d location(#)==mem[#+2].int {\.{DVI} byte number for a movement command}
14305
14306 @<Glob...@>=
14307 @!down_ptr,@!right_ptr:pointer; {heads of the down and right stacks}
14308
14309 @ @<Set init...@>=
14310 down_ptr:=null; right_ptr:=null;
14311
14312 @ Here is a subroutine that produces a \.{DVI} command for some specified
14313 downward or rightward motion. It has two parameters: |w| is the amount
14314 of motion, and |o| is either |down1| or |right1|. We use the fact that
14315 the command codes have convenient arithmetic properties: |y1-down1=w1-right1|
14316 and |z1-down1=x1-right1|.
14317
14318 @p procedure movement(@!w:scaled;@!o:eight_bits);
14319 label exit,found,not_found,2,1;
14320 var mstate:small_number; {have we seen a |y| or |z|?}
14321 @!p,@!q:pointer; {current and top nodes on the stack}
14322 @!k:integer; {index into |dvi_buf|, modulo |dvi_buf_size|}
14323 begin q:=get_node(movement_node_size); {new node for the top of the stack}
14324 width(q):=w; location(q):=dvi_offset+dvi_ptr;
14325 if o=down1 then
14326 begin link(q):=down_ptr; down_ptr:=q;
14327 end
14328 else begin link(q):=right_ptr; right_ptr:=q;
14329 end;
14330 @<Look at the other stack entries until deciding what sort of \.{DVI} command
14331 to generate; |goto found| if node |p| is a ``hit''@>;
14332 @<Generate a |down| or |right| command for |w| and |return|@>;
14333 found: @<Generate a |y0| or |z0| command in order to reuse a previous
14334 appearance of~|w|@>;
14335 exit:end;
14336
14337 @ The |info| fields in the entries of the down stack or the right stack
14338 have six possible settings: |y_here| or |z_here| mean that the \.{DVI}
14339 command refers to |y| or |z|, respectively (or to |w| or |x|, in the
14340 case of horizontal motion); |yz_OK| means that the \.{DVI} command is
14341 \\{down} (or \\{right}) but can be changed to either |y| or |z| (or
14342 to either |w| or |x|); |y_OK| means that it is \\{down} and can be changed
14343 to |y| but not |z|; |z_OK| is similar; and |d_fixed| means it must stay
14344 \\{down}.
14345
14346 The four settings |yz_OK|, |y_OK|, |z_OK|, |d_fixed| would not need to
14347 be distinguished from each other if we were simply solving the
14348 digit-subscripting problem mentioned above. But in \TeX's case there is
14349 a complication because of the nested structure of |push| and |pop|
14350 commands. Suppose we add parentheses to the digit-subscripting problem,
14351 redefining hits so that $\delta_y\ldots \delta_y$ is a hit if all $y$'s between
14352 the $\delta$'s are enclosed in properly nested parentheses, and if the
14353 parenthesis level of the right-hand $\delta_y$ is deeper than or equal to
14354 that of the left-hand one. Thus, `(' and `)' correspond to `|push|'
14355 and `|pop|'. Now if we want to assign a subscript to the final 1 in the
14356 sequence
14357 $$2_y\,7_d\,1_d\,(\,8_z\,2_y\,8_z\,)\,1$$
14358 we cannot change the previous $1_d$ to $1_y$, since that would invalidate
14359 the $2_y\ldots2_y$ hit. But we can change it to $1_z$, scoring a hit
14360 since the intervening $8_z$'s are enclosed in parentheses.
14361
14362 The program below removes movement nodes that are introduced after a |push|,
14363 before it outputs the corresponding |pop|.
14364
14365 @d y_here=1 {|info| when the movement entry points to a |y| command}
14366 @d z_here=2 {|info| when the movement entry points to a |z| command}
14367 @d yz_OK=3 {|info| corresponding to an unconstrained \\{down} command}
14368 @d y_OK=4 {|info| corresponding to a \\{down} that can't become a |z|}
14369 @d z_OK=5 {|info| corresponding to a \\{down} that can't become a |y|}
14370 @d d_fixed=6 {|info| corresponding to a \\{down} that can't change}
14371
14372 @ When the |movement| procedure gets to the label |found|, the value of
14373 |info(p)| will be either |y_here| or |z_here|. If it is, say, |y_here|,
14374 the procedure generates a |y0| command (or a |w0| command), and marks
14375 all |info| fields between |q| and |p| so that |y| is not OK in that range.
14376
14377 @<Generate a |y0| or |z0| command...@>=
14378 info(q):=info(p);
14379 if info(q)=y_here then
14380 begin dvi_out(o+y0-down1); {|y0| or |w0|}
14381 while link(q)<>p do
14382 begin q:=link(q);
14383 case info(q) of
14384 yz_OK: info(q):=z_OK;
14385 y_OK: info(q):=d_fixed;
14386 othercases do_nothing
14387 endcases;
14388 end;
14389 end
14390 else begin dvi_out(o+z0-down1); {|z0| or |x0|}
14391 while link(q)<>p do
14392 begin q:=link(q);
14393 case info(q) of
14394 yz_OK: info(q):=y_OK;
14395 z_OK: info(q):=d_fixed;
14396 othercases do_nothing
14397 endcases;
14398 end;
14399 end
14400
14401 @ @<Generate a |down| or |right|...@>=
14402 info(q):=yz_OK;
14403 if abs(w)>=@'40000000 then
14404 begin dvi_out(o+3); {|down4| or |right4|}
14405 dvi_four(w); return;
14406 end;
14407 if abs(w)>=@'100000 then
14408 begin dvi_out(o+2); {|down3| or |right3|}
14409 if w<0 then w:=w+@'100000000;
14410 dvi_out(w div @'200000); w:=w mod @'200000; goto 2;
14411 end;
14412 if abs(w)>=@'200 then
14413 begin dvi_out(o+1); {|down2| or |right2|}
14414 if w<0 then w:=w+@'200000;
14415 goto 2;
14416 end;
14417 dvi_out(o); {|down1| or |right1|}
14418 if w<0 then w:=w+@'400;
14419 goto 1;
14420 2: dvi_out(w div @'400);
14421 1: dvi_out(w mod @'400); return
14422
14423 @ As we search through the stack, we are in one of three states,
14424 |y_seen|, |z_seen|, or |none_seen|, depending on whether we have
14425 encountered |y_here| or |z_here| nodes. These states are encoded as
14426 multiples of 6, so that they can be added to the |info| fields for quick
14427 decision-making.
14428 @^inner loop@>
14429
14430 @d none_seen=0 {no |y_here| or |z_here| nodes have been encountered yet}
14431 @d y_seen=6 {we have seen |y_here| but not |z_here|}
14432 @d z_seen=12 {we have seen |z_here| but not |y_here|}
14433
14434 @<Look at the other stack entries until deciding...@>=
14435 p:=link(q); mstate:=none_seen;
14436 while p<>null do
14437 begin if width(p)=w then @<Consider a node with matching width;
14438 |goto found| if it's a hit@>
14439 else case mstate+info(p) of
14440 none_seen+y_here: mstate:=y_seen;
14441 none_seen+z_here: mstate:=z_seen;
14442 y_seen+z_here,z_seen+y_here: goto not_found;
14443 othercases do_nothing
14444 endcases;
14445 p:=link(p);
14446 end;
14447 not_found:
14448
14449 @ We might find a valid hit in a |y| or |z| byte that is already gone
14450 from the buffer. But we can't change bytes that are gone forever; ``the
14451 moving finger writes, $\ldots\,\,$.''
14452
14453 @<Consider a node with matching width...@>=
14454 case mstate+info(p) of
14455 none_seen+yz_OK,none_seen+y_OK,z_seen+yz_OK,z_seen+y_OK:@t@>@;@/
14456 if location(p)<dvi_gone then goto not_found
14457 else @<Change buffered instruction to |y| or |w| and |goto found|@>;
14458 none_seen+z_OK,y_seen+yz_OK,y_seen+z_OK:@t@>@;@/
14459 if location(p)<dvi_gone then goto not_found
14460 else @<Change buffered instruction to |z| or |x| and |goto found|@>;
14461 none_seen+y_here,none_seen+z_here,y_seen+z_here,z_seen+y_here: goto found;
14462 othercases do_nothing
14463 endcases
14464
14465 @ @<Change buffered instruction to |y| or |w| and |goto found|@>=
14466 begin k:=location(p)-dvi_offset;
14467 if k<0 then k:=k+dvi_buf_size;
14468 dvi_buf[k]:=dvi_buf[k]+y1-down1;
14469 info(p):=y_here; goto found;
14470 end
14471
14472 @ @<Change buffered instruction to |z| or |x| and |goto found|@>=
14473 begin k:=location(p)-dvi_offset;
14474 if k<0 then k:=k+dvi_buf_size;
14475 dvi_buf[k]:=dvi_buf[k]+z1-down1;
14476 info(p):=z_here; goto found;
14477 end
14478
14479 @ In case you are wondering when all the movement nodes are removed from
14480 \TeX's memory, the answer is that they are recycled just before
14481 |hlist_out| and |vlist_out| finish outputting a box. This restores the
14482 down and right stacks to the state they were in before the box was output,
14483 except that some |info|'s may have become more restrictive.
14484
14485 @p procedure prune_movements(@!l:integer);
14486 {delete movement nodes with |location>=l|}
14487 label done,exit;
14488 var p:pointer; {node being deleted}
14489 begin while down_ptr<>null do
14490 begin if location(down_ptr)<l then goto done;
14491 p:=down_ptr; down_ptr:=link(p); free_node(p,movement_node_size);
14492 end;
14493 done: while right_ptr<>null do
14494 begin if location(right_ptr)<l then return;
14495 p:=right_ptr; right_ptr:=link(p); free_node(p,movement_node_size);
14496 end;
14497 exit:end;
14498
14499 @ The actual distances by which we want to move might be computed as the
14500 sum of several separate movements. For example, there might be several
14501 glue nodes in succession, or we might want to move right by the width of
14502 some box plus some amount of glue. More importantly, the baselineskip
14503 distances are computed in terms of glue together with the depth and
14504 height of adjacent boxes, and we want the \.{DVI} file to lump these
14505 three quantities together into a single motion.
14506
14507 Therefore, \TeX\ maintains two pairs of global variables: |dvi_h| and |dvi_v|
14508 are the |h| and |v| coordinates corresponding to the commands actually
14509 output to the \.{DVI} file, while |cur_h| and |cur_v| are the coordinates
14510 corresponding to the current state of the output routines. Coordinate
14511 changes will accumulate in |cur_h| and |cur_v| without being reflected
14512 in the output, until such a change becomes necessary or desirable; we
14513 can call the |movement| procedure whenever we want to make |dvi_h=cur_h|
14514 or |dvi_v=cur_v|.
14515
14516 The current font reflected in the \.{DVI} output is called |dvi_f|;
14517 there is no need for a `\\{cur\_f}' variable.
14518
14519 The depth of nesting of |hlist_out| and |vlist_out| is called |cur_s|;
14520 this is essentially the depth of |push| commands in the \.{DVI} output.
14521
14522 For mixed direction text (\TeXXeT) the current text direction is called
14523 |cur_dir|. As the box being shipped out will never be used again and
14524 soon be recycled, we can simply reverse any R-text (i.e., right-to-left)
14525 segments of hlist nodes as well as complete hlist nodes embedded in such
14526 segments. Moreover this can be done iteratively rather than recursively.
14527 There are, however, two complications related to leaders that require
14528 some additional bookkeeping: (1)~One and the same hlist node might be
14529 used more than once (but never inside both L- and R-text); and
14530 (2)~leader boxes inside hlists must be aligned with respect to the left
14531 edge of the original hlist.
14532
14533 A math node is changed into a kern node whenever the text direction
14534 remains the same, it is replaced by an |edge_node| if the text direction
14535 changes; the subtype of an an |hlist_node| inside R-text is changed to
14536 |reversed| once its hlist has been reversed.
14537 @!@^data structure assumptions@>
14538
14539 @d reversed=1 {subtype for an |hlist_node| whose hlist has been reversed}
14540 @d dlist=2 {subtype for an |hlist_node| from display math mode}
14541 @d box_lr(#) == (qo(subtype(#))) {direction mode of a box}
14542 @d set_box_lr(#) == subtype(#):=set_box_lr_end
14543 @d set_box_lr_end(#) == qi(#)
14544 @#
14545 @d left_to_right=0
14546 @d right_to_left=1
14547 @d reflected==1-cur_dir {the opposite of |cur_dir|}
14548 @#
14549 @d synch_h==if cur_h<>dvi_h then
14550 begin movement(cur_h-dvi_h,right1); dvi_h:=cur_h;
14551 end
14552 @d synch_v==if cur_v<>dvi_v then
14553 begin movement(cur_v-dvi_v,down1); dvi_v:=cur_v;
14554 end
14555
14556 @<Glob...@>=
14557 @!dvi_h,@!dvi_v:scaled; {a \.{DVI} reader program thinks we are here}
14558 @!cur_h,@!cur_v:scaled; {\TeX\ thinks we are here}
14559 @!dvi_f:internal_font_number; {the current font}
14560 @!cur_s:integer; {current depth of output box nesting, initially $-1$}
14561
14562 @ @<Calculate DVI page dimensions and margins@>=
14563 cur_h_offset := h_offset;
14564 cur_v_offset := v_offset;
14565 if pdf_page_width <> 0 then
14566 cur_page_width := pdf_page_width
14567 else
14568 cur_page_width := width(p) + 2*cur_h_offset + 2*4736286;
14569 {4736286 = 1in, the funny DVI origin offset}
14570 if pdf_page_height <> 0 then
14571 cur_page_height := pdf_page_height
14572 else
14573 cur_page_height := height(p) + depth(p) + 2*cur_v_offset + 2*4736286
14574 {4736286 = 1in, the funny DVI origin offset}
14575
14576 @ @<Initialize variables as |ship_out| begins@>=
14577 dvi_h:=0; dvi_v:=0; cur_h:=h_offset; dvi_f:=null_font;
14578 @<Calculate DVI page dimensions and margins@>;
14579 ensure_dvi_open;
14580 if total_pages=0 then
14581 begin dvi_out(pre); dvi_out(id_byte); {output the preamble}
14582 @^preamble of \.{DVI} file@>
14583 dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
14584 prepare_mag; dvi_four(mag); {magnification factor is frozen}
14585 old_setting:=selector; selector:=new_string;
14586 print(" TeX output "); print_int(year); print_char(".");
14587 print_two(month); print_char("."); print_two(day);
14588 print_char(":"); print_two(time div 60);
14589 print_two(time mod 60);
14590 selector:=old_setting; dvi_out(cur_length);
14591 for s:=str_start[str_ptr] to pool_ptr-1 do dvi_out(so(str_pool[s]));
14592 pool_ptr:=str_start[str_ptr]; {flush the current string}
14593 end
14594
14595 @ When |hlist_out| is called, its duty is to output the box represented
14596 by the |hlist_node| pointed to by |temp_ptr|. The reference point of that
14597 box has coordinates |(cur_h,cur_v)|.
14598
14599 Similarly, when |vlist_out| is called, its duty is to output the box represented
14600 by the |vlist_node| pointed to by |temp_ptr|. The reference point of that
14601 box has coordinates |(cur_h,cur_v)|.
14602 @^recursion@>
14603
14604 @p procedure@?vlist_out; forward; {|hlist_out| and |vlist_out| are mutually
14605 recursive}
14606
14607 @ The recursive procedures |hlist_out| and |vlist_out| each have local variables
14608 |save_h| and |save_v| to hold the values of |dvi_h| and |dvi_v| just before
14609 entering a new level of recursion. In effect, the values of |save_h| and
14610 |save_v| on \TeX's run-time stack correspond to the values of |h| and |v|
14611 that a \.{DVI}-reading program will push onto its coordinate stack.
14612
14613 @d move_past=13 {go to this label when advancing past glue or a rule}
14614 @d fin_rule=14 {go to this label to finish processing a rule}
14615 @d next_p=15 {go to this label when finished with node |p|}
14616
14617 @p @t\4@>@<Declare procedures needed in |hlist_out|, |vlist_out|@>@t@>@/
14618 procedure hlist_out; {output an |hlist_node| box}
14619 label reswitch, move_past, fin_rule, next_p;
14620 var base_line: scaled; {the baseline coordinate for this box}
14621 @!left_edge: scaled; {the left coordinate for this box}
14622 @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
14623 @!this_box: pointer; {pointer to containing box}
14624 @!g_order: glue_ord; {applicable order of infinity for glue}
14625 @!g_sign: normal..shrinking; {selects type of glue}
14626 @!p:pointer; {current position in the hlist}
14627 @!save_loc:integer; {\.{DVI} byte location upon entry}
14628 @!leader_box:pointer; {the leader box being replicated}
14629 @!leader_wd:scaled; {width of leader box being replicated}
14630 @!lx:scaled; {extra space between leader boxes}
14631 @!outer_doing_leaders:boolean; {were we doing leaders?}
14632 @!edge:scaled; {right edge of sub-box or leader space}
14633 @!prev_p:pointer; {one step behind |p|}
14634 @!glue_temp:real; {glue value before rounding}
14635 @!cur_glue:real; {glue seen so far}
14636 @!cur_g:scaled; {rounded equivalent of |cur_glue| times the glue ratio}
14637 begin cur_g:=0; cur_glue:=float_constant(0);
14638 this_box:=temp_ptr; g_order:=glue_order(this_box);
14639 g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
14640 incr(cur_s);
14641 if cur_s>0 then dvi_out(push);
14642 if cur_s>max_push then max_push:=cur_s;
14643 save_loc:=dvi_offset+dvi_ptr; base_line:=cur_v;
14644 prev_p:=this_box+list_offset;
14645 @<Initialize |hlist_out| for mixed direction typesetting@>;
14646 left_edge:=cur_h;
14647 while p<>null do @<Output node |p| for |hlist_out| and move to the next node,
14648 maintaining the condition |cur_v=base_line|@>;
14649 @<Finish |hlist_out| for mixed direction typesetting@>;
14650 prune_movements(save_loc);
14651 if cur_s>0 then dvi_pop(save_loc);
14652 decr(cur_s);
14653 end;
14654
14655 @ We ought to give special care to the efficiency of one part of |hlist_out|,
14656 since it belongs to \TeX's inner loop. When a |char_node| is encountered,
14657 we save a little time by processing several nodes in succession until
14658 reaching a non-|char_node|. The program uses the fact that |set_char_0=0|.
14659 @^inner loop@>
14660
14661 @<Output node |p| for |hlist_out|...@>=
14662 reswitch: if is_char_node(p) then
14663 begin synch_h; synch_v;
14664 repeat f:=font(p); c:=character(p);
14665 if f<>dvi_f then @<Change font |dvi_f| to |f|@>;
14666 if c>=qi(128) then dvi_out(set1);
14667 dvi_out(qo(c));@/
14668 cur_h:=cur_h+char_width(f)(char_info(f)(c));
14669 prev_p:=link(prev_p); {N.B.: not |prev_p:=p|, |p| might be |lig_trick|}
14670 p:=link(p);
14671 until not is_char_node(p);
14672 dvi_h:=cur_h;
14673 end
14674 else @<Output the non-|char_node| |p| for |hlist_out|
14675 and move to the next node@>
14676
14677 @ @<Change font |dvi_f| to |f|@>=
14678 begin if not font_used[f] then
14679 begin dvi_font_def(f); font_used[f]:=true;
14680 end;
14681 if f<=64+font_base then dvi_out(f-font_base-1+fnt_num_0)
14682 else begin dvi_out(fnt1); dvi_out(f-font_base-1);
14683 end;
14684 dvi_f:=f;
14685 end
14686
14687 @ @<Output the non-|char_node| |p| for |hlist_out|...@>=
14688 begin case type(p) of
14689 hlist_node,vlist_node:@<Output a box in an hlist@>;
14690 rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
14691 goto fin_rule;
14692 end;
14693 whatsit_node: @<Output the whatsit node |p| in an hlist@>;
14694 glue_node: @<Move right or output leaders@>;
14695 margin_kern_node,
14696 kern_node:cur_h:=cur_h+width(p);
14697 math_node: @<Handle a math node in |hlist_out|@>;
14698 ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>;
14699 @/@<Cases of |hlist_out| that arise in mixed direction text only@>@;
14700 othercases do_nothing
14701 endcases;@/
14702 goto next_p;
14703 fin_rule: @<Output a rule in an hlist@>;
14704 move_past: cur_h:=cur_h+rule_wd;
14705 next_p:prev_p:=p; p:=link(p);
14706 end
14707
14708 @ @<Output a box in an hlist@>=
14709 if list_ptr(p)=null then cur_h:=cur_h+width(p)
14710 else begin save_h:=dvi_h; save_v:=dvi_v;
14711 cur_v:=base_line+shift_amount(p); {shift the box down}
14712 temp_ptr:=p; edge:=cur_h+width(p);
14713 if cur_dir=right_to_left then cur_h:=edge;
14714 if type(p)=vlist_node then vlist_out@+else hlist_out;
14715 dvi_h:=save_h; dvi_v:=save_v;
14716 cur_h:=edge; cur_v:=base_line;
14717 end
14718
14719 @ @<Output a rule in an hlist@>=
14720 if is_running(rule_ht) then rule_ht:=height(this_box);
14721 if is_running(rule_dp) then rule_dp:=depth(this_box);
14722 rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
14723 if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
14724 begin synch_h; cur_v:=base_line+rule_dp; synch_v;
14725 dvi_out(set_rule); dvi_four(rule_ht); dvi_four(rule_wd);
14726 cur_v:=base_line; dvi_h:=dvi_h+rule_wd;
14727 end
14728
14729 @ @d billion==float_constant(1000000000)
14730 @d vet_glue(#)== glue_temp:=#;
14731 if glue_temp>billion then
14732 glue_temp:=billion
14733 else if glue_temp<-billion then
14734 glue_temp:=-billion
14735 @#
14736 @d round_glue==g:=glue_ptr(p); rule_wd:=width(g)-cur_g;
14737 if g_sign<>normal then
14738 begin if g_sign=stretching then
14739 begin if stretch_order(g)=g_order then
14740 begin cur_glue:=cur_glue+stretch(g);
14741 vet_glue(float(glue_set(this_box))*cur_glue);
14742 @^real multiplication@>
14743 cur_g:=round(glue_temp);
14744 end;
14745 end
14746 else if shrink_order(g)=g_order then
14747 begin cur_glue:=cur_glue-shrink(g);
14748 vet_glue(float(glue_set(this_box))*cur_glue);
14749 cur_g:=round(glue_temp);
14750 end;
14751 end;
14752 rule_wd:=rule_wd+cur_g
14753
14754 @<Move right or output leaders@>=
14755 begin round_glue;
14756 if eTeX_ex then @<Handle a glue node for mixed direction typesetting@>;
14757 if subtype(p)>=a_leaders then
14758 @<Output leaders in an hlist, |goto fin_rule| if a rule
14759 or to |next_p| if done@>;
14760 goto move_past;
14761 end
14762
14763 @ @<Output leaders in an hlist...@>=
14764 begin leader_box:=leader_ptr(p);
14765 if type(leader_box)=rule_node then
14766 begin rule_ht:=height(leader_box); rule_dp:=depth(leader_box);
14767 goto fin_rule;
14768 end;
14769 leader_wd:=width(leader_box);
14770 if (leader_wd>0)and(rule_wd>0) then
14771 begin rule_wd:=rule_wd+10; {compensate for floating-point rounding}
14772 if cur_dir=right_to_left then cur_h:=cur_h-10;
14773 edge:=cur_h+rule_wd; lx:=0;
14774 @<Let |cur_h| be the position of the first box, and set |leader_wd+lx|
14775 to the spacing between corresponding parts of boxes@>;
14776 while cur_h+leader_wd<=edge do
14777 @<Output a leader box at |cur_h|,
14778 then advance |cur_h| by |leader_wd+lx|@>;
14779 if cur_dir=right_to_left then cur_h:=edge
14780 else cur_h:=edge-10;
14781 goto next_p;
14782 end;
14783 end
14784
14785 @ The calculations related to leaders require a bit of care. First, in the
14786 case of |a_leaders| (aligned leaders), we want to move |cur_h| to
14787 |left_edge| plus the smallest multiple of |leader_wd| for which the result
14788 is not less than the current value of |cur_h|; i.e., |cur_h| should become
14789 $|left_edge|+|leader_wd|\times\lceil
14790 (|cur_h|-|left_edge|)/|leader_wd|\rceil$. The program here should work in
14791 all cases even though some implementations of \PASCAL\ give nonstandard
14792 results for the |div| operation when |cur_h| is less than |left_edge|.
14793
14794 In the case of |c_leaders| (centered leaders), we want to increase |cur_h|
14795 by half of the excess space not occupied by the leaders; and in the
14796 case of |x_leaders| (expanded leaders) we increase |cur_h|
14797 by $1/(q+1)$ of this excess space, where $q$ is the number of times the
14798 leader box will be replicated. Slight inaccuracies in the division might
14799 accumulate; half of this rounding error is placed at each end of the leaders.
14800
14801 @<Let |cur_h| be the position of the first box, ...@>=
14802 if subtype(p)=a_leaders then
14803 begin save_h:=cur_h;
14804 cur_h:=left_edge+leader_wd*((cur_h-left_edge)@!div leader_wd);
14805 if cur_h<save_h then cur_h:=cur_h+leader_wd;
14806 end
14807 else begin lq:=rule_wd div leader_wd; {the number of box copies}
14808 lr:=rule_wd mod leader_wd; {the remaining space}
14809 if subtype(p)=c_leaders then cur_h:=cur_h+(lr div 2)
14810 else begin lx:=lr div (lq+1);
14811 cur_h:=cur_h+((lr-(lq-1)*lx) div 2);
14812 end;
14813 end
14814
14815 @ The `\\{synch}' operations here are intended to decrease the number of
14816 bytes needed to specify horizontal and vertical motion in the \.{DVI} output.
14817
14818 @<Output a leader box at |cur_h|, ...@>=
14819 begin cur_v:=base_line+shift_amount(leader_box); synch_v; save_v:=dvi_v;@/
14820 synch_h; save_h:=dvi_h; temp_ptr:=leader_box;
14821 if cur_dir=right_to_left then cur_h:=cur_h+leader_wd;
14822 outer_doing_leaders:=doing_leaders; doing_leaders:=true;
14823 if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
14824 doing_leaders:=outer_doing_leaders;
14825 dvi_v:=save_v; dvi_h:=save_h; cur_v:=base_line;
14826 cur_h:=save_h+leader_wd+lx;
14827 end
14828
14829 @ The |vlist_out| routine is similar to |hlist_out|, but a bit simpler.
14830
14831 @p procedure vlist_out; {output a |vlist_node| box}
14832 label move_past, fin_rule, next_p;
14833 var left_edge: scaled; {the left coordinate for this box}
14834 @!top_edge: scaled; {the top coordinate for this box}
14835 @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
14836 @!this_box: pointer; {pointer to containing box}
14837 @!g_order: glue_ord; {applicable order of infinity for glue}
14838 @!g_sign: normal..shrinking; {selects type of glue}
14839 @!p:pointer; {current position in the vlist}
14840 @!save_loc:integer; {\.{DVI} byte location upon entry}
14841 @!leader_box:pointer; {the leader box being replicated}
14842 @!leader_ht:scaled; {height of leader box being replicated}
14843 @!lx:scaled; {extra space between leader boxes}
14844 @!outer_doing_leaders:boolean; {were we doing leaders?}
14845 @!edge:scaled; {bottom boundary of leader space}
14846 @!glue_temp:real; {glue value before rounding}
14847 @!cur_glue:real; {glue seen so far}
14848 @!cur_g:scaled; {rounded equivalent of |cur_glue| times the glue ratio}
14849 begin cur_g:=0; cur_glue:=float_constant(0);
14850 this_box:=temp_ptr; g_order:=glue_order(this_box);
14851 g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
14852 incr(cur_s);
14853 if cur_s>0 then dvi_out(push);
14854 if cur_s>max_push then max_push:=cur_s;
14855 save_loc:=dvi_offset+dvi_ptr; left_edge:=cur_h; cur_v:=cur_v-height(this_box);
14856 top_edge:=cur_v;
14857 while p<>null do @<Output node |p| for |vlist_out| and move to the next node,
14858 maintaining the condition |cur_h=left_edge|@>;
14859 prune_movements(save_loc);
14860 if cur_s>0 then dvi_pop(save_loc);
14861 decr(cur_s);
14862 end;
14863
14864 @ @<Output node |p| for |vlist_out|...@>=
14865 begin if is_char_node(p) then confusion("vlistout")
14866 @:this can't happen vlistout}{\quad vlistout@>
14867 else @<Output the non-|char_node| |p| for |vlist_out|@>;
14868 next_p:p:=link(p);
14869 end
14870
14871 @ @<Output the non-|char_node| |p| for |vlist_out|@>=
14872 begin case type(p) of
14873 hlist_node,vlist_node:@<Output a box in a vlist@>;
14874 rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
14875 goto fin_rule;
14876 end;
14877 whatsit_node: @<Output the whatsit node |p| in a vlist@>;
14878 glue_node: @<Move down or output leaders@>;
14879 kern_node:cur_v:=cur_v+width(p);
14880 othercases do_nothing
14881 endcases;@/
14882 goto next_p;
14883 fin_rule: @<Output a rule in a vlist, |goto next_p|@>;
14884 move_past: cur_v:=cur_v+rule_ht;
14885 end
14886
14887 @ The |synch_v| here allows the \.{DVI} output to use one-byte commands
14888 for adjusting |v| in most cases, since the baselineskip distance will
14889 usually be constant.
14890
14891 @<Output a box in a vlist@>=
14892 if list_ptr(p)=null then cur_v:=cur_v+height(p)+depth(p)
14893 else begin cur_v:=cur_v+height(p); synch_v;
14894 save_h:=dvi_h; save_v:=dvi_v;
14895 if cur_dir=right_to_left then cur_h:=left_edge-shift_amount(p)
14896 else cur_h:=left_edge+shift_amount(p); {shift the box right}
14897 temp_ptr:=p;
14898 if type(p)=vlist_node then vlist_out@+else hlist_out;
14899 dvi_h:=save_h; dvi_v:=save_v;
14900 cur_v:=save_v+depth(p); cur_h:=left_edge;
14901 end
14902
14903 @ @<Output a rule in a vlist...@>=
14904 if is_running(rule_wd) then rule_wd:=width(this_box);
14905 rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
14906 cur_v:=cur_v+rule_ht;
14907 if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
14908 begin if cur_dir=right_to_left then cur_h:=cur_h-rule_wd;
14909 synch_h; synch_v;
14910 dvi_out(put_rule); dvi_four(rule_ht); dvi_four(rule_wd);
14911 cur_h:=left_edge;
14912 end;
14913 goto next_p
14914
14915 @ @<Move down or output leaders@>=
14916 begin g:=glue_ptr(p); rule_ht:=width(g)-cur_g;
14917 if g_sign<>normal then
14918 begin if g_sign=stretching then
14919 begin if stretch_order(g)=g_order then
14920 begin cur_glue:=cur_glue+stretch(g);
14921 vet_glue(float(glue_set(this_box))*cur_glue);
14922 @^real multiplication@>
14923 cur_g:=round(glue_temp);
14924 end;
14925 end
14926 else if shrink_order(g)=g_order then
14927 begin cur_glue:=cur_glue-shrink(g);
14928 vet_glue(float(glue_set(this_box))*cur_glue);
14929 cur_g:=round(glue_temp);
14930 end;
14931 end;
14932 rule_ht:=rule_ht+cur_g;
14933 if subtype(p)>=a_leaders then
14934 @<Output leaders in a vlist, |goto fin_rule| if a rule
14935 or to |next_p| if done@>;
14936 goto move_past;
14937 end
14938
14939 @ @<Output leaders in a vlist...@>=
14940 begin leader_box:=leader_ptr(p);
14941 if type(leader_box)=rule_node then
14942 begin rule_wd:=width(leader_box); rule_dp:=0;
14943 goto fin_rule;
14944 end;
14945 leader_ht:=height(leader_box)+depth(leader_box);
14946 if (leader_ht>0)and(rule_ht>0) then
14947 begin rule_ht:=rule_ht+10; {compensate for floating-point rounding}
14948 edge:=cur_v+rule_ht; lx:=0;
14949 @<Let |cur_v| be the position of the first box, and set |leader_ht+lx|
14950 to the spacing between corresponding parts of boxes@>;
14951 while cur_v+leader_ht<=edge do
14952 @<Output a leader box at |cur_v|,
14953 then advance |cur_v| by |leader_ht+lx|@>;
14954 cur_v:=edge-10; goto next_p;
14955 end;
14956 end
14957
14958 @ @<Let |cur_v| be the position of the first box, ...@>=
14959 if subtype(p)=a_leaders then
14960 begin save_v:=cur_v;
14961 cur_v:=top_edge+leader_ht*((cur_v-top_edge)@!div leader_ht);
14962 if cur_v<save_v then cur_v:=cur_v+leader_ht;
14963 end
14964 else begin lq:=rule_ht div leader_ht; {the number of box copies}
14965 lr:=rule_ht mod leader_ht; {the remaining space}
14966 if subtype(p)=c_leaders then cur_v:=cur_v+(lr div 2)
14967 else begin lx:=lr div (lq+1);
14968 cur_v:=cur_v+((lr-(lq-1)*lx) div 2);
14969 end;
14970 end
14971
14972 @ When we reach this part of the program, |cur_v| indicates the top of a
14973 leader box, not its baseline.
14974
14975 @<Output a leader box at |cur_v|, ...@>=
14976 begin if cur_dir=right_to_left then
14977 cur_h:=left_edge-shift_amount(leader_box)
14978 else cur_h:=left_edge+shift_amount(leader_box);
14979 synch_h; save_h:=dvi_h;@/
14980 cur_v:=cur_v+height(leader_box); synch_v; save_v:=dvi_v;
14981 temp_ptr:=leader_box;
14982 outer_doing_leaders:=doing_leaders; doing_leaders:=true;
14983 if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
14984 doing_leaders:=outer_doing_leaders;
14985 dvi_v:=save_v; dvi_h:=save_h; cur_h:=left_edge;
14986 cur_v:=save_v-height(leader_box)+leader_ht+lx;
14987 end
14988
14989 @ The |hlist_out| and |vlist_out| procedures are now complete, so we are
14990 ready for the |dvi_ship_out| routine that gets them started in the first place.
14991
14992 @p procedure dvi_ship_out(@!p:pointer); {output the box |p|}
14993 label done;
14994 var page_loc:integer; {location of the current |bop|}
14995 @!j,@!k:0..9; {indices to first ten count registers}
14996 @!s:pool_pointer; {index into |str_pool|}
14997 @!old_setting:0..max_selector; {saved |selector| setting}
14998 begin if tracing_output>0 then
14999 begin print_nl(""); print_ln;
15000 print("Completed box being shipped out");
15001 @.Completed box...@>
15002 end;
15003 if term_offset>max_print_line-9 then print_ln
15004 else if (term_offset>0)or(file_offset>0) then print_char(" ");
15005 print_char("["); j:=9;
15006 while (count(j)=0)and(j>0) do decr(j);
15007 for k:=0 to j do
15008 begin print_int(count(k));
15009 if k<j then print_char(".");
15010 end;
15011 update_terminal;
15012 if tracing_output>0 then
15013 begin print_char("]");
15014 begin_diagnostic; show_box(p); end_diagnostic(true);
15015 end;
15016 @<Ship box |p| out@>;
15017 if eTeX_ex then @<Check for LR anomalies at the end of |ship_out|@>;
15018 if tracing_output<=0 then print_char("]");
15019 dead_cycles:=0;
15020 update_terminal; {progress report}
15021 @<Flush the box from memory, showing statistics if requested@>;
15022 end;
15023
15024 @ @<Flush the box from memory, showing statistics if requested@>=
15025 @!stat if tracing_stats>1 then
15026 begin print_nl("Memory usage before: ");
15027 @.Memory usage...@>
15028 print_int(var_used); print_char("&");
15029 print_int(dyn_used); print_char(";");
15030 end;
15031 tats@/
15032 flush_node_list(p);
15033 @!stat if tracing_stats>1 then
15034 begin print(" after: ");
15035 print_int(var_used); print_char("&");
15036 print_int(dyn_used); print("; still untouched: ");
15037 print_int(hi_mem_min-lo_mem_max-1); print_ln;
15038 end;
15039 tats
15040
15041 @ @<Ship box |p| out@>=
15042 @<Update the values of |max_h| and |max_v|; but if the page is too large,
15043 |goto done|@>;
15044 @<Initialize variables as |ship_out| begins@>;
15045 page_loc:=dvi_offset+dvi_ptr;
15046 dvi_out(bop);
15047 for k:=0 to 9 do dvi_four(count(k));
15048 dvi_four(last_bop); last_bop:=page_loc;
15049 cur_v:=height(p)+v_offset; temp_ptr:=p;
15050 if type(p)=vlist_node then vlist_out@+else hlist_out;
15051 dvi_out(eop); incr(total_pages); cur_s:=-1;
15052 done:
15053
15054 @ Sometimes the user will generate a huge page because other error messages
15055 are being ignored. Such pages are not output to the \.{dvi} file, since they
15056 may confuse the printing software.
15057
15058 @<Update the values of |max_h| and |max_v|; but if the page is too large...@>=
15059 if (height(p)>max_dimen)or@|(depth(p)>max_dimen)or@|
15060 (height(p)+depth(p)+v_offset>max_dimen)or@|
15061 (width(p)+h_offset>max_dimen) then
15062 begin print_err("Huge page cannot be shipped out");
15063 @.Huge page...@>
15064 help2("The page just created is more than 18 feet tall or")@/
15065 ("more than 18 feet wide, so I suspect something went wrong.");
15066 error;
15067 if tracing_output<=0 then
15068 begin begin_diagnostic;
15069 print_nl("The following box has been deleted:");
15070 @.The following...deleted@>
15071 show_box(p);
15072 end_diagnostic(true);
15073 end;
15074 goto done;
15075 end;
15076 if height(p)+depth(p)+v_offset>max_v then max_v:=height(p)+depth(p)+v_offset;
15077 if width(p)+h_offset>max_h then max_h:=width(p)+h_offset
15078
15079 @ At the end of the program, we must finish things off by writing the
15080 post\-amble. If |total_pages=0|, the \.{DVI} file was never opened.
15081 If |total_pages>=65536|, the \.{DVI} file will lie. And if
15082 |max_push>=65536|, the user deserves whatever chaos might ensue.
15083
15084 An integer variable |k| will be declared for use by this routine.
15085
15086 @<Finish the \.{DVI} file@>=
15087 while cur_s>-1 do
15088 begin if cur_s>0 then dvi_out(pop)
15089 else begin dvi_out(eop); incr(total_pages);
15090 end;
15091 decr(cur_s);
15092 end;
15093 if total_pages=0 then print_nl("No pages of output.")
15094 @.No pages of output@>
15095 else begin dvi_out(post); {beginning of the postamble}
15096 dvi_four(last_bop); last_bop:=dvi_offset+dvi_ptr-5; {|post| location}
15097 dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
15098 prepare_mag; dvi_four(mag); {magnification factor}
15099 dvi_four(max_v); dvi_four(max_h);@/
15100 dvi_out(max_push div 256); dvi_out(max_push mod 256);@/
15101 dvi_out((total_pages div 256) mod 256); dvi_out(total_pages mod 256);@/
15102 @<Output the font definitions for all fonts that were used@>;
15103 dvi_out(post_post); dvi_four(last_bop); dvi_out(id_byte);@/
15104 k:=4+((dvi_buf_size-dvi_ptr) mod 4); {the number of 223's}
15105 while k>0 do
15106 begin dvi_out(223); decr(k);
15107 end;
15108 @<Empty the last bytes out of |dvi_buf|@>;
15109 print_nl("Output written on "); slow_print(output_file_name);
15110 @.Output written on x@>
15111 print(" ("); print_int(total_pages); print(" page");
15112 if total_pages<>1 then print_char("s");
15113 print(", "); print_int(dvi_offset+dvi_ptr); print(" bytes).");
15114 b_close(dvi_file);
15115 end
15116
15117 @ @<Output the font definitions...@>=
15118 while font_ptr>font_base do
15119 begin if font_used[font_ptr] then dvi_font_def(font_ptr);
15120 decr(font_ptr);
15121 end
15122
15123
15124 @* \[32a] \pdfTeX\ basic. Initialize \pdfTeX's parameters to some useful
15125 default value. Helpful in case one forgets to set them during \.{INITEX} run.
15126
15127 @<Initialize table entries...@>=
15128 pdf_h_origin := (one_hundred_inch + 50) div 100;
15129 pdf_v_origin := (one_hundred_inch + 50) div 100;
15130 pdf_compress_level := 9;
15131 pdf_objcompresslevel := 0;
15132 pdf_decimal_digits := 3;
15133 pdf_image_resolution := 72;
15134 pdf_major_version := 1;
15135 pdf_minor_version := 4;
15136 pdf_gamma := 1000;
15137 pdf_image_gamma := 2200;
15138 pdf_image_hicolor := 1;
15139 pdf_image_apply_gamma := 0;
15140 pdf_px_dimen := one_bp;
15141 pdf_draftmode := 0;
15142
15143 @ The subroutines define the corresponding macros so we can use them
15144 in C.
15145
15146 @d flushable(#) == (# = str_ptr - 1)
15147
15148 @d is_valid_char(#)==((font_bc[f] <= #) and (# <= font_ec[f]) and
15149 char_exists(char_info(f)(#)))
15150
15151 @p function get_pdf_compress_level: integer;
15152 begin
15153 get_pdf_compress_level := pdf_compress_level;
15154 end;
15155
15156 function get_pdf_suppress_warning_dup_map: integer;
15157 begin
15158 get_pdf_suppress_warning_dup_map := pdf_suppress_warning_dup_map;
15159 end;
15160
15161 function get_pdf_suppress_warning_page_group: integer;
15162 begin
15163 get_pdf_suppress_warning_page_group := pdf_suppress_warning_page_group;
15164 end;
15165
15166 function get_pdf_suppress_ptex_info: integer;
15167 begin
15168 get_pdf_suppress_ptex_info := pdf_suppress_ptex_info;
15169 end;
15170
15171 function get_pdf_omit_charset: integer;
15172 begin
15173 get_pdf_omit_charset := pdf_omit_charset;
15174 end;
15175
15176 function get_ptex_use_underscore: boolean;
15177 begin
15178 get_ptex_use_underscore
15179 := (pdf_ptex_use_underscore > 0) or (pdf_major_version >= 2)
15180 end;
15181
15182 function get_nullfont: internal_font_number;
15183 begin
15184 get_nullfont := null_font;
15185 end;
15186
15187 function get_fontbase: internal_font_number;
15188 begin
15189 get_fontbase := font_base;
15190 end;
15191
15192 function get_nullcs: pointer;
15193 begin
15194 get_nullcs := null_cs;
15195 end;
15196
15197 function get_nullptr: pointer;
15198 begin
15199 get_nullptr := null;
15200 end;
15201
15202 function get_tex_int(code: integer): integer;
15203 begin
15204 get_tex_int := int_par(code);
15205 end;
15206
15207 function get_tex_dimen(code: integer): scaled;
15208 begin
15209 get_tex_dimen := dimen_par(code);
15210 end;
15211
15212 function get_x_height(f: internal_font_number): scaled;
15213 begin
15214 get_x_height := x_height(f);
15215 end;
15216
15217 function get_charwidth(f: internal_font_number; c: eight_bits): scaled;
15218 begin
15219 if is_valid_char(c) then
15220 get_charwidth := char_width(f)(char_info(f)(c))
15221 else
15222 get_charwidth := 0;
15223 end;
15224
15225 function get_charheight(f: internal_font_number; c: eight_bits): scaled;
15226 begin
15227 if is_valid_char(c) then
15228 get_charheight := char_height(f)(height_depth(char_info(f)(c)))
15229 else
15230 get_charheight := 0;
15231 end;
15232
15233 function get_chardepth(f: internal_font_number; c: eight_bits): scaled;
15234 begin
15235 if is_valid_char(c) then
15236 get_chardepth := char_depth(f)(height_depth(char_info(f)(c)))
15237 else
15238 get_chardepth := 0;
15239 end;
15240
15241 function get_quad(f: internal_font_number): scaled;
15242 begin
15243 get_quad := quad(f);
15244 end;
15245
15246 function get_slant(f: internal_font_number): scaled;
15247 begin
15248 get_slant := slant(f);
15249 end;
15250
15251 @ Helper for debugging purposes:
15252
15253 @p procedure short_display_n(@!p, m:integer); {prints highlights of list |p|}
15254 var n:integer; {for replacement counts}
15255 i: integer;
15256 begin
15257 i := 0;
15258 font_in_short_display:=null_font;
15259 if p = null then
15260 return;
15261 while p>mem_min do
15262 begin if is_char_node(p) then
15263 begin if p<=mem_end then
15264 begin if font(p)<>font_in_short_display then
15265 begin if (font(p)<font_base)or(font(p)>font_max) then
15266 print_char("*")
15267 @.*\relax@>
15268 else print_font_identifier(font(p));
15269 print_char(" "); font_in_short_display:=font(p);
15270 end;
15271 print_ASCII(qo(character(p)));
15272 end;
15273 end
15274 else begin
15275 if (type(p) = glue_node) or
15276 (type(p) = disc_node) or
15277 (type(p) = penalty_node) or
15278 ((type(p) = kern_node) and (subtype(p) = explicit)) then
15279 incr(i);
15280 if i >= m then
15281 return;
15282 if (type(p) = disc_node) then begin
15283 print("|");
15284 short_display(pre_break(p));
15285 print("|");
15286 short_display(post_break(p));
15287 print("|");
15288 n:=replace_count(p);
15289 while n>0 do
15290 begin if link(p)<>null then p:=link(p);
15291 decr(n);
15292 end;
15293 end
15294 else
15295 @<Print a short indication of the contents of node |p|@>;
15296 end;
15297 p:=link(p);
15298 if p = null then
15299 return;
15300 end;
15301 update_terminal;
15302 end;
15303
15304 @ Sometimes it is necessary to allocate memory for PDF output that cannot
15305 be deallocated then, so we use |pdf_mem| for this purpose.
15306
15307 @<Constants...@>=
15308 @!inf_pdf_mem_size = 10000; {min size of the |pdf_mem| array}
15309 @!sup_pdf_mem_size = 10000000; {max size of the |pdf_mem| array}
15310
15311 @ @<Glob...@>=
15312 @!pdf_mem_size: integer;
15313 @!pdf_mem: ^integer;
15314 @!pdf_mem_ptr: integer;
15315
15316 @ @<Set init...@>=
15317 pdf_mem_ptr := 1; {the first word is not used so we can use zero as a value for testing
15318 whether a pointer to |pdf_mem| is valid}
15319 pdf_mem_size := inf_pdf_mem_size; {allocated size of |pdf_mem| array}
15320
15321 @ We use |pdf_get_mem| to allocate memory in |pdf_mem|.
15322
15323 @p function pdf_get_mem(s: integer): integer; {allocate |s| words in |pdf_mem|}
15324 var a: integer;
15325 begin
15326 if s > sup_pdf_mem_size - pdf_mem_ptr then
15327 overflow("PDF memory size (pdf_mem_size)", pdf_mem_size);
15328 if pdf_mem_ptr + s > pdf_mem_size then begin
15329 a := 0.2 * pdf_mem_size;
15330 if pdf_mem_ptr + s > pdf_mem_size + a then
15331 pdf_mem_size := pdf_mem_ptr + s
15332 else if pdf_mem_size < sup_pdf_mem_size - a then
15333 pdf_mem_size := pdf_mem_size + a
15334 else
15335 pdf_mem_size := sup_pdf_mem_size;
15336 pdf_mem := xrealloc_array(pdf_mem, integer, pdf_mem_size);
15337 end;
15338 pdf_get_mem := pdf_mem_ptr;
15339 pdf_mem_ptr := pdf_mem_ptr + s;
15340 end;
15341
15342 @* \[32b] \pdfTeX\ output low-level subroutines.
15343 We use the similar subroutines to handle the output buffer for
15344 PDF output. When compress is used, the state of writing to buffer
15345 is held in |zip_write_state|. We must write the header of PDF
15346 output file in initialization to ensure that it will be the first
15347 written bytes.
15348
15349 @<Constants...@>=
15350 @!pdf_op_buf_size = 16384; {size of the PDF output buffer}
15351 @!inf_pdf_os_buf_size = 1; {initial value of |pdf_os_buf_size|}
15352 @!sup_pdf_os_buf_size = 5000000; {arbitrary upper hard limit of |pdf_os_buf_size|}
15353 @!pdf_os_max_objs = 100; {maximum number of objects in object stream}
15354
15355 @ The following macros are similar as for \.{DVI} buffer handling:
15356
15357 @d pdf_offset == (pdf_gone + pdf_ptr) {the file offset of last byte in PDF
15358 buffer that |pdf_ptr| points to}
15359
15360 @d no_zip == 0 {no \.{ZIP} compression}
15361 @d zip_writing == 1 {\.{ZIP} compression being used}
15362 @d zip_finish == 2 {finish \.{ZIP} compression}
15363
15364 @d pdf_quick_out(#) == {output a byte to PDF buffer without checking of
15365 overflow}
15366 begin
15367 pdf_buf[pdf_ptr] := #;
15368 incr(pdf_ptr);
15369 end
15370
15371 @d pdf_room(#) == {make sure that there are at least |n| bytes free in PDF buffer}
15372 begin
15373 if pdf_os_mode and (# + pdf_ptr > pdf_buf_size) then
15374 pdf_os_get_os_buf(#)
15375 else if not pdf_os_mode and (# > pdf_buf_size) then
15376 overflow("PDF output buffer", pdf_op_buf_size)
15377 else if not pdf_os_mode and (# + pdf_ptr > pdf_buf_size) then
15378 pdf_flush;
15379 end
15380
15381 @d pdf_out(#) == {do the same as |pdf_quick_out| and flush the PDF
15382 buffer if necessary}
15383 begin
15384 pdf_room(1);
15385 pdf_quick_out(#);
15386 end
15387
15388 @<Glob...@>=
15389 @!pdf_file: byte_file; {the PDF output file}
15390 @!pdf_buf: ^eight_bits; {pointer to the PDF output buffer or PDF object stream buffer}
15391 @!pdf_buf_size: integer; {end of PDF output buffer or PDF object stream buffer}
15392 @!pdf_ptr: integer; {pointer to the first unused byte in the PDF buffer or object stream buffer}
15393 @!pdf_op_buf: ^eight_bits; {the PDF output buffer}
15394 @!pdf_os_buf: ^eight_bits; {the PDF object stream buffer}
15395 @!pdf_os_buf_size: integer; {current size of the PDF object stream buffer, grows dynamically}
15396 @!pdf_os_objnum: ^integer; {array of object numbers within object stream}
15397 @!pdf_os_objoff: ^integer; {array of object offsets within object stream}
15398 @!pdf_os_objidx: pointer; {pointer into |pdf_os_objnum| and |pdf_os_objoff|}
15399 @!pdf_os_cntr: integer; {counter for object stream objects}
15400 @!pdf_op_ptr: integer; {store for PDF buffer |pdf_ptr| while inside object streams}
15401 @!pdf_os_ptr: integer; {store for object stream |pdf_ptr| while outside object streams}
15402 @!pdf_os_mode: boolean; {true if producing object stream}
15403 @!pdf_os_enable: boolean; {true if object streams are globally enabled}
15404 @!pdf_os_cur_objnum: integer; {number of current object stream object}
15405 @!pdf_gone: longinteger; {number of bytes that were flushed to output}
15406 @!pdf_save_offset: longinteger; {to save |pdf_offset|}
15407 @!zip_write_state: integer; {which state of compression we are in}
15408 @!fixed_pdf_major_version: integer; {fixed major part of the PDF version}
15409 @!fixed_pdf_minor_version: integer; {fixed minor part of the PDF version}
15410 @!fixed_pdf_objcompresslevel: integer; {fixed level for activating PDF object streams}
15411 @!pdf_version_written: boolean; {flag if the PDF version has been written}
15412 @!fixed_pdfoutput: integer; {fixed output format}
15413 @!fixed_pdfoutput_set: boolean; {|fixed_pdfoutput| has been set?}
15414 @!fixed_gamma: integer;
15415 @!fixed_image_gamma: integer;
15416 @!fixed_image_hicolor: boolean;
15417 @!fixed_image_apply_gamma: integer;
15418 @!epochseconds: integer;
15419 @!microseconds: integer;
15420 @!fixed_pdf_draftmode: integer; {fixed \\pdfdraftmode}
15421 @!fixed_pdf_draftmode_set: boolean; {|fixed_pdf_draftmode| has been set?}
15422 @!pdf_page_group_val: integer;
15423
15424 @ @<Set init...@>=
15425 pdf_gone := 0;
15426 pdf_os_mode := false;
15427 pdf_ptr := 0;
15428 pdf_op_ptr := 0;
15429 pdf_os_ptr := 0;
15430 pdf_os_cur_objnum := 0;
15431 pdf_os_cntr := 0;
15432 pdf_buf_size := pdf_op_buf_size;
15433 pdf_os_buf_size := inf_pdf_os_buf_size;
15434 pdf_buf := pdf_op_buf;
15435 pdf_seek_write_length := false;
15436 zip_write_state := no_zip;
15437 pdf_version_written := false;
15438 fixed_pdfoutput_set := false;
15439 fixed_pdf_draftmode_set := false;
15440
15441
15442 @ @p
15443 function fix_int(val, min, max: integer): integer;
15444 begin
15445 if val < min then
15446 fix_int := min
15447 else if val > max then
15448 fix_int := max
15449 else
15450 fix_int := val;
15451 end;
15452
15453 @ This ensures that |pdf_major_version| and |pdf_minor_version| are set
15454 to reasonable values before any bytes have been written to the generated
15455 PDF file. We also save their current values in case the user tries to
15456 change them later, along with |pdf_objcompresslevel|,
15457 |pdf_image_hicolor|, and various other parameters that must be fixed
15458 before any PDF output happens.
15459
15460 Here also the PDF file is opened by |ensure_pdf_open| and the PDF header
15461 is written.
15462
15463 @p procedure check_pdfversion;
15464 begin
15465 if not pdf_version_written then begin
15466 pdf_version_written := true;
15467 if pdf_major_version < 1 then begin
15468 print_err("pdfTeX error (invalid pdfmajorversion)");
15469 print_ln;
15470 help2 ("The pdfmajorversion must be 1 or greater.")@/
15471 ("I changed this to 1.");
15472 int_error (pdf_major_version);
15473 pdf_major_version := 1;
15474 end;
15475 if (pdf_minor_version < 0) or (pdf_minor_version > 9) then begin
15476 print_err("pdfTeX error (invalid pdfminorversion)");
15477 print_ln;
15478 help2 ("The pdfminorversion must be between 0 and 9.")@/
15479 ("I changed this to 4.");
15480 int_error (pdf_minor_version);
15481 pdf_minor_version := 4;
15482 end;
15483 fixed_pdf_major_version := pdf_major_version;
15484 fixed_pdf_minor_version := pdf_minor_version;
15485 fixed_gamma := fix_int(pdf_gamma, 0, 1000000);
15486 fixed_image_gamma := fix_int(pdf_image_gamma, 0, 1000000);
15487 fixed_image_hicolor := fix_int(pdf_image_hicolor, 0, 1);
15488 fixed_image_apply_gamma := fix_int(pdf_image_apply_gamma, 0, 1);
15489 fixed_pdf_objcompresslevel := fix_int(pdf_objcompresslevel, 0, 3);
15490 fixed_pdf_draftmode := fix_int(pdf_draftmode, 0, 1);
15491 fixed_inclusion_copy_font := fix_int(pdf_inclusion_copy_font, 0, 1);
15492 if ((fixed_pdf_major_version > 1) or (fixed_pdf_minor_version >= 5))
15493 and (fixed_pdf_objcompresslevel > 0) then
15494 pdf_os_enable := true
15495 else begin
15496 if fixed_pdf_objcompresslevel > 0 then begin
15497 pdf_warning("Object streams", "\pdfobjcompresslevel > 0 requires PDF-1.5 or greater. Object streams disabled now.", true, true);
15498 fixed_pdf_objcompresslevel := 0;
15499 end;
15500 pdf_os_enable := false;
15501 end;
15502 ensure_pdf_open;
15503 fix_pdfoutput;
15504 pdf_print("%PDF-");
15505 pdf_print_int(fixed_pdf_major_version);
15506 pdf_print(".");
15507 pdf_print_int_ln(fixed_pdf_minor_version);
15508 pdf_print("%");
15509 pdf_out(208); {'P' + 128}
15510 pdf_out(212); {'T' + 128}
15511 pdf_out(197); {'E' + 128}
15512 pdf_out(216); {'X' + 128}
15513 pdf_print_nl;
15514 end
15515 else begin
15516 if (fixed_pdf_minor_version <> pdf_minor_version)
15517 or (fixed_pdf_major_version <> pdf_major_version) then
15518 pdf_error("setup",
15519 "PDF version cannot be changed after data is written to the PDF file");
15520 end;
15521 end;
15522
15523 @ Checks that we have a name for the generated PDF file and that it's open.
15524
15525 @p procedure ensure_pdf_open;
15526 begin
15527 if output_file_name <> 0 then
15528 return;
15529 if job_name = 0 then
15530 open_log_file;
15531 pack_job_name(".pdf");
15532 if fixed_pdf_draftmode = 0 then
15533 while not b_open_out(pdf_file) do
15534 prompt_file_name("file name for output",".pdf");
15535 output_file_name := b_make_name_string(pdf_file);
15536 end;
15537
15538 @ The PDF buffer is flushed by calling |pdf_flush|, which checks the
15539 variable |zip_write_state| and will compress the buffer before flushing if
15540 necessary. We call |pdf_begin_stream| to begin a stream and |pdf_end_stream|
15541 to finish it. The stream contents will be compressed if compression is turn on.
15542
15543 @p procedure pdf_flush; {flush out the |pdf_buf|}
15544 var saved_pdf_gone : longinteger;
15545 begin
15546 if not pdf_os_mode then begin
15547 saved_pdf_gone := pdf_gone;
15548 case zip_write_state of
15549 no_zip: if pdf_ptr > 0 then begin
15550 if fixed_pdf_draftmode = 0 then write_pdf(0, pdf_ptr - 1);
15551 pdf_gone := pdf_gone + pdf_ptr;
15552 pdf_last_byte := pdf_buf[pdf_ptr - 1];
15553 end;
15554 zip_writing:
15555 if fixed_pdf_draftmode = 0 then write_zip(false);
15556 zip_finish: begin
15557 if fixed_pdf_draftmode = 0 then write_zip(true);
15558 zip_write_state := no_zip;
15559 end;
15560 end;
15561 pdf_ptr := 0;
15562 if saved_pdf_gone > pdf_gone then
15563 pdf_error("file size", "File size exceeds architectural limits (pdf_gone wraps around)");
15564 end;
15565 end;
15566
15567 procedure pdf_begin_stream; {begin a stream}
15568 begin
15569 pdf_print_ln("/Length ");
15570 pdf_seek_write_length := true; {fill in length at |pdf_end_stream| call}
15571 pdf_stream_length_offset := pdf_offset - 11;
15572 pdf_stream_length := 0;
15573 pdf_last_byte := 0;
15574 if pdf_compress_level > 0 then begin
15575 pdf_print_ln("/Filter /FlateDecode");
15576 pdf_print_ln(">>");
15577 pdf_print_ln("stream");
15578 pdf_flush;
15579 zip_write_state := zip_writing;
15580 end
15581 else begin
15582 pdf_print_ln(">>");
15583 pdf_print_ln("stream");
15584 pdf_save_offset := pdf_offset;
15585 end;
15586 end;
15587
15588 procedure pdf_end_stream; {end a stream}
15589 begin
15590 if zip_write_state = zip_writing then
15591 zip_write_state := zip_finish
15592 else
15593 pdf_stream_length := pdf_offset - pdf_save_offset;
15594 pdf_flush;
15595 if pdf_seek_write_length then
15596 write_stream_length(pdf_stream_length, pdf_stream_length_offset);
15597 pdf_seek_write_length := false;
15598 pdf_out(pdf_new_line_char);
15599 pdf_print_ln("endstream");
15600 pdf_end_obj;
15601 end;
15602
15603 @ Basic printing procedures for PDF output are very similar to \TeX\ basic
15604 printing ones but the output is going to PDF buffer. Subroutines with
15605 suffix |_ln| append a new-line character to the PDF output.
15606
15607 @d pdf_new_line_char == 10 {new-line character for UNIX platforms}
15608
15609 @d pdf_print_nl == {output a new-line character to PDF buffer}
15610 pdf_out(pdf_new_line_char)
15611
15612 @d pdf_print_ln(#) == {print out a string to PDF buffer followed by
15613 a new-line character}
15614 begin
15615 pdf_print(#);
15616 pdf_print_nl;
15617 end
15618
15619 @d pdf_print_int_ln(#) == {print out an integer to PDF buffer followed by
15620 a new-line character}
15621 begin
15622 pdf_print_int(#);
15623 pdf_print_nl;
15624 end
15625
15626 @<Declare procedures that need to be declared forward for \pdfTeX@>=
15627 procedure pdf_error(t, p: str_number);
15628 begin
15629 normalize_selector;
15630 print_err("pdfTeX error");
15631 if t <> 0 then begin
15632 print(" (");
15633 print(t);
15634 print(")");
15635 end;
15636 print(": "); print(p);
15637 succumb;
15638 end;
15639
15640 procedure pdf_warning(t, p: str_number; prepend_nl, append_nl: boolean);
15641 begin
15642 if interaction = error_stop_mode then
15643 wake_up_terminal;
15644 if prepend_nl then
15645 print_ln;
15646 print("pdfTeX warning");
15647 if t <> 0 then begin
15648 print(" (");
15649 print(t);
15650 print(")");
15651 end;
15652 print(": "); print(p);
15653 if append_nl then
15654 print_ln;
15655 if history=spotless then history:=warning_issued;
15656 end;
15657
15658 procedure pdf_os_get_os_buf(s: integer); {check that |s| bytes more
15659 fit into |pdf_os_buf|; increase it if required}
15660 var a: integer;
15661 begin
15662 if s > sup_pdf_os_buf_size - pdf_ptr then
15663 overflow("PDF object stream buffer", pdf_os_buf_size);
15664 if pdf_ptr + s > pdf_os_buf_size then begin
15665 a := 0.2 * pdf_os_buf_size;
15666 if pdf_ptr + s > pdf_os_buf_size + a then
15667 pdf_os_buf_size := pdf_ptr + s
15668 else if pdf_os_buf_size < sup_pdf_os_buf_size - a then
15669 pdf_os_buf_size := pdf_os_buf_size + a
15670 else
15671 pdf_os_buf_size := sup_pdf_os_buf_size;
15672 pdf_os_buf := xrealloc_array(pdf_os_buf, eight_bits, pdf_os_buf_size);
15673 pdf_buf := pdf_os_buf;
15674 pdf_buf_size := pdf_os_buf_size;
15675 end;
15676 end;
15677
15678 procedure remove_last_space;
15679 begin
15680 if (pdf_ptr > 0) and (pdf_buf[pdf_ptr - 1] = 32) then
15681 decr(pdf_ptr);
15682 end;
15683
15684 procedure pdf_print_octal(n: integer); {prints an integer in octal form to
15685 PDF buffer}
15686 var k:0..23; {index to current digit; we assume that $|n|<10^{23}$}
15687 begin
15688 k:=0;
15689 repeat dig[k]:=n mod 8; n:=n div 8; incr(k);
15690 until n=0;
15691 if k = 1 then begin
15692 pdf_out("0");
15693 pdf_out("0");
15694 end;
15695 if k = 2 then
15696 pdf_out("0");
15697 while k>0 do begin
15698 decr(k);
15699 pdf_out("0"+dig[k]);
15700 end;
15701 end;
15702
15703 procedure pdf_print_char(f: internal_font_number; c: integer);
15704 { print out a character to PDF buffer; the character will be printed in octal
15705 form in the following cases: chars <= 32, backslash (92), left parenthesis
15706 (40) and right parenthesis (41) }
15707 begin
15708 pdf_mark_char(f, c);
15709 if (c <= 32) or (c = 92) or (c = 40) or (c = 41) or (c > 127) then begin
15710 pdf_out(92); {output a backslash}
15711 pdf_print_octal(c);
15712 end
15713 else
15714 pdf_out(c);
15715 end;
15716
15717 procedure pdf_print(s: str_number); {print out a string to PDF buffer}
15718 var j: pool_pointer; {current character code position}
15719 c: integer;
15720 begin
15721 j := str_start[s];
15722 while j < str_start[s + 1] do begin
15723 c := str_pool[j];
15724 pdf_out(c);
15725 incr(j);
15726 end;
15727 end;
15728
15729 function str_in_str(s, r: str_number; i: integer): boolean;
15730 {test equality of strings}
15731 label not_found; {loop exit}
15732 var j, k: pool_pointer; {running indices}
15733 begin
15734 str_in_str := false;
15735 if length(s) < i + length(r) then
15736 return;
15737 j := i + str_start[s];
15738 k := str_start[r];
15739 while (j < str_start[s + 1]) and (k < str_start[r + 1]) do begin
15740 if str_pool[j] <> str_pool[k] then
15741 return;
15742 incr(j);
15743 incr(k);
15744 end;
15745 str_in_str := true;
15746 end;
15747
15748 procedure pdf_print_int(n:longinteger); {print out a integer to PDF buffer}
15749 var k:integer; {index to current digit ($0\le k\le23$); we assume that $|n|<10^{23}$}
15750 m:longinteger; {used to negate |n| in possibly dangerous cases}
15751 begin
15752 k:=0;
15753 if n<0 then
15754 begin pdf_out("-");
15755 if n>-100000000 then negate(n)
15756 else begin m:=-1-n; n:=m div 10; m:=(m mod 10)+1; k:=1;
15757 if m<10 then dig[0]:=m
15758 else begin dig[0]:=0; incr(n);
15759 end;
15760 end;
15761 end;
15762 repeat dig[k]:=n mod 10; n:=n div 10; incr(k);
15763 until n=0;
15764 pdf_room(k);
15765 while k>0 do begin
15766 decr(k);
15767 pdf_quick_out("0"+dig[k]);
15768 end;
15769 end;
15770
15771 procedure pdf_print_two(n:integer); {prints two least significant digits in
15772 decimal form to PDF buffer}
15773 begin n:=abs(n) mod 100; pdf_out("0"+(n div 10));
15774 pdf_out("0"+(n mod 10));
15775 end;
15776
15777 function tokens_to_string(p: pointer): str_number; {return a string from tokens
15778 list}
15779 begin
15780 if selector = new_string then
15781 pdf_error("tokens", "tokens_to_string() called while selector = new_string");
15782 old_setting:=selector; selector:=new_string;
15783 show_token_list(link(p),null,pool_size-pool_ptr);
15784 selector:=old_setting;
15785 last_tokens_string := make_string;
15786 tokens_to_string := last_tokens_string;
15787 end;
15788
15789
15790 @ To print |scaled| value to PDF output we need some subroutines to ensure
15791 accuracy.
15792
15793 @d max_integer == @"7FFFFFFF {$2^{31}-1$}
15794 @d call_func(#) == begin if # <> 0 then do_nothing end
15795
15796 @<Glob...@>=
15797 @!one_bp: scaled; {scaled value corresponds to 1bp}
15798 @!one_hundred_bp: scaled; {scaled value corresponds to 100bp}
15799 @!one_hundred_inch: scaled; {scaled value corresponds to 100in}
15800 @!one_inch: integer; {(1in in sp)/|maxdimen|}
15801 @!ten_pow: array[0..9] of integer; {$10^0..10^9$}
15802 @!scaled_out: integer; {amount of |scaled| that was taken out in
15803 |divide_scaled|}
15804 @!init_pdf_output: boolean;
15805 @!adv_char_width_s: integer; {to save result of calculation done in |adv_char_width|}
15806 @!adv_char_width_s_out: scaled;
15807
15808 @ @<Set init...@>=
15809 one_bp := 65782; {65781.76}
15810 one_hundred_bp := 6578176;
15811 one_hundred_inch := 473628672;
15812 one_inch := 226;
15813 ten_pow[0] := 1;
15814 for i := 1 to 9 do
15815 ten_pow[i] := 10*ten_pow[i - 1];
15816 init_pdf_output := false;
15817
15818
15819 @ The following function divides |s| by |m|. |dd| is number of decimal digits.
15820 The result is $r = (s/m) \times 10^{dd}$, and the remainder after
15821 the division is $s - |scaled_out|$
15822
15823
15824 @<Declare procedures that need to be declared forward for \pdfTeX@>=
15825 function divide_scaled(s, m: scaled; dd: integer): scaled;
15826 var q, r: scaled;
15827 sign, i: integer;
15828 begin
15829 sign := 1;
15830 if s < 0 then begin
15831 sign := -sign;
15832 s := -s;
15833 end;
15834 if m < 0 then begin
15835 sign := -sign;
15836 m := -m;
15837 end;
15838 if m = 0 then
15839 pdf_error("arithmetic", "divided by zero")
15840 else if m >= (max_integer div 10) then
15841 pdf_error("arithmetic", "number too big");
15842 q := s div m;
15843 r := s mod m;
15844 for i := 1 to dd do begin
15845 q := 10*q + (10*r) div m;
15846 r := (10*r) mod m;
15847 end;
15848 if 2*r >= m then begin
15849 incr(q);
15850 r := r - m;
15851 end;
15852 scaled_out := sign*(s - (r div ten_pow[dd]));
15853 divide_scaled := sign*q;
15854 end;
15855
15856 function round_xn_over_d(@!x:scaled; @!n,@!d:integer):scaled;
15857 var positive:boolean; {was |x>=0|?}
15858 @!t,@!u,@!v:nonnegative_integer; {intermediate quantities}
15859 begin if x>=0 then positive:=true
15860 else begin negate(x); positive:=false;
15861 end;
15862 t:=(x mod @'100000)*n;
15863 u:=(x div @'100000)*n+(t div @'100000);
15864 v:=(u mod d)*@'100000 + (t mod @'100000);
15865 if u div d>=@'100000 then arith_error:=true
15866 else u:=@'100000*(u div d) + (v div d);
15867 v := v mod d;
15868 if 2*v >= d then
15869 incr(u);
15870 if positive then
15871 round_xn_over_d := u
15872 else
15873 round_xn_over_d := -u;
15874 end;
15875
15876 function is_bit_set(n: integer; s: small_number): boolean;
15877 {check if $s$-th bit (one-based) of $n$ is set}
15878 var m, i: integer;
15879 begin
15880 m := 1;
15881 for i := 1 to s - 1 do
15882 m := m * 2;
15883 is_bit_set := (n div m) mod 2;
15884 end;
15885
15886 @ Next subroutines are needed for controlling spacing in PDF page description.
15887 For a given character |c| from a font |f|,
15888 the procedure |adv_char_width| advances |pdf_h|
15889 by {\it about\/} the amount |w|, which is the character width.
15890 But we cannot simply add |w| to |pdf_h|.
15891 Instead we have to bring the required shift into the same raster,
15892 on which also the \.{/Widths} array values,
15893 as they appear in the PDF file, are based.
15894 The |scaled_out| value is the |w| value moved into this raster.
15895 The \.{/Widths} values are used by the PDF reader independently
15896 to update its positions.
15897 So one has to be sure, that calculations are properly synchronized.
15898 Currently the \.{/Widths} array values are output
15899 with one digit after the decimal point,
15900 therefore the raster on which |adv_char_width| is operating
15901 is $1/10000$ of the |pdf_font_size|.
15902
15903 For PK fonts things are more complicated,
15904 as we have to deal with scaling bitmaps as well.
15905
15906 @p
15907 procedure adv_char_width(f: internal_font_number; c: eight_bits);
15908 {update |pdf_delta_h| by character width |w| from font |f|}
15909 var w, s_out: scaled;
15910 s: integer;
15911 begin
15912 w := char_width(f)(char_info(f)(c));
15913 if isscalable(f) then begin
15914 if pdf_cur_Tm_a = 0 then begin
15915 s := divide_scaled(w, pdf_font_size[f], 4);
15916 s_out := scaled_out;
15917 pdf_delta_h := pdf_delta_h + s_out;
15918 end
15919 else begin
15920 s := divide_scaled(round_xn_over_d(w, 1000, 1000 + pdf_cur_Tm_a),
15921 pdf_font_size[f],
15922 4);
15923 s_out := round_xn_over_d(round_xn_over_d(pdf_font_size[f], abs(s), 10000),
15924 1000 + pdf_cur_Tm_a, 1000);
15925 if s < 0 then
15926 s_out := -s_out;
15927 pdf_delta_h := pdf_delta_h + s_out;
15928 end;
15929 adv_char_width_s := round(s/10);
15930 adv_char_width_s_out := s_out;
15931 end else
15932 pdf_delta_h := pdf_delta_h + get_pk_char_width(f, w);
15933 end;
15934
15935 procedure pdf_print_real(m, d: integer); {print $m/10^d$ as real}
15936 begin
15937 if m < 0 then begin
15938 pdf_out("-");
15939 m := -m;
15940 end;
15941 pdf_print_int(m div ten_pow[d]);
15942 m := m mod ten_pow[d];
15943 if m > 0 then begin
15944 pdf_out(".");
15945 decr(d);
15946 while m < ten_pow[d] do begin
15947 pdf_out("0");
15948 decr(d);
15949 end;
15950 while m mod 10 = 0 do
15951 m := m div 10;
15952 pdf_print_int(m);
15953 end;
15954 end;
15955
15956 procedure pdf_print_bp(s: scaled); {print scaled as |bp|}
15957 begin
15958 pdf_print_real(divide_scaled(s, one_hundred_bp, fixed_decimal_digits + 2),
15959 fixed_decimal_digits);
15960 end;
15961
15962 procedure pdf_print_mag_bp(s: scaled); {take |mag| into account}
15963 begin
15964 prepare_mag;
15965 if mag <> 1000 then
15966 s := round_xn_over_d(s, mag, 1000);
15967 pdf_print_bp(s);
15968 end;
15969
15970 @* \[32c] PDF page description.
15971
15972 @d pdf_x(#) == ((#) - pdf_origin_h) {convert $x$-coordinate from \.{DVI} to
15973 PDF}
15974 @d pdf_y(#) == (pdf_origin_v - (#)) {convert $y$-coordinate from \.{DVI} to
15975 PDF}
15976 @d dvi_x(#) == ((#) + pdf_origin_h) {convert $x$-coordinate from \.{PDF} to
15977 DVI}
15978 @d dvi_y(#) == (pdf_origin_v - (#)) {convert $y$-coordinate from \.{PDF} to
15979 DVI}
15980
15981 @<Glob...@>=
15982 @!pdf_f: internal_font_number; {the current font in PDF output page}
15983 @!pdf_h: scaled; {current horizontal coordinate in PDF output page}
15984 @!pdf_v: scaled; {current vertical coordinate in PDF output page}
15985 @!pdf_tj_start_h: scaled; {horizontal coordinate in PDF output page just before \.{TJ} array start}
15986 @!cur_delta_h: scaled; {horizontal |cur_h| offset from |pdf_tj_start_h|}
15987 @!pdf_delta_h: scaled; {horizontal offset from |pdf_tj_start_h|}
15988 @!pdf_origin_h: scaled; {current horizontal origin in PDF output page}
15989 @!pdf_origin_v: scaled; {current vertical origin in PDF output page}
15990 @!pdf_doing_string: boolean; {we are writing string to PDF file?}
15991 @!pdf_doing_text: boolean; {we are writing text section to PDF file?}
15992 @!min_bp_val: scaled;
15993 @!min_font_val: scaled; {(TJ array system)}
15994 @!fixed_pk_resolution: integer;
15995 @!fixed_decimal_digits: integer;
15996 @!fixed_gen_tounicode: integer;
15997 @!fixed_inclusion_copy_font: integer;
15998 @!pk_scale_factor: integer;
15999 @!pdf_output_option: integer;
16000 @!pdf_output_value: integer;
16001 @!pdf_draftmode_option: integer;
16002 @!pdf_draftmode_value: integer;
16003 @!pdf_cur_Tm_a: integer; {|a| value of the current text matrix, i.e., the current
16004 horizontal scaling factor}
16005 @!pdf_last_f: internal_font_number; {last font in PDF output page; this can differ from |pdf_f|}
16006 @!pdf_last_fs: internal_font_number; {last font size in PDF output page}
16007 @!pdf_dummy_font: internal_font_number; {font used to insert artificial interword spaces}
16008
16009 @ Following procedures implement low-level subroutines to convert \TeX{}
16010 internal structures to PDF page description.
16011
16012 @p procedure pdf_set_origin(h, v: scaled); {set the origin to |h|, |v|}
16013 begin
16014 if (abs(h - pdf_origin_h) >= min_bp_val) or
16015 (abs(v - pdf_origin_v) >= min_bp_val) then begin
16016 pdf_print("1 0 0 1 ");
16017 pdf_print_bp(h - pdf_origin_h);
16018 pdf_origin_h := pdf_origin_h + scaled_out;
16019 pdf_out(" ");
16020 pdf_print_bp(pdf_origin_v - v);
16021 pdf_origin_v := pdf_origin_v - scaled_out;
16022 pdf_print_ln(" cm");
16023 end;
16024 pdf_h := pdf_origin_h;
16025 pdf_tj_start_h := pdf_h;
16026 pdf_v := pdf_origin_v;
16027 end;
16028
16029 procedure pdf_set_origin_temp(h, v: scaled); {set the origin to |h|, |v| inside group}
16030 begin
16031 if (abs(h - pdf_origin_h) >= min_bp_val) or
16032 (abs(v - pdf_origin_v) >= min_bp_val) then begin
16033 pdf_print("1 0 0 1 ");
16034 pdf_print_bp(h - pdf_origin_h);
16035 pdf_out(" ");
16036 pdf_print_bp(pdf_origin_v - v);
16037 pdf_print_ln(" cm");
16038 end;
16039 end;
16040
16041 procedure pdf_end_string; {end the current string}
16042 begin
16043 if pdf_doing_string then begin
16044 pdf_print(")]TJ");
16045 pdf_doing_string := false;
16046 end;
16047 end;
16048
16049 procedure pdf_end_string_nl; {end the current string, with new-line}
16050 begin
16051 if pdf_doing_string then begin
16052 pdf_print_ln(")]TJ");
16053 pdf_doing_string := false;
16054 end;
16055 end;
16056
16057 function get_font_auto_expand_ratio(f: internal_font_number): integer;
16058 {return |pdf_font_expand_ratio[f]| if f is auto-expanded, 0 otherwise}
16059 begin
16060 if pdf_font_auto_expand[f] then
16061 get_font_auto_expand_ratio := pdf_font_expand_ratio[f]
16062 else
16063 get_font_auto_expand_ratio := 0;
16064 end;
16065
16066 procedure pdf_set_text_pos(v, v_out: scaled; f: internal_font_number);
16067 {set the next starting point for text to |cur_h|, |cur_v|}
16068 var pdf_new_Tm_a: integer; {|a| value of the new text matrix}
16069 begin
16070 pdf_out(" ");
16071 pdf_new_Tm_a := get_font_auto_expand_ratio(f);
16072 if (pdf_new_Tm_a <> 0) or
16073 ((pdf_new_Tm_a = 0) and (pdf_cur_Tm_a <> 0)) then begin
16074 pdf_print_real(1000 + pdf_new_Tm_a, 3);
16075 pdf_print(" 0 0 1 ");
16076 pdf_print_bp(cur_h - pdf_origin_h);
16077 pdf_h := pdf_origin_h + scaled_out;
16078 pdf_out(" ");
16079 pdf_print_bp(pdf_origin_v - cur_v);
16080 pdf_v := pdf_origin_v - scaled_out;
16081 pdf_print(" Tm");
16082 pdf_cur_Tm_a := pdf_new_Tm_a;
16083 pdfassert(pdf_cur_Tm_a > -1000);
16084 end else begin
16085 pdf_print_bp(cur_h - pdf_tj_start_h); {works only for unexpanded fonts}
16086 pdf_h := pdf_tj_start_h + scaled_out;
16087 pdf_out(" ");
16088 pdf_print_real(v, fixed_decimal_digits); {use |v| and |v_out| to avoid duplicate calculation}
16089 pdf_v := pdf_v - v_out;
16090 pdf_print(" Td");
16091 end;
16092 pdf_tj_start_h := pdf_h;
16093 pdf_delta_h := 0;
16094 end;
16095
16096 procedure pdf_use_font(f: internal_font_number; fontnum: integer);
16097 {mark |f| as a used font; set |font_used[f]|, |pdf_font_size[f]| and |pdf_font_num[f]|}
16098 begin
16099 call_func(divide_scaled(font_size[f], one_hundred_bp, 6));
16100 pdf_font_size[f] := scaled_out;
16101 font_used[f] := true;
16102 pdfassert((fontnum > 0) or ((fontnum < 0) and (pdf_font_num[-fontnum] > 0)));
16103 pdf_font_num[f] := fontnum;
16104 if pdf_move_chars > 0 then begin
16105 pdf_warning(0,"Primitive \pdfmovechars is obsolete.",true, true);
16106 pdf_move_chars := 0; {warn only once}
16107 end;
16108 end;
16109
16110 @ To set PDF font we need to find out fonts with the same name, because \TeX\
16111 can load the same font several times for various sizes. For such fonts we
16112 define only one font resource. The array |pdf_font_num| holds the object
16113 number of font resource. A negative value of an entry of |pdf_font_num|
16114 indicates that the corresponding font shares the font resource with the font.
16115
16116 @d pdf_print_resname_prefix ==
16117 if pdf_resname_prefix <> 0 then
16118 pdf_print(pdf_resname_prefix)
16119
16120 @p procedure pdf_init_font(f: internal_font_number);
16121 {create a font object}
16122 var k, b: internal_font_number;
16123 i: integer;
16124 begin
16125 pdfassert(not font_used[f]);
16126
16127 {if |f| is auto expanded then ensure the base font is initialized}
16128 if pdf_font_auto_expand[f] and (pdf_font_blink[f] <> null_font) then begin
16129 b := pdf_font_blink[f];
16130 if not isscalable(b) then
16131 pdf_error("font expansion", "auto expansion is only possible with scalable fonts");
16132 if not font_used[b] then
16133 pdf_init_font(b);
16134 pdf_font_map[f] := pdf_font_map[b];
16135 end;
16136
16137 {check whether |f| can share the font object with some |k|: we have 2 cases
16138 here: 1) |f| and |k| have the same tfm name (so they have been loaded at
16139 different sizes, e.g., 'cmr10' and 'cmr10 at 11pt'); 2) |f| has been auto
16140 expanded from |k|}
16141 if isscalable(f) then begin
16142 i := head_tab[obj_type_font];
16143 while i <> 0 do begin
16144 k := obj_info(i);
16145 if isscalable(k) and
16146 (pdf_font_map[k] = pdf_font_map[f]) and
16147 (str_eq_str(font_name[k], font_name[f]) or
16148 (pdf_font_auto_expand[f] and
16149 (pdf_font_blink[f] <> null_font) and
16150 str_eq_str(font_name[k], font_name[pdf_font_blink[f]]))) then
16151 begin
16152 pdfassert(pdf_font_num[k] <> 0);
16153 if pdf_font_num[k] < 0 then
16154 pdf_use_font(f, pdf_font_num[k])
16155 else
16156 pdf_use_font(f, -k);
16157 return;
16158 end;
16159 i := obj_link(i);
16160 end;
16161 end;
16162
16163 {create a new font object for |f|}
16164 pdf_create_obj(obj_type_font, f);
16165 pdf_font_has_space_char[f] := hasspacechar(f) and (char_width(f)(char_info(f)(32)) > one_bp);
16166 pdf_use_font(f, obj_ptr);
16167 end;
16168
16169 procedure pdf_init_font_cur_val;
16170 begin
16171 pdf_init_font(cur_val);
16172 end;
16173
16174 procedure pdf_set_font(f: internal_font_number);
16175 {set the actual font on PDF page}
16176 label found, found1;
16177 var p: pointer;
16178 k: internal_font_number;
16179 begin
16180 pdf_f := f;
16181 if not font_used[f] then
16182 pdf_init_font(f);
16183 set_ff(f); {set |ff| to the tfm number of the font sharing the font object
16184 with |f|; |ff| is either |f| or some font with the same tfm name
16185 at different size and/or expansion}
16186 k := ff;
16187 p := pdf_font_list;
16188 while p <> null do begin
16189 set_ff(info(p));
16190 if ff = k then
16191 goto found;
16192 p := link(p);
16193 end;
16194 pdf_append_list(f)(pdf_font_list); {|f| not found in |pdf_font_list|, append it now}
16195 found:
16196 if (k = pdf_last_f) and (font_size[f] = pdf_last_fs) then
16197 return;
16198 pdf_print("/F");
16199 pdf_print_int(k);
16200 pdf_print_resname_prefix;
16201 pdf_out(" ");
16202 pdf_print_real(divide_scaled(font_size[f], one_hundred_bp, 6), 4);
16203 pdf_print(" Tf");
16204 pdf_last_f := k;
16205 pdf_last_fs := font_size[f];
16206 end;
16207
16208 procedure pdf_begin_text; {begin a text section}
16209 begin
16210 pdf_set_origin(0, cur_page_height);
16211 pdf_print_ln("BT");
16212 pdf_doing_text := true;
16213 pdf_f := null_font;
16214 pdf_last_f := null_font;
16215 pdf_last_fs := 0;
16216 pdf_doing_string := false;
16217 pdf_cur_Tm_a := 0;
16218 end;
16219
16220 procedure pdf_read_dummy_font;
16221 begin
16222 if pdf_dummy_font = null_font then begin
16223 pdf_dummy_font := read_font_info(null_cs, pdf_space_font_name, "", -1000);
16224 pdfmaplinesp;
16225 pdf_mark_char(pdf_dummy_font, 32);
16226 end;
16227 end;
16228
16229 procedure pdf_insert_interword_space;
16230 {insert an artificial interword space}
16231 begin
16232 pdf_read_dummy_font;
16233 pdf_set_font(pdf_dummy_font);
16234 pdf_print("( )Tj");
16235 end;
16236
16237 procedure pdf_begin_string(f: internal_font_number); {begin to draw a string}
16238 var s_out, v, v_out: scaled;
16239 s: integer;
16240 must_end_string: boolean; {must we end the current string?}
16241 must_insert_space: boolean; {must we insert an interword space?}
16242 must_set_text_pos: boolean; {move must be set using Tm or Td operator}
16243 move_looks_like_interword_space: boolean; {move could be a space}
16244 begin
16245 must_end_string := false;
16246 must_insert_space := false;
16247 must_set_text_pos := false;
16248
16249 if not pdf_doing_text then begin
16250 pdf_begin_text;
16251 must_set_text_pos := true;
16252 end;
16253
16254 {delay font switch if we must insert interword space}
16255 if (not gen_faked_interword_space and pdf_f <> f)
16256 or (gen_faked_interword_space and not (font_used[f] and font_used[pdf_f]))
16257 then begin
16258 pdf_end_string;
16259 pdf_set_font(f);
16260 end;
16261 if pdf_cur_Tm_a = 0 then begin
16262 s := divide_scaled(cur_h - (pdf_tj_start_h + pdf_delta_h), pdf_font_size[f], 3);
16263 s_out := scaled_out;
16264 end
16265 else begin
16266 s := divide_scaled(round_xn_over_d(cur_h - (pdf_tj_start_h + pdf_delta_h), 1000,
16267 1000 + pdf_cur_Tm_a),
16268 pdf_font_size[f],
16269 3);
16270 if abs(s) < @'100000 then begin
16271 s_out := round_xn_over_d(round_xn_over_d(pdf_font_size[f], abs(s), 1000),
16272 1000 + pdf_cur_Tm_a, 1000);
16273 if s < 0 then
16274 s_out := -s_out;
16275 end;
16276 {no need to calculate |s_out| when |abs(s) >= @'100000|, since the text
16277 matrix will be reset below}
16278 end;
16279 if abs(cur_v - pdf_v) >= min_bp_val then begin
16280 v := divide_scaled(pdf_v - cur_v, one_hundred_bp,
16281 fixed_decimal_digits + 2);
16282 v_out := scaled_out;
16283 end
16284 else begin
16285 v := 0;
16286 v_out := 0;
16287 end;
16288
16289 if not must_set_text_pos then begin
16290 must_set_text_pos := (v <> 0)
16291 or (abs(s) >= @'100000)
16292 or (get_font_auto_expand_ratio(f) <> pdf_cur_Tm_a)
16293 or get_font_auto_expand_ratio(f) <> get_font_auto_expand_ratio(pdf_f);
16294 end;
16295
16296 if must_set_text_pos then begin
16297 must_end_string := true;
16298 end;
16299
16300 move_looks_like_interword_space := (space(f) > one_bp)
16301 and (s_out > space(f) - space_shrink(f) - one_bp div 10)
16302 and (v = 0);
16303
16304 if gen_faked_interword_space
16305 and move_looks_like_interword_space
16306 then begin
16307 must_insert_space := true;
16308 end;
16309
16310 if (must_insert_space) then begin
16311 {insert a real space char from the font when possible}
16312 if pdf_font_has_space_char[f] and pdf_doing_string then begin
16313 pdf_out(" ");
16314 adv_char_width(f, 32); { update |pdf_delta_h|, get |adv_char_width_s| and |adv_char_width_s_out|}
16315 s := s - adv_char_width_s;
16316 s_out := s_out - adv_char_width_s_out;
16317 pdf_mark_char(f, 32);
16318 end
16319 else
16320 must_end_string := true;
16321 end;
16322
16323 if must_end_string then begin
16324 pdf_end_string;
16325 {insert a space char from the dummy font if needed}
16326 if (must_insert_space) and (not pdf_font_has_space_char[f]) then begin
16327 pdf_insert_interword_space; {this will change the current font}
16328 end;
16329 pdf_set_font(f);
16330 pdf_set_text_pos(v, v_out, f);
16331 s := 0;
16332 end;
16333
16334 {do font switch here after interword space could have been inserted}
16335 if gen_faked_interword_space and (pdf_f <> f) then begin
16336 pdf_end_string;
16337 pdf_set_font(f);
16338 end;
16339
16340 if not pdf_doing_string then begin
16341 pdf_print(" [");
16342 if s = 0 then
16343 pdf_out("(");
16344 end;
16345
16346 if s <> 0 then begin
16347 if pdf_doing_string then
16348 pdf_out(")");
16349 pdf_print_int(-s);
16350 pdf_out("(");
16351 pdf_delta_h := pdf_delta_h + s_out;
16352 end;
16353 pdf_doing_string := true;
16354 end;
16355
16356 procedure pdf_insert_fake_space;
16357 var s: integer; {to save |gen_faked_interword_space|}
16358 begin
16359 s := gen_faked_interword_space;
16360 gen_faked_interword_space := 0; {to prevent inserting another fake space in |pdf_begin_string|}
16361
16362 pdf_read_dummy_font;
16363 pdf_begin_string(pdf_dummy_font);
16364 pdf_print(" ");
16365 adv_char_width(pdf_dummy_font, 32);
16366 pdf_end_string_nl;
16367
16368 gen_faked_interword_space := s;
16369 end;
16370
16371
16372 procedure pdf_end_text; {end a text section}
16373 begin
16374 if pdf_doing_text then begin
16375 pdf_end_string_nl;
16376 pdf_print_ln("ET");
16377 pdf_doing_text := false;
16378 end;
16379 end;
16380
16381 procedure pdf_set_rule(x, y, w, h: scaled); {draw a rule}
16382 begin
16383 pdf_end_text;
16384 pdf_print_ln("q");
16385 if h <= one_bp then begin
16386 pdf_set_origin_temp(x, y - (h + 1)/2);
16387 pdf_print("[]0 d 0 J ");
16388 pdf_print_bp(h); pdf_print(" w 0 0 m ");
16389 pdf_print_bp(w); pdf_print_ln(" 0 l S");
16390 end
16391 else if w <= one_bp then begin
16392 pdf_set_origin_temp(x + (w + 1)/2, y);
16393 pdf_print("[]0 d 0 J ");
16394 pdf_print_bp(w); pdf_print(" w 0 0 m 0 ");
16395 pdf_print_bp(h); pdf_print_ln(" l S");
16396 end
16397 else begin
16398 pdf_set_origin_temp(x, y);
16399 pdf_print("0 0 ");
16400 pdf_print_bp(w); pdf_out(" ");
16401 pdf_print_bp(h); pdf_print_ln(" re f");
16402 end;
16403 pdf_print_ln("Q");
16404 end;
16405
16406 procedure pdf_rectangle(left, top, right, bottom: scaled); {output a
16407 rectangle specification to PDF file}
16408 begin
16409 prepare_mag;
16410 pdf_print("/Rect [");
16411 pdf_print_mag_bp(pdf_x(left)); pdf_out(" ");
16412 pdf_print_mag_bp(pdf_y(bottom)); pdf_out(" ");
16413 pdf_print_mag_bp(pdf_x(right)); pdf_out(" ");
16414 pdf_print_mag_bp(pdf_y(top));
16415 pdf_print_ln("]");
16416 end;
16417
16418 {Prints first |len| characters of string |s| (if it's that long).
16419 There must be a better way to print a substring?}
16420 procedure slow_print_substr(@!s,@!max_len:integer);
16421 var j:pool_pointer; {current character code position}
16422 begin if (s>=str_ptr) or (s<256) then print(s)
16423 else begin j:=str_start[s];
16424 while (j<str_start[s+1]) and (j<=str_start[s]+max_len) do
16425 begin print(so(str_pool[j])); incr(j);
16426 end;
16427 end;
16428 if j<str_start[s+1] then print("..."); {indicate truncation}
16429 end;
16430
16431 procedure literal(s: str_number; literal_mode: integer; warn: boolean);
16432 var j: pool_pointer; {current character code position}
16433 begin
16434 j:=str_start[s];
16435 if literal_mode = scan_special then begin
16436 if not (str_in_str(s, "PDF:", 0) or str_in_str(s, "pdf:", 0)) then begin
16437 if warn and not (str_in_str(s, "SRC:", 0)
16438 or str_in_str(s, "src:", 0)
16439 or (length(s) = 0)) then begin
16440 print_nl("Non-PDF special ignored!");
16441 print_nl("<special> ");
16442 slow_print_substr(s, 64);
16443 {length of printed line should be <=78; good enough.}
16444 print_ln;
16445 end;
16446 return;
16447 end;
16448 j := j + length("PDF:");
16449 if str_in_str(s, "direct:", length("PDF:")) then begin
16450 j := j + length("direct:");
16451 literal_mode := direct_always; end
16452 else if str_in_str(s, "page:", length("PDF:")) then begin
16453 j := j + length("page:");
16454 literal_mode := direct_page; end
16455 else
16456 literal_mode := set_origin;
16457 end;
16458 case literal_mode of
16459 set_origin: begin
16460 pdf_end_text;
16461 pdf_set_origin(cur_h, cur_v);
16462 end;
16463 direct_page:
16464 pdf_end_text;
16465 direct_always:
16466 pdf_end_string_nl;
16467 othercases confusion("literal1")
16468 endcases;
16469 while j<str_start[s+1] do begin
16470 pdf_out(str_pool[j]);
16471 incr(j);
16472 end;
16473 pdf_print_nl;
16474 end;
16475
16476 @* \[32d] The cross-reference table. The cross-reference table |obj_tab| is an
16477 array of |obj_tab_size| of |obj_entry|. Each entry contains five integer fields
16478 and represents an object in PDF file whose object number is the index of this
16479 entry in |obj_tab|. Objects in |obj_tab| maybe linked into list; objects in
16480 such a linked list have the same type.
16481
16482 @<Types...@>=
16483 @!obj_entry = record@;@/
16484 int0, int1: integer;
16485 int2: longinteger;
16486 int3, int4: integer;
16487 end;
16488
16489 @ The first field contains information representing identifier of this object.
16490 It is usually a number for most of object types, but it may be a string number
16491 for named destination or named thread.
16492
16493 The second field of |obj_entry| contains link to the next
16494 object in |obj_tab| if this object is linked in a list.
16495
16496 The third field holds the byte offset of the object in the output PDF file,
16497 or its byte offset within an object stream. As long as the object is not
16498 written, this field is used for flags about the write status of the object;
16499 then it has a negative value.
16500
16501 The fourth field holds the object number of the object stream, into which
16502 the object is included.
16503
16504 The last field usually represents the pointer to some auxiliary data
16505 structure depending on the object type; however it may be used as a counter as
16506 well.
16507
16508 @d obj_info(#) == obj_tab[#].int0 {information representing identifier of this object}
16509 @d obj_link(#) == obj_tab[#].int1 {link to the next entry in linked list}
16510 @d obj_offset(#) == obj_tab[#].int2 {negative (flags), or byte offset for this object in PDF output file, or object stream number for this object}
16511 @d obj_os_idx(#) == obj_tab[#].int3 {index of this object in object stream}
16512 @d obj_aux(#) == obj_tab[#].int4 {auxiliary pointer}
16513
16514 @d set_obj_fresh(#) == obj_offset(#) := -2
16515 @d set_obj_scheduled(#) == if obj_offset(#) = -2 then obj_offset(#) := -1
16516 @d is_obj_scheduled(#) == (obj_offset(#) > -2)
16517 @d is_obj_written(#) == (obj_offset(#) > -1)
16518
16519 @# {types of objects}
16520 @d obj_type_others == 0 {objects which are not linked in any list}
16521 @d obj_type_page == 1 {index of linked list of Page objects}
16522 @d obj_type_pages == 2 {index of linked list of Pages objects}
16523 @d obj_type_font == 3 {index of linked list of Fonts objects}
16524 @d obj_type_outline == 4 {index of linked list of outline objects}
16525 @d obj_type_dest == 5 {index of linked list of destination objects}
16526 @d obj_type_struct_dest == 6 {index of linked list of structure destination objects}
16527 @d obj_type_obj == 7 {index of linked list of raw objects}
16528 @d obj_type_xform == 8 {index of linked list of XObject forms}
16529 @d obj_type_ximage == 9 {index of linked list of XObject image}
16530 @d obj_type_thread == 10 {index of linked list of num article threads}
16531 @d head_tab_max == obj_type_thread {max index of |head_tab|}
16532
16533 @# {max number of kids for balanced trees}
16534 @d pages_tree_kids_max == 6 {max number of kids of Pages tree node}
16535 @d name_tree_kids_max == 6 {max number of kids of node of name tree for
16536 name destinations}
16537
16538 @# {when a whatsit node representing annotation is created, words |1..3| are
16539 width, height and depth of this annotation; after shipping out words |1..4|
16540 are rectangle specification of annotation. For whatsit node representing
16541 destination |pdf_left| and |pdf_top| are used for some types of destinations}
16542
16543 @# {coordinates of destinations/threads/annotations (in whatsit node)}
16544 @d pdf_left(#) == mem[# + 1].sc
16545 @d pdf_top(#) == mem[# + 2].sc
16546 @d pdf_right(#) == mem[# + 3].sc
16547 @d pdf_bottom(#) == mem[# + 4].sc
16548
16549 @# {dimension of destinations/threads/annotations (in whatsit node)}
16550 @d pdf_width(#) == mem[# + 1].sc
16551 @d pdf_height(#) == mem[# + 2].sc
16552 @d pdf_depth(#) == mem[# + 3].sc
16553
16554 @# {data structure for \.{\\pdfliteral}}
16555 @d pdf_literal_data(#) == link(#+1) {data}
16556 @d pdf_literal_mode(#) == info(#+1) {mode of resetting the text matrix
16557 while writing data to the page stream}
16558 @# {modes of setting the current transformation matrix (CTM)}
16559 @d set_origin == 0 {end text (ET) if needed, set CTM to current point}
16560 @d direct_page == 1 {end text (ET) if needed, but don't change the CTM}
16561 @d direct_always == 2 {don't end text, don't change the CTM}
16562 @d scan_special == 3 {look into special text}
16563
16564 @# {data structure for \.{\\pdfcolorstack}}
16565 @d pdf_colorstack_node_size == 3
16566 @d pdf_colorstack_setter_node_size == 3
16567 @d pdf_colorstack_getter_node_size == 2
16568 @d pdf_colorstack_stack(#) == link(#+1) {stack number}
16569 @d pdf_colorstack_cmd(#) == info(#+1) {command: set, push, pop, current}
16570 @d pdf_colorstack_data(#) == link(#+2) {data}
16571
16572 @# {color stack commands}
16573 @d colorstack_set == 0
16574 @d colorstack_push == 1
16575 @d colorstack_data == 1 { last value where data field is set }
16576 @d colorstack_pop == 2
16577 @d colorstack_current == 3
16578
16579 @# {data structure for \.{\\pdfsetmatrix}}
16580 @d pdf_setmatrix_node_size == 2
16581 @d pdf_setmatrix_data(#) == link(#+1) {data}
16582
16583 @# {data structure for \.{\\pdfsave}}
16584 @d pdf_save_node_size == 2
16585
16586 @# {data structure for \.{\\pdfrestore}}
16587 @d pdf_restore_node_size == 2
16588
16589 @# {data structure for \.{\\pdfobj} and \.{\\pdfrefobj}}
16590 @d pdf_refobj_node_size == 2 {size of whatsit node representing the raw object}
16591 @d pdf_obj_objnum(#) == info(# + 1) {number of the raw object}
16592 @d obj_data_ptr == obj_aux {pointer to |pdf_mem|}
16593 @d pdfmem_obj_size == 4 {size of memory in |pdf_mem| which
16594 |obj_data_ptr| holds}
16595 @d obj_obj_data(#) == pdf_mem[obj_data_ptr(#) + 0] {object data}
16596 @d obj_obj_is_stream(#) == pdf_mem[obj_data_ptr(#) + 1] {will this object
16597 be written as a stream instead of a dictionary?}
16598 @d obj_obj_stream_attr(#) == pdf_mem[obj_data_ptr(#) + 2] {additional
16599 object attributes for streams}
16600 @d obj_obj_is_file(#) == pdf_mem[obj_data_ptr(#) + 3] {data should be
16601 read from an external file?}
16602
16603 @# {data structure for \.{\\pdfxform} and \.{\\pdfrefxform}}
16604 @d pdf_refxform_node_size == 5 {size of whatsit node for xform; words 1..3 are
16605 form dimensions}
16606 @d pdf_xform_objnum(#) == info(# + 4) {object number}
16607 @d pdfmem_xform_size == 6 {size of memory in |pdf_mem| which
16608 |obj_data_ptr| holds}
16609 @d obj_xform_width(#) == pdf_mem[obj_data_ptr(#) + 0]
16610 @d obj_xform_height(#) == pdf_mem[obj_data_ptr(#) + 1]
16611 @d obj_xform_depth(#) == pdf_mem[obj_data_ptr(#) + 2]
16612 @d obj_xform_box(#) == pdf_mem[obj_data_ptr(#) + 3] {this field holds
16613 pointer to the corresponding box}
16614 @d obj_xform_attr(#) == pdf_mem[obj_data_ptr(#) + 4] {additional xform
16615 attributes}
16616 @d obj_xform_resources(#) == pdf_mem[obj_data_ptr(#) + 5] {additional xform
16617 Resources}
16618
16619 @# {data structure for \.{\\pdfximage} and \.{\\pdfrefximage}}
16620 @d pdf_refximage_node_size == 5 {size of whatsit node for ximage; words 1..3
16621 are image dimensions}
16622 @d pdf_ximage_objnum(#) == info(# + 4) {object number}
16623 @d pdfmem_ximage_size == 5 {size of memory in |pdf_mem| which
16624 |obj_data_ptr| holds}
16625 @d obj_ximage_width(#) == pdf_mem[obj_data_ptr(#) + 0]
16626 @d obj_ximage_height(#) == pdf_mem[obj_data_ptr(#) + 1]
16627 @d obj_ximage_depth(#) == pdf_mem[obj_data_ptr(#) + 2]
16628 @d obj_ximage_attr(#) == pdf_mem[obj_data_ptr(#) + 3] {additional ximage attributes}
16629 @d obj_ximage_data(#) == pdf_mem[obj_data_ptr(#) + 4] {pointer to image data}
16630
16631 @# {data structure of annotations; words 1..4 represent the coordinates of
16632 the annotation}
16633 @d obj_annot_ptr == obj_aux {pointer to corresponding whatsit node}
16634 @d pdf_annot_node_size == 7 {size of whatsit node representing annotation}
16635 @d pdf_annot_data(#) == info(# + 5) {raw data of general annotations}
16636 @d pdf_link_attr(#) == info(# + 5) {attributes of link annotations}
16637 @d pdf_link_action(#) == link(# + 5) {pointer to action structure}
16638 @d pdf_annot_objnum(#) == mem[# + 6].int {object number of corresponding object}
16639 @d pdf_link_objnum(#) == mem[# + 6].int {object number of corresponding object}
16640
16641 @# {types of actions}
16642 @d pdf_action_page == 0 {GoTo action}
16643 @d pdf_action_goto == 1 {GoTo action}
16644 @d pdf_action_thread == 2 {Thread action}
16645 @d pdf_action_user == 3 {user-defined action}
16646
16647 @# {data structure of actions}
16648 @d pdf_action_size == 4 {size of action structure in |mem|}
16649 @d pdf_action_type == type {action type}
16650 @d pdf_action_named_id == subtype {identifier is type of name}
16651 @d pdf_action_id == link {destination/thread name identifier}
16652 @d pdf_action_file(#) == info(# + 1) {file name for external action}
16653 @d pdf_action_new_window(#)== link(# + 1) {open a new window?}
16654 @d pdf_action_page_tokens(#) == info(# + 2) {specification of GoTo page action}
16655 @d pdf_action_user_tokens(#) == info(# + 2) {user-defined action string}
16656 @d pdf_action_refcount(#) == link(# + 2) {counter of references to this action}
16657 @d pdf_action_struct_id(#) == link(# + 3) {structure destination identifier}
16658
16659 @# {data structure of outlines; it's not able to write out outline entries
16660 before all outline entries are defined, so memory allocated for outline
16661 entries can't not be deallocated and will stay in memory. For this reason we
16662 will store data of outline entries in |pdf_mem| instead of |mem|}
16663
16664 @d pdfmem_outline_size == 8 {size of memory in |pdf_mem| which
16665 |obj_outline_ptr| points to}
16666 @d obj_outline_count == obj_info{count of all opened children}
16667 @d obj_outline_ptr == obj_aux {pointer to |pdf_mem|}
16668 @d obj_outline_title(#) == pdf_mem[obj_outline_ptr(#)]
16669 @d obj_outline_parent(#) == pdf_mem[obj_outline_ptr(#) + 1]
16670 @d obj_outline_prev(#) == pdf_mem[obj_outline_ptr(#) + 2]
16671 @d obj_outline_next(#) == pdf_mem[obj_outline_ptr(#) + 3]
16672 @d obj_outline_first(#) == pdf_mem[obj_outline_ptr(#) + 4]
16673 @d obj_outline_last(#) == pdf_mem[obj_outline_ptr(#) + 5]
16674 @d obj_outline_action_objnum(#) == pdf_mem[obj_outline_ptr(#) + 6] {object number of
16675 action}
16676 @d obj_outline_attr(#) == pdf_mem[obj_outline_ptr(#) + 7]
16677
16678 @# {types of destinations}
16679 @d pdf_dest_xyz == 0
16680 @d pdf_dest_fit == 1
16681 @d pdf_dest_fith == 2
16682 @d pdf_dest_fitv == 3
16683 @d pdf_dest_fitb == 4
16684 @d pdf_dest_fitbh == 5
16685 @d pdf_dest_fitbv == 6
16686 @d pdf_dest_fitr == 7
16687
16688 @# {data structure of structure and regular destinations}
16689 @d obj_dest_ptr == obj_aux {pointer to |pdf_dest_node|}
16690 @d pdf_dest_node_size == 7 {size of whatsit node for destination;
16691 words |1..4| hold dest dimensions, word |6| identifier type, subtype
16692 and identifier of destination, word |6| the corresponding object number}
16693 @d pdf_dest_type(#) == type(# + 5) {type of destination}
16694 @d pdf_dest_named_id(#) == subtype(# + 5) {is named identifier?}
16695 @d pdf_dest_id(#) == link(# + 5) {destination identifier}
16696 @d pdf_dest_xyz_zoom(#) == info(# + 6) {zoom factor for |destxyz| destination}
16697 @d pdf_dest_objnum(#) == link(# + 6) {object number of corresponding
16698 object}
16699
16700 @# {data structure of threads; words 1..4 represent the coordinates of the
16701 corners}
16702 @d pdf_thread_node_size == 7
16703 @d pdf_thread_named_id(#) == subtype(# + 5) {is a named identifier}
16704 @d pdf_thread_id(#) == link(# + 5) {thread identifier}
16705 @d pdf_thread_attr(#) == info(# + 6) {attributes of thread}
16706 @d obj_thread_first == obj_aux {pointer to the first bead}
16707
16708 @# {data structure of beads}
16709 @d pdfmem_bead_size == 5 {size of memory in |pdf_mem| which
16710 |obj_bead_ptr| points to}
16711 @d obj_bead_ptr == obj_aux {pointer to |pdf_mem|}
16712 @d obj_bead_rect(#) == pdf_mem[obj_bead_ptr(#)]
16713 @d obj_bead_page(#) == pdf_mem[obj_bead_ptr(#) + 1]
16714 @d obj_bead_next(#) == pdf_mem[obj_bead_ptr(#) + 2]
16715 @d obj_bead_prev(#) == pdf_mem[obj_bead_ptr(#) + 3]
16716 @d obj_bead_attr(#) == pdf_mem[obj_bead_ptr(#) + 4]
16717 @d obj_bead_data == obj_bead_rect {pointer to the corresponding
16718 whatsit node; |obj_bead_rect| is needed only when the bead rectangle has
16719 been written out and after that |obj_bead_data| is not needed any more
16720 so we can use this field for both}
16721
16722 @# {data structure of snap node}
16723 @d snap_node_size == 3
16724 @d snap_glue_ptr(#) == info(# + 1)
16725 @d final_skip(#) == mem[# + 2].sc {the amount to skip}
16726 @# {data structure of snap compensation node}
16727 @d snapy_comp_ratio(#) == mem[# + 1].int
16728
16729 @<Constants...@>=
16730 @!inf_obj_tab_size = 1000; {min size of the cross-reference table for PDF output}
16731 @!sup_obj_tab_size = 8388607; {max size of the cross-reference table for PDF output}
16732 @!inf_dest_names_size = 1000; {min size of the destination names table for PDF output}
16733 @!sup_dest_names_size = 500000; {max size of the destination names table for PDF output}
16734 @!inf_pk_dpi = 72; {min PK pixel density value from \.{texmf.cnf}}
16735 @!sup_pk_dpi = 8000; {max PK pixel density value from \.{texmf.cnf}}
16736 @!pdf_objtype_max = head_tab_max;
16737
16738 @ @<Glob...@>=
16739 @!obj_tab_size:integer;
16740 @!obj_tab:^obj_entry;
16741 @!head_tab: array[1..head_tab_max] of integer;
16742 @!pages_tail: integer;
16743 @!obj_ptr: integer; {user objects counter}
16744 @!sys_obj_ptr: integer; {system objects counter, including object streams}
16745 @!pdf_last_pages: integer; {pointer to most recently generated pages object}
16746 @!pdf_last_page: integer; {pointer to most recently generated page object}
16747 @!pdf_last_stream: integer; {pointer to most recently generated stream}
16748 @!pdf_stream_length: longinteger; {length of most recently generated stream}
16749 @!pdf_stream_length_offset: longinteger; {file offset of the last stream length}
16750 @!pdf_seek_write_length: boolean; {flag whether to seek back and write \.{/Length}}
16751 @!pdf_last_byte: eight_bits; {byte most recently written to PDF file; for \.{endstream} in new line}
16752 @!pdf_append_list_arg: integer; {for use with |pdf_append_list|}
16753 @!ff: integer; {for use with |set_ff|}
16754 @!pdf_box_spec_media: integer;
16755 @!pdf_box_spec_crop: integer;
16756 @!pdf_box_spec_bleed: integer;
16757 @!pdf_box_spec_trim: integer;
16758 @!pdf_box_spec_art: integer;
16759
16760 @ @<Set init...@>=
16761 obj_ptr := 0;
16762 sys_obj_ptr := 0;
16763 obj_tab_size := inf_obj_tab_size; {allocated size of |obj_tab| array}
16764 dest_names_size := inf_dest_names_size; {allocated size of |dest_names| array}
16765 for k := 1 to head_tab_max do
16766 head_tab[k] := 0;
16767 pdf_box_spec_media := 1;
16768 pdf_box_spec_crop := 2;
16769 pdf_box_spec_bleed := 3;
16770 pdf_box_spec_trim := 4;
16771 pdf_box_spec_art := 5;
16772 pdf_dummy_font := null_font;
16773
16774 @ Here we implement subroutines for work with objects and related things.
16775 Some of them are used in former parts too, so we need to declare them
16776 forward.
16777
16778 @d pdf_append_list_end(#) == # := append_ptr(#, pdf_append_list_arg); end
16779 @d pdf_append_list(#) == begin pdf_append_list_arg := #; pdf_append_list_end
16780 @d set_ff(#) == begin
16781 if pdf_font_num[#] < 0 then
16782 ff := -pdf_font_num[#]
16783 else
16784 ff := #;
16785 end
16786
16787 @<Declare procedures that need to be declared forward for \pdfTeX@>=
16788 procedure append_dest_name(s: str_number; n: integer);
16789 var a: integer;
16790 begin
16791 if pdf_dest_names_ptr = sup_dest_names_size then
16792 overflow("number of destination names (dest_names_size)", dest_names_size);
16793 if pdf_dest_names_ptr = dest_names_size then begin
16794 a := 0.2 * dest_names_size;
16795 if dest_names_size < sup_dest_names_size - a then
16796 dest_names_size := dest_names_size + a
16797 else
16798 dest_names_size := sup_dest_names_size;
16799 dest_names := xrealloc_array(dest_names, dest_name_entry, dest_names_size);
16800 end;
16801 dest_names[pdf_dest_names_ptr].objname := s;
16802 dest_names[pdf_dest_names_ptr].objnum := n;
16803 incr(pdf_dest_names_ptr);
16804 end;
16805
16806 procedure pdf_create_obj(t, i: integer); {create an object with type |t| and
16807 identifier |i|}
16808 label done;
16809 var a, p, q: integer;
16810 begin
16811 if sys_obj_ptr = sup_obj_tab_size then
16812 overflow("indirect objects table size", obj_tab_size);
16813 if sys_obj_ptr = obj_tab_size then begin
16814 a := 0.2 * obj_tab_size;
16815 if obj_tab_size < sup_obj_tab_size - a then
16816 obj_tab_size := obj_tab_size + a
16817 else
16818 obj_tab_size := sup_obj_tab_size;
16819 obj_tab := xrealloc_array(obj_tab, obj_entry, obj_tab_size);
16820 end;
16821 incr(sys_obj_ptr);
16822 obj_ptr := sys_obj_ptr;
16823 obj_info(obj_ptr) := i;
16824 set_obj_fresh(obj_ptr);
16825 obj_aux(obj_ptr) := 0;
16826 avl_put_obj(obj_ptr, t);
16827 if t = obj_type_page then begin
16828 p := head_tab[t];
16829 {find the right position to insert newly created object}@/
16830 if (p = 0) or (obj_info(p) < i) then begin
16831 obj_link(obj_ptr) := p;
16832 head_tab[t] := obj_ptr;
16833 end
16834 else begin
16835 while p <> 0 do begin
16836 if obj_info(p) < i then
16837 goto done;
16838 q := p;
16839 p := obj_link(p);
16840 end;
16841 done:
16842 obj_link(q) := obj_ptr;
16843 obj_link(obj_ptr) := p;
16844 end;
16845 end
16846 else if t <> obj_type_others then begin
16847 obj_link(obj_ptr) := head_tab[t];
16848 head_tab[t] := obj_ptr;
16849 if (t = obj_type_dest) and (i < 0) then
16850 append_dest_name(-obj_info(obj_ptr), obj_ptr);
16851 end;
16852 end;
16853
16854 function pdf_new_objnum: integer; {create a new object and return its number}
16855 begin
16856 pdf_create_obj(obj_type_others, 0);
16857 pdf_new_objnum := obj_ptr;
16858 end;
16859
16860 procedure pdf_os_switch(pdf_os: boolean); {switch between PDF stream and object stream mode}
16861 begin
16862 if pdf_os and pdf_os_enable then begin
16863 if not pdf_os_mode then begin {back up PDF stream variables}
16864 pdf_op_ptr := pdf_ptr;
16865 pdf_ptr := pdf_os_ptr;
16866 pdf_buf := pdf_os_buf;
16867 pdf_buf_size := pdf_os_buf_size;
16868 pdf_os_mode := true; {switch to object stream}
16869 end;
16870 end else begin
16871 if pdf_os_mode then begin {back up object stream variables}
16872 pdf_os_ptr := pdf_ptr;
16873 pdf_ptr := pdf_op_ptr;
16874 pdf_buf := pdf_op_buf;
16875 pdf_buf_size := pdf_op_buf_size;
16876 pdf_os_mode := false; {switch to PDF stream}
16877 end;
16878 end;
16879 end;
16880
16881 procedure pdf_os_prepare_obj(i: integer; pdf_os_level: integer); {create new \.{/ObjStm} object
16882 if required, and set up cross reference info}
16883 begin
16884 pdf_os_switch((pdf_os_level > 0) and (fixed_pdf_objcompresslevel >= pdf_os_level));
16885 if pdf_os_mode then begin
16886 if pdf_os_cur_objnum = 0 then begin
16887 pdf_os_cur_objnum := pdf_new_objnum;
16888 decr(obj_ptr); {object stream is not accessible to user}
16889 incr(pdf_os_cntr); {only for statistics}
16890 pdf_os_objidx := 0;
16891 pdf_ptr := 0; {start fresh object stream}
16892 end else
16893 incr(pdf_os_objidx);
16894 obj_os_idx(i) := pdf_os_objidx;
16895 obj_offset(i) := pdf_os_cur_objnum;
16896 pdf_os_objnum[pdf_os_objidx] := i;
16897 pdf_os_objoff[pdf_os_objidx] := pdf_ptr;
16898 end else begin
16899 obj_offset(i) := pdf_offset;
16900 obj_os_idx(i) := -1; {mark it as not included in object stream}
16901 end;
16902 end;
16903
16904 procedure pdf_begin_obj(i: integer; pdf_os_level: integer); {begin a PDF object}
16905 begin
16906 check_pdfversion;
16907 pdf_os_prepare_obj(i, pdf_os_level);
16908 if not pdf_os_mode then begin
16909 pdf_print_int(i);
16910 pdf_print_ln(" 0 obj");
16911 end else if pdf_compress_level = 0 then begin
16912 pdf_print("% "); {debugging help}
16913 pdf_print_int(i);
16914 pdf_print_ln(" 0 obj");
16915 end;
16916 end;
16917
16918 procedure pdf_new_obj(t, i: integer; pdf_os: integer); {begin a new PDF object}
16919 begin
16920 pdf_create_obj(t, i);
16921 pdf_begin_obj(obj_ptr, pdf_os);
16922 end;
16923
16924 procedure pdf_end_obj; {end a PDF object}
16925 begin
16926 if pdf_os_mode then begin
16927 if pdf_os_objidx = pdf_os_max_objs - 1 then
16928 pdf_os_write_objstream;
16929 end else
16930 pdf_print_ln("endobj"); {end a PDF object}
16931 end;
16932
16933 procedure pdf_begin_dict(i: integer; pdf_os_level: integer); {begin a PDF dictionary object}
16934 begin
16935 check_pdfversion;
16936 pdf_os_prepare_obj(i, pdf_os_level);
16937 if not pdf_os_mode then begin
16938 pdf_print_int(i);
16939 pdf_print_ln(" 0 obj");
16940 end else if pdf_compress_level = 0 then begin
16941 pdf_print("% "); {debugging help}
16942 pdf_print_int(i);
16943 pdf_print_ln(" 0 obj");
16944 end;
16945 pdf_print_ln("<<");
16946 end;
16947
16948 procedure pdf_new_dict(t, i: integer; pdf_os: integer); {begin a new PDF dictionary object}
16949 begin
16950 pdf_create_obj(t, i);
16951 pdf_begin_dict(obj_ptr, pdf_os);
16952 end;
16953
16954 procedure pdf_end_dict; {end a PDF dictionary object}
16955 begin
16956 if pdf_os_mode then begin
16957 pdf_print_ln(">>");
16958 if pdf_os_objidx = pdf_os_max_objs - 1 then
16959 pdf_os_write_objstream;
16960 end else begin
16961 pdf_print_ln(">>");
16962 pdf_print_ln("endobj");
16963 end;
16964 end;
16965
16966 @ Write out an accumulated object stream.
16967 First the object number and byte offset pairs are generated
16968 and appended to the ready buffered object stream.
16969 By this the value of \.{/First} can be calculated.
16970 Then a new \.{/ObjStm} object is generated, and everything is
16971 copied to the PDF output buffer, where also compression is done.
16972 When calling this procedure, |pdf_os_mode| must be |true|.
16973
16974 @<Declare procedures that need to be declared forward for \pdfTeX@>=
16975 procedure pdf_os_write_objstream;
16976 var i, j, p, q: pointer;
16977 begin
16978 if pdf_os_cur_objnum = 0 then {no object stream started}
16979 return;
16980 p := pdf_ptr;
16981 i := 0;
16982 j := 0;
16983 while i <= pdf_os_objidx do begin {assemble object number and byte offset pairs}
16984 pdf_print_int(pdf_os_objnum[i]);
16985 pdf_print(" ");
16986 pdf_print_int(pdf_os_objoff[i]);
16987 if j = 9 then begin {print out in groups of ten for better readability}
16988 pdf_out(pdf_new_line_char);
16989 j := 0;
16990 end else begin
16991 pdf_print(" ");
16992 incr(j);
16993 end;
16994 incr(i);
16995 end;
16996 pdf_buf[pdf_ptr - 1] := pdf_new_line_char; {no risk of flush, as we are in |pdf_os_mode|}
16997 q := pdf_ptr;
16998 pdf_begin_dict(pdf_os_cur_objnum, 0); {switch to PDF stream writing}
16999 pdf_print_ln("/Type /ObjStm");
17000 pdf_print("/N ");
17001 pdf_print_int_ln(pdf_os_objidx + 1);
17002 pdf_print("/First ");
17003 pdf_print_int_ln(q - p);
17004 pdf_begin_stream;
17005 pdf_room(q - p); {should always fit into the PDF output buffer}
17006 i := p;
17007 while i < q do begin {write object number and byte offset pairs}
17008 pdf_quick_out(pdf_os_buf[i]);
17009 incr(i);
17010 end;
17011 i := 0;
17012 while i < p do begin
17013 q := i + pdf_buf_size;
17014 if q > p then q := p;
17015 pdf_room(q - i);
17016 while i < q do begin {write the buffered objects}
17017 pdf_quick_out(pdf_os_buf[i]);
17018 incr(i);
17019 end;
17020 end;
17021 pdf_end_stream;
17022 pdf_os_cur_objnum := 0; {to force object stream generation next time}
17023 end;
17024
17025 @ @<Declare procedures that need to be declared forward for \pdfTeX@>=
17026 function append_ptr(p: pointer; i: integer): pointer; {appends a pointer with
17027 info |i| to the end of linked list with head |p|}
17028 var q: pointer;
17029 begin
17030 append_ptr := p;
17031 fast_get_avail(q);
17032 info(q) := i;
17033 link(q) := null;
17034 if p = null then begin
17035 append_ptr := q;
17036 return;
17037 end;
17038 while link(p) <> null do
17039 p := link(p);
17040 link(p) := q;
17041 end;
17042
17043 function pdf_lookup_list(p: pointer; i: integer): pointer; {looks up for pointer
17044 with info |i| in list |p|}
17045 begin
17046 pdf_lookup_list := null;
17047 while p <> null do begin
17048 if info(p) = i then begin
17049 pdf_lookup_list := p;
17050 return;
17051 end;
17052 p := link(p);
17053 end;
17054 end;
17055
17056 @ @<Glob...@>=
17057 @!pdf_image_procset: integer; {collection of image types used in current page/form}
17058 @!pdf_text_procset: boolean; {mask of used ProcSet's in the current page/form}
17059
17060 @ Subroutines to print out various PDF objects:
17061
17062 @d is_hex_char(#) == (((# >= '0') and (# <= '9')) or
17063 ((# >= 'A') and (# <= 'F')) or
17064 ((# >= 'a') and (# <= 'f')))
17065
17066 @p procedure pdf_print_fw_int(n: longinteger; w: integer); {print out an integer with
17067 fixed width; used for outputting cross-reference table}
17068 var k: integer; {$0\le k\le23$}
17069 begin
17070 k := 0;
17071 repeat dig[k] := n mod 10; n := n div 10; incr(k);
17072 until k = w;
17073 pdf_room(k);
17074 while k > 0 do begin
17075 decr(k);
17076 pdf_quick_out("0" + dig[k]);
17077 end;
17078 end;
17079
17080 procedure pdf_out_bytes(n: longinteger; w: integer); {print out an integer as
17081 a number of bytes; used for outputting \.{/XRef} cross-reference stream}
17082 var k: integer;
17083 byte: array[0..7] of integer; {digits in a number being output}
17084 begin
17085 k := 0;
17086 repeat byte[k] := n mod 256; n := n div 256; incr(k);
17087 until k = w;
17088 pdf_room(k);
17089 while k > 0 do begin
17090 decr(k);
17091 pdf_quick_out(byte[k]);
17092 end;
17093 end;
17094
17095 procedure pdf_int_entry(s: str_number; v: integer); {print out an entry in
17096 dictionary with integer value to PDF buffer}
17097 begin
17098 pdf_out("/");
17099 pdf_print(s);
17100 pdf_out(" ");
17101 pdf_print_int(v);
17102 end;
17103
17104 procedure pdf_int_entry_ln(s: str_number; v: integer);
17105 begin
17106 pdf_int_entry(s, v);
17107 pdf_print_nl;
17108 end;
17109
17110 procedure pdf_indirect(s: str_number; o: integer); {print out an indirect
17111 entry in dictionary}
17112 begin
17113 pdf_out("/");
17114 pdf_print(s);
17115 pdf_out(" ");
17116 pdf_print_int(o);
17117 pdf_print(" 0 R");
17118 end;
17119
17120 procedure pdf_indirect_ln(s: str_number; o: integer);
17121 begin
17122 pdf_indirect(s, o);
17123 pdf_print_nl;
17124 end;
17125
17126 procedure pdf_print_str(s: str_number); {print out |s| as string in PDF
17127 output}
17128 label done;
17129 var i, j: pool_pointer;
17130 is_hex_string: boolean;
17131 begin
17132 i := str_start[s];
17133 j := i + length(s) - 1;
17134 if i > j then begin
17135 pdf_print("()"); {null string}
17136 return;
17137 end;
17138 if (str_pool[i] = '(') and (str_pool[j] = ')') then begin
17139 pdf_print(s);
17140 return;
17141 end;
17142 is_hex_string := false;
17143 if (str_pool[i] <> '<') or (str_pool[j] <> '>') or odd(length(s)) then
17144 goto done;
17145 incr(i);
17146 decr(j);
17147 while i < j do begin
17148 if is_hex_char(str_pool[i]) and is_hex_char(str_pool[i + 1]) then
17149 i := i + 2
17150 else
17151 goto done;
17152 end;
17153 is_hex_string := true;
17154 done:
17155 if is_hex_string then
17156 pdf_print(s)
17157 else begin
17158 pdf_out("(");
17159 pdf_print(s);
17160 pdf_out(")");
17161 end;
17162 end;
17163
17164 procedure pdf_print_str_ln(s: str_number); {print out |s| as string in PDF
17165 output}
17166 begin
17167 pdf_print_str(s);
17168 pdf_print_nl;
17169 end;
17170
17171 procedure pdf_str_entry(s, v: str_number); {print out an entry in
17172 dictionary with string value to PDF buffer}
17173 begin
17174 if v = 0 then
17175 return;
17176 pdf_out("/");
17177 pdf_print(s);
17178 pdf_out(" ");
17179 pdf_print_str(v);
17180 end;
17181
17182 procedure pdf_str_entry_ln(s, v: str_number);
17183 begin
17184 if v = 0 then
17185 return;
17186 pdf_str_entry(s, v);
17187 pdf_print_nl;
17188 end;
17189
17190 @* \[32e] Font processing. As \pdfTeX{} should also act as a back-end driver,
17191 it needs to support virtual fonts too. Information about virtual fonts can be
17192 found in the source of some \.{DVI}-related programs.
17193
17194 Whenever we want to write out a character in a font to PDF output, we
17195 should check whether the used font is a new (has not been used yet),
17196 virtual or real font. The array |pdf_font_type| holds a flag of each used
17197 font. After initialization the flag of each font is set to |new_font_type|.
17198 The first time a character of a font is written out, \pdfTeX{} looks for
17199 the corresponding virtual font. If the corresponding virtual font exists, then
17200 the font type is set to |virtual_font_type|; otherwise it will be set to
17201 |real_font_type|. |subst_font_type| indicates fonts that have been substituted
17202 during adjusting spacing. Such fonts are linked via the |pdf_font_elink| array.
17203
17204 @d new_font_type = 0 {new font (has not been used yet)}
17205 @d virtual_font_type = 1 {virtual font}
17206 @d real_font_type = 2 {real font}
17207 @d subst_font_type = 3 {substituted font}
17208
17209 @<Declare procedures that need to be declared forward for \pdfTeX@>=
17210 procedure pdf_check_vf_cur_val; forward;
17211 procedure pdf_init_font_cur_val; forward;
17212 procedure scan_pdf_ext_toks; forward;
17213
17214 @ @<Glob...@>=
17215 @!pdf_font_type: ^eight_bits; {the type of font}
17216 @!pdf_font_attr: ^str_number; {pointer to additional attributes}
17217 @!pdf_font_nobuiltin_tounicode: ^boolean; {disable generating ToUnicode for this font?}
17218
17219 @ Here come some subroutines to deal with expanded fonts for HZ-algorithm.
17220
17221 @d set_char_and_font(#) ==
17222 if is_char_node(#) then begin
17223 c := character(#);
17224 f := font(#);
17225 end
17226 else if type(#) = ligature_node then begin
17227 c := character(lig_char(#));
17228 f := font(lig_char(#));
17229 end
17230
17231 @d non_existent_path == "///..."
17232
17233 @p
17234 procedure set_tag_code(f: internal_font_number; c: eight_bits; i: integer);
17235 var fixedi:integer;
17236 begin
17237 if is_valid_char(c) then
17238 begin fixedi := abs(fix_int(i,-7,0));
17239 if fixedi >= 4 then begin
17240 if char_tag(char_info(f)(c)) = ext_tag then
17241 op_byte(char_info(f)(c)) := (op_byte(char_info(f)(c))) - ext_tag;
17242 fixedi := fixedi - 4;
17243 end;
17244 if fixedi >= 2 then begin
17245 if char_tag(char_info(f)(c)) = list_tag then
17246 op_byte(char_info(f)(c)) := (op_byte(char_info(f)(c))) - list_tag;
17247 fixedi := fixedi - 2;
17248 end;
17249 if fixedi >= 1 then begin
17250 if char_tag(char_info(f)(c)) = lig_tag then
17251 op_byte(char_info(f)(c)) := (op_byte(char_info(f)(c))) - lig_tag;
17252 end;
17253 end;
17254 end;
17255
17256 procedure set_no_ligatures(f: internal_font_number);
17257 var c:integer;
17258 begin
17259 for c := font_bc[f] to font_ec[f] do
17260 if char_exists(orig_char_info(f)(c)) then
17261 if char_tag(orig_char_info(f)(c))=lig_tag then
17262 op_byte(orig_char_info(f)(c)) := (op_byte(orig_char_info(f)(c))) - lig_tag;
17263 end;
17264
17265 function init_font_base(v: integer): integer;
17266 var i, j: integer;
17267 begin
17268 i := pdf_get_mem(256);
17269 for j := 0 to 255 do
17270 pdf_mem[i + j] := v;
17271 init_font_base := i;
17272 end;
17273
17274 procedure set_lp_code(f: internal_font_number; c: eight_bits; i: integer);
17275 begin
17276 if pdf_font_lp_base[f] = 0 then
17277 pdf_font_lp_base[f] := init_font_base(0);
17278 pdf_mem[pdf_font_lp_base[f] + c] := fix_int(i, -1000, 1000);
17279 end;
17280
17281 procedure set_rp_code(f: internal_font_number; c: eight_bits; i: integer);
17282 begin
17283 if pdf_font_rp_base[f] = 0 then
17284 pdf_font_rp_base[f] := init_font_base(0);
17285 pdf_mem[pdf_font_rp_base[f] + c] := fix_int(i, -1000, 1000);
17286 end;
17287
17288 procedure set_ef_code(f: internal_font_number; c: eight_bits; i: integer);
17289 begin
17290 if pdf_font_ef_base[f] = 0 then
17291 pdf_font_ef_base[f] := init_font_base(1000);
17292 pdf_mem[pdf_font_ef_base[f] + c] := fix_int(i, 0, 1000);
17293 end;
17294
17295 procedure set_kn_bs_code(f: internal_font_number; c: eight_bits; i: integer);
17296 begin
17297 if pdf_font_kn_bs_base[f] = 0 then
17298 pdf_font_kn_bs_base[f] := init_font_base(0);
17299 pdf_mem[pdf_font_kn_bs_base[f] + c] := fix_int(i, -1000, 1000);
17300 end;
17301
17302 procedure set_st_bs_code(f: internal_font_number; c: eight_bits; i: integer);
17303 begin
17304 if pdf_font_st_bs_base[f] = 0 then
17305 pdf_font_st_bs_base[f] := init_font_base(0);
17306 pdf_mem[pdf_font_st_bs_base[f] + c] := fix_int(i, -1000, 1000);
17307 end;
17308
17309 procedure set_sh_bs_code(f: internal_font_number; c: eight_bits; i: integer);
17310 begin
17311 if pdf_font_sh_bs_base[f] = 0 then
17312 pdf_font_sh_bs_base[f] := init_font_base(0);
17313 pdf_mem[pdf_font_sh_bs_base[f] + c] := fix_int(i, -1000, 1000);
17314 end;
17315
17316 procedure set_kn_bc_code(f: internal_font_number; c: eight_bits; i: integer);
17317 begin
17318 if pdf_font_kn_bc_base[f] = 0 then
17319 pdf_font_kn_bc_base[f] := init_font_base(0);
17320 pdf_mem[pdf_font_kn_bc_base[f] + c] := fix_int(i, -1000, 1000);
17321 end;
17322
17323 procedure set_kn_ac_code(f: internal_font_number; c: eight_bits; i: integer);
17324 begin
17325 if pdf_font_kn_ac_base[f] = 0 then
17326 pdf_font_kn_ac_base[f] := init_font_base(0);
17327 pdf_mem[pdf_font_kn_ac_base[f] + c] := fix_int(i, -1000, 1000);
17328 end;
17329
17330 procedure adjust_interword_glue(p, g: pointer); {adjust the interword
17331 glue |g| after a character |p|}
17332 var kn, st, sh: scaled;
17333 q, r: pointer;
17334 c: halfword;
17335 f: internal_font_number;
17336 begin
17337 if not (not is_char_node(g) and type(g) = glue_node) then begin
17338 pdf_warning("adjust_interword_glue", "g is not a glue", true, true);
17339 return;
17340 end;
17341
17342 c := non_char; {no char before interword glue yet}
17343 set_char_and_font(p) {set |f| and |c| if |p| is a char or ligature}
17344 else if (type(p) = kern_node) and
17345 (subtype(p) = auto_kern) and
17346 (save_tail <> null) then
17347 begin
17348 r := save_tail;
17349 while (link(r) <> null) and (link(r) <> p) do
17350 r := link(r);
17351 if (link(r) = p) then
17352 set_char_and_font(r); {set |f| and |c| if |r| is a char or ligature}
17353 end;
17354 if (c = non_char) then
17355 return;
17356
17357 kn := get_kn_bs_code(f, c);
17358 st := get_st_bs_code(f, c);
17359 sh := get_sh_bs_code(f, c);
17360 if (kn <> 0) or (st <> 0) or (sh <> 0) then begin
17361 q := new_spec(glue_ptr(g));
17362 delete_glue_ref(glue_ptr(g));
17363 width(q) := width(q) + round_xn_over_d(quad(f), kn, 1000);
17364 stretch(q) := stretch(q) + round_xn_over_d(quad(f), st, 1000);
17365 shrink(q) := shrink(q) + round_xn_over_d(quad(f), sh, 1000);
17366 glue_ptr(g) := q;
17367 end;
17368 end;
17369
17370 function get_auto_kern(f: internal_font_number; l, r: halfword): pointer;
17371 {return a pointer to an auto kern node, or |null|}
17372 var tmp_w: scaled;
17373 k: integer;
17374 p: pointer;
17375 begin
17376 pdfassert((l >= 0) and (r >= 0));
17377 get_auto_kern := null;
17378 if (pdf_append_kern <= 0) and (pdf_prepend_kern <= 0) then
17379 return;
17380 tmp_w := 0;
17381 if (pdf_append_kern > 0) and (l < non_char) then begin
17382 k := get_kn_ac_code(f, l);
17383 if k <> 0 then
17384 tmp_w := round_xn_over_d(quad(f), k, 1000);
17385 end;
17386 if (pdf_prepend_kern > 0) and (r < non_char) then begin
17387 k := get_kn_bc_code(f, r);
17388 if k <> 0 then
17389 tmp_w := tmp_w + round_xn_over_d(quad(f), k, 1000);
17390 end;
17391 if tmp_w <> 0 then begin
17392 p := new_kern(tmp_w);
17393 subtype(p) := auto_kern;
17394 get_auto_kern := p;
17395 end;
17396 end;
17397
17398
17399 function expand_font_name(f: internal_font_number; e: integer): str_number;
17400 var old_setting:0..max_selector; {holds |selector| setting}
17401 begin
17402 old_setting:=selector; selector:=new_string;
17403 print(font_name[f]);
17404 if e > 0 then
17405 print("+"); {minus sign will be printed by |print_int|}
17406 print_int(e);
17407 selector:=old_setting;
17408 expand_font_name := make_string;
17409 end;
17410
17411 function auto_expand_font(f: internal_font_number; e: integer): internal_font_number;
17412 {creates an expanded font from the base font; doesn't load expanded tfm at all}
17413 var k: internal_font_number;
17414 nw, nk, ni, i: integer;
17415 begin
17416 k := font_ptr + 1;
17417 incr(font_ptr);
17418 if (font_ptr >= font_max) then
17419 overflow("maximum internal font number (font_max)", font_max);
17420 font_name[k] := expand_font_name(f, e);
17421 font_area[k] := font_area[f];
17422 font_id_text(k) := font_id_text(f);
17423 hyphen_char[k] := hyphen_char[f];
17424 skew_char[k] := skew_char[f];
17425 font_bchar[k] := font_bchar[f];
17426 font_false_bchar[k] := font_false_bchar[f];
17427 font_bc[k] := font_bc[f];
17428 font_ec[k] := font_ec[f];
17429 font_size[k] := font_size[f];
17430 font_dsize[k] := font_dsize[f];
17431 font_params[k] := font_params[f];
17432 font_glue[k] := font_glue[f];
17433 bchar_label[k] := bchar_label[f];
17434
17435 char_base[k] := char_base[f];
17436 height_base[k] := height_base[f];
17437 depth_base[k] := depth_base[f];
17438 lig_kern_base[k] := lig_kern_base[f];
17439 exten_base[k] := exten_base[f];
17440 param_base[k] := param_base[f];
17441
17442 nw := height_base[f] - width_base[f];
17443 ni := lig_kern_base[f] - italic_base[f];
17444 nk := exten_base[f] - (kern_base[f] + kern_base_offset);
17445 if (fmem_ptr + nw + ni + nk >= font_mem_size) then
17446 overflow("number of words of font memory (font_mem_size)", font_mem_size);
17447 width_base[k] := fmem_ptr;
17448 italic_base[k] := width_base[k] + nw;
17449 kern_base[k] := italic_base[k] + ni - kern_base_offset;
17450 fmem_ptr := fmem_ptr + nw + ni + nk;
17451
17452 for i := 0 to nw - 1 do
17453 font_info[width_base[k] + i].sc :=
17454 round_xn_over_d(font_info[width_base[f] + i].sc, 1000 + e, 1000);
17455 for i := 0 to ni - 1 do
17456 font_info[italic_base[k] + i].sc :=
17457 round_xn_over_d(font_info[italic_base[f] + i].sc, 1000 + e, 1000);
17458 for i := 0 to nk - 1 do
17459 font_info[kern_base[k] + kern_base_offset + i].sc :=
17460 round_xn_over_d(font_info[kern_base[f] + kern_base_offset + i].sc, 1000 + e, 1000);
17461
17462 auto_expand_font := k;
17463 end;
17464
17465 procedure copy_expand_params(k, f: internal_font_number; e: integer);
17466 {set expansion-related parameters for an expanded font |k|, based on the base
17467 font |f| and the expansion amount |e|}
17468 begin
17469 if pdf_font_rp_base[f] = 0 then
17470 pdf_font_rp_base[f] := init_font_base(0);
17471 if pdf_font_lp_base[f] = 0 then
17472 pdf_font_lp_base[f] := init_font_base(0);
17473 if pdf_font_ef_base[f] = 0 then
17474 pdf_font_ef_base[f] := init_font_base(1000);
17475 pdf_font_expand_ratio[k] := e;
17476 pdf_font_step[k] := pdf_font_step[f];
17477 pdf_font_auto_expand[k] := pdf_font_auto_expand[f];
17478 pdf_font_blink[k] := f;
17479 pdf_font_lp_base[k] := pdf_font_lp_base[f];
17480 pdf_font_rp_base[k] := pdf_font_rp_base[f];
17481 pdf_font_ef_base[k] := pdf_font_ef_base[f];
17482
17483 if pdf_font_kn_bs_base[f] = 0 then
17484 pdf_font_kn_bs_base[f] := init_font_base(0);
17485 if pdf_font_st_bs_base[f] = 0 then
17486 pdf_font_st_bs_base[f] := init_font_base(0);
17487 if pdf_font_sh_bs_base[f] = 0 then
17488 pdf_font_sh_bs_base[f] := init_font_base(0);
17489 if pdf_font_kn_bc_base[f] = 0 then
17490 pdf_font_kn_bc_base[f] := init_font_base(0);
17491 if pdf_font_kn_ac_base[f] = 0 then
17492 pdf_font_kn_ac_base[f] := init_font_base(0);
17493 pdf_font_kn_bs_base[k] := pdf_font_kn_bs_base[f];
17494 pdf_font_st_bs_base[k] := pdf_font_st_bs_base[f];
17495 pdf_font_sh_bs_base[k] := pdf_font_sh_bs_base[f];
17496 pdf_font_kn_bc_base[k] := pdf_font_kn_bc_base[f];
17497 pdf_font_kn_ac_base[k] := pdf_font_kn_ac_base[f];
17498 end;
17499
17500 function tfm_lookup(s: str_number; fs: scaled): internal_font_number;
17501 {looks up for a TFM with name |s| loaded at |fs| size; if found then flushes |s|}
17502 var k: internal_font_number;
17503 begin
17504 if fs <> 0 then begin
17505 for k := font_base + 1 to font_ptr do
17506 if (font_area[k] <> non_existent_path) and
17507 str_eq_str(font_name[k], s) and
17508 (font_size[k] = fs) then
17509 begin
17510 flush_str(s);
17511 tfm_lookup := k;
17512 return;
17513 end;
17514 end
17515 else begin
17516 for k := font_base + 1 to font_ptr do
17517 if (font_area[k] <> non_existent_path) and
17518 str_eq_str(font_name[k], s) then
17519 begin
17520 flush_str(s);
17521 tfm_lookup := k;
17522 return;
17523 end;
17524 end;
17525 tfm_lookup := null_font;
17526 end;
17527
17528 function load_expand_font(f: internal_font_number; e: integer): internal_font_number;
17529 {loads font |f| expanded by |e| thousandths into font memory; |e| is nonzero
17530 and is a multiple of |pdf_font_step[f]|}
17531 label found;
17532 var s: str_number; {font name}
17533 k: internal_font_number;
17534 begin
17535 s := expand_font_name(f, e);
17536 k := tfm_lookup(s, font_size[f]);
17537 if k = null_font then begin
17538 if pdf_font_auto_expand[f] then
17539 k := auto_expand_font(f, e)
17540 else
17541 k := read_font_info(null_cs, s, "", font_size[f]);
17542 end;
17543 if k <> null_font then
17544 copy_expand_params(k, f, e);
17545 load_expand_font := k;
17546 end;
17547
17548 function fix_expand_value(f: internal_font_number; e: integer): integer;
17549 {return the multiple of |pdf_font_step[f]| that is nearest to |e|}
17550 var step: integer;
17551 max_expand: integer;
17552 neg: boolean;
17553 begin
17554 fix_expand_value := 0;
17555 if e = 0 then
17556 return;
17557 if e < 0 then begin
17558 e := -e;
17559 neg := true;
17560 max_expand := -pdf_font_expand_ratio[pdf_font_shrink[f]];
17561 end
17562 else begin
17563 neg := false;
17564 max_expand := pdf_font_expand_ratio[pdf_font_stretch[f]];
17565 end;
17566 if e > max_expand then
17567 e := max_expand
17568 else begin
17569 step := pdf_font_step[f];
17570 if e mod step > 0 then
17571 e := step*round_xn_over_d(e, 1, step);
17572 end;
17573 if neg then
17574 e := -e;
17575 fix_expand_value := e;
17576 end;
17577
17578 function get_expand_font(f: internal_font_number; e: integer): internal_font_number;
17579 {look up and create if not found an expanded version of |f|; |f| is an
17580 expandable font; |e| is nonzero and is a multiple of |pdf_font_step[f]|}
17581 var k: internal_font_number;
17582 begin
17583 k := pdf_font_elink[f];
17584 while k <> null_font do begin
17585 if pdf_font_expand_ratio[k] = e then begin
17586 get_expand_font := k;
17587 return;
17588 end;
17589 k := pdf_font_elink[k];
17590 end;
17591 k := load_expand_font(f, e);
17592 pdf_font_elink[k] := pdf_font_elink[f];
17593 pdf_font_elink[f] := k;
17594 get_expand_font := k;
17595 end;
17596
17597 function expand_font(f: internal_font_number; e: integer): internal_font_number;
17598 {looks up for font |f| expanded by |e| thousandths, |e| is an arbitrary value
17599 between max stretch and max shrink of |f|; if not found then creates it}
17600 begin
17601 expand_font := f;
17602 if e = 0 then
17603 return;
17604 e := fix_expand_value(f, e);
17605 if e = 0 then
17606 return;
17607 if pdf_font_elink[f] = null_font then
17608 pdf_error("font expansion", "uninitialized pdf_font_elink");
17609 expand_font := get_expand_font(f, e);
17610 end;
17611
17612 procedure set_expand_params(f: internal_font_number; auto_expand: boolean;
17613 stretch_limit, shrink_limit, font_step, expand_ratio: integer);
17614 {expand a font with given parameters}
17615 begin
17616 pdf_font_step[f] := font_step;
17617 pdf_font_auto_expand[f] := auto_expand;
17618 if stretch_limit > 0 then
17619 pdf_font_stretch[f] := get_expand_font(f, stretch_limit);
17620 if shrink_limit > 0 then
17621 pdf_font_shrink[f] := get_expand_font(f, -shrink_limit);
17622 if expand_ratio <> 0 then
17623 pdf_font_expand_ratio[f] := expand_ratio;
17624 end;
17625
17626 procedure vf_expand_local_fonts(f: internal_font_number);
17627 var lf: internal_font_number;
17628 k: integer;
17629 begin
17630 pdfassert(pdf_font_type[f] = virtual_font_type);
17631 for k := 0 to vf_local_font_num[f] - 1 do begin
17632 lf := vf_i_fnts[vf_default_font[f] + k];
17633 set_expand_params(lf, pdf_font_auto_expand[f],
17634 pdf_font_expand_ratio[pdf_font_stretch[f]],
17635 -pdf_font_expand_ratio[pdf_font_shrink[f]],
17636 pdf_font_step[f], pdf_font_expand_ratio[f]);
17637 if pdf_font_type[lf] = virtual_font_type then
17638 vf_expand_local_fonts(lf);
17639 end;
17640 end;
17641
17642 procedure read_expand_font; {read font expansion spec and load expanded font}
17643 var shrink_limit, stretch_limit, font_step: integer;
17644 f: internal_font_number;
17645 auto_expand: boolean;
17646 begin
17647 {read font expansion parameters}
17648 scan_font_ident;
17649 f := cur_val;
17650 if f = null_font then
17651 pdf_error("font expansion", "invalid font identifier");
17652 if pdf_font_blink[f] <> null_font then
17653 pdf_error("font expansion", "\pdffontexpand cannot be used this way (the base font has been expanded)");
17654 scan_optional_equals;
17655 scan_int;
17656 stretch_limit := fix_int(cur_val, 0, 1000);
17657 scan_int;
17658 shrink_limit := fix_int(cur_val, 0, 500);
17659 scan_int;
17660 font_step := fix_int(cur_val, 0, 100);
17661 if font_step = 0 then
17662 pdf_error("font expansion", "invalid step");
17663 stretch_limit := stretch_limit - stretch_limit mod font_step;
17664 if stretch_limit < 0 then
17665 stretch_limit := 0;
17666 shrink_limit := shrink_limit - shrink_limit mod font_step;
17667 if shrink_limit < 0 then
17668 shrink_limit := 0;
17669 if (stretch_limit = 0) and (shrink_limit = 0) then
17670 pdf_error("font expansion", "invalid limit(s)");
17671 auto_expand := false;
17672 if scan_keyword("autoexpand") then begin
17673 auto_expand := true;
17674 @<Scan an optional space@>;
17675 end;
17676
17677 {check if the font can be expanded}
17678 if (pdf_font_expand_ratio[f] <> 0) then
17679 pdf_error("font expansion", "this font has been expanded by another font so it cannot be used now");
17680 if (pdf_font_step[f] <> 0) then
17681 {this font has been expanded, ensure the expansion parameters are identical}
17682 begin
17683 if pdf_font_step[f] <> font_step then
17684 pdf_error("font expansion", "font has been expanded with different expansion step");
17685
17686 if ((pdf_font_stretch[f] = null_font) and (stretch_limit <> 0)) or
17687 ((pdf_font_stretch[f] <> null_font) and
17688 (pdf_font_expand_ratio[pdf_font_stretch[f]] <> stretch_limit)) then
17689 pdf_error("font expansion", "font has been expanded with different stretch limit");
17690
17691 if ((pdf_font_shrink[f] = null_font) and (shrink_limit <> 0)) or
17692 ((pdf_font_shrink[f] <> null_font) and
17693 (-pdf_font_expand_ratio[pdf_font_shrink[f]] <> shrink_limit)) then
17694 pdf_error("font expansion", "font has been expanded with different shrink limit");
17695
17696 if pdf_font_auto_expand[f] <> auto_expand then
17697 pdf_error("font expansion", "font has been expanded with different auto expansion value");
17698 end
17699 else begin
17700 if (pdf_font_type[f] <> new_font_type) and (pdf_font_type[f] <> virtual_font_type) then
17701 pdf_warning("font expansion", "font should be expanded before its first use", true, true);
17702 set_expand_params(f, auto_expand, stretch_limit, shrink_limit, font_step, 0);
17703 if pdf_font_type[f] = virtual_font_type then
17704 vf_expand_local_fonts(f);
17705 end;
17706 end;
17707
17708 @ We implement robust letter spacing using virtual font.
17709
17710 @d vf_replace_z ==
17711 begin
17712 vf_alpha:=16;
17713 while vf_z>=@'40000000 do begin
17714 vf_z:=vf_z div 2;
17715 vf_alpha:=vf_alpha+vf_alpha;
17716 end;
17717 vf_beta:=256 div vf_alpha;
17718 vf_alpha:=vf_alpha*vf_z;
17719 end
17720
17721 @p
17722 function letter_space_font(u: pointer; f: internal_font_number; e: integer): internal_font_number;
17723 var k: internal_font_number;
17724 w, r: scaled;
17725 s: str_number;
17726 i, nw: integer;
17727 old_setting:0..max_selector;
17728 vf_z: integer;
17729 vf_alpha: integer;
17730 vf_beta: 1..16;
17731 begin
17732 {read a new font and expand the character widths}
17733 k := read_font_info(u, font_name[f], "", font_size[f]);
17734 if scan_keyword("nolig") then
17735 set_no_ligatures(k); {disable ligatures for letter-spaced fonts}
17736 nw := height_base[k] - width_base[k];
17737
17738 if (quad(k) = 0) and (quad(f) > 0) then
17739 quad(k) := quad(f);
17740 if quad(k) = 0 then
17741 pdf_warning("\letterspacefont", "font has zero em size (\fontdimen6)", true, true);
17742
17743 for i := 0 to nw - 1 do
17744 font_info[width_base[k] + i].sc :=
17745 font_info[width_base[k] + i].sc + round_xn_over_d(quad(k), e, 1000);
17746
17747 {append, e.g., '+100ls' to font name}
17748 str_room(length(font_name[k]) + 7); {|abs(e) <= 1000|}
17749 old_setting := selector;
17750 selector := new_string;
17751 print(font_name[k]);
17752 if e > 0 then
17753 print("+"); {minus sign will be printed by |print_int|}
17754 print_int(e);
17755 print("ls");
17756 selector := old_setting;
17757 font_name[k] := make_string;
17758
17759 {create the corresponding virtual font}
17760 allocvffnts;
17761 vf_e_fnts[vf_nf] := 0;
17762 vf_i_fnts[vf_nf] := f;
17763 incr(vf_nf);
17764 vf_local_font_num[k] := 1;
17765 vf_default_font[k] := vf_nf - 1;
17766 pdf_font_type[k] := virtual_font_type;
17767
17768 vf_z := font_size[f];
17769 vf_replace_z;
17770 w := round_xn_over_d(quad(f), e, 2000);
17771 if w >= 0 then
17772 tmp_b0 := 0
17773 else begin
17774 tmp_b0 := 255;
17775 w := vf_alpha + w;
17776 end;
17777 r := w*vf_beta;
17778 tmp_b1 := r div vf_z;
17779 r := r mod vf_z;
17780 if r = 0 then
17781 tmp_b2 := 0
17782 else begin
17783 r := r * 256;
17784 tmp_b2 := r div vf_z;
17785 r := r mod vf_z;
17786 end;
17787 if r = 0 then
17788 tmp_b3 := 0
17789 else begin
17790 r := r * 256;
17791 tmp_b3 := r div vf_z;
17792 end;
17793 vf_packet_base[k] := new_vf_packet(k);
17794 for c := font_bc[k] to font_ec[k] do begin
17795 str_room(12);
17796 append_char(right1 + 3);
17797 append_char(tmp_b0);
17798 append_char(tmp_b1);
17799 append_char(tmp_b2);
17800 append_char(tmp_b3);
17801 if c < set1 then
17802 append_char(c)
17803 else begin
17804 append_char(set1);
17805 append_char(c);
17806 end;
17807 append_char(right1 + 3);
17808 append_char(tmp_b0);
17809 append_char(tmp_b1);
17810 append_char(tmp_b2);
17811 append_char(tmp_b3);
17812 s := make_string;
17813 storepacket(k, c, s);
17814 flush_str(s);
17815 end;
17816 letter_space_font := k;
17817 end;
17818
17819 procedure new_letterspaced_font(a: small_number);
17820 {letter-space a font by creating a virtual font}
17821 var u:pointer; {user's font identifier}
17822 @!t:str_number; {name for the frozen font identifier}
17823 @!old_setting:0..max_selector; {holds |selector| setting}
17824 @!f, k:internal_font_number;
17825 begin
17826 get_r_token; u:=cur_cs;
17827 if u>=hash_base then t:=text(u)
17828 else if u>=single_base then
17829 if u=null_cs then t:="FONT"@+else t:=u-single_base
17830 else begin old_setting:=selector; selector:=new_string;
17831 print("FONT"); print(u-active_base); selector:=old_setting;
17832 @.FONTx@>
17833 str_room(1); t:=make_string;
17834 end;
17835 define(u,set_font,null_font); scan_optional_equals; scan_font_ident;
17836 k := cur_val;
17837 scan_int;
17838 f := letter_space_font(u, k, fix_int(cur_val, -1000, 1000));
17839 equiv(u):=f; eqtb[font_id_base+f]:=eqtb[u]; font_id_text(f):=t;
17840 end;
17841
17842 function is_letterspaced_font(f: internal_font_number): boolean;
17843 label done;
17844 var i, j: pool_pointer;
17845 begin
17846 is_letterspaced_font := false;
17847 if pdf_font_type[f] <> virtual_font_type then
17848 return;
17849 i := str_start[font_name[f] + 1] - 1;
17850 j := str_start[font_name[f]];
17851 if (str_pool[i - 1] <> 'l') or (str_pool[i] <> 's') then
17852 return;
17853 i := i - 2;
17854 while i >= j do begin
17855 if (str_pool[i] < '0') or (str_pool[i] > '9') then
17856 goto done;
17857 i := i - 1;
17858 end;
17859 done:
17860 if i < j then
17861 return;
17862 if (str_pool[i] <> '+') and (str_pool[i] <> '-') then
17863 return;
17864 is_letterspaced_font := true;
17865 end;
17866
17867 function copy_font_info(f: internal_font_number): internal_font_number;
17868 {create a copy of |f| in the font mem}
17869 var lf, bc, ec, i: halfword;
17870 k: internal_font_number;
17871 begin
17872 if (pdf_font_expand_ratio[f] <> 0) or (pdf_font_step[f] <> 0) then
17873 pdf_error("\pdfcopyfont", "cannot copy an expanded font");
17874 if is_letterspaced_font(f) then
17875 pdf_error("\pdfcopyfont", "cannot copy a letterspaced font");
17876
17877 k := font_ptr + 1;
17878 incr(font_ptr);
17879 if (font_ptr >= font_max) then
17880 overflow("maximum internal font number (font_max)", font_max);
17881 font_name[k] := font_name[f];
17882 font_area[k] := non_existent_path; {to avoid interferences with |new_font()| and |tfm_lookup()|}
17883 hyphen_char[k] := hyphen_char[f];
17884 skew_char[k] := skew_char[f];
17885 font_bchar[k] := font_bchar[f];
17886 font_false_bchar[k] := font_false_bchar[f];
17887 font_bc[k] := font_bc[f];
17888 font_ec[k] := font_ec[f];
17889 font_size[k] := font_size[f];
17890 font_dsize[k] := font_dsize[f];
17891 font_params[k] := font_params[f];
17892 font_glue[k] := font_glue[f];
17893 bchar_label[k] := bchar_label[f];
17894
17895 {set base addresses}
17896 bc := font_bc[f];
17897 ec := font_ec[f];
17898 char_base[k] := fmem_ptr - bc;
17899 width_base[k] := char_base[k] + ec + 1;
17900
17901 height_base[k] := width_base[k] + (height_base[f] - width_base[f]);
17902 depth_base[k] := height_base[k] + (depth_base[f] - height_base[f]);
17903 italic_base[k] := depth_base[k] + (italic_base[f] - depth_base[f]);
17904 lig_kern_base[k] := italic_base[k] + (lig_kern_base[f] - italic_base[f]);
17905 kern_base[k] := lig_kern_base[k] + (kern_base[f] - lig_kern_base[f]);
17906 exten_base[k] := kern_base[k] + (exten_base[f] - kern_base[f]);
17907 param_base[k] := exten_base[k] + (param_base[f] - exten_base[f]);
17908
17909 {allocate memory for the new font |k| and copy data from |f|}
17910 lf := (param_base[f] - char_base[f]) + font_params[f] + 1;
17911 if (fmem_ptr + lf >= font_mem_size) then
17912 overflow("number of words of font memory (font_mem_size)", font_mem_size);
17913 for i := 0 to lf - 1 do
17914 font_info[char_base[k] + bc + i] := font_info[char_base[f] + bc + i];
17915 fmem_ptr := fmem_ptr + lf;
17916
17917 copy_font_info := k;
17918 end;
17919
17920 procedure make_font_copy(a: small_number);
17921 {make a font copy for further use with font expansion}
17922 var u:pointer; {user's font identifier}
17923 @!t:str_number; {name for the frozen font identifier}
17924 @!old_setting:0..max_selector; {holds |selector| setting}
17925 @!f, k:internal_font_number;
17926 begin
17927 get_r_token; u:=cur_cs;
17928 if u>=hash_base then t:=text(u)
17929 else if u>=single_base then
17930 if u=null_cs then t:="FONT"@+else t:=u-single_base
17931 else begin old_setting:=selector; selector:=new_string;
17932 print("FONT"); print(u-active_base); selector:=old_setting;
17933 @.FONTx@>
17934 str_room(1); t:=make_string;
17935 end;
17936 define(u,set_font,null_font); scan_optional_equals; scan_font_ident;
17937 k := cur_val;
17938 f := copy_font_info(k);
17939 equiv(u):=f; eqtb[font_id_base+f]:=eqtb[u]; font_id_text(f):=t;
17940 end;
17941
17942 @ We need to hold information about used characters in each font for partial
17943 downloading.
17944
17945 @<Types...@>=
17946 char_used_array = array[0..31] of eight_bits;
17947 char_map_array = array[0..32] of eight_bits; {move chars in range 0..32}
17948 fm_entry_ptr = ^integer;
17949
17950 @ @<Glob...@>=
17951 @!pdf_char_used: ^char_used_array; {to mark used chars}
17952 @!pdf_font_size: ^scaled; {used size of font in PDF file}
17953 @!pdf_font_num: ^integer; {mapping between internal font number in \TeX\ and
17954 font name defined in resources in PDF file}
17955 @!pdf_font_map: ^fm_entry_ptr; {pointer into AVL tree of font mappings}
17956 @!pdf_font_list: pointer; {list of used fonts in current page}
17957 @!pdf_resname_prefix: str_number; {global prefix of resources name}
17958 @!last_tokens_string: str_number; {the number of the most recently string
17959 created by |tokens_to_string|}
17960
17961 @ @<Set init...@>=
17962 pdf_resname_prefix := 0;
17963 last_tokens_string := 0;
17964
17965 @ Here we implement reading information from \.{VF} file.
17966
17967 @d vf_max_packet_length = 10000 {max length of character packet in \.{VF} file}
17968 @#
17969 @d do_char = 70 {label to go to typesetting a character of virtual font}
17970 @#
17971 @d long_char = 242 {\.{VF} command for general character packet}
17972 @d vf_id = 202 {identifies \.{VF} files}
17973 @d put1=133 {typeset a character}
17974 @d four_cases(#) == #,#+1,#+2,#+3
17975 @#
17976 @d tmp_b0 == tmp_w.qqqq.b0
17977 @d tmp_b1 == tmp_w.qqqq.b1
17978 @d tmp_b2 == tmp_w.qqqq.b2
17979 @d tmp_b3 == tmp_w.qqqq.b3
17980 @d tmp_int == tmp_w.int
17981 @#
17982 @d bad_vf(#) == vf_error(font_name[f], #) {quit with an error message telling the vf filename}
17983
17984 @<Glob...@>=
17985 @!vf_packet_base: ^integer; {base addresses of character packets from virtual fonts}
17986 @!vf_default_font: ^internal_font_number; {default font in a \.{VF} file}
17987 @!vf_local_font_num: ^internal_font_number; {number of local fonts in a \.{VF} file}
17988 @!vf_packet_length: integer; {length of the current packet}
17989 @!vf_file: byte_file;
17990 @!vf_nf: internal_font_number; {the local fonts counter}
17991 @!vf_e_fnts: ^integer; {external font numbers}
17992 @!vf_i_fnts: ^internal_font_number; {corresponding internal font numbers}
17993 @!tmp_w: memory_word; {accumulator}
17994
17995 @ @<Set init...@>=
17996 vf_nf := 0;
17997
17998 @ The |do_vf| procedure attempts to read the \.{VF} file for a font, and sets
17999 |pdf_font_type| to |real_font_type| if the \.{VF} file could not be found
18000 or loaded, otherwise sets |pdf_font_type| to |virtual_font_type|. To
18001 process font definitions in virtual font we call |vf_def_font|.
18002
18003 @p
18004 procedure vf_error(filename, msg: str_number);
18005 var old_setting:0..max_selector; {holds print |selector|}
18006 s: str_number;
18007 begin
18008 str_room(length(filename) + 3);
18009 old_setting:=selector; selector:=new_string;
18010 print(filename);
18011 print(".vf");
18012 s := make_string;
18013 selector:=old_setting;
18014 pdf_error(s, msg);
18015 end;
18016
18017 function vf_byte: eight_bits; {read a byte from |vf_file|}
18018 var i: integer;
18019 begin
18020 i := getc(vf_file);
18021 if i < 0 then
18022 pdf_error("vf", "unexpected EOF or error");
18023 vf_byte := i;
18024 end;
18025
18026 function vf_read_signed(k: integer): integer;
18027 {read |k| bytes as an signed integer from \.{VF} file}
18028 var i: integer;
18029 begin
18030 pdfassert((k > 0) and (k <= 4));
18031 i := vf_byte;
18032 if i >= 128 then
18033 i := i - 256;
18034 decr(k);
18035 while k > 0 do begin
18036 i := i*256 + vf_byte;
18037 decr(k);
18038 end;
18039 vf_read_signed := i;
18040 end;
18041
18042 function vf_read_unsigned(k: integer): integer;
18043 {read |k| bytes as an unsigned integer from \.{VF} file}
18044 var i: integer;
18045 begin
18046 pdfassert((k > 0) and (k <= 4));
18047 i := vf_byte;
18048 if (k = 4) and (i >= 128) then
18049 bad_vf("number too big");
18050 decr(k);
18051 while k > 0 do begin
18052 i := i*256 + vf_byte;
18053 decr(k);
18054 end;
18055 vf_read_unsigned := i;
18056 end;
18057
18058 procedure vf_local_font_warning(f, k: internal_font_number; s: str_number);
18059 {print a warning message if an error occurs during processing local fonts in
18060 \.{VF} file}
18061 begin
18062 print_nl(s);
18063 print(" in local font ");
18064 print(font_name[k]);
18065 print(" in virtual font ");
18066 print(font_name[f]);
18067 print(".vf ignored.");
18068 end;
18069
18070 function vf_def_font(f: internal_font_number): internal_font_number;
18071 {process a local font in \.{VF} file}
18072 var k: internal_font_number;
18073 s: str_number;
18074 ds, fs: scaled;
18075 cs: four_quarters;
18076 begin
18077 cs.b0 := vf_byte; cs.b1 := vf_byte; cs.b2 := vf_byte; cs.b3 := vf_byte;
18078 fs := store_scaled_f(vf_read_signed(4), font_size[f]);
18079 ds := vf_read_signed(4) div @'20;
18080 tmp_b0 := vf_byte;
18081 tmp_b1 := vf_byte;
18082 while tmp_b0 > 0 do begin
18083 decr(tmp_b0);
18084 call_func(vf_byte); {skip the font path}
18085 end;
18086 str_room(tmp_b1);
18087 while tmp_b1 > 0 do begin
18088 decr(tmp_b1);
18089 append_char(vf_byte);
18090 end;
18091 s := make_string;
18092 k := tfm_lookup(s, fs);
18093 if k = null_font then
18094 k := read_font_info(null_cs, s, "", fs);
18095 if k <> null_font then begin
18096 if ((cs.b0 <> 0) or (cs.b1 <> 0) or (cs.b2 <> 0) or (cs.b3 <> 0)) and
18097 ((font_check[k].b0 <> 0) or (font_check[k].b1 <> 0) or
18098 (font_check[k].b2 <> 0) or (font_check[k].b3 <> 0)) and
18099 ((cs.b0 <> font_check[k].b0) or (cs.b1 <> font_check[k].b1) or
18100 (cs.b2 <> font_check[k].b2) or (cs.b3 <> font_check[k].b3)) then
18101 vf_local_font_warning(f, k, "checksum mismatch");
18102 if ds <> font_dsize[k] then
18103 vf_local_font_warning(f, k, "design size mismatch");
18104 if (pdf_font_step[f] <> 0) then
18105 set_expand_params(k, pdf_font_auto_expand[f],
18106 pdf_font_expand_ratio[pdf_font_stretch[f]],
18107 -pdf_font_expand_ratio[pdf_font_shrink[f]],
18108 pdf_font_step[f], pdf_font_expand_ratio[f]);
18109 end;
18110 vf_def_font := k;
18111 end;
18112
18113 procedure do_vf(f: internal_font_number); {process \.{VF} file with font internal number |f|}
18114 var cmd, k, n: integer;
18115 cc, cmd_length, packet_length: integer;
18116 tfm_width: scaled;
18117 s: str_number;
18118 stack_level: vf_stack_index;
18119 save_vf_nf: internal_font_number;
18120 begin
18121 pdf_font_type[f] := real_font_type;
18122 if auto_expand_vf(f) then
18123 return; {auto-expanded virtual font}
18124 stack_level := 0;
18125 @<Open |vf_file|, return if not found@>;
18126 @<Process the preamble@>;@/
18127 @<Process the font definitions@>;@/
18128 @<Allocate memory for the new virtual font@>;@/
18129 while cmd <= long_char do begin@/
18130 @<Build a character packet@>;@/
18131 end;
18132 if cmd <> post then
18133 bad_vf("POST command expected");
18134 b_close(vf_file);
18135 pdf_font_type[f] := virtual_font_type;
18136 end;
18137
18138 @ @<Open |vf_file|, return if not found@>=
18139 pack_file_name(font_name[f], "", ".vf");
18140 if not vf_b_open_in(vf_file) then
18141 return
18142
18143 @ @<Process the preamble@>=
18144 if vf_byte <> pre then
18145 bad_vf("PRE command expected");
18146 if vf_byte <> vf_id then
18147 bad_vf("wrong id byte");
18148 cmd_length := vf_byte;
18149 for k := 1 to cmd_length do
18150 call_func(vf_byte); {skip the comment}
18151 tmp_b0 := vf_byte; tmp_b1 := vf_byte; tmp_b2 := vf_byte; tmp_b3 := vf_byte;
18152 if ((tmp_b0 <> 0) or (tmp_b1 <> 0) or (tmp_b2 <> 0) or (tmp_b3 <> 0)) and
18153 ((font_check[f].b0 <> 0) or (font_check[f].b1 <> 0) or
18154 (font_check[f].b2 <> 0) or (font_check[f].b3 <> 0)) and
18155 ((tmp_b0 <> font_check[f].b0) or (tmp_b1 <> font_check[f].b1) or
18156 (tmp_b2 <> font_check[f].b2) or (tmp_b3 <> font_check[f].b3)) then begin
18157 print_nl("checksum mismatch in font ");
18158 print(font_name[f]);
18159 print(".vf ignored");
18160 end;
18161 if vf_read_signed(4) div @'20 <> font_dsize[f] then begin
18162 print_nl("design size mismatch in font ");
18163 print(font_name[f]);
18164 print(".vf ignored");
18165 end;
18166 update_terminal
18167
18168 @ @<Process the font definitions@>=
18169 cmd := vf_byte;
18170 save_vf_nf := vf_nf;
18171 while (cmd >= fnt_def1) and (cmd <= fnt_def1 + 3) do begin
18172 allocvffnts;
18173 vf_e_fnts[vf_nf] := vf_read_unsigned(cmd - fnt_def1 + 1);
18174 vf_i_fnts[vf_nf] := vf_def_font(f);
18175 incr(vf_nf);
18176 cmd := vf_byte;
18177 end;
18178 vf_default_font[f] := save_vf_nf;
18179 vf_local_font_num[f] := vf_nf - save_vf_nf;
18180
18181 @ @<Allocate memory for the new virtual font@>=
18182 vf_packet_base[f] := new_vf_packet(f)
18183
18184 @ @<Build a character packet@>=
18185 if cmd = long_char then begin
18186 packet_length := vf_read_unsigned(4);
18187 cc := vf_read_unsigned(4);
18188 if not is_valid_char(cc) then
18189 bad_vf("invalid character code");
18190 tfm_width := store_scaled_f(vf_read_signed(4), font_size[f]);
18191 end
18192 else begin
18193 packet_length := cmd;
18194 cc := vf_byte;
18195 if not is_valid_char(cc) then
18196 bad_vf("invalid character code");
18197 tfm_width := store_scaled_f(vf_read_unsigned(3), font_size[f]);
18198 end;
18199 if packet_length < 0 then
18200 bad_vf("negative packet length");
18201 if packet_length > vf_max_packet_length then
18202 bad_vf("packet length too long");
18203 if tfm_width <> char_width(f)(char_info(f)(cc)) then begin
18204 print_nl("character width mismatch in font ");
18205 print(font_name[f]);
18206 print(".vf ignored");
18207 end;
18208 str_room(packet_length);
18209 while packet_length > 0 do begin
18210 cmd := vf_byte;
18211 decr(packet_length);
18212 @<Cases of \.{DVI} commands that can appear in character packet@>;
18213 if cmd <> nop then
18214 append_char(cmd);
18215 packet_length := packet_length - cmd_length;
18216 while cmd_length > 0 do begin
18217 decr(cmd_length);
18218 append_char(vf_byte);
18219 end;
18220 end;
18221 if stack_level <> 0 then
18222 bad_vf("more PUSHs than POPs in character packet");
18223 if packet_length <> 0 then
18224 bad_vf("invalid packet length or DVI command in packet");
18225 @<Store the packet being built@>;
18226 cmd := vf_byte
18227
18228 @ @<Store the packet being built@>=
18229 s := make_string;
18230 storepacket(f, cc, s);
18231 flush_str(s)
18232
18233 @ @<Cases of \.{DVI} commands that can appear in character packet@>=
18234 if (cmd >= set_char_0) and (cmd <= set_char_0 + 127) then
18235 cmd_length := 0
18236 else if ((fnt_num_0 <= cmd) and (cmd <= fnt_num_0 + 63)) or
18237 ((fnt1 <= cmd) and (cmd <= fnt1 + 3)) then begin
18238 if cmd >= fnt1 then begin
18239 k := vf_read_unsigned(cmd - fnt1 + 1);
18240 packet_length := packet_length - (cmd - fnt1 + 1);
18241 end
18242 else
18243 k := cmd - fnt_num_0;
18244 if k >= 256 then
18245 bad_vf("too many local fonts");
18246 n := 0;
18247 while (n < vf_local_font_num[f]) and
18248 (vf_e_fnts[vf_default_font[f] + n] <> k) do
18249 incr(n);
18250 if n = vf_local_font_num[f] then
18251 bad_vf("undefined local font");
18252 if k <= 63 then
18253 append_char(fnt_num_0 + k)
18254 else begin
18255 append_char(fnt1);
18256 append_char(k);
18257 end;
18258 cmd_length := 0;
18259 cmd := nop;
18260 end
18261 else case cmd of
18262 set_rule, put_rule: cmd_length := 8;
18263 four_cases(set1): cmd_length := cmd - set1 + 1;
18264 four_cases(put1): cmd_length := cmd - put1 + 1;
18265 four_cases(right1): cmd_length := cmd - right1 + 1;
18266 four_cases(w1): cmd_length := cmd - w1 + 1;
18267 four_cases(x1): cmd_length := cmd - x1 + 1;
18268 four_cases(down1): cmd_length := cmd - down1 + 1;
18269 four_cases(y1): cmd_length := cmd - y1 + 1;
18270 four_cases(z1): cmd_length := cmd - z1 + 1;
18271 four_cases(xxx1): begin
18272 cmd_length := vf_read_unsigned(cmd - xxx1 + 1);
18273 packet_length := packet_length - (cmd - xxx1 + 1);
18274 if cmd_length > vf_max_packet_length then
18275 bad_vf("packet length too long");
18276 if cmd_length < 0 then
18277 bad_vf("string of negative length");
18278 append_char(xxx1);
18279 append_char(cmd_length);
18280 cmd := nop; {|cmd| has been already stored above as |xxx1|}
18281 end;
18282 w0, x0, y0, z0, nop:
18283 cmd_length := 0;
18284 push, pop: begin
18285 cmd_length := 0;
18286 if cmd = push then
18287 if stack_level = vf_stack_size then
18288 overflow("virtual font stack size", vf_stack_size)
18289 else
18290 incr(stack_level)
18291 else
18292 if stack_level = 0 then
18293 bad_vf("more POPs than PUSHs in character")
18294 else
18295 decr(stack_level);
18296 end;
18297 othercases
18298 bad_vf("improver DVI command");
18299 endcases
18300
18301 @ @p
18302 procedure pdf_check_vf_cur_val;
18303 var f: internal_font_number;
18304 begin
18305 f := cur_val;
18306 do_vf(f);
18307 if pdf_font_type[f] = virtual_font_type then
18308 pdf_error("font", "command cannot be used with virtual font");
18309 end;
18310
18311 function auto_expand_vf(f: internal_font_number): boolean;
18312 {check for a virtual auto-expanded font}
18313 var bf, lf: internal_font_number;
18314 e, k: integer;
18315 begin
18316 auto_expand_vf := false;
18317 if (not pdf_font_auto_expand[f]) or (pdf_font_blink[f] = null_font) then
18318 return; {not an auto-expanded font}
18319 bf := pdf_font_blink[f];
18320 if pdf_font_type[bf] = new_font_type then {we must process the base font first}
18321 do_vf(bf);
18322 if pdf_font_type[bf] <> virtual_font_type then
18323 return; {not a virtual font}
18324
18325 e := pdf_font_expand_ratio[f];
18326 for k := 0 to vf_local_font_num[bf] - 1 do begin
18327 lf := vf_default_font[bf] + k;
18328 allocvffnts;
18329 {copy vf local font numbers:}
18330 vf_e_fnts[vf_nf] := vf_e_fnts[lf];
18331 {definition of local vf fonts are expanded from base fonts:}
18332 vf_i_fnts[vf_nf] := auto_expand_font(vf_i_fnts[lf], e);
18333 copy_expand_params(vf_i_fnts[vf_nf], vf_i_fnts[lf], e);
18334 incr(vf_nf);
18335 end;
18336 vf_packet_base[f] := vf_packet_base[bf];
18337 vf_local_font_num[f] := vf_local_font_num[bf];
18338 vf_default_font[f] := vf_nf - vf_local_font_num[f];
18339
18340 pdf_font_type[f] := virtual_font_type;
18341 auto_expand_vf := true;
18342 end;
18343
18344 @ The |do_vf_packet| procedure is called in order to interpret the
18345 character packet for a virtual character. Such a packet may contain the
18346 instruction to typeset a character from the same or an other virtual
18347 font; in such cases |do_vf_packet| calls itself recursively. The
18348 recursion level, i.e., the number of times this has happened, is kept
18349 in the global variable |vf_cur_s| and should not exceed |vf_max_recursion|.
18350
18351 @<Constants...@>=
18352 @!vf_max_recursion=10; {\.{VF} files shouldn't recurse beyond this level}
18353 @!vf_stack_size=100; {\.{DVI} files shouldn't |push| beyond this depth}
18354
18355 @ @<Types...@>=
18356 @!vf_stack_index=0..vf_stack_size; {an index into the stack}
18357 @!vf_stack_record=record
18358 stack_h, stack_v, stack_w, stack_x, stack_y, stack_z: scaled;
18359 end;
18360
18361 @ @<Glob...@>=
18362 @!vf_cur_s: 0..vf_max_recursion; {current recursion level}
18363 @!vf_stack: array [vf_stack_index] of vf_stack_record;
18364 @!vf_stack_ptr: vf_stack_index; {pointer into |vf_stack|}
18365
18366 @ @<Set init...@>=
18367 vf_cur_s := 0;
18368 vf_stack_ptr := 0;
18369
18370 @ Some functions for processing character packets.
18371
18372 @p function packet_read_signed(k: integer): integer;
18373 {read |k| bytes as a signed integer from character packet}
18374 var i: integer;
18375 begin
18376 pdfassert((k > 0) and (k <= 4));
18377 i := packet_byte;
18378 if i >= 128 then
18379 i := i - 256;
18380 decr(k);
18381 while k > 0 do begin
18382 i := i*256 + packet_byte;
18383 decr(k);
18384 end;
18385 packet_read_signed := i;
18386 end;
18387
18388 function packet_read_unsigned(k: integer): integer;
18389 {read |k| bytes as an unsigned integer from character packet}
18390 var i: integer;
18391 begin
18392 pdfassert((k > 0) and (k <= 4));
18393 i := packet_byte;
18394 if (k = 4) and (i >= 128) then
18395 bad_vf("number too big");
18396 decr(k);
18397 while k > 0 do begin
18398 i := i*256 + packet_byte;
18399 decr(k);
18400 end;
18401 packet_read_unsigned := i;
18402 end;
18403
18404 function packet_scaled(k: integer; fs: scaled): scaled;
18405 {get |k| bytes from packet as scaled}
18406 begin
18407 packet_scaled := store_scaled_f(packet_read_signed(k), fs);
18408 end;
18409
18410 procedure do_vf_packet(vf_f: internal_font_number; c: eight_bits); {typeset the
18411 \.{DVI} commands in the character packet for character |c| in current font |f|}
18412 label do_char, continue;
18413 var f, k, n: internal_font_number;
18414 save_cur_h, save_cur_v: scaled;
18415 cmd: integer;
18416 char_move: boolean;
18417 w, x, y, z: scaled;
18418 s: str_number;
18419 begin
18420 incr(vf_cur_s);
18421 if vf_cur_s > vf_max_recursion then
18422 overflow("max level recursion of virtual fonts", vf_max_recursion);
18423 save_cur_v := cur_v;
18424 save_cur_h := cur_h;
18425 push_packet_state; {save pointer and length of the current packet}
18426 start_packet(vf_f, c); {set pointer and length of the new packet}
18427 f := vf_i_fnts[vf_default_font[vf_f]];
18428 w := 0; x := 0; y := 0; z := 0;
18429 while vf_packet_length > 0 do begin
18430 cmd := packet_byte;
18431 @<Do typesetting the \.{DVI} commands in virtual character packet@>;
18432 continue:
18433 end;
18434 pop_packet_state; {restore pointer and length of the previous packet}
18435 cur_v := save_cur_v;
18436 cur_h := save_cur_h;
18437 decr(vf_cur_s);
18438 end;
18439
18440 @ The following code typesets a character to PDF output.
18441
18442 @d output_one_char(#) == begin
18443 if pdf_font_type[f] = new_font_type then
18444 do_vf(f);
18445 if pdf_font_type[f] = virtual_font_type then
18446 do_vf_packet(f, #)
18447 else begin
18448 pdf_begin_string(f);
18449 pdf_print_char(f, #);
18450 adv_char_width(f, #);
18451 end;
18452 end
18453
18454 @<Do typesetting the \.{DVI} commands in virtual character packet@>=
18455 if (cmd >= set_char_0) and (cmd <= set_char_0 + 127) then begin
18456 if not is_valid_char(cmd) then begin
18457 char_warning(f, cmd);
18458 goto continue;
18459 end;
18460 c := cmd;
18461 char_move := true;
18462 goto do_char;
18463 end
18464 else if ((fnt_num_0 <= cmd) and (cmd <= fnt_num_0 + 63)) or (cmd = fnt1) then begin
18465 if cmd = fnt1 then
18466 k := packet_byte
18467 else
18468 k := cmd - fnt_num_0;
18469 n := 0;
18470 while (n < vf_local_font_num[vf_f]) and
18471 (vf_e_fnts[vf_default_font[vf_f] + n] <> k) do
18472 incr(n);
18473 if (n = vf_local_font_num[vf_f]) then
18474 pdf_error("vf", "local font not found")
18475 else
18476 f := vf_i_fnts[vf_default_font[vf_f] + n];
18477 end
18478 else case cmd of
18479 push: begin
18480 vf_stack[vf_stack_ptr].stack_h := cur_h;
18481 vf_stack[vf_stack_ptr].stack_v := cur_v;
18482 vf_stack[vf_stack_ptr].stack_w := w;
18483 vf_stack[vf_stack_ptr].stack_x := x;
18484 vf_stack[vf_stack_ptr].stack_y := y;
18485 vf_stack[vf_stack_ptr].stack_z := z;
18486 incr(vf_stack_ptr);
18487 end;
18488 pop: begin
18489 decr(vf_stack_ptr);
18490 cur_h := vf_stack[vf_stack_ptr].stack_h;
18491 cur_v := vf_stack[vf_stack_ptr].stack_v;
18492 w := vf_stack[vf_stack_ptr].stack_w;
18493 x := vf_stack[vf_stack_ptr].stack_x;
18494 y := vf_stack[vf_stack_ptr].stack_y;
18495 z := vf_stack[vf_stack_ptr].stack_z;
18496 end;
18497 four_cases(set1), four_cases(put1): begin
18498 if (set1 <= cmd) and (cmd <= set1 + 3) then begin
18499 tmp_int := packet_read_unsigned(cmd - set1 + 1);
18500 char_move := true;
18501 end
18502 else begin
18503 tmp_int := packet_read_unsigned(cmd - put1 + 1);
18504 char_move := false;
18505 end;
18506 if not is_valid_char(tmp_int) then begin
18507 char_warning(f, tmp_int);
18508 goto continue;
18509 end;
18510 c := tmp_int;
18511 goto do_char;
18512 end;
18513 set_rule, put_rule: begin
18514 rule_ht := packet_scaled(4, font_size[vf_f]);
18515 rule_wd := packet_scaled(4, font_size[vf_f]);
18516 if (rule_wd > 0) and (rule_ht > 0) then begin
18517 pdf_set_rule(cur_h, cur_v, rule_wd, rule_ht);
18518 if cmd = set_rule then
18519 cur_h := cur_h + rule_wd;
18520 end;
18521 end;
18522 four_cases(right1):
18523 cur_h := cur_h + packet_scaled(cmd - right1 + 1, font_size[vf_f]);
18524 w0, four_cases(w1): begin
18525 if cmd > w0 then
18526 w := packet_scaled(cmd - w0, font_size[vf_f]);
18527 cur_h := cur_h + w;
18528 end;
18529 x0, four_cases(x1): begin
18530 if cmd > x0 then
18531 x := packet_scaled(cmd - x0, font_size[vf_f]);
18532 cur_h := cur_h + x;
18533 end;
18534 four_cases(down1):
18535 cur_v := cur_v + packet_scaled(cmd - down1 + 1, font_size[vf_f]);
18536 y0, four_cases(y1): begin
18537 if cmd > y0 then
18538 y := packet_scaled(cmd - y0, font_size[vf_f]);
18539 cur_v := cur_v + y;
18540 end;
18541 z0, four_cases(z1): begin
18542 if cmd > z0 then
18543 z := packet_scaled(cmd - z0, font_size[vf_f]);
18544 cur_v := cur_v + z;
18545 end;
18546 four_cases(xxx1): begin
18547 tmp_int := packet_read_unsigned(cmd - xxx1 + 1);
18548 str_room(tmp_int);
18549 while tmp_int > 0 do begin
18550 decr(tmp_int);
18551 append_char(packet_byte);
18552 end;
18553 s := make_string;
18554 literal(s, scan_special, false);
18555 flush_str(s);
18556 end;
18557 othercases pdf_error("vf", "invalid DVI command");
18558 endcases;
18559 goto continue;
18560 do_char:
18561 if is_valid_char(c) then
18562 output_one_char(c)
18563 else
18564 char_warning(f, c);
18565 if char_move then
18566 cur_h := cur_h + char_width(f)(char_info(f)(c))
18567
18568 @* \[32f] PDF shipping out.
18569 To ship out a \TeX\ box to PDF page description we need to implement
18570 |pdf_hlist_out|, |pdf_vlist_out| and |pdf_ship_out|, which are equivalent to
18571 the \TeX' original |hlist_out|, |vlist_out| and |ship_out| resp. But first we
18572 need to declare some procedures needed in |pdf_hlist_out| and |pdf_vlist_out|.
18573
18574 @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
18575 procedure pdf_out_literal(p:pointer);
18576 var old_setting:0..max_selector; {holds print |selector|}
18577 s: str_number;
18578 h: halfword;
18579 @!q,@!r:pointer; {temporary variables for list manipulation}
18580 @!old_mode:integer; {saved |mode|}
18581 begin
18582 old_setting:=selector;
18583 if subtype(p)=pdf_lateliteral_node then
18584 begin @<Expand macros in the token list
18585 and make |link(def_ref)| point to the result@>;
18586 h:=def_ref;
18587 end
18588 else h:=pdf_literal_data(p);
18589 selector:=new_string;
18590 show_token_list(link(h),null,pool_size-pool_ptr);
18591 selector:=old_setting;
18592 s := make_string;
18593 literal(s, pdf_literal_mode(p), false);
18594 flush_str(s);
18595 if subtype(p)=pdf_lateliteral_node then
18596 flush_list(def_ref);
18597 end;
18598
18599 procedure pdf_out_colorstack(p:pointer);
18600 var old_setting: 0..max_selector; {holds print |selector|}
18601 s: str_number;
18602 cmd: integer;
18603 stack_no: integer;
18604 literal_mode: integer;
18605 begin
18606 cmd := pdf_colorstack_cmd(p);
18607 stack_no := pdf_colorstack_stack(p);
18608 if stack_no >= colorstackused then begin
18609 print_nl("");
18610 print("Color stack ");
18611 print_int(stack_no);
18612 print(" is not initialized for use!");
18613 print_nl("");
18614 return;
18615 end;
18616 case cmd of
18617 colorstack_set, colorstack_push: begin
18618 old_setting:=selector; selector:=new_string;
18619 show_token_list(link(pdf_colorstack_data(p)),null,pool_size-pool_ptr);
18620 selector:=old_setting;
18621 s := make_string;
18622 if cmd = colorstack_set then
18623 literal_mode := colorstackset(stack_no, s)
18624 else
18625 literal_mode := colorstackpush(stack_no, s);
18626 if length(s) > 0 then
18627 literal(s, literal_mode, false);
18628 flush_str(s);
18629 return;
18630 end;
18631 colorstack_pop: literal_mode := colorstackpop(stack_no);
18632 colorstack_current: literal_mode := colorstackcurrent(stack_no);
18633 othercases confusion("pdfcolorstack")
18634 endcases;
18635 if cur_length > 0 then begin
18636 s := make_string;
18637 literal(s, literal_mode, false);
18638 flush_str(s);
18639 end
18640 end;
18641
18642 procedure pdf_out_colorstack_startpage;
18643 var i: integer;
18644 max: integer;
18645 start_status: integer;
18646 literal_mode: integer;
18647 s: str_number;
18648 begin
18649 i := 0;
18650 max := colorstackused;
18651 while i < max do begin
18652 start_status := colorstackskippagestart(i);
18653 if start_status = 0 then begin
18654 literal_mode := colorstackcurrent(i);
18655 if cur_length > 0 then begin
18656 s := make_string;
18657 literal(s, literal_mode, false);
18658 flush_str(s);
18659 end;
18660 end;
18661 incr(i);
18662 end;
18663 end;
18664
18665 procedure pdf_out_setmatrix(p:pointer);
18666 var old_setting:0..max_selector; {holds print |selector|}
18667 s: str_number;
18668 begin
18669 old_setting:=selector; selector:=new_string;
18670 show_token_list(link(pdf_setmatrix_data(p)),null,pool_size-pool_ptr);
18671 selector:=old_setting;
18672 str_room(7);
18673 str_pool[pool_ptr] := 0; { make C string for pdfsetmatrix }
18674 if pdfsetmatrix(str_start[str_ptr], cur_h, cur_page_height - cur_v) = 1 then begin
18675 str_room(7);
18676 append_char(" ");
18677 append_char("0");
18678 append_char(" ");
18679 append_char("0");
18680 append_char(" ");
18681 append_char("c");
18682 append_char("m");
18683 s := make_string;
18684 literal(s, set_origin, false);
18685 end
18686 else begin
18687 pdf_error("\pdfsetmatrix", "Unrecognized format.");
18688 end;
18689 flush_str(s);
18690 end;
18691
18692 procedure pdf_out_save(p:pointer);
18693 begin
18694 checkpdfsave(cur_h, cur_v);
18695 literal("q", set_origin, false);
18696 end;
18697
18698 procedure pdf_out_restore(p:pointer);
18699 begin
18700 checkpdfrestore(cur_h, cur_v);
18701 literal("Q", set_origin, false);
18702 end;
18703
18704 procedure pdf_special(p: pointer);
18705 var old_setting:0..max_selector; {holds print |selector|}
18706 s: str_number;
18707 h: halfword;
18708 @!q,@!r:pointer; {temporary variables for list manipulation}
18709 @!old_mode:integer; {saved |mode|}
18710 begin
18711 old_setting:=selector;
18712 selector:=selector;
18713 if subtype(p)=latespecial_node then
18714 begin @<Expand macros in the token list
18715 and make |link(def_ref)| point to the result@>;
18716 h:=def_ref;
18717 end
18718 else h:=write_tokens(p);
18719 selector:=new_string;
18720 show_token_list(link(h),null,pool_size-pool_ptr);
18721 selector:=old_setting;
18722 s := make_string;
18723 literal(s, scan_special, true);
18724 flush_str(s);
18725 if subtype(p)=latespecial_node then
18726 flush_list(def_ref);
18727 end;
18728
18729 procedure pdf_print_toks(p: pointer); {print tokens list |p|}
18730 var s: str_number;
18731 begin
18732 s := tokens_to_string(p);
18733 if length(s) > 0 then
18734 pdf_print(s);
18735 flush_str(s);
18736 end;
18737
18738 procedure pdf_print_toks_ln(p: pointer); {print tokens list |p|}
18739 var s: str_number;
18740 begin
18741 s := tokens_to_string(p);
18742 if length(s) > 0 then begin
18743 pdf_print_ln(s);
18744 end;
18745 flush_str(s);
18746 end;
18747
18748 @ Similar to |vlist_out|, |pdf_vlist_out| needs to be declared forward.
18749
18750 @p procedure@?pdf_vlist_out; forward;
18751
18752 @ The implementation of procedure |pdf_hlist_out| is similar to |hlist_out|.
18753
18754 @p @t\4@>@<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>@t@>@/
18755
18756 procedure pdf_hlist_out; {output an |hlist_node| box}
18757 label reswitch, move_past, fin_rule, next_p;
18758 var base_line: scaled; {the baseline coordinate for this box}
18759 @!left_edge: scaled; {the left coordinate for this box}
18760 @!save_h: scaled; {what |cur_h| should pop to}
18761 @!this_box: pointer; {pointer to containing box}
18762 @!g_order: glue_ord; {applicable order of infinity for glue}
18763 @!g_sign: normal..shrinking; {selects type of glue}
18764 @!p:pointer; {current position in the hlist}
18765 @!leader_box:pointer; {the leader box being replicated}
18766 @!leader_wd:scaled; {width of leader box being replicated}
18767 @!lx:scaled; {extra space between leader boxes}
18768 @!outer_doing_leaders:boolean; {were we doing leaders?}
18769 @!edge:scaled; {right edge of sub-box or leader space}
18770 @!prev_p:pointer; {one step behind |p|}
18771 @!glue_temp:real; {glue value before rounding}
18772 @!cur_glue:real; {glue seen so far}
18773 @!cur_g:scaled; {rounded equivalent of |cur_glue| times the glue ratio}
18774 @!i: small_number; {index to scan |pdf_link_stack|}
18775 begin cur_g:=0; cur_glue:=float_constant(0);
18776 this_box:=temp_ptr; g_order:=glue_order(this_box);
18777 g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
18778 incr(cur_s);
18779 base_line:=cur_v;
18780 prev_p:=this_box+list_offset;
18781 @<Initialize |hlist_out| for mixed...@>;
18782 left_edge:=cur_h;
18783 @<Create link annotations for the current hbox if needed@>;
18784 while p<>null do
18785 @<Output node |p| for |pdf_hlist_out| and move to the next node,
18786 maintaining the condition |cur_v=base_line|@>;
18787 @<Finish |hlist_out| for mixed...@>;
18788 decr(cur_s);
18789 end;
18790
18791 @ @<Create link annotations for the current hbox if needed@>=
18792 for i := 1 to pdf_link_stack_ptr do begin
18793 pdfassert(is_running(pdf_width(pdf_link_stack[i].link_node)));
18794 if (pdf_link_stack[i].nesting_level = cur_s) and gen_running_link then
18795 append_link(this_box, left_edge, base_line, i);
18796 end
18797
18798 @ @<Output node |p| for |pdf_hlist_out|...@>=
18799 reswitch: if is_char_node(p) then
18800 begin
18801 repeat f:=font(p); c:=character(p);
18802 if is_valid_char(c) then
18803 output_one_char(c)
18804 else
18805 char_warning(f, c);
18806 cur_h:=cur_h+char_width(f)(char_info(f)(c));
18807 prev_p:=link(prev_p); {N.B.: not |prev_p:=p|, |p| might be |lig_trick|}
18808 p:=link(p);
18809 until not is_char_node(p);
18810 end
18811 else @<Output the non-|char_node| |p| for |pdf_hlist_out|
18812 and move to the next node@>
18813
18814 @ @<Output the non-|char_node| |p| for |pdf_hlist_out|...@>=
18815 begin case type(p) of
18816 hlist_node,vlist_node:@<(\pdfTeX) Output a box in an hlist@>;
18817 rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
18818 goto fin_rule;
18819 end;
18820 whatsit_node: @<Output the whatsit node |p| in |pdf_hlist_out|@>;
18821 glue_node: @<(\pdfTeX) Move right or output leaders@>;
18822 margin_kern_node,
18823 kern_node:cur_h:=cur_h+width(p);
18824 math_node: @<Handle a math node in |hlist_out|@>;
18825 ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>;
18826 @/@<Cases of |hlist_out| that arise in mixed direction text only@>@;
18827 othercases do_nothing
18828 endcases;@/
18829 goto next_p;
18830 fin_rule: @<(\pdfTeX) Output a rule in an hlist@>;
18831 move_past: cur_h:=cur_h+rule_wd;
18832 next_p:prev_p:=p; p:=link(p);
18833 end
18834
18835 @ @<(\pdfTeX) Output a box in an hlist@>=
18836 if list_ptr(p)=null then cur_h:=cur_h+width(p)
18837 else begin
18838 cur_v:=base_line+shift_amount(p); {shift the box down}
18839 temp_ptr:=p; edge:=cur_h+width(p);
18840 if cur_dir=right_to_left then cur_h:=edge;
18841 if type(p)=vlist_node then pdf_vlist_out@+else pdf_hlist_out;
18842 cur_h:=edge; cur_v:=base_line;
18843 end
18844
18845 @ @<(\pdfTeX) Output a rule in an hlist@>=
18846 if is_running(rule_ht) then rule_ht:=height(this_box);
18847 if is_running(rule_dp) then rule_dp:=depth(this_box);
18848 rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
18849 if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
18850 begin cur_v:=base_line+rule_dp;
18851 pdf_set_rule(cur_h, cur_v, rule_wd, rule_ht);
18852 cur_v:=base_line;
18853 end
18854
18855 @ @<(\pdfTeX) Move right or output leaders@>=
18856 begin g:=glue_ptr(p); rule_wd:=width(g)-cur_g;
18857 if g_sign<>normal then
18858 begin if g_sign=stretching then
18859 begin if stretch_order(g)=g_order then
18860 begin cur_glue:=cur_glue+stretch(g);
18861 vet_glue(float(glue_set(this_box))*cur_glue);
18862 @^real multiplication@>
18863 cur_g:=round(glue_temp);
18864 end;
18865 end
18866 else if shrink_order(g)=g_order then
18867 begin cur_glue:=cur_glue-shrink(g);
18868 vet_glue(float(glue_set(this_box))*cur_glue);
18869 cur_g:=round(glue_temp);
18870 end;
18871 end;
18872 rule_wd:=rule_wd+cur_g;
18873 if eTeX_ex then @<Handle a glue node for mixed...@>;
18874 if subtype(p)>=a_leaders then
18875 @<(\pdfTeX) Output leaders in an hlist, |goto fin_rule| if a rule
18876 or to |next_p| if done@>;
18877 goto move_past;
18878 end
18879
18880 @ @<(\pdfTeX) Output leaders in an hlist...@>=
18881 begin leader_box:=leader_ptr(p);
18882 if type(leader_box)=rule_node then
18883 begin rule_ht:=height(leader_box); rule_dp:=depth(leader_box);
18884 goto fin_rule;
18885 end;
18886 leader_wd:=width(leader_box);
18887 if (leader_wd>0)and(rule_wd>0) then
18888 begin rule_wd:=rule_wd+10; {compensate for floating-point rounding}
18889 if cur_dir=right_to_left then cur_h:=cur_h-10;
18890 edge:=cur_h+rule_wd; lx:=0;
18891 @<Let |cur_h| be the position of the first box, and set |leader_wd+lx|
18892 to the spacing between corresponding parts of boxes@>;
18893 while cur_h+leader_wd<=edge do
18894 @<(\pdfTeX) Output a leader box at |cur_h|,
18895 then advance |cur_h| by |leader_wd+lx|@>;
18896 if cur_dir=right_to_left then cur_h:=edge
18897 else cur_h:=edge-10;
18898 goto next_p;
18899 end;
18900 end
18901
18902 @ @<(\pdfTeX) Output a leader box at |cur_h|, ...@>=
18903 begin cur_v:=base_line+shift_amount(leader_box);@/
18904 save_h:=cur_h; temp_ptr:=leader_box;
18905 if cur_dir=right_to_left then cur_h:=cur_h+leader_wd;
18906 outer_doing_leaders:=doing_leaders; doing_leaders:=true;
18907 if type(leader_box)=vlist_node then pdf_vlist_out@+else pdf_hlist_out;
18908 doing_leaders:=outer_doing_leaders;
18909 cur_v:=base_line;
18910 cur_h:=save_h+leader_wd+lx;
18911 end
18912
18913 @ The |pdf_vlist_out| routine is similar to |pdf_hlist_out|, but a bit simpler.
18914 @p procedure pdf_vlist_out; {output a |pdf_vlist_node| box}
18915 label move_past, fin_rule, next_p;
18916 var left_edge: scaled; {the left coordinate for this box}
18917 @!top_edge: scaled; {the top coordinate for this box}
18918 @!save_v: scaled; {what |cur_v| should pop to}
18919 @!this_box: pointer; {pointer to containing box}
18920 @!g_order: glue_ord; {applicable order of infinity for glue}
18921 @!g_sign: normal..shrinking; {selects type of glue}
18922 @!p:pointer; {current position in the vlist}
18923 @!leader_box:pointer; {the leader box being replicated}
18924 @!leader_ht:scaled; {height of leader box being replicated}
18925 @!lx:scaled; {extra space between leader boxes}
18926 @!outer_doing_leaders:boolean; {were we doing leaders?}
18927 @!edge:scaled; {bottom boundary of leader space}
18928 @!glue_temp:real; {glue value before rounding}
18929 @!cur_glue:real; {glue seen so far}
18930 @!cur_g:scaled; {rounded equivalent of |cur_glue| times the glue ratio}
18931 begin cur_g:=0; cur_glue:=float_constant(0);
18932 this_box:=temp_ptr; g_order:=glue_order(this_box);
18933 g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
18934 incr(cur_s);
18935 left_edge:=cur_h; cur_v:=cur_v-height(this_box); top_edge:=cur_v;
18936 @<Create thread for the current vbox if needed@>;
18937 while p<>null do
18938 @<Output node |p| for |pdf_vlist_out| and move to the next node,
18939 maintaining the condition |cur_h=left_edge|@>;
18940 decr(cur_s);
18941 end;
18942
18943 @ @<Create thread for the current vbox if needed@>=
18944 if (last_thread <> null) and is_running(pdf_thread_dp) and
18945 (pdf_thread_level = cur_s) then
18946 append_thread(this_box, left_edge, top_edge + height(this_box))
18947
18948 @ @<Output node |p| for |pdf_vlist_out|...@>=
18949 begin if is_char_node(p) then confusion("pdfvlistout")
18950 @:this can't happen pdfvlistout}{\quad pdfvlistout@>
18951 else @<Output the non-|char_node| |p| for |pdf_vlist_out|@>;
18952 next_p:p:=link(p);
18953 end
18954
18955 @ @<Output the non-|char_node| |p| for |pdf_vlist_out|@>=
18956 begin case type(p) of
18957 hlist_node,vlist_node:@<(\pdfTeX) Output a box in a vlist@>;
18958 rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
18959 goto fin_rule;
18960 end;
18961 whatsit_node: @<Output the whatsit node |p| in |pdf_vlist_out|@>;
18962 glue_node: @<(\pdfTeX) Move down or output leaders@>;
18963 kern_node:cur_v:=cur_v+width(p);
18964 othercases do_nothing
18965 endcases;@/
18966 goto next_p;
18967 fin_rule: @<(\pdfTeX) Output a rule in a vlist, |goto next_p|@>;
18968 move_past: cur_v:=cur_v+rule_ht;
18969 end
18970
18971 @ @<(\pdfTeX) Output a box in a vlist@>=
18972 if list_ptr(p)=null then cur_v:=cur_v+height(p)+depth(p)
18973 else begin cur_v:=cur_v+height(p); save_v:=cur_v;
18974 if cur_dir=right_to_left then cur_h:=left_edge-shift_amount(p)
18975 else cur_h:=left_edge+shift_amount(p); {shift the box right}
18976 temp_ptr:=p;
18977 if type(p)=vlist_node then pdf_vlist_out@+else pdf_hlist_out;
18978 cur_v:=save_v+depth(p); cur_h:=left_edge;
18979 end
18980
18981 @ @<(\pdfTeX) Output a rule in a vlist...@>=
18982 if is_running(rule_wd) then rule_wd:=width(this_box);
18983 rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
18984 cur_v:=cur_v+rule_ht;
18985 if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
18986 begin if cur_dir=right_to_left then cur_h:=cur_h-rule_wd;
18987 pdf_set_rule(cur_h, cur_v, rule_wd, rule_ht);
18988 cur_h:=left_edge;
18989 end;
18990 goto next_p
18991
18992 @ @<(\pdfTeX) Move down or output leaders@>=
18993 begin g:=glue_ptr(p); rule_ht:=width(g)-cur_g;
18994 if g_sign<>normal then
18995 begin if g_sign=stretching then
18996 begin if stretch_order(g)=g_order then
18997 begin cur_glue:=cur_glue+stretch(g);
18998 vet_glue(float(glue_set(this_box))*cur_glue);
18999 @^real multiplication@>
19000 cur_g:=round(glue_temp);
19001 end;
19002 end
19003 else if shrink_order(g)=g_order then
19004 begin cur_glue:=cur_glue-shrink(g);
19005 vet_glue(float(glue_set(this_box))*cur_glue);
19006 cur_g:=round(glue_temp);
19007 end;
19008 end;
19009 rule_ht:=rule_ht+cur_g;
19010 if subtype(p)>=a_leaders then
19011 @<(\pdfTeX) Output leaders in a vlist, |goto fin_rule| if a rule
19012 or to |next_p| if done@>;
19013 goto move_past;
19014 end
19015
19016 @ @<(\pdfTeX) Output leaders in a vlist...@>=
19017 begin leader_box:=leader_ptr(p);
19018 if type(leader_box)=rule_node then
19019 begin rule_wd:=width(leader_box); rule_dp:=0;
19020 goto fin_rule;
19021 end;
19022 leader_ht:=height(leader_box)+depth(leader_box);
19023 if (leader_ht>0)and(rule_ht>0) then
19024 begin rule_ht:=rule_ht+10; {compensate for floating-point rounding}
19025 edge:=cur_v+rule_ht; lx:=0;
19026 @<Let |cur_v| be the position of the first box, and set |leader_ht+lx|
19027 to the spacing between corresponding parts of boxes@>;
19028 while cur_v+leader_ht<=edge do
19029 @<(\pdfTeX) Output a leader box at |cur_v|,
19030 then advance |cur_v| by |leader_ht+lx|@>;
19031 cur_v:=edge-10; goto next_p;
19032 end;
19033 end
19034
19035 @ @<(\pdfTeX) Output a leader box at |cur_v|, ...@>=
19036 begin if cur_dir=right_to_left then
19037 cur_h:=left_edge-shift_amount(leader_box)
19038 else cur_h:=left_edge+shift_amount(leader_box);
19039 cur_v:=cur_v+height(leader_box); save_v:=cur_v;
19040 temp_ptr:=leader_box;
19041 outer_doing_leaders:=doing_leaders; doing_leaders:=true;
19042 if type(leader_box)=vlist_node then pdf_vlist_out@+else pdf_hlist_out;
19043 doing_leaders:=outer_doing_leaders;
19044 cur_h:=left_edge;
19045 cur_v:=save_v-height(leader_box)+leader_ht+lx;
19046 end
19047
19048 @ |fix_pdfoutput| freezes |pdfoutput| when something has been written to
19049 the output.
19050
19051 @p procedure fix_pdfoutput;
19052 begin
19053 if not fixed_pdfoutput_set then begin
19054 fixed_pdfoutput := pdf_output;
19055 fixed_pdfoutput_set := true;
19056 end
19057 else if fixed_pdfoutput <> pdf_output then
19058 pdf_error("setup",
19059 "\pdfoutput can only be changed before anything is written to the output");
19060 if fixed_pdfoutput_set then fix_pdf_draftmode;
19061 end;
19062
19063 @ |fix_pdf_draftmode| freezes |pdfdraftmode| when something has been written to
19064 the output and also switches some things off when draftmode is on.
19065 @p procedure fix_pdf_draftmode;
19066 begin
19067 if not fixed_pdf_draftmode_set then begin
19068 fixed_pdf_draftmode := pdf_draftmode;
19069 fixed_pdf_draftmode_set := true;
19070 end
19071 else if fixed_pdf_draftmode <> pdf_draftmode then
19072 pdf_error("setup",
19073 "\pdfdraftmode can only be changed before anything is written to the output");
19074 if fixed_pdf_draftmode_set and fixed_pdf_draftmode > 0 then begin
19075 fixed_pdf_draftmode_set := true;
19076 pdf_compress_level := 0;
19077 fixed_pdf_objcompresslevel := 0;
19078 end;
19079 end;
19080
19081 @ |substr_of_str| is used in |pdf_ship_out| and |pdf_print_info|.
19082 @p function substr_of_str(s, t: str_number):boolean;
19083 label continue,exit;
19084 var j, k, kk: pool_pointer; {running indices}
19085 begin
19086 k:=str_start[t];
19087 while (k < str_start[t+1] - length(s)) do begin
19088 j:=str_start[s];
19089 kk:=k;
19090 while (j < str_start[s+1]) do begin
19091 if str_pool[j] <> str_pool[kk] then
19092 goto continue;
19093 incr(j);
19094 incr(kk);
19095 end;
19096 substr_of_str:=true;
19097 return;
19098 continue: incr(k);
19099 end;
19100 substr_of_str:=false;
19101 end;
19102
19103 @ |pdf_ship_out| is used instead of |ship_out| to shipout a box to PDF
19104 output. If |shipping_page| is not set then the output will be a Form object,
19105 otherwise it will be a Page object.
19106
19107 @p procedure pdf_ship_out(p: pointer; shipping_page: boolean); {output the box |p|}
19108 label done, done1;
19109 var i,j,k:integer; {general purpose accumulators}
19110 s: pool_pointer; {index into |str_pool|}
19111 mediabox_given: boolean;
19112 save_font_list: pointer; {to save |pdf_font_list| during flushing pending forms}
19113 save_obj_list: pointer; {to save |pdf_obj_list|}
19114 save_ximage_list: pointer; {to save |pdf_ximage_list|}
19115 save_xform_list: pointer; {to save |pdf_xform_list|}
19116 save_image_procset: integer; {to save |pdf_image_procset|}
19117 save_text_procset: integer; {to save |pdf_text_procset|}
19118 pdf_last_resources: integer; {pointer to most recently generated Resources object}
19119 begin if tracing_output>0 then
19120 begin print_nl(""); print_ln;
19121 print("Completed box being shipped out");
19122 @.Completed box...@>
19123 end;
19124 if not init_pdf_output then begin
19125 @<Initialize variables for \.{PDF} output@>;
19126 init_pdf_output := true;
19127 end;
19128 is_shipping_page := shipping_page;
19129 if shipping_page then begin
19130 if term_offset>max_print_line-9 then print_ln
19131 else if (term_offset>0)or(file_offset>0) then print_char(" ");
19132 print_char("["); j:=9;
19133 while (count(j)=0)and(j>0) do decr(j);
19134 for k:=0 to j do
19135 begin print_int(count(k));
19136 if k<j then print_char(".");
19137 end;
19138 update_terminal;
19139 end;
19140 if tracing_output>0 then
19141 begin if shipping_page then print_char("]");
19142 begin_diagnostic; show_box(p); end_diagnostic(true);
19143 end;
19144 @<(\pdfTeX) Ship box |p| out@>;
19145 if eTeX_ex then @<Check for LR anomalies at the end of |ship_out|@>;
19146 if (tracing_output<=0) and shipping_page then print_char("]");
19147 dead_cycles:=0;
19148 update_terminal; {progress report}
19149 @<Flush the box from memory, showing statistics if requested@>;
19150 end;
19151
19152 @ @<(\pdfTeX) Ship box |p| out@>=
19153 @<Update the values of |max_h| and |max_v|; but if the page is too large,
19154 |goto done|@>;
19155 @<Initialize variables as |pdf_ship_out| begins@>;
19156 if type(p)=vlist_node then pdf_vlist_out@+else pdf_hlist_out;
19157 if shipping_page then
19158 incr(total_pages);
19159 cur_s:=-1;
19160 @<Finish shipping@>;
19161 done:
19162
19163 @ @<Initialize variables as |pdf_ship_out| begins@>=
19164 fix_pdfoutput;
19165 temp_ptr:=p;
19166 prepare_mag;
19167 pdf_last_resources := pdf_new_objnum;
19168 pdf_page_group_val := 0;
19169 @<Reset resource lists@>;
19170 if not shipping_page then begin
19171 pdf_xform_width := width(p);
19172 pdf_xform_height := height(p);
19173 pdf_xform_depth := depth(p);
19174 pdf_begin_dict(pdf_cur_form, 0);
19175 pdf_last_stream := pdf_cur_form;
19176 cur_v := height(p);
19177 cur_h := 0;
19178 pdf_origin_h := 0;
19179 pdf_origin_v := pdf_xform_height + pdf_xform_depth;
19180 end
19181 else begin
19182 @<Calculate page dimensions and margins@>;
19183 pdf_last_page := get_obj(obj_type_page, total_pages + 1, 0);
19184 obj_aux(pdf_last_page) := 1; {mark that this page has been created}
19185 pdf_new_dict(obj_type_others, 0, 0);
19186 pdf_last_stream := obj_ptr;
19187 cur_h := cur_h_offset;
19188 cur_v := height(p) + cur_v_offset;
19189 pdf_origin_h := 0;
19190 pdf_origin_v := cur_page_height;
19191 @<Reset PDF mark lists@>;
19192 end;
19193 if not shipping_page then begin
19194 @<Write out Form stream header@>;
19195 end;
19196 @<Start stream of page/form contents@>
19197
19198 @ @<Reset resource lists@>=
19199 pdf_font_list := null;
19200 pdf_obj_list := null;
19201 pdf_xform_list := null;
19202 pdf_ximage_list := null;
19203 pdf_text_procset := false;
19204 pdf_image_procset := 0
19205
19206 @ @<Reset PDF mark lists@>=
19207 pdf_annot_list := null;
19208 pdf_link_list := null;
19209 pdf_dest_list := null;
19210 pdf_bead_list := null;
19211 last_thread := null
19212
19213 @ @<Calculate page dimensions and margins@>=
19214 cur_h_offset := pdf_h_origin + h_offset;
19215 cur_v_offset := pdf_v_origin + v_offset;
19216 if pdf_page_width <> 0 then
19217 cur_page_width := pdf_page_width
19218 else
19219 cur_page_width := width(p) + 2*cur_h_offset;
19220 if pdf_page_height <> 0 then
19221 cur_page_height := pdf_page_height
19222 else
19223 cur_page_height := height(p) + depth(p) + 2*cur_v_offset
19224
19225 @ Here we write out the header for Form.
19226
19227 @<Write out Form stream header@>=
19228 pdf_print_ln("/Type /XObject");
19229 pdf_print_ln("/Subtype /Form");
19230 if obj_xform_attr(pdf_cur_form) <> null then begin
19231 pdf_print_toks_ln(obj_xform_attr(pdf_cur_form));
19232 delete_toks(obj_xform_attr(pdf_cur_form));
19233 end;
19234 pdf_print("/BBox [");
19235 pdf_print("0 0 ");
19236 pdf_print_bp(pdf_xform_width); pdf_out(" ");
19237 pdf_print_bp(pdf_xform_height + pdf_xform_depth); pdf_print_ln("]");
19238 pdf_print_ln("/FormType 1");
19239 pdf_print_ln("/Matrix [1 0 0 1 0 0]");
19240 pdf_indirect_ln("Resources", pdf_last_resources)
19241
19242 @ @<Start stream of page/form contents@>=
19243 pdf_begin_stream;
19244 if shipping_page then begin
19245 @<Adjust transformation matrix for the magnification ratio@>;
19246 end;
19247 pdfshipoutbegin(shipping_page);
19248 if shipping_page then
19249 pdf_out_colorstack_startpage;
19250
19251 @ @<Adjust transformation matrix for the magnification ratio@>=
19252 prepare_mag;
19253 if mag <> 1000 then begin
19254 pdf_print_real(mag, 3);
19255 pdf_print(" 0 0 ");
19256 pdf_print_real(mag, 3);
19257 pdf_print_ln(" 0 0 cm");
19258 end
19259
19260 @ @<Finish shipping@>=
19261 @<Finish stream of page/form contents@>;
19262 if shipping_page then begin
19263 @<Write out page object@>;
19264 end;
19265 @<Write out resource lists@>;
19266 if shipping_page then begin
19267 @<Write out pending PDF marks@>;
19268 end;
19269 @<Write out resources dictionary@>;
19270 @<Flush resource lists@>;
19271 if shipping_page then begin
19272 @<Flush PDF mark lists@>;
19273 end
19274
19275 @ @<Finish stream of page/form contents@>=
19276 pdf_end_text;
19277 pdfshipoutend(shipping_page);
19278 pdf_end_stream
19279
19280 @ We need to write forms last, since the recursive call to |ship_out|
19281 would reset global state such as |pdfpagegroupval|, which is needed
19282 while writing images.
19283
19284 @<Write out resource lists@>=
19285 @<Write out pending raw objects@>;
19286 @<Write out pending images@>;
19287 @<Write out pending forms@>
19288
19289 @ @<Write out resources dictionary@>=
19290 pdf_begin_dict(pdf_last_resources, 1);
19291 @<Print additional resources@>;
19292 @<Generate font resources@>;
19293 @<Generate XObject resources@>;
19294 @<Generate ProcSet if desired@>;
19295 pdf_end_dict
19296
19297 @ @<Print additional resources@>=
19298 if shipping_page then begin
19299 if pdf_page_resources <> null then
19300 pdf_print_toks_ln(pdf_page_resources);
19301 end
19302 else begin
19303 if obj_xform_resources(pdf_cur_form) <> null then begin
19304 pdf_print_toks_ln(obj_xform_resources(pdf_cur_form));
19305 delete_toks(obj_xform_resources(pdf_cur_form));
19306 end;
19307 end
19308
19309 @ In the end of shipping out a page we reset all the lists holding objects
19310 have been created during the page shipping.
19311
19312 @d delete_toks(#) == begin delete_token_ref(#); # := null; end
19313
19314 @<Flush resource lists@>=
19315 flush_list(pdf_font_list);
19316 flush_list(pdf_obj_list);
19317 flush_list(pdf_xform_list);
19318 flush_list(pdf_ximage_list)
19319
19320 @ @<Flush PDF mark lists@>=
19321 flush_list(pdf_annot_list);
19322 flush_list(pdf_link_list);
19323 flush_list(pdf_dest_list);
19324 flush_list(pdf_bead_list)
19325
19326 @ @<Generate font resources@>=
19327 if pdf_font_list <> null then begin
19328 pdf_print("/Font << ");
19329 k := pdf_font_list;
19330 while k <> null do begin
19331 pdf_print("/F");
19332 set_ff(info(k));
19333 pdf_print_int(ff);
19334 pdf_print_resname_prefix;
19335 pdf_out(" ");
19336 pdf_print_int(pdf_font_num[ff]);
19337 pdf_print(" 0 R ");
19338 k := link(k);
19339 end;
19340 pdf_print_ln(">>");
19341 pdf_text_procset := true;
19342 end
19343
19344 @ @<Generate XObject resources@>=
19345 if (pdf_xform_list <> null) or (pdf_ximage_list <> null) then begin
19346 pdf_print("/XObject << ");
19347 k := pdf_xform_list;
19348 while k <> null do begin
19349 pdf_print("/Fm");
19350 pdf_print_int(obj_info(info(k)));
19351 pdf_print_resname_prefix;
19352 pdf_out(" ");
19353 pdf_print_int(info(k));
19354 pdf_print(" 0 R ");
19355 k := link(k);
19356 end;
19357 k := pdf_ximage_list;
19358 while k <> null do begin
19359 pdf_print("/Im");
19360 pdf_print_int(obj_info(info(k)));
19361 pdf_print_resname_prefix;
19362 pdf_out(" ");
19363 pdf_print_int(info(k));
19364 pdf_print(" 0 R ");
19365 update_image_procset(obj_ximage_data(info(k)));
19366 k := link(k);
19367 end;
19368 pdf_print_ln(">>");
19369 end
19370
19371 @ @<Generate ProcSet if desired@>=
19372 if (pdf_omit_procset < 0) or
19373 ((pdf_omit_procset = 0) and (pdf_major_version < 2)) then
19374 begin
19375 pdf_print("/ProcSet [ /PDF");
19376 if pdf_text_procset then
19377 pdf_print(" /Text");
19378 if check_image_b(pdf_image_procset) then
19379 pdf_print(" /ImageB");
19380 if check_image_c(pdf_image_procset) then
19381 pdf_print(" /ImageC");
19382 if check_image_i(pdf_image_procset) then
19383 pdf_print(" /ImageI");
19384 pdf_print_ln(" ]")
19385 end
19386
19387 @ @<Write out page object@>=
19388 pdf_begin_dict(pdf_last_page, 1);
19389 pdf_print_ln("/Type /Page");
19390 pdf_indirect_ln("Contents", pdf_last_stream);
19391 pdf_indirect_ln("Resources", pdf_last_resources);
19392 mediabox_given:=false;
19393 if pdf_page_attr <> null then begin
19394 s:=tokens_to_string(pdf_page_attr);
19395 mediabox_given:=substr_of_str("/MediaBox", s);
19396 flush_str(s);
19397 end;
19398 if not mediabox_given then begin
19399 pdf_print("/MediaBox [0 0 ");
19400 pdf_print_mag_bp(cur_page_width); pdf_out(" ");
19401 pdf_print_mag_bp(cur_page_height);
19402 pdf_print_ln("]");
19403 end;
19404 if pdf_page_attr <> null then
19405 pdf_print_toks_ln(pdf_page_attr);
19406 @<Generate parent pages object@>;
19407 if pdf_page_group_val > 0 then begin
19408 pdf_print("/Group ");
19409 pdf_print_int(pdf_page_group_val);
19410 pdf_print_ln(" 0 R");
19411 end;
19412 @<Generate array of annotations or beads in page@>;
19413 pdf_end_dict
19414
19415 @ @<Generate parent pages object@>=
19416 if total_pages mod pages_tree_kids_max = 1 then begin
19417 pdf_create_obj(obj_type_pages, pages_tree_kids_max);
19418 pdf_last_pages := obj_ptr;
19419 end;
19420 pdf_indirect_ln("Parent", pdf_last_pages)
19421
19422 @ @<Generate array of annotations or beads in page@>=
19423 if (pdf_annot_list <> null) or (pdf_link_list <> null) then begin
19424 pdf_print("/Annots [ ");
19425 k := pdf_annot_list;
19426 while k <> null do begin
19427 pdf_print_int(info(k));
19428 pdf_print(" 0 R ");
19429 k := link(k);
19430 end;
19431 k := pdf_link_list;
19432 while k <> null do begin
19433 pdf_print_int(info(k));
19434 pdf_print(" 0 R ");
19435 k := link(k);
19436 end;
19437 pdf_print_ln("]");
19438 end;
19439 if pdf_bead_list <> null then begin
19440 k := pdf_bead_list;
19441 pdf_print("/B [ ");
19442 while k <> null do begin
19443 pdf_print_int(info(k));
19444 pdf_print(" 0 R ");
19445 k := link(k);
19446 end;
19447 pdf_print_ln("]");
19448 end
19449
19450 @ @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
19451 procedure pdf_write_obj(n: integer); {write a raw PDF object}
19452 var s: str_number;
19453 f: byte_file;
19454 begin
19455 s := tokens_to_string(obj_obj_data(n));
19456 delete_toks(obj_obj_data(n));
19457 if obj_obj_is_stream(n) > 0 then begin
19458 pdf_begin_dict(n, 0);
19459 if obj_obj_stream_attr(n) <> null then begin
19460 pdf_print_toks_ln(obj_obj_stream_attr(n));
19461 delete_toks(obj_obj_stream_attr(n));
19462 end;
19463 pdf_begin_stream;
19464 end
19465 else
19466 pdf_begin_obj(n, 1);
19467 if obj_obj_is_file(n) > 0 then begin
19468 cur_name := s;
19469 cur_area := "";
19470 cur_ext := "";
19471 pack_cur_name;
19472 if not tex_b_openin(f) then begin
19473 print_nl("! "); print(s); print(" not found.");
19474 pdf_error("ext5", "cannot open file for embedding");
19475 end;
19476 print("<<");
19477 print(s);
19478 if not eof(f) then begin {at least one byte available}
19479 while not eof(f) do
19480 pdf_out(getc(f));
19481 if (not obj_obj_is_stream(n)) and (pdf_ptr > 0) and (pdf_buf[pdf_ptr - 1] <> 10) then
19482 pdf_out(10);
19483 end;
19484 print(">>");
19485 b_close(f);
19486 end
19487 else if obj_obj_is_stream(n) > 0 then
19488 pdf_print(s)
19489 else
19490 pdf_print_ln(s);
19491 if obj_obj_is_stream(n) > 0 then
19492 pdf_end_stream
19493 else
19494 pdf_end_obj;
19495 flush_str(s);
19496 end;
19497
19498 procedure flush_whatsit_node(p: pointer; s: small_number);
19499 begin
19500 type(p) := whatsit_node;
19501 subtype(p) := s;
19502 if link(p) <> null then
19503 pdf_error("flush_whatsit_node", "link(p) is not null");
19504 flush_node_list(p);
19505 end;
19506
19507 @ @<Write out pending raw objects@>=
19508 if pdf_obj_list <> null then begin
19509 k := pdf_obj_list;
19510 while k <> null do begin
19511 if not is_obj_written(info(k)) then
19512 pdf_write_obj(info(k));
19513 k := link(k);
19514 end;
19515 end
19516
19517 @ @<Glob...@>=
19518 @!saved_pdf_cur_form: integer;
19519
19520 @ When flushing pending forms we need to save and restore resource lists
19521 (|pdf_font_list|, |pdf_obj_list|, |pdf_xform_list| and |pdf_ximage_list|),
19522 which are also used by page shipping.
19523
19524 @<Write out pending forms@>=
19525 if pdf_xform_list <> null then begin
19526 k := pdf_xform_list;
19527 while k <> null do begin
19528 if not is_obj_written(info(k)) then begin
19529 saved_pdf_cur_form := pdf_cur_form;
19530 pdf_cur_form := info(k);
19531 @<Save resource lists@>;
19532 @<Reset resource lists@>;
19533 pdf_ship_out(obj_xform_box(pdf_cur_form), false);
19534 pdf_cur_form := saved_pdf_cur_form;
19535 @<Restore resource lists@>;
19536 end;
19537 k := link(k);
19538 end;
19539 end
19540
19541 @ @<Save resource lists@>=
19542 save_font_list := pdf_font_list;
19543 save_obj_list := pdf_obj_list;
19544 save_xform_list := pdf_xform_list;
19545 save_ximage_list := pdf_ximage_list;
19546 save_text_procset := pdf_text_procset;
19547 save_image_procset := pdf_image_procset
19548
19549 @ @<Restore resource lists@>=
19550 pdf_font_list := save_font_list;
19551 pdf_obj_list := save_obj_list;
19552 pdf_xform_list := save_xform_list;
19553 pdf_ximage_list := save_ximage_list;
19554 pdf_text_procset := save_text_procset;
19555 pdf_image_procset := save_image_procset
19556
19557 @ @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
19558 procedure pdf_write_image(n: integer); {write an image}
19559 begin
19560 pdf_begin_dict(n, 0);
19561 if obj_ximage_attr(n) <> null then begin
19562 pdf_print_toks_ln(obj_ximage_attr(n));
19563 delete_toks(obj_ximage_attr(n));
19564 end;
19565 if fixed_pdf_draftmode = 0 then write_image(obj_ximage_data(n));
19566 delete_image(obj_ximage_data(n));
19567 end;
19568
19569 @ @<Write out pending images@>=
19570 if pdf_ximage_list <> null then begin
19571 k := pdf_ximage_list;
19572 while k <> null do begin
19573 if not is_obj_written(info(k)) then
19574 pdf_write_image(info(k));
19575 k := link(k);
19576 end;
19577 end
19578
19579 @ @<Write out pending PDF marks@>=
19580 pdf_origin_h := 0;
19581 pdf_origin_v := cur_page_height;
19582 @<Write out PDF annotations@>;
19583 @<Write out PDF link annotations@>;
19584 @<Write out PDF mark destinations@>;
19585 @<Write out PDF bead rectangle specifications@>
19586
19587 @ @<Write out PDF annotations@>=
19588 if pdf_annot_list <> null then begin
19589 k := pdf_annot_list;
19590 while k <> null do begin
19591 i := obj_annot_ptr(info(k)); {|i| points to |pdf_annot_node|}
19592 pdf_begin_dict(info(k), 1);
19593 pdf_print_ln("/Type /Annot");
19594 pdf_print_toks_ln(pdf_annot_data(i));
19595 pdf_rectangle(pdf_left(i), pdf_top(i), pdf_right(i), pdf_bottom(i));
19596 pdf_end_dict;
19597 k := link(k);
19598 end;
19599 end
19600
19601 @ @<Write out PDF link annotations@>=
19602 if pdf_link_list <> null then begin
19603 k := pdf_link_list;
19604 while k <> null do begin
19605 i := obj_annot_ptr(info(k));
19606 pdf_begin_dict(info(k), 1);
19607 pdf_print_ln("/Type /Annot");
19608 if pdf_action_type(pdf_link_action(i)) <> pdf_action_user then
19609 pdf_print_ln("/Subtype /Link");
19610 if pdf_link_attr(i) <> null then
19611 pdf_print_toks_ln(pdf_link_attr(i));
19612 pdf_rectangle(pdf_left(i), pdf_top(i), pdf_right(i), pdf_bottom(i));
19613 if pdf_action_type(pdf_link_action(i)) <> pdf_action_user then
19614 pdf_print("/A ");
19615 write_action(pdf_link_action(i));
19616 pdf_end_dict;
19617 k := link(k);
19618 end;
19619 @<Flush |pdf_start_link_node|'s created by |append_link|@>;
19620 end
19621
19622 @ @<Flush |pdf_start_link_node|'s created by |append_link|@>=
19623 k := pdf_link_list;
19624 while k <> null do begin
19625 i := obj_annot_ptr(info(k));
19626 {nodes with |info = max_halfword| were created by |append_link| and
19627 must be flushed here, as they are not linked in any list}
19628 if info(i) = max_halfword then
19629 flush_whatsit_node(i, pdf_start_link_node);
19630 k := link(k);
19631 end
19632
19633 @ @<Write out PDF mark destinations@>=
19634 if pdf_dest_list <> null then begin
19635 k := pdf_dest_list;
19636 while k <> null do begin
19637 if is_obj_written(info(k)) then
19638 pdf_error("ext5",
19639 "destination has been already written (this shouldn't happen)")
19640 else begin
19641 i := obj_dest_ptr(info(k));
19642 if (pdf_dest_named_id(i) > 0) and (pdf_dest_objnum(i) = null) then begin
19643 pdf_begin_dict(info(k), 1);
19644 pdf_print("/D ");
19645 end
19646 else
19647 pdf_begin_obj(info(k), 1);
19648 pdf_out("[");
19649 if pdf_dest_objnum(i) = null then
19650 pdf_print_int(pdf_last_page)
19651 else
19652 pdf_print_int(pdf_dest_objnum(i));
19653 pdf_print(" 0 R ");
19654 case pdf_dest_type(i) of
19655 pdf_dest_xyz: begin
19656 pdf_print("/XYZ ");
19657 pdf_print_mag_bp(pdf_x(pdf_left(i))); pdf_out(" ");
19658 pdf_print_mag_bp(pdf_y(pdf_top(i))); pdf_out(" ");
19659 if pdf_dest_xyz_zoom(i) = null then
19660 pdf_print("null")
19661 else begin
19662 pdf_print_int(pdf_dest_xyz_zoom(i) div 1000);
19663 pdf_out(".");
19664 pdf_print_int((pdf_dest_xyz_zoom(i) mod 1000));
19665 end;
19666 end;
19667 pdf_dest_fit:
19668 pdf_print("/Fit");
19669 pdf_dest_fith: begin
19670 pdf_print("/FitH ");
19671 pdf_print_mag_bp(pdf_y(pdf_top(i)));
19672 end;
19673 pdf_dest_fitv: begin
19674 pdf_print("/FitV ");
19675 pdf_print_mag_bp(pdf_x(pdf_left(i)));
19676 end;
19677 pdf_dest_fitb:
19678 pdf_print("/FitB");
19679 pdf_dest_fitbh: begin
19680 pdf_print("/FitBH ");
19681 pdf_print_mag_bp(pdf_y(pdf_top(i)));
19682 end;
19683 pdf_dest_fitbv: begin
19684 pdf_print("/FitBV ");
19685 pdf_print_mag_bp(pdf_x(pdf_left(i)));
19686 end;
19687 pdf_dest_fitr: begin
19688 pdf_print("/FitR ");
19689 pdf_print_rect_spec(i);
19690 end;
19691 othercases pdf_error("ext5", "unknown dest type");
19692 endcases;
19693 pdf_print_ln("]");
19694 if (pdf_dest_named_id(i) > 0) and (pdf_dest_objnum(i) = null) then
19695 pdf_end_dict
19696 else
19697 pdf_end_obj;
19698 end;
19699 k := link(k);
19700 end;
19701 end
19702
19703 @ @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
19704 procedure pdf_print_rect_spec(r: pointer); {prints a rect spec}
19705 begin
19706 pdf_print_mag_bp(pdf_x(pdf_left(r)));
19707 pdf_out(" ");
19708 pdf_print_mag_bp(pdf_y(pdf_bottom(r)));
19709 pdf_out(" ");
19710 pdf_print_mag_bp(pdf_x(pdf_right(r)));
19711 pdf_out(" ");
19712 pdf_print_mag_bp(pdf_y(pdf_top(r)));
19713 end;
19714
19715 @ @<Write out PDF bead rectangle specifications@>=
19716 if pdf_bead_list <> null then begin
19717 k := pdf_bead_list;
19718 while k <> null do begin
19719 pdf_new_obj(obj_type_others, 0, 1);
19720 pdf_out("[");
19721 i := obj_bead_data(info(k)); {pointer to a whatsit or whatsit-like node}
19722 pdf_print_rect_spec(i);
19723 if info(i) = max_halfword then {not a whatsit node, so must be destroyed here}
19724 flush_whatsit_node(i, pdf_start_thread_node);
19725 pdf_print_ln("]");
19726 obj_bead_rect(info(k)) := obj_ptr; {rewrite |obj_bead_data|}
19727 pdf_end_obj;
19728 k := link(k);
19729 end;
19730 end
19731
19732 @ In the end we must flush PDF objects that cannot be written out
19733 immediately after shipping out pages.
19734
19735 @ @<Output outlines@>=
19736 if pdf_first_outline <> 0 then begin
19737 pdf_new_dict(obj_type_others, 0, 1);
19738 outlines := obj_ptr;
19739 l := pdf_first_outline; k := 0;
19740 repeat
19741 incr(k);
19742 a := open_subentries(l);
19743 if obj_outline_count(l) > 0 then
19744 k := k + a;
19745 obj_outline_parent(l) := obj_ptr;
19746 l := obj_outline_next(l);
19747 until l = 0;
19748 pdf_print_ln("/Type /Outlines");
19749 pdf_indirect_ln("First", pdf_first_outline);
19750 pdf_indirect_ln("Last", pdf_last_outline);
19751 pdf_int_entry_ln("Count", k);
19752 pdf_end_dict;
19753 @<Output PDF outline entries@>;
19754 end
19755 else
19756 outlines := 0
19757
19758 @ @<Output PDF outline entries@>=
19759 k := head_tab[obj_type_outline];
19760 while k <> 0 do begin
19761 if obj_outline_parent(k) = pdf_parent_outline then begin
19762 if obj_outline_prev(k) = 0 then
19763 pdf_first_outline := k;
19764 if obj_outline_next(k) = 0 then
19765 pdf_last_outline := k;
19766 end;
19767 pdf_begin_dict(k, 1);
19768 pdf_indirect_ln("Title", obj_outline_title(k));
19769 pdf_indirect_ln("A", obj_outline_action_objnum(k));
19770 if obj_outline_parent(k) <> 0 then
19771 pdf_indirect_ln("Parent", obj_outline_parent(k));
19772 if obj_outline_prev(k) <> 0 then
19773 pdf_indirect_ln("Prev", obj_outline_prev(k));
19774 if obj_outline_next(k) <> 0 then
19775 pdf_indirect_ln("Next", obj_outline_next(k));
19776 if obj_outline_first(k) <> 0 then
19777 pdf_indirect_ln("First", obj_outline_first(k));
19778 if obj_outline_last(k) <> 0 then
19779 pdf_indirect_ln("Last", obj_outline_last(k));
19780 if obj_outline_count(k) <> 0 then
19781 pdf_int_entry_ln("Count", obj_outline_count(k));
19782 if obj_outline_attr(k) <> 0 then begin
19783 pdf_print_toks_ln(obj_outline_attr(k));
19784 delete_toks(obj_outline_attr(k));
19785 end;
19786 pdf_end_dict;
19787 k := obj_link(k);
19788 end
19789
19790 @ @<Output article threads@>=
19791 if head_tab[obj_type_thread] <> 0 then begin
19792 pdf_new_obj(obj_type_others, 0, 1);
19793 threads := obj_ptr;
19794 pdf_out("[");
19795 k := head_tab[obj_type_thread];
19796 while k <> 0 do begin
19797 pdf_print_int(k);
19798 pdf_print(" 0 R ");
19799 k := obj_link(k);
19800 end;
19801 remove_last_space;
19802 pdf_print_ln("]");
19803 pdf_end_obj;
19804 k := head_tab[obj_type_thread];
19805 while k <> 0 do begin
19806 out_thread(k);
19807 k := obj_link(k);
19808 end;
19809 end
19810 else
19811 threads := 0
19812
19813 @ Now we are ready to declare our new procedure |ship_out|. It will call
19814 |pdf_ship_out| if the integer parameter |pdf_output| is positive; otherwise it
19815 will call |dvi_ship_out|, which is the \TeX\ original |ship_out|.
19816
19817 @p procedure ship_out(p:pointer); {output the box |p|}
19818 begin
19819 fix_pdfoutput;
19820 if pdf_output > 0 then
19821 pdf_ship_out(p, true)
19822 else
19823 dvi_ship_out(p);
19824 end;
19825
19826 @ @<Initialize variables for \.{PDF} output@>=
19827 check_pdfversion;
19828 prepare_mag;
19829 fixed_decimal_digits := fix_int(pdf_decimal_digits, 0, 4);
19830 min_bp_val :=
19831 divide_scaled(one_hundred_bp, ten_pow[fixed_decimal_digits + 2], 0);
19832 if pdf_pk_resolution = 0 then {if not set from format file or by user}
19833 pdf_pk_resolution := pk_dpi; {take it from \.{texmf.cnf}}
19834 fixed_pk_resolution := fix_int(pdf_pk_resolution, 72, 8000);
19835 pk_scale_factor :=
19836 divide_scaled(72, fixed_pk_resolution, 5 + fixed_decimal_digits);
19837 if pdf_pk_mode <> null then begin
19838 kpse_init_prog('PDFTEX', fixed_pk_resolution,
19839 make_cstring(tokens_to_string(pdf_pk_mode)), nil);
19840 flush_string;
19841 end else
19842 kpse_init_prog('PDFTEX', fixed_pk_resolution, nil, nil);
19843 kpse_set_program_enabled (kpse_pk_format, 1, kpse_src_compile);
19844 set_job_id(year, month, day, time);
19845 if (pdf_unique_resname > 0) and (pdf_resname_prefix = 0) then
19846 pdf_resname_prefix := get_resname_prefix
19847
19848 @ Finishing the PDF output file.
19849
19850 The following procedures sort the table of destination names.
19851 @d get_next_char(#)==
19852 c@&# := str_pool[j@&#];
19853 incr(j@&#);
19854 if (c@&# = 92) and (j@&# < e@&#) then begin
19855 c@&# := str_pool[j@&#];
19856 incr(j@&#);
19857 if (c@&# >= 48) and (c@&# <= 55) then begin
19858 c@&# := c@&# - 48;
19859 if (j@&# < e@&#) and (str_pool[j@&#] >= 48)
19860 and (str_pool[j@&#] <= 55) then begin
19861 c@&# := 8 * c@&# + str_pool[j@&#] - 48;
19862 incr(j@&#);
19863 if (j@&# < e@&#) and (str_pool[j@&#] >= 48)
19864 and (str_pool[j@&#] <= 55)
19865 and (c@&# < 32) then begin
19866 c@&# := 8 * c@&# + str_pool[j@&#] - 48;
19867 incr(j@&#);
19868 end;
19869 end;
19870 end else begin
19871 case c@&# of
19872 98: c@&# := 8; {`\.b': backspace}
19873 102: c@&# := 12; {`\.f': form feed}
19874 110: c@&# := 10; {`\.n': line feed}
19875 114: c@&# := 13; {`\.r': carriage return}
19876 116: c@&# := 9; {`\.t': horizontal tab}
19877 {nothing to do for `\.{\\}', `\.(', `\.)'}
19878 othercases do_nothing
19879 endcases;
19880 end;
19881 end
19882
19883 @p function str_less_str(s1, s2: str_number): boolean; {compare two pdf strings}
19884 var j1, j2, e1, e2: pool_pointer;
19885 c1, c2: packed_ASCII_code;
19886 begin
19887 {Minimal requirement: output of \.{\\pdfescapestring} must be supported.}
19888 {This implementation also supports all escape sequences}
19889 {listed in the table `Escape sequences in literal strings'}
19890 {of the pdf specification.}
19891 {End-of-line markers are not detected:}
19892 {The marker is not replaced by `\.{\\n}' or removed if it is escaped.}
19893 j1 := str_start[s1];
19894 j2 := str_start[s2];
19895 e1 := j1 + length(s1);
19896 e2 := j2 + length(s2);
19897 while (j1 < e1) and (j2 < e2) do begin
19898 {get next character of first string}
19899 get_next_char(1);
19900 {get next character of second string}
19901 get_next_char(2);
19902 {compare characters}
19903 if c1 < c2 then begin
19904 str_less_str := true;
19905 return;
19906 end
19907 else if c1 > c2 then begin
19908 str_less_str := false;
19909 return;
19910 end;
19911 end;
19912 {compare string lengths}
19913 if (j1 >= e1) and (j2 < e2) then
19914 str_less_str := true
19915 else
19916 str_less_str := false;
19917 exit: end;
19918
19919 procedure sort_dest_names(l, r: integer); {sorts |dest_names| by names}
19920 var i, j: integer;
19921 s: str_number;
19922 e: dest_name_entry;
19923 begin
19924 i := l;
19925 j := r;
19926 s := dest_names[(l + r) div 2].objname;
19927 repeat
19928 while str_less_str(dest_names[i].objname, s) do
19929 incr(i);
19930 while str_less_str(s, dest_names[j].objname) do
19931 decr(j);
19932 if i <= j then begin
19933 e := dest_names[i];
19934 dest_names[i] := dest_names[j];
19935 dest_names[j] := e;
19936 incr(i);
19937 decr(j);
19938 end;
19939 until i > j;
19940 if l < j then
19941 sort_dest_names(l, j);
19942 if i < r then
19943 sort_dest_names(i, r);
19944 end;
19945
19946 @ Now the finish of PDF output file. At this moment all Page objects
19947 are already written completely to PDF output file.
19948
19949 @<Finish the PDF file@>=
19950 if total_pages=0 then begin
19951 print_nl("No pages of output.");
19952 @.No pages of output@>
19953 if pdf_gone > 0 then
19954 garbage_warning;
19955 end
19956 else begin
19957 if fixed_pdf_draftmode = 0 then begin
19958 pdf_flush; {to make sure that the output file name has been already
19959 created}
19960 if total_pages mod pages_tree_kids_max <> 0 then
19961 obj_info(pdf_last_pages) := total_pages mod pages_tree_kids_max;
19962 {last pages object may have less than |pages_tree_kids_max| children}
19963 flush_jbig2_page0_objects; {flush page 0 objects from JBIG2 images, if any}
19964 @<Check for non-existing pages@>;
19965 @<Reverse the linked list of Page and Pages objects@>;
19966 @<Check for non-existing destinations@>;
19967 @<Check for non-existing structure destinations@>;
19968 @<Output fonts definition@>;
19969 @<Output pages tree@>;
19970 @<Output outlines@>;
19971 @<Output name tree@>;
19972 @<Output article threads@>;
19973 @<Output the catalog object@>;
19974 if pdf_omit_info_dict = 0 then pdf_print_info; {last candidate for object stream}
19975 if pdf_os_enable then begin
19976 pdf_os_switch(true);
19977 pdf_os_write_objstream;
19978 pdf_flush;
19979 pdf_os_switch(false);
19980 @<Output the cross-reference stream dictionary@>;
19981 pdf_flush;
19982 end else begin
19983 @<Output the |obj_tab|@>;
19984 end;
19985 @<Output the trailer@>;
19986 pdf_flush;
19987 print_nl("Output written on "); print_file_name(0, output_file_name, 0);
19988 @.Output written on x@>
19989 print(" ("); print_int(total_pages); print(" page");
19990 if total_pages<>1 then print_char("s");
19991 print(", "); print_int(pdf_offset); print(" bytes).");
19992 end;
19993 libpdffinish;
19994 if fixed_pdf_draftmode = 0 then b_close(pdf_file)
19995 else pdf_warning(0, "\pdfdraftmode enabled, not changing output pdf", true, true)
19996 end
19997
19998 @ Destinations that have been referenced but don't exists have
19999 |obj_dest_ptr=null|. Leaving them undefined might cause troubles for
20000 PDF browsers, so we need to fix them.
20001
20002 @p procedure pdf_fix_dest(k: integer);
20003 begin
20004 if obj_dest_ptr(k) <> null then
20005 return;
20006 pdf_warning("dest", "", true, false);
20007 if obj_info(k) < 0 then begin
20008 print("name{");
20009 print(-obj_info(k));
20010 print("}");
20011 end
20012 else begin
20013 print("num");
20014 print_int(obj_info(k));
20015 end;
20016 print(" has been referenced but does not exist, replaced by a fixed one");
20017 print_ln; print_ln;
20018 pdf_begin_obj(k, 1);
20019 pdf_out("[");
20020 pdf_print_int(head_tab[obj_type_page]);
20021 pdf_print_ln(" 0 R /Fit]");
20022 pdf_end_obj;
20023 end;
20024
20025 @ @<Check for non-existing destinations@>=
20026 k := head_tab[obj_type_dest];
20027 while k <> 0 do begin
20028 pdf_fix_dest(k);
20029 k := obj_link(k);
20030 end
20031
20032 @ The same for structure destinations, except that there is no sensible default
20033 object to point to.
20034
20035 @p procedure pdf_fix_struct_dest(k: integer);
20036 begin
20037 if obj_dest_ptr(k) <> null then
20038 return;
20039 pdf_warning("structure dest", "", false, false);
20040 if obj_info(k) < 0 then begin
20041 print("name{");
20042 print(-obj_info(k));
20043 print("}");
20044 end
20045 else begin
20046 print("num");
20047 print_int(obj_info(k));
20048 end;
20049 print(" has been referenced but does not exist");
20050 print_ln; print_ln;
20051 @{pdf_begin_obj(k, 1);
20052 pdf_out("[");
20053 pdf_print_int(head_tab[obj_type_page]);
20054 pdf_print_ln(" 0 R /Fit]");
20055 pdf_end_obj;@}
20056 end;
20057
20058 @ @<Check for non-existing structure destinations@>=
20059 k := head_tab[obj_type_struct_dest];
20060 while k <> 0 do begin
20061 pdf_fix_struct_dest(k);
20062 k := obj_link(k);
20063 end
20064
20065 @ @<Check for non-existing pages@>=
20066 k := head_tab[obj_type_page];
20067 while obj_aux(k) = 0 do begin
20068 pdf_warning("dest", "Page ", true, false);
20069 print_int(obj_info(k));
20070 print(" has been referenced but does not exist!");
20071 print_ln; print_ln;
20072 k := obj_link(k);
20073 end;
20074 head_tab[obj_type_page] := k
20075
20076 @ @<Reverse the linked list of Page and Pages objects@>=
20077 k := head_tab[obj_type_page];
20078 l := 0;
20079 repeat
20080 i := obj_link(k);
20081 obj_link(k) := l;
20082 l := k;
20083 k := i;
20084 until k = 0;
20085 head_tab[obj_type_page] := l;
20086 k := head_tab[obj_type_pages];
20087 pages_tail := k;
20088 l := 0;
20089 repeat
20090 i := obj_link(k);
20091 obj_link(k) := l;
20092 l := k;
20093 k := i;
20094 until k = 0;
20095 head_tab[obj_type_pages] := l
20096
20097 @ @<Output fonts definition@>=
20098 for k := font_base + 1 to font_ptr do
20099 if font_used[k] and hasfmentry(k) and (pdf_font_num[k] < 0) then begin
20100 i := -pdf_font_num[k];
20101 pdfassert(pdf_font_num[i] > 0);
20102 for j := 0 to 255 do
20103 if pdf_char_marked(k, j) then
20104 pdf_mark_char(i, j);
20105 if (length(pdf_font_attr[i]) = 0) and (length(pdf_font_attr[k]) <> 0) then
20106 pdf_font_attr[i] := pdf_font_attr[k]
20107 else if (length(pdf_font_attr[k]) = 0) and (length(pdf_font_attr[i]) <> 0) then
20108 pdf_font_attr[k] := pdf_font_attr[i]
20109 else if (length(pdf_font_attr[i]) <> 0) and (length(pdf_font_attr[k]) <> 0) and
20110 not str_eq_str(pdf_font_attr[i], pdf_font_attr[k]) then begin
20111 pdf_warning("\pdffontattr", "fonts ", true, false);
20112 print_font_identifier(i);
20113 print(" and ");
20114 print_font_identifier(k);
20115 print(" have conflicting attributes; I will ignore the attributes assigned to ");
20116 print_font_identifier(i);
20117 print_ln; print_ln;
20118 end;
20119 end;
20120 fixed_gen_tounicode := pdf_gen_tounicode;
20121 k := head_tab[obj_type_font];
20122 while k <> 0 do begin
20123 f := obj_info(k);
20124 pdfassert(pdf_font_num[f] > 0);
20125 do_pdf_font(k, f);
20126 k := obj_link(k);
20127 end;
20128 write_fontstuff
20129
20130 @ We will generate in each single step the parents of all Pages/Page objects in
20131 the previous level. These new generated Pages object will create a new level of
20132 the Pages tree. We will repeat this until we have only one Pages object. This
20133 one will be the Root object.
20134
20135 @<Output pages tree@>=
20136 a := sys_obj_ptr + 1; {all Pages objects whose children are not Page objects
20137 should have index greater than |a|}
20138 l := head_tab[obj_type_pages]; {|l| is the index of current Pages object
20139 which is being output}
20140 k := head_tab[obj_type_page]; {|k| is the index of current child of |l|}
20141 b := 0;
20142 repeat
20143 i := 0; {counter of Pages object in current level}
20144 c := 0; {first Pages object in previous level}
20145 if obj_link(l) = 0 then
20146 is_root := true {only Pages object; total pages is
20147 not greater than |pages_tree_kids_max|}
20148 else
20149 is_root := false;
20150 repeat
20151 if not is_root then begin
20152 if i mod pages_tree_kids_max = 0 then begin {create a new Pages object
20153 for next level}
20154 pdf_last_pages := pdf_new_objnum;
20155 if c = 0 then
20156 c := pdf_last_pages;
20157 obj_link(pages_tail) := pdf_last_pages;
20158 pages_tail := pdf_last_pages;
20159 obj_link(pdf_last_pages) := 0;
20160 obj_info(pdf_last_pages) := obj_info(l);
20161 end
20162 else
20163 obj_info(pdf_last_pages) := obj_info(pdf_last_pages) +
20164 obj_info(l);
20165 end;
20166 @<Output the current Pages object in this level@>;
20167 incr(i);
20168 l := obj_link(l);
20169 until (l = c);
20170 b := c;
20171 if l = 0 then
20172 goto done;
20173 until false;
20174 done:
20175
20176 @ @<Output the current Pages object in this level@>=
20177 pdf_begin_dict(l, 1);
20178 pdf_print_ln("/Type /Pages");
20179 pdf_int_entry_ln("Count", obj_info(l));
20180 if not is_root then
20181 pdf_indirect_ln("Parent", pdf_last_pages);
20182 pdf_print("/Kids [");
20183 j := 0;
20184 repeat
20185 pdf_print_int(k);
20186 pdf_print(" 0 R ");
20187 k := obj_link(k);
20188 incr(j);
20189 until ((l < a) and (j = obj_info(l))) or
20190 (k = 0) or ((k = b) and (b <> 0)) or
20191 (j = pages_tree_kids_max);
20192 remove_last_space;
20193 pdf_print_ln("]");
20194 if k = 0 then begin
20195 k := head_tab[obj_type_pages];
20196 head_tab[obj_type_pages] := 0;
20197 end;
20198 if is_root and (pdf_pages_attr <> null) then
20199 pdf_print_toks_ln(pdf_pages_attr);
20200 pdf_end_dict;
20201
20202 @ The name tree is very similar to Pages tree so its construction should be
20203 certain from Pages tree construction. For intermediate node |obj_info| will be
20204 the first name and |obj_link| will be the last name in \.{\\Limits} array.
20205 Note that |pdf_dest_names_ptr| will be less than |obj_ptr|, so we test if
20206 |k < pdf_dest_names_ptr| then |k| is index of leaf in |dest_names|; else
20207 |k| will be index in |obj_tab| of some intermediate node.
20208
20209 @<Output name tree@>=
20210 if pdf_dest_names_ptr = 0 then begin
20211 dests := 0;
20212 goto done1;
20213 end;
20214 sort_dest_names(0, pdf_dest_names_ptr - 1);
20215 names_head := 0;
20216 names_tail := 0;
20217 k := 0; {index of current child of |l|; if |k < pdf_dest_names_ptr|
20218 then this is pointer to |dest_names| array;
20219 otherwise it is the pointer to |obj_tab| (object number)}
20220 is_names := true; {flag whether Names or Kids}
20221 b := 0;
20222 repeat
20223 repeat
20224 pdf_create_obj(obj_type_others, 0); {create a new node}
20225 l := obj_ptr;
20226 if b = 0 then
20227 b := l; {first in this level}
20228 if names_head = 0 then begin
20229 names_head := l;
20230 names_tail := l;
20231 end else begin
20232 obj_link(names_tail) := l;
20233 names_tail := l;
20234 end;
20235 obj_link(names_tail) := 0;
20236 @<Output the current node in this level@>;
20237 until b = 0;
20238 if k = l then begin
20239 dests := l;
20240 goto done1;
20241 end;
20242 until false;
20243 done1:
20244 if (dests <> 0) or (pdf_names_toks <> null) then begin
20245 pdf_new_dict(obj_type_others, 0, 1);
20246 if (dests <> 0) then
20247 pdf_indirect_ln("Dests", dests);
20248 if pdf_names_toks <> null then begin
20249 pdf_print_toks_ln(pdf_names_toks);
20250 delete_toks(pdf_names_toks);
20251 end;
20252 pdf_end_dict;
20253 names_tree := obj_ptr;
20254 end
20255 else
20256 names_tree := 0
20257
20258 @ @<Output the current node in this level@>=
20259 pdf_begin_dict(l, 1);
20260 j := 0;
20261 if is_names then begin
20262 obj_info(l) := dest_names[k].objname;
20263 pdf_print("/Names [");
20264 repeat
20265 pdf_print_str(dest_names[k].objname);
20266 pdf_out(" ");
20267 pdf_print_int(dest_names[k].objnum);
20268 pdf_print(" 0 R ");
20269 incr(j);
20270 incr(k);
20271 until (j = name_tree_kids_max) or (k = pdf_dest_names_ptr);
20272 remove_last_space;
20273 pdf_print_ln("]");
20274 obj_aux(l) := dest_names[k - 1].objname;
20275 if k = pdf_dest_names_ptr then begin
20276 is_names := false;
20277 k := names_head;
20278 b := 0;
20279 end;
20280 end
20281 else begin
20282 obj_info(l) := obj_info(k);
20283 pdf_print("/Kids [");
20284 repeat
20285 pdf_print_int(k);
20286 pdf_print(" 0 R ");
20287 incr(j);
20288 obj_aux(l) := obj_aux(k);
20289 k := obj_link(k);
20290 until (j = name_tree_kids_max) or (k = b) or (obj_link(k) = 0);
20291 remove_last_space;
20292 pdf_print_ln("]");
20293 if k = b then
20294 b := 0;
20295 end;
20296 pdf_print("/Limits [");
20297 pdf_print_str(obj_info(l));
20298 pdf_out(" ");
20299 pdf_print_str(obj_aux(l));
20300 pdf_print_ln("]");
20301 pdf_end_dict;
20302
20303 @ @<Output the catalog object@>=
20304 pdf_new_dict(obj_type_others, 0, 1);
20305 root := obj_ptr;
20306 pdf_print_ln("/Type /Catalog");
20307 pdf_indirect_ln("Pages", pdf_last_pages);
20308 if threads <> 0 then
20309 pdf_indirect_ln("Threads", threads);
20310 if outlines <> 0 then
20311 pdf_indirect_ln("Outlines", outlines);
20312 if names_tree <> 0 then
20313 pdf_indirect_ln("Names", names_tree);
20314 if pdf_catalog_toks <> null then begin
20315 pdf_print_toks_ln(pdf_catalog_toks);
20316 delete_toks(pdf_catalog_toks);
20317 end;
20318 if pdf_catalog_openaction <> 0 then
20319 pdf_indirect_ln("OpenAction", pdf_catalog_openaction);
20320 pdf_end_dict
20321
20322 @ If the same keys in a dictionary are given several times, then it is not
20323 defined which value is chosen by an application. Therefore the keys
20324 |/Producer| and |/Creator| are only set if the token list
20325 |pdf_info_toks| converted to a string does not contain these key strings.
20326
20327 @p procedure pdf_print_info; {print info object}
20328 var s: str_number;
20329 creator_given, producer_given, creationdate_given, moddate_given, trapped_given: boolean;
20330 begin
20331 pdf_new_dict(obj_type_others, 0, 3); {keep Info readable unless explicitly forced}
20332 creator_given:=false;
20333 producer_given:=false;
20334 creationdate_given:=false;
20335 moddate_given:=false;
20336 trapped_given:=false;
20337 if pdf_info_toks <> null then begin
20338 s:=tokens_to_string(pdf_info_toks);
20339 creator_given:=substr_of_str("/Creator", s);
20340 producer_given:=substr_of_str("/Producer", s);
20341 creationdate_given:=substr_of_str("/CreationDate", s);
20342 moddate_given:=substr_of_str("/ModDate", s);
20343 trapped_given:=substr_of_str("/Trapped", s);
20344 end;
20345 if not producer_given then begin
20346 @<Print the Producer key@>;
20347 end;
20348 if pdf_info_toks <> null then begin
20349 if length(s) > 0 then begin
20350 pdf_print_ln(s);
20351 end;
20352 flush_str(s);
20353 delete_toks(pdf_info_toks);
20354 end;
20355 if not creator_given then
20356 pdf_str_entry_ln("Creator", "TeX");
20357 if pdf_info_omit_date = 0 then begin
20358 if not creationdate_given then begin
20359 @<Print the CreationDate key@>;
20360 end;
20361 if not moddate_given then begin
20362 @<Print the ModDate key@>;
20363 end;
20364 end;
20365 if not trapped_given then begin
20366 pdf_print_ln("/Trapped /False");
20367 end;
20368 if pdf_suppress_ptex_info mod 2 = 0 then begin
20369 if get_ptex_use_underscore then
20370 pdf_str_entry_ln("PTEX_Fullbanner", pdftex_banner)
20371 else
20372 pdf_str_entry_ln("PTEX.Fullbanner", pdftex_banner);
20373 end;
20374 pdf_end_dict;
20375 end;
20376
20377 @ @<Print the Producer key@>=
20378 pdf_print("/Producer (pdfTeX-");
20379 pdf_print_int(pdftex_version div 100);
20380 pdf_out(".");
20381 pdf_print_int(pdftex_version mod 100);
20382 pdf_out(".");
20383 pdf_print(pdftex_revision);
20384 pdf_print_ln(")")
20385
20386 @ @<Print the CreationDate key@>=
20387 print_creation_date;
20388
20389 @ @<Print the ModDate key@>=
20390 print_mod_date;
20391
20392 @ @<Glob...@>=
20393 @!pdftex_banner: str_number; {the complete banner}
20394
20395 @ @<Build a linked list of free objects@>=
20396 l := 0;
20397 set_obj_fresh(l); {null object at begin of list of free objects}
20398 for k := 1 to sys_obj_ptr do
20399 if not is_obj_written(k) then begin
20400 obj_link(l) := k;
20401 l := k;
20402 end;
20403 obj_link(l) := 0
20404
20405 @ @<Output the |obj_tab|@>=
20406 @<Build a linked list of free objects@>;
20407 pdf_save_offset := pdf_offset;
20408 pdf_print_ln("xref");
20409 pdf_print("0 "); pdf_print_int_ln(obj_ptr + 1);
20410 pdf_print_fw_int(obj_link(0), 10);
20411 pdf_print_ln(" 65535 f ");
20412 for k := 1 to obj_ptr do begin
20413 if not is_obj_written(k) then begin
20414 pdf_print_fw_int(obj_link(k), 10);
20415 pdf_print_ln(" 00000 f ");
20416 end
20417 else begin
20418 pdf_print_fw_int(obj_offset(k), 10);
20419 pdf_print_ln(" 00000 n ");
20420 end;
20421 end
20422
20423 @ @<Output the cross-reference stream dictionary@>=
20424 pdf_new_dict(obj_type_others, 0, 0);
20425 if ((obj_offset(sys_obj_ptr)/256) > 16777215) then
20426 xref_offset_width := 5
20427 else if obj_offset(sys_obj_ptr) > 16777215 then
20428 xref_offset_width := 4
20429 else if obj_offset(sys_obj_ptr) > 65535 then
20430 xref_offset_width := 3
20431 else
20432 xref_offset_width := 2;
20433 @<Build a linked list of free objects@>;
20434 pdf_print_ln("/Type /XRef");
20435 pdf_print("/Index [0 ");
20436 pdf_print_int(obj_ptr + 1);
20437 pdf_print_ln("]");
20438 pdf_int_entry_ln("Size", obj_ptr + 1);
20439 pdf_print("/W [1 ");
20440 pdf_print_int(xref_offset_width);
20441 pdf_print_ln(" 1]");
20442 pdf_indirect_ln("Root", root);
20443 if pdf_omit_info_dict = 0 then pdf_indirect_ln("Info", obj_ptr - 1);
20444 if pdf_trailer_toks <> null then begin
20445 pdf_print_toks_ln(pdf_trailer_toks);
20446 delete_toks(pdf_trailer_toks);
20447 end;
20448 if pdf_trailer_id_toks <> null then
20449 print_ID_alt(pdf_trailer_id_toks)
20450 else
20451 print_ID(output_file_name);
20452 pdf_print_nl;
20453 pdf_begin_stream;
20454 for k := 0 to sys_obj_ptr do begin
20455 if not is_obj_written(k) then begin {a free object}
20456 pdf_out(0);
20457 pdf_out_bytes(obj_link(k), xref_offset_width);
20458 pdf_out(255);
20459 end else begin
20460 if obj_os_idx(k) = -1 then begin {object not in object stream}
20461 pdf_out(1);
20462 pdf_out_bytes(obj_offset(k), xref_offset_width);
20463 pdf_out(0);
20464 end else begin {object in object stream}
20465 pdf_out(2);
20466 pdf_out_bytes(obj_offset(k), xref_offset_width);
20467 pdf_out(obj_os_idx(k));
20468 end;
20469 end;
20470 end;
20471 pdf_end_stream;
20472
20473 @ @<Output the trailer@>=
20474 if not pdf_os_enable then begin
20475 pdf_print_ln("trailer");
20476 pdf_print("<< ");
20477 pdf_int_entry_ln("Size", sys_obj_ptr + 1);
20478 pdf_indirect_ln("Root", root);
20479 if pdf_omit_info_dict = 0 then pdf_indirect_ln("Info", sys_obj_ptr);
20480 if pdf_trailer_toks <> null then begin
20481 pdf_print_toks_ln(pdf_trailer_toks);
20482 delete_toks(pdf_trailer_toks);
20483 end;
20484 if pdf_trailer_id_toks <> null then
20485 print_ID_alt(pdf_trailer_id_toks)
20486 else
20487 print_ID(output_file_name);
20488 pdf_print_ln(" >>");
20489 end;
20490 pdf_print_ln("startxref");
20491 if pdf_os_enable then
20492 pdf_print_int_ln(obj_offset(sys_obj_ptr))
20493 else
20494 pdf_print_int_ln(pdf_save_offset);
20495 pdf_print_ln("%%EOF")
20496
20497 @* \[33] Packaging.
20498 We're essentially done with the parts of \TeX\ that are concerned with
20499 the input (|get_next|) and the output (|ship_out|). So it's time to
20500 get heavily into the remaining part, which does the real work of typesetting.
20501
20502 After lists are constructed, \TeX\ wraps them up and puts them into boxes.
20503 Two major subroutines are given the responsibility for this task: |hpack|
20504 applies to horizontal lists (hlists) and |vpack| applies to vertical lists
20505 (vlists). The main duty of |hpack| and |vpack| is to compute the dimensions
20506 of the resulting boxes, and to adjust the glue if one of those dimensions
20507 is pre-specified. The computed sizes normally enclose all of the material
20508 inside the new box; but some items may stick out if negative glue is used,
20509 if the box is overfull, or if a \.{\\vbox} includes other boxes that have
20510 been shifted left.
20511
20512 The subroutine call |hpack(p,w,m)| returns a pointer to an |hlist_node|
20513 for a box containing the hlist that starts at |p|. Parameter |w| specifies
20514 a width; and parameter |m| is either `|exactly|' or `|additional|'. Thus,
20515 |hpack(p,w,exactly)| produces a box whose width is exactly |w|, while
20516 |hpack(p,w,additional)| yields a box whose width is the natural width plus
20517 |w|. It is convenient to define a macro called `|natural|' to cover the
20518 most common case, so that we can say |hpack(p,natural)| to get a box that
20519 has the natural width of list |p|.
20520
20521 Similarly, |vpack(p,w,m)| returns a pointer to a |vlist_node| for a
20522 box containing the vlist that starts at |p|. In this case |w| represents
20523 a height instead of a width; the parameter |m| is interpreted as in |hpack|.
20524
20525 @d exactly=0 {a box dimension is pre-specified}
20526 @d additional=1 {a box dimension is increased from the natural one}
20527 @d natural==0,additional {shorthand for parameters to |hpack| and |vpack|}
20528
20529 @ The parameters to |hpack| and |vpack| correspond to \TeX's primitives
20530 like `\.{\\hbox} \.{to} \.{300pt}', `\.{\\hbox} \.{spread} \.{10pt}'; note
20531 that `\.{\\hbox}' with no dimension following it is equivalent to
20532 `\.{\\hbox} \.{spread} \.{0pt}'. The |scan_spec| subroutine scans such
20533 constructions in the user's input, including the mandatory left brace that
20534 follows them, and it puts the specification onto |save_stack| so that the
20535 desired box can later be obtained by executing the following code:
20536 $$\vbox{\halign{#\hfil\cr
20537 |save_ptr:=save_ptr-2;|\cr
20538 |hpack(p,saved(1),saved(0)).|\cr}}$$
20539 Special care is necessary to ensure that the special |save_stack| codes
20540 are placed just below the new group code, because scanning can change
20541 |save_stack| when \.{\\csname} appears.
20542
20543 @p procedure scan_spec(@!c:group_code;@!three_codes:boolean);
20544 {scans a box specification and left brace}
20545 label found;
20546 var @!s:integer; {temporarily saved value}
20547 @!spec_code:exactly..additional;
20548 begin if three_codes then s:=saved(0);
20549 if scan_keyword("to") then spec_code:=exactly
20550 @.to@>
20551 else if scan_keyword("spread") then spec_code:=additional
20552 @.spread@>
20553 else begin spec_code:=additional; cur_val:=0;
20554 goto found;
20555 end;
20556 scan_normal_dimen;
20557 found: if three_codes then
20558 begin saved(0):=s; incr(save_ptr);
20559 end;
20560 saved(0):=spec_code; saved(1):=cur_val; save_ptr:=save_ptr+2;
20561 new_save_level(c); scan_left_brace;
20562 end;
20563
20564 @ To figure out the glue setting, |hpack| and |vpack| determine how much
20565 stretchability and shrinkability are present, considering all four orders
20566 of infinity. The highest order of infinity that has a nonzero coefficient
20567 is then used as if no other orders were present.
20568
20569 For example, suppose that the given list contains six glue nodes with
20570 the respective stretchabilities 3pt, 8fill, 5fil, 6pt, $-3$fil, $-8$fill.
20571 Then the total is essentially 2fil; and if a total additional space of 6pt
20572 is to be achieved by stretching, the actual amounts of stretch will be
20573 0pt, 0pt, 15pt, 0pt, $-9$pt, and 0pt, since only `fil' glue will be
20574 considered. (The `fill' glue is therefore not really stretching infinitely
20575 with respect to `fil'; nobody would actually want that to happen.)
20576
20577 The arrays |total_stretch| and |total_shrink| are used to determine how much
20578 glue of each kind is present. A global variable |last_badness| is used
20579 to implement \.{\\badness}.
20580
20581 @<Glob...@>=
20582 @!total_stretch, @!total_shrink: array[glue_ord] of scaled;
20583 {glue found by |hpack| or |vpack|}
20584 @!last_badness:integer; {badness of the most recently packaged box}
20585
20586 @ If the global variable |adjust_tail| is non-null, the |hpack| routine
20587 also removes all occurrences of |ins_node|, |mark_node|, and |adjust_node|
20588 items and appends the resulting material onto the list that ends at
20589 location |adjust_tail|.
20590
20591 @<Glob...@>=
20592 @!adjust_tail:pointer; {tail of adjustment list}
20593
20594 @ @<Set init...@>=adjust_tail:=null; last_badness:=0;
20595
20596 @ @<Glob...@>=
20597 @!pdf_font_blink: ^internal_font_number; {link to base font (used for expanded fonts only)}
20598 @!pdf_font_elink: ^internal_font_number; {link to expanded fonts (used for base fonts only)}
20599 @!pdf_font_has_space_char: ^boolean; {has font a real space char?}
20600 @!pdf_font_stretch: ^integer; {link to font expanded by stretch limi}
20601 @!pdf_font_shrink: ^integer; {link to font expanded by shrink limit}
20602 @!pdf_font_step: ^integer; {amount of one step of expansion}
20603 @!pdf_font_expand_ratio: ^integer; {expansion ratio of a particular font}
20604 @!pdf_font_auto_expand: ^boolean; {this font is auto-expanded?}
20605 @!pdf_font_lp_base: ^integer; {base of left-protruding factor}
20606 @!pdf_font_rp_base: ^integer; {base of right-protruding factor}
20607 @!pdf_font_ef_base: ^integer; {base of font expansion factor}
20608 @!pdf_font_kn_bs_base: ^integer; {base of kern before space}
20609 @!pdf_font_st_bs_base: ^integer; {base of stretch before space}
20610 @!pdf_font_sh_bs_base: ^integer; {base of shrink before space}
20611 @!pdf_font_kn_bc_base: ^integer; {base of kern before character}
20612 @!pdf_font_kn_ac_base: ^integer; {base of kern after character}
20613 @!font_expand_ratio: integer; {current expansion ratio}
20614 @!last_leftmost_char: pointer;
20615 @!last_rightmost_char: pointer;
20616 @!hlist_stack:array[0..max_hlist_stack] of pointer; {stack for |find_protchar_left()| and |find_protchar_right()|}
20617 @!hlist_stack_level:0..max_hlist_stack; {fill level for |hlist_stack|}
20618
20619 @ @d cal_margin_kern_var(#) ==
20620 begin
20621 character(cp) := character(#);
20622 font(cp) := font(#);
20623 do_subst_font(cp, 1000);
20624 if font(cp) <> font(#) then
20625 margin_kern_stretch := margin_kern_stretch + left_pw(#) - left_pw(cp);
20626 font(cp) := font(#);
20627 do_subst_font(cp, -1000);
20628 if font(cp) <> font(#) then
20629 margin_kern_shrink := margin_kern_shrink + left_pw(cp) - left_pw(#);
20630 end
20631
20632 @<Calculate variations of marginal kerns@>=
20633 begin
20634 lp := last_leftmost_char;
20635 rp := last_rightmost_char;
20636 fast_get_avail(cp);
20637 if lp <> null then
20638 cal_margin_kern_var(lp);
20639 if rp <> null then
20640 cal_margin_kern_var(rp);
20641 free_avail(cp);
20642 end
20643
20644 @ Here is |hpack|, which is place where we do font substituting when
20645 font expansion is being used. We define some constants used when calling
20646 |hpack| to deal with font expansion.
20647
20648 @d cal_expand_ratio == 2 {calculate amount for font expansion after breaking
20649 paragraph into lines}
20650 @d subst_ex_font == 3 {substitute fonts}
20651
20652 @d substituted = 3 {|subtype| of kern nodes that should be substituted}
20653
20654 @d left_pw(#) == char_pw(#, left_side)
20655 @d right_pw(#) == char_pw(#, right_side)
20656
20657 @p
20658 function check_expand_pars(f: internal_font_number): boolean;
20659 var k: internal_font_number;
20660 begin
20661 check_expand_pars := false;
20662 if (pdf_font_step[f] = 0) or ((pdf_font_stretch[f] = null_font) and
20663 (pdf_font_shrink[f] = null_font)) then
20664 return;
20665 if cur_font_step < 0 then
20666 cur_font_step := pdf_font_step[f]
20667 else if cur_font_step <> pdf_font_step[f] then
20668 pdf_error("font expansion", "using fonts with different step of expansion in one paragraph is not allowed");
20669 k := pdf_font_stretch[f];
20670 if k <> null_font then begin
20671 if max_stretch_ratio < 0 then
20672 max_stretch_ratio := pdf_font_expand_ratio[k]
20673 else if max_stretch_ratio <> pdf_font_expand_ratio[k] then
20674 pdf_error("font expansion", "using fonts with different limit of expansion in one paragraph is not allowed");
20675 end;
20676 k := pdf_font_shrink[f];
20677 if k <> null_font then begin
20678 if max_shrink_ratio < 0 then
20679 max_shrink_ratio := -pdf_font_expand_ratio[k]
20680 else if max_shrink_ratio <> -pdf_font_expand_ratio[k] then
20681 pdf_error("font expansion", "using fonts with different limit of expansion in one paragraph is not allowed");
20682 end;
20683 check_expand_pars := true;
20684 end;
20685
20686 function char_stretch(f: internal_font_number; c: eight_bits): scaled;
20687 var k: internal_font_number;
20688 dw: scaled;
20689 ef: integer;
20690 begin
20691 char_stretch := 0;
20692 k := pdf_font_stretch[f];
20693 ef := get_ef_code(f, c);
20694 if (k <> null_font) and (ef > 0) then begin
20695 dw := char_width(k)(char_info(k)(c)) - char_width(f)(char_info(f)(c));
20696 if dw > 0 then
20697 char_stretch := round_xn_over_d(dw, ef, 1000);
20698 end;
20699 end;
20700
20701 function char_shrink(f: internal_font_number; c: eight_bits): scaled;
20702 var k: internal_font_number;
20703 dw: scaled;
20704 ef: integer;
20705 begin
20706 char_shrink := 0;
20707 k := pdf_font_shrink[f];
20708 ef := get_ef_code(f, c);
20709 if (k <> null_font) and (ef > 0) then begin
20710 dw := char_width(f)(char_info(f)(c)) - char_width(k)(char_info(k)(c));
20711 if dw > 0 then
20712 char_shrink := round_xn_over_d(dw, ef, 1000);
20713 end;
20714 end;
20715
20716 function get_kern(f: internal_font_number; lc, rc: eight_bits): scaled;
20717 label continue;
20718 var i: four_quarters;
20719 j: four_quarters;
20720 k: font_index;
20721 begin
20722 get_kern := 0;
20723 i := char_info(f)(lc);
20724 if char_tag(i) <> lig_tag then
20725 return;
20726 k := lig_kern_start(f)(i);
20727 j := font_info[k].qqqq;
20728 if skip_byte(j) <= stop_flag then
20729 goto continue + 1;
20730 k := lig_kern_restart(f)(j);
20731 continue:
20732 j := font_info[k].qqqq;
20733 continue + 1:
20734 if (next_char(j) = rc) and (skip_byte(j) <= stop_flag) and
20735 (op_byte(j) >= kern_flag)
20736 then begin
20737 get_kern := char_kern(f)(j);
20738 return;
20739 end;
20740 if skip_byte(j) = qi(0) then
20741 incr(k)
20742 else begin
20743 if skip_byte(j) >= stop_flag then
20744 return;
20745 k := k + qo(skip_byte(j)) + 1;
20746 end;
20747 goto continue;
20748 end;
20749
20750 function kern_stretch(p: pointer): scaled;
20751 var l, r: pointer;
20752 d: scaled;
20753 begin
20754 kern_stretch := 0;
20755 if (prev_char_p = null) or (link(prev_char_p) <> p) or (link(p) = null)
20756 then
20757 return;
20758 l := prev_char_p;
20759 r := link(p);
20760 if not is_char_node(l) then
20761 if type(l) = ligature_node then
20762 l := lig_char(l)
20763 else
20764 return;
20765 if not is_char_node(r) then
20766 if type(r) = ligature_node then
20767 r := lig_char(r)
20768 else
20769 return;
20770 if not ((font(l) = font(r)) and
20771 (pdf_font_stretch[font(l)] <> null_font))
20772 then
20773 return;
20774 d := get_kern(pdf_font_stretch[font(l)], character(l), character(r));
20775 kern_stretch := round_xn_over_d(d - width(p),
20776 get_ef_code(font(l), character(l)), 1000);
20777 end;
20778
20779 function kern_shrink(p: pointer): scaled;
20780 var l, r: pointer;
20781 d: scaled;
20782 begin
20783 kern_shrink := 0;
20784 if (prev_char_p = null) or (link(prev_char_p) <> p) or (link(p) = null)
20785 then
20786 return;
20787 l := prev_char_p;
20788 r := link(p);
20789 if not is_char_node(l) then
20790 if type(l) = ligature_node then
20791 l := lig_char(l)
20792 else
20793 return;
20794 if not is_char_node(r) then
20795 if type(r) = ligature_node then
20796 r := lig_char(r)
20797 else
20798 return;
20799 if not ((font(l) = font(r)) and
20800 (pdf_font_shrink[font(l)] <> null_font))
20801 then
20802 return;
20803 d := get_kern(pdf_font_shrink[font(l)], character(l), character(r));
20804 kern_shrink := round_xn_over_d(width(p) - d,
20805 get_ef_code(font(l), character(l)), 1000);
20806 end;
20807
20808 procedure do_subst_font(p: pointer; ex_ratio: integer);
20809 var f, k: internal_font_number;
20810 r: pointer;
20811 ef: integer;
20812 begin
20813 if not is_char_node(p) and (type(p) = disc_node) then begin
20814 r := pre_break(p);
20815 while r <> null do begin
20816 if is_char_node(r) or (type(r) = ligature_node) then
20817 do_subst_font(r, ex_ratio);
20818 r := link(r);
20819 end;
20820 r := post_break(p);
20821 while r <> null do begin
20822 if is_char_node(r) or (type(r) = ligature_node) then
20823 do_subst_font(r, ex_ratio);
20824 r := link(r);
20825 end;
20826 return;
20827 end;
20828 if is_char_node(p) then
20829 r := p
20830 else if type(p) = ligature_node then
20831 r := lig_char(p)
20832 else begin
20833 {|short_display_n(p, 5);|}
20834 pdf_error("font expansion", "invalid node type");
20835 end;
20836 f := font(r);
20837 ef := get_ef_code(f, character(r));
20838 if ef = 0 then
20839 return;
20840 if (pdf_font_stretch[f] <> null_font) and (ex_ratio > 0) then
20841 k := expand_font(f, ext_xn_over_d(ex_ratio*ef,
20842 pdf_font_expand_ratio[pdf_font_stretch[f]],
20843 1000000))
20844 else if (pdf_font_shrink[f] <> null_font) and (ex_ratio < 0) then
20845 k := expand_font(f, ext_xn_over_d(ex_ratio*ef,
20846 -pdf_font_expand_ratio[pdf_font_shrink[f]],
20847 1000000))
20848 else
20849 k := f;
20850 if k <> f then begin
20851 font(r) := k;
20852 if not is_char_node(p) then begin
20853 r := lig_ptr(p);
20854 while r <> null do begin
20855 font(r) := k;
20856 r := link(r);
20857 end;
20858 end;
20859 end;
20860 end;
20861
20862 function char_pw(p: pointer; side: small_number): scaled;
20863 var f: internal_font_number;
20864 c: integer;
20865 begin
20866 char_pw := 0;
20867 if side = left_side then
20868 last_leftmost_char := null
20869 else
20870 last_rightmost_char := null;
20871 if p = null then
20872 return;
20873 if not is_char_node(p) then begin
20874 if type(p) = ligature_node then
20875 p := lig_char(p)
20876 else
20877 return;
20878 end;
20879 f := font(p);
20880 if side = left_side then begin
20881 c := get_lp_code(f, character(p));
20882 last_leftmost_char := p;
20883 end
20884 else begin
20885 c := get_rp_code(f, character(p));
20886 last_rightmost_char := p;
20887 end;
20888 if c = 0 then
20889 return;
20890 char_pw :=
20891 round_xn_over_d(quad(f), c, 1000);
20892 end;
20893
20894 function new_margin_kern(w: scaled; p: pointer; side: small_number): pointer;
20895 var k: pointer;
20896 begin
20897 k := get_node(margin_kern_node_size);
20898 type(k) := margin_kern_node;
20899 subtype(k) := side;
20900 width(k) := w;
20901 if p = null then
20902 pdf_error("margin kerning", "invalid pointer to marginal char node");
20903 fast_get_avail(margin_char(k));
20904 character(margin_char(k)) := character(p);
20905 font(margin_char(k)) := font(p);
20906 new_margin_kern := k;
20907 end;
20908
20909 function hpack(@!p:pointer;@!w:scaled;@!m:small_number):pointer;
20910 label reswitch, common_ending, exit;
20911 var r:pointer; {the box node that will be returned}
20912 @!q:pointer; {trails behind |p|}
20913 @!h,@!d,@!x:scaled; {height, depth, and natural width}
20914 @!s:scaled; {shift amount}
20915 @!g:pointer; {points to a glue specification}
20916 @!o:glue_ord; {order of infinity}
20917 @!f:internal_font_number; {the font in a |char_node|}
20918 @!i:four_quarters; {font information about a |char_node|}
20919 @!hd:eight_bits; {height and depth indices for a character}
20920 font_stretch: scaled;
20921 font_shrink: scaled;
20922 k: scaled;
20923 begin last_badness:=0; r:=get_node(box_node_size); type(r):=hlist_node;
20924 subtype(r):=min_quarterword; shift_amount(r):=0;
20925 q:=r+list_offset; link(q):=p;@/
20926 if m = cal_expand_ratio then begin
20927 prev_char_p := null;
20928 font_stretch := 0;
20929 font_shrink := 0;
20930 font_expand_ratio := 0;
20931 end;
20932 h:=0; @<Clear dimensions to zero@>;
20933 if TeXXeT_en then @<Initialize the LR stack@>;
20934 while p<>null do @<Examine node |p| in the hlist, taking account of its effect
20935 on the dimensions of the new box, or moving it to the adjustment list;
20936 then advance |p| to the next node@>;
20937 if adjust_tail<>null then link(adjust_tail):=null;
20938 if pre_adjust_tail<>null then link(pre_adjust_tail):=null;
20939 height(r):=h; depth(r):=d;@/
20940 @<Determine the value of |width(r)| and the appropriate glue setting;
20941 then |return| or |goto common_ending|@>;
20942 common_ending: @<Finish issuing a diagnostic message
20943 for an overfull or underfull hbox@>;
20944 exit: if TeXXeT_en then @<Check for LR anomalies at the end of |hpack|@>;
20945 if (m = cal_expand_ratio) and (font_expand_ratio <> 0) then begin
20946 font_expand_ratio := fix_int(font_expand_ratio, -1000, 1000);
20947 q := list_ptr(r);
20948 free_node(r, box_node_size);
20949 r := hpack(q, w, subst_ex_font);
20950 end;
20951 hpack:=r;
20952 end;
20953
20954 @ @<Clear dimensions to zero@>=
20955 d:=0; x:=0;
20956 total_stretch[normal]:=0; total_shrink[normal]:=0;
20957 total_stretch[fil]:=0; total_shrink[fil]:=0;
20958 total_stretch[fill]:=0; total_shrink[fill]:=0;
20959 total_stretch[filll]:=0; total_shrink[filll]:=0
20960
20961 @ @<Examine node |p| in the hlist, taking account of its effect...@>=
20962 @^inner loop@>
20963 begin reswitch: while is_char_node(p) do
20964 @<Incorporate character dimensions into the dimensions of
20965 the hbox that will contain~it, then move to the next node@>;
20966 if p<>null then
20967 begin case type(p) of
20968 hlist_node,vlist_node,rule_node,unset_node:
20969 @<Incorporate box dimensions into the dimensions of
20970 the hbox that will contain~it@>;
20971 ins_node,mark_node,adjust_node: if (adjust_tail<>null) or (pre_adjust_tail<> null) then
20972 @<Transfer node |p| to the adjustment list@>;
20973 whatsit_node:@<Incorporate a whatsit node into an hbox@>;
20974 glue_node:@<Incorporate glue into the horizontal totals@>;
20975 margin_kern_node: begin
20976 if m = cal_expand_ratio then begin
20977 f := font(margin_char(p));
20978 do_subst_font(margin_char(p), 1000);
20979 if f <> font(margin_char(p)) then
20980 font_stretch := font_stretch - width(p) -
20981 char_pw(margin_char(p), subtype(p));
20982 font(margin_char(p)) := f;
20983 do_subst_font(margin_char(p), -1000);
20984 if f <> font(margin_char(p)) then
20985 font_shrink := font_shrink - width(p) -
20986 char_pw(margin_char(p), subtype(p));
20987 font(margin_char(p)) := f;
20988 end
20989 else if m = subst_ex_font then begin
20990 do_subst_font(margin_char(p), font_expand_ratio);
20991 width(p) := -char_pw(margin_char(p), subtype(p));
20992 end;
20993 x := x + width(p);
20994 end;
20995 kern_node: begin
20996 if subtype(p) = normal then begin
20997 if m = cal_expand_ratio then begin
20998 font_stretch := font_stretch + kern_stretch(p);
20999 font_shrink := font_shrink + kern_shrink(p);
21000 end
21001 else if m = subst_ex_font then begin
21002 if font_expand_ratio > 0 then
21003 k := kern_stretch(p)
21004 else if font_expand_ratio < 0 then
21005 k := kern_shrink(p)
21006 else
21007 pdfassert(0);
21008 if k <> 0 then begin
21009 if is_char_node(link(p)) then
21010 width(p) := get_kern(font(prev_char_p),
21011 character(prev_char_p),
21012 character(link(p)))
21013 else if type(link(p)) = ligature_node then
21014 width(p) := get_kern(font(prev_char_p),
21015 character(prev_char_p),
21016 character(lig_char(link(p))));
21017 end;
21018 end;
21019 end;
21020 x := x + width(p);
21021 end;
21022 math_node: begin x:=x+width(p);
21023 if TeXXeT_en then @<Adjust \(t)the LR stack for the |hpack| routine@>;
21024 end;
21025 ligature_node: begin
21026 if m = subst_ex_font then
21027 do_subst_font(p, font_expand_ratio);
21028 @<Make node |p| look like a |char_node| and |goto reswitch|@>;
21029 end;
21030 disc_node:
21031 if m = subst_ex_font then
21032 do_subst_font(p, font_expand_ratio);
21033 othercases do_nothing
21034 endcases;@/
21035 p:=link(p);
21036 end;
21037 end
21038
21039
21040 @ @<Make node |p| look like a |char_node| and |goto reswitch|@>=
21041 begin mem[lig_trick]:=mem[lig_char(p)]; link(lig_trick):=link(p);
21042 p:=lig_trick; goto reswitch;
21043 end
21044
21045 @ The code here implicitly uses the fact that running dimensions are
21046 indicated by |null_flag|, which will be ignored in the calculations
21047 because it is a highly negative number.
21048
21049 @<Incorporate box dimensions into the dimensions of the hbox...@>=
21050 begin x:=x+width(p);
21051 if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
21052 if height(p)-s>h then h:=height(p)-s;
21053 if depth(p)+s>d then d:=depth(p)+s;
21054 end
21055
21056 @ The following code is part of \TeX's inner loop; i.e., adding another
21057 character of text to the user's input will cause each of these instructions
21058 to be exercised one more time.
21059 @^inner loop@>
21060
21061 @<Incorporate character dimensions into the dimensions of the hbox...@>=
21062 begin
21063 if m >= cal_expand_ratio then begin
21064 prev_char_p := p;
21065 case m of
21066 cal_expand_ratio: begin
21067 f := font(p);
21068 add_char_stretch(font_stretch)(character(p));
21069 add_char_shrink(font_shrink)(character(p));
21070 end;
21071 subst_ex_font:
21072 do_subst_font(p, font_expand_ratio);
21073 endcases;
21074 end;
21075 f:=font(p); i:=char_info(f)(character(p)); hd:=height_depth(i);
21076 x:=x+char_width(f)(i);@/
21077 s:=char_height(f)(hd);@+if s>h then h:=s;
21078 s:=char_depth(f)(hd);@+if s>d then d:=s;
21079 p:=link(p);
21080 end
21081
21082 @ Although node |q| is not necessarily the immediate predecessor of node |p|,
21083 it always points to some node in the list preceding |p|. Thus, we can delete
21084 nodes by moving |q| when necessary. The algorithm takes linear time, and the
21085 extra computation does not intrude on the inner loop unless it is necessary
21086 to make a deletion.
21087 @^inner loop@>
21088
21089 @<Glob...@>=
21090 @!pre_adjust_tail: pointer;
21091
21092 @ @<Set init...@>=
21093 pre_adjust_tail := null;
21094
21095 @ Materials in \.{\\vadjust} used with \.{pre} keyword will be appended to
21096 |pre_adjust_tail| instead of |adjust_tail|.
21097
21098 @d update_adjust_list(#) == begin
21099 if # = null then
21100 confusion("pre vadjust");
21101 link(#) := adjust_ptr(p);
21102 while link(#) <> null do
21103 # := link(#);
21104 end
21105
21106 @<Transfer node |p| to the adjustment list@>=
21107 begin while link(q)<>p do q:=link(q);
21108 if type(p) = adjust_node then begin
21109 if adjust_pre(p) <> 0 then
21110 update_adjust_list(pre_adjust_tail)
21111 else
21112 update_adjust_list(adjust_tail);
21113 p := link(p); free_node(link(q), small_node_size);
21114 end
21115 else begin link(adjust_tail):=p; adjust_tail:=p; p:=link(p);
21116 end;
21117 link(q):=p; p:=q;
21118 end
21119
21120 @ @<Incorporate glue into the horizontal totals@>=
21121 begin g:=glue_ptr(p); x:=x+width(g);@/
21122 o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
21123 o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
21124 if subtype(p)>=a_leaders then
21125 begin g:=leader_ptr(p);
21126 if height(g)>h then h:=height(g);
21127 if depth(g)>d then d:=depth(g);
21128 end;
21129 end
21130
21131 @ When we get to the present part of the program, |x| is the natural width
21132 of the box being packaged.
21133
21134 @<Determine the value of |width(r)| and the appropriate glue setting...@>=
21135 if m=additional then w:=x+w;
21136 width(r):=w; x:=w-x; {now |x| is the excess to be made up}
21137 if x=0 then
21138 begin glue_sign(r):=normal; glue_order(r):=normal;
21139 set_glue_ratio_zero(glue_set(r));
21140 return;
21141 end
21142 else if x>0 then @<Determine horizontal glue stretch setting, then |return|
21143 or \hbox{|goto common_ending|}@>
21144 else @<Determine horizontal glue shrink setting, then |return|
21145 or \hbox{|goto common_ending|}@>
21146
21147 @ If |hpack| is called with |m=cal_expand_ratio| we calculate
21148 |font_expand_ratio| and return without checking for overfull or underfull box.
21149
21150 @<Determine horizontal glue stretch setting...@>=
21151 begin @<Determine the stretch order@>;
21152 if (m = cal_expand_ratio) and (o = normal) and (font_stretch > 0) then begin
21153 font_expand_ratio := divide_scaled(x, font_stretch, 3);
21154 return;
21155 end;
21156 glue_order(r):=o; glue_sign(r):=stretching;
21157 if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
21158 @^real division@>
21159 else begin glue_sign(r):=normal;
21160 set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
21161 end;
21162 if o=normal then if list_ptr(r)<>null then
21163 @<Report an underfull hbox and |goto common_ending|, if this box
21164 is sufficiently bad@>;
21165 return;
21166 end
21167
21168 @ @<Determine the stretch order@>=
21169 if total_stretch[filll]<>0 then o:=filll
21170 else if total_stretch[fill]<>0 then o:=fill
21171 else if total_stretch[fil]<>0 then o:=fil
21172 else o:=normal
21173
21174 @ @<Report an underfull hbox and |goto common_ending|, if...@>=
21175 begin last_badness:=badness(x,total_stretch[normal]);
21176 if last_badness>hbadness then
21177 begin print_ln;
21178 if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
21179 print(" \hbox (badness "); print_int(last_badness);
21180 @.Underfull \\hbox...@>
21181 @.Loose \\hbox...@>
21182 goto common_ending;
21183 end;
21184 end
21185
21186 @ In order to provide a decent indication of where an overfull or underfull
21187 box originated, we use a global variable |pack_begin_line| that is
21188 set nonzero only when |hpack| is being called by the paragraph builder
21189 or the alignment finishing routine.
21190
21191 @<Glob...@>=
21192 @!pack_begin_line:integer; {source file line where the current paragraph
21193 or alignment began; a negative value denotes alignment}
21194
21195 @ @<Set init...@>=
21196 pack_begin_line:=0;
21197
21198 @ @<Finish issuing a diagnostic message for an overfull or underfull hbox@>=
21199 if output_active then print(") has occurred while \output is active")
21200 else begin if pack_begin_line<>0 then
21201 begin if pack_begin_line>0 then print(") in paragraph at lines ")
21202 else print(") in alignment at lines ");
21203 print_int(abs(pack_begin_line));
21204 print("--");
21205 end
21206 else print(") detected at line ");
21207 print_int(line);
21208 end;
21209 print_ln;@/
21210 font_in_short_display:=null_font; short_display(list_ptr(r)); print_ln;@/
21211 begin_diagnostic; show_box(r); end_diagnostic(true)
21212
21213 @ @<Determine horizontal glue shrink setting...@>=
21214 begin @<Determine the shrink order@>;
21215 if (m = cal_expand_ratio) and (o = normal) and (font_shrink > 0) then begin
21216 font_expand_ratio := divide_scaled(x, font_shrink, 3);
21217 return;
21218 end;
21219 glue_order(r):=o; glue_sign(r):=shrinking;
21220 if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
21221 @^real division@>
21222 else begin glue_sign(r):=normal;
21223 set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
21224 end;
21225 if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
21226 begin last_badness:=1000000;
21227 set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
21228 @<Report an overfull hbox and |goto common_ending|, if this box
21229 is sufficiently bad@>;
21230 end
21231 else if o=normal then if list_ptr(r)<>null then
21232 @<Report a tight hbox and |goto common_ending|, if this box
21233 is sufficiently bad@>;
21234 return;
21235 end
21236
21237 @ @<Determine the shrink order@>=
21238 if total_shrink[filll]<>0 then o:=filll
21239 else if total_shrink[fill]<>0 then o:=fill
21240 else if total_shrink[fil]<>0 then o:=fil
21241 else o:=normal
21242
21243 @ @<Report an overfull hbox and |goto common_ending|, if...@>=
21244 if (-x-total_shrink[normal]>hfuzz)or(hbadness<100) then
21245 begin if (overfull_rule>0)and(-x-total_shrink[normal]>hfuzz) then
21246 begin while link(q)<>null do q:=link(q);
21247 link(q):=new_rule;
21248 width(link(q)):=overfull_rule;
21249 end;
21250 print_ln; print_nl("Overfull \hbox (");
21251 @.Overfull \\hbox...@>
21252 print_scaled(-x-total_shrink[normal]); print("pt too wide");
21253 goto common_ending;
21254 end
21255
21256 @ @<Report a tight hbox and |goto common_ending|, if...@>=
21257 begin last_badness:=badness(-x,total_shrink[normal]);
21258 if last_badness>hbadness then
21259 begin print_ln; print_nl("Tight \hbox (badness "); print_int(last_badness);
21260 @.Tight \\hbox...@>
21261 goto common_ending;
21262 end;
21263 end
21264
21265 @ The |vpack| subroutine is actually a special case of a slightly more
21266 general routine called |vpackage|, which has four parameters. The fourth
21267 parameter, which is |max_dimen| in the case of |vpack|, specifies the
21268 maximum depth of the page box that is constructed. The depth is first
21269 computed by the normal rules; if it exceeds this limit, the reference
21270 point is simply moved down until the limiting depth is attained.
21271
21272 @d vpack(#)==vpackage(#,max_dimen) {special case of unconstrained depth}
21273
21274 @p function vpackage(@!p:pointer;@!h:scaled;@!m:small_number;@!l:scaled):
21275 pointer;
21276 label common_ending, exit;
21277 var r:pointer; {the box node that will be returned}
21278 @!w,@!d,@!x:scaled; {width, depth, and natural height}
21279 @!s:scaled; {shift amount}
21280 @!g:pointer; {points to a glue specification}
21281 @!o:glue_ord; {order of infinity}
21282 begin last_badness:=0; r:=get_node(box_node_size); type(r):=vlist_node;
21283 subtype(r):=min_quarterword; shift_amount(r):=0;
21284 list_ptr(r):=p;@/
21285 w:=0; @<Clear dimensions to zero@>;
21286 while p<>null do @<Examine node |p| in the vlist, taking account of its effect
21287 on the dimensions of the new box; then advance |p| to the next node@>;
21288 width(r):=w;
21289 if d>l then
21290 begin x:=x+d-l; depth(r):=l;
21291 end
21292 else depth(r):=d;
21293 @<Determine the value of |height(r)| and the appropriate glue setting;
21294 then |return| or |goto common_ending|@>;
21295 common_ending: @<Finish issuing a diagnostic message
21296 for an overfull or underfull vbox@>;
21297 exit: vpackage:=r;
21298 end;
21299
21300 @ @<Examine node |p| in the vlist, taking account of its effect...@>=
21301 begin if is_char_node(p) then confusion("vpack")
21302 @:this can't happen vpack}{\quad vpack@>
21303 else case type(p) of
21304 hlist_node,vlist_node,rule_node,unset_node:
21305 @<Incorporate box dimensions into the dimensions of
21306 the vbox that will contain~it@>;
21307 whatsit_node:@<Incorporate a whatsit node into a vbox@>;
21308 glue_node: @<Incorporate glue into the vertical totals@>;
21309 kern_node: begin x:=x+d+width(p); d:=0;
21310 end;
21311 othercases do_nothing
21312 endcases;
21313 p:=link(p);
21314 end
21315
21316 @ @<Incorporate box dimensions into the dimensions of the vbox...@>=
21317 begin x:=x+d+height(p); d:=depth(p);
21318 if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
21319 if width(p)+s>w then w:=width(p)+s;
21320 end
21321
21322 @ @<Incorporate glue into the vertical totals@>=
21323 begin x:=x+d; d:=0;@/
21324 g:=glue_ptr(p); x:=x+width(g);@/
21325 o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
21326 o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
21327 if subtype(p)>=a_leaders then
21328 begin g:=leader_ptr(p);
21329 if width(g)>w then w:=width(g);
21330 end;
21331 end
21332
21333 @ When we get to the present part of the program, |x| is the natural height
21334 of the box being packaged.
21335
21336 @<Determine the value of |height(r)| and the appropriate glue setting...@>=
21337 if m=additional then h:=x+h;
21338 height(r):=h; x:=h-x; {now |x| is the excess to be made up}
21339 if x=0 then
21340 begin glue_sign(r):=normal; glue_order(r):=normal;
21341 set_glue_ratio_zero(glue_set(r));
21342 return;
21343 end
21344 else if x>0 then @<Determine vertical glue stretch setting, then |return|
21345 or \hbox{|goto common_ending|}@>
21346 else @<Determine vertical glue shrink setting, then |return|
21347 or \hbox{|goto common_ending|}@>
21348
21349 @ @<Determine vertical glue stretch setting...@>=
21350 begin @<Determine the stretch order@>;
21351 glue_order(r):=o; glue_sign(r):=stretching;
21352 if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
21353 @^real division@>
21354 else begin glue_sign(r):=normal;
21355 set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
21356 end;
21357 if o=normal then if list_ptr(r)<>null then
21358 @<Report an underfull vbox and |goto common_ending|, if this box
21359 is sufficiently bad@>;
21360 return;
21361 end
21362
21363 @ @<Report an underfull vbox and |goto common_ending|, if...@>=
21364 begin last_badness:=badness(x,total_stretch[normal]);
21365 if last_badness>vbadness then
21366 begin print_ln;
21367 if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
21368 print(" \vbox (badness "); print_int(last_badness);
21369 @.Underfull \\vbox...@>
21370 @.Loose \\vbox...@>
21371 goto common_ending;
21372 end;
21373 end
21374
21375 @ @<Finish issuing a diagnostic message for an overfull or underfull vbox@>=
21376 if output_active then print(") has occurred while \output is active")
21377 else begin if pack_begin_line<>0 then {it's actually negative}
21378 begin print(") in alignment at lines ");
21379 print_int(abs(pack_begin_line));
21380 print("--");
21381 end
21382 else print(") detected at line ");
21383 print_int(line);
21384 print_ln;@/
21385 end;
21386 begin_diagnostic; show_box(r); end_diagnostic(true)
21387
21388 @ @<Determine vertical glue shrink setting...@>=
21389 begin @<Determine the shrink order@>;
21390 glue_order(r):=o; glue_sign(r):=shrinking;
21391 if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
21392 @^real division@>
21393 else begin glue_sign(r):=normal;
21394 set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
21395 end;
21396 if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
21397 begin last_badness:=1000000;
21398 set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
21399 @<Report an overfull vbox and |goto common_ending|, if this box
21400 is sufficiently bad@>;
21401 end
21402 else if o=normal then if list_ptr(r)<>null then
21403 @<Report a tight vbox and |goto common_ending|, if this box
21404 is sufficiently bad@>;
21405 return;
21406 end
21407
21408 @ @<Report an overfull vbox and |goto common_ending|, if...@>=
21409 if (-x-total_shrink[normal]>vfuzz)or(vbadness<100) then
21410 begin print_ln; print_nl("Overfull \vbox (");
21411 @.Overfull \\vbox...@>
21412 print_scaled(-x-total_shrink[normal]); print("pt too high");
21413 goto common_ending;
21414 end
21415
21416 @ @<Report a tight vbox and |goto common_ending|, if...@>=
21417 begin last_badness:=badness(-x,total_shrink[normal]);
21418 if last_badness>vbadness then
21419 begin print_ln; print_nl("Tight \vbox (badness "); print_int(last_badness);
21420 @.Tight \\vbox...@>
21421 goto common_ending;
21422 end;
21423 end
21424
21425 @ When a box is being appended to the current vertical list, the
21426 baselineskip calculation is handled by the |append_to_vlist| routine.
21427
21428 @p procedure append_to_vlist(@!b:pointer);
21429 var d:scaled; {deficiency of space between baselines}
21430 @!p:pointer; {a new glue node}
21431 begin if prev_depth>pdf_ignored_dimen then
21432 begin d:=width(baseline_skip)-prev_depth-height(b);
21433 if d<line_skip_limit then p:=new_param_glue(line_skip_code)
21434 else begin p:=new_skip_param(baseline_skip_code);
21435 width(temp_ptr):=d; {|temp_ptr=glue_ptr(p)|}
21436 end;
21437 link(tail):=p; tail:=p;
21438 end;
21439 link(tail):=b; tail:=b; prev_depth:=depth(b);
21440 end;
21441
21442 @* \[34] Data structures for math mode.
21443 When \TeX\ reads a formula that is enclosed between \.\$'s, it constructs an
21444 {\sl mlist}, which is essentially a tree structure representing that
21445 formula. An mlist is a linear sequence of items, but we can regard it as
21446 a tree structure because mlists can appear within mlists. For example, many
21447 of the entries can be subscripted or superscripted, and such ``scripts''
21448 are mlists in their own right.
21449
21450 An entire formula is parsed into such a tree before any of the actual
21451 typesetting is done, because the current style of type is usually not
21452 known until the formula has been fully scanned. For example, when the
21453 formula `\.{\$a+b \\over c+d\$}' is being read, there is no way to tell
21454 that `\.{a+b}' will be in script size until `\.{\\over}' has appeared.
21455
21456 During the scanning process, each element of the mlist being built is
21457 classified as a relation, a binary operator, an open parenthesis, etc.,
21458 or as a construct like `\.{\\sqrt}' that must be built up. This classification
21459 appears in the mlist data structure.
21460
21461 After a formula has been fully scanned, the mlist is converted to an hlist
21462 so that it can be incorporated into the surrounding text. This conversion is
21463 controlled by a recursive procedure that decides all of the appropriate
21464 styles by a ``top-down'' process starting at the outermost level and working
21465 in towards the subformulas. The formula is ultimately pasted together using
21466 combinations of horizontal and vertical boxes, with glue and penalty nodes
21467 inserted as necessary.
21468
21469 An mlist is represented internally as a linked list consisting chiefly
21470 of ``noads'' (pronounced ``no-adds''), to distinguish them from the somewhat
21471 similar ``nodes'' in hlists and vlists. Certain kinds of ordinary nodes are
21472 allowed to appear in mlists together with the noads; \TeX\ tells the difference
21473 by means of the |type| field, since a noad's |type| is always greater than
21474 that of a node. An mlist does not contain character nodes, hlist nodes, vlist
21475 nodes, math nodes, ligature nodes,
21476 or unset nodes; in particular, each mlist item appears in the
21477 variable-size part of |mem|, so the |type| field is always present.
21478
21479 @ Each noad is four or more words long. The first word contains the |type|
21480 and |subtype| and |link| fields that are already so familiar to us; the
21481 second, third, and fourth words are called the noad's |nucleus|, |subscr|,
21482 and |supscr| fields.
21483
21484 Consider, for example, the simple formula `\.{\$x\^2\$}', which would be
21485 parsed into an mlist containing a single element called an |ord_noad|.
21486 The |nucleus| of this noad is a representation of `\.x', the |subscr| is
21487 empty, and the |supscr| is a representation of `\.2'.
21488
21489 The |nucleus|, |subscr|, and |supscr| fields are further broken into
21490 subfields. If |p| points to a noad, and if |q| is one of its principal
21491 fields (e.g., |q=subscr(p)|), there are several possibilities for the
21492 subfields, depending on the |math_type| of |q|.
21493
21494 \yskip\hang|math_type(q)=math_char| means that |fam(q)| refers to one of
21495 the sixteen font families, and |character(q)| is the number of a character
21496 within a font of that family, as in a character node.
21497
21498 \yskip\hang|math_type(q)=math_text_char| is similar, but the character is
21499 unsubscripted and unsuperscripted and it is followed immediately by another
21500 character from the same font. (This |math_type| setting appears only
21501 briefly during the processing; it is used to suppress unwanted italic
21502 corrections.)
21503
21504 \yskip\hang|math_type(q)=empty| indicates a field with no value (the
21505 corresponding attribute of noad |p| is not present).
21506
21507 \yskip\hang|math_type(q)=sub_box| means that |info(q)| points to a box
21508 node (either an |hlist_node| or a |vlist_node|) that should be used as the
21509 value of the field. The |shift_amount| in the subsidiary box node is the
21510 amount by which that box will be shifted downward.
21511
21512 \yskip\hang|math_type(q)=sub_mlist| means that |info(q)| points to
21513 an mlist; the mlist must be converted to an hlist in order to obtain
21514 the value of this field.
21515
21516 \yskip\noindent In the latter case, we might have |info(q)=null|. This
21517 is not the same as |math_type(q)=empty|; for example, `\.{\$P\_\{\}\$}'
21518 and `\.{\$P\$}' produce different results (the former will not have the
21519 ``italic correction'' added to the width of |P|, but the ``script skip''
21520 will be added).
21521
21522 The definitions of subfields given here are evidently wasteful of space,
21523 since a halfword is being used for the |math_type| although only three
21524 bits would be needed. However, there are hardly ever many noads present at
21525 once, since they are soon converted to nodes that take up even more space,
21526 so we can afford to represent them in whatever way simplifies the
21527 programming.
21528
21529 @d noad_size=4 {number of words in a normal noad}
21530 @d nucleus(#)==#+1 {the |nucleus| field of a noad}
21531 @d supscr(#)==#+2 {the |supscr| field of a noad}
21532 @d subscr(#)==#+3 {the |subscr| field of a noad}
21533 @d math_type==link {a |halfword| in |mem|}
21534 @d fam==font {a |quarterword| in |mem|}
21535 @d math_char=1 {|math_type| when the attribute is simple}
21536 @d sub_box=2 {|math_type| when the attribute is a box}
21537 @d sub_mlist=3 {|math_type| when the attribute is a formula}
21538 @d math_text_char=4 {|math_type| when italic correction is dubious}
21539
21540 @ Each portion of a formula is classified as Ord, Op, Bin, Rel, Open,
21541 Close, Punct, or Inner, for purposes of spacing and line breaking. An
21542 |ord_noad|, |op_noad|, |bin_noad|, |rel_noad|, |open_noad|, |close_noad|,
21543 |punct_noad|, or |inner_noad| is used to represent portions of the various
21544 types. For example, an `\.=' sign in a formula leads to the creation of a
21545 |rel_noad| whose |nucleus| field is a representation of an equals sign
21546 (usually |fam=0|, |character=@'75|). A formula preceded by \.{\\mathrel}
21547 also results in a |rel_noad|. When a |rel_noad| is followed by an
21548 |op_noad|, say, and possibly separated by one or more ordinary nodes (not
21549 noads), \TeX\ will insert a penalty node (with the current |rel_penalty|)
21550 just after the formula that corresponds to the |rel_noad|, unless there
21551 already was a penalty immediately following; and a ``thick space'' will be
21552 inserted just before the formula that corresponds to the |op_noad|.
21553
21554 A noad of type |ord_noad|, |op_noad|, \dots, |inner_noad| usually
21555 has a |subtype=normal|. The only exception is that an |op_noad| might
21556 have |subtype=limits| or |no_limits|, if the normal positioning of
21557 limits has been overridden for this operator.
21558
21559 @d ord_noad=unset_node+3 {|type| of a noad classified Ord}
21560 @d op_noad=ord_noad+1 {|type| of a noad classified Op}
21561 @d bin_noad=ord_noad+2 {|type| of a noad classified Bin}
21562 @d rel_noad=ord_noad+3 {|type| of a noad classified Rel}
21563 @d open_noad=ord_noad+4 {|type| of a noad classified Open}
21564 @d close_noad=ord_noad+5 {|type| of a noad classified Close}
21565 @d punct_noad=ord_noad+6 {|type| of a noad classified Punct}
21566 @d inner_noad=ord_noad+7 {|type| of a noad classified Inner}
21567 @d limits=1 {|subtype| of |op_noad| whose scripts are to be above, below}
21568 @d no_limits=2 {|subtype| of |op_noad| whose scripts are to be normal}
21569
21570 @ A |radical_noad| is five words long; the fifth word is the |left_delimiter|
21571 field, which usually represents a square root sign.
21572
21573 A |fraction_noad| is six words long; it has a |right_delimiter| field
21574 as well as a |left_delimiter|.
21575
21576 Delimiter fields are of type |four_quarters|, and they have four subfields
21577 called |small_fam|, |small_char|, |large_fam|, |large_char|. These subfields
21578 represent variable-size delimiters by giving the ``small'' and ``large''
21579 starting characters, as explained in Chapter~17 of {\sl The \TeX book}.
21580 @:TeXbook}{\sl The \TeX book@>
21581
21582 A |fraction_noad| is actually quite different from all other noads. Not
21583 only does it have six words, it has |thickness|, |denominator|, and
21584 |numerator| fields instead of |nucleus|, |subscr|, and |supscr|. The
21585 |thickness| is a scaled value that tells how thick to make a fraction
21586 rule; however, the special value |default_code| is used to stand for the
21587 |default_rule_thickness| of the current size. The |numerator| and
21588 |denominator| point to mlists that define a fraction; we always have
21589 $$\hbox{|math_type(numerator)=math_type(denominator)=sub_mlist|}.$$ The
21590 |left_delimiter| and |right_delimiter| fields specify delimiters that will
21591 be placed at the left and right of the fraction. In this way, a
21592 |fraction_noad| is able to represent all of \TeX's operators \.{\\over},
21593 \.{\\atop}, \.{\\above}, \.{\\overwithdelims}, \.{\\atopwithdelims}, and
21594 \.{\\abovewithdelims}.
21595
21596 @d left_delimiter(#)==#+4 {first delimiter field of a noad}
21597 @d right_delimiter(#)==#+5 {second delimiter field of a fraction noad}
21598 @d radical_noad=inner_noad+1 {|type| of a noad for square roots}
21599 @d radical_noad_size=5 {number of |mem| words in a radical noad}
21600 @d fraction_noad=radical_noad+1 {|type| of a noad for generalized fractions}
21601 @d fraction_noad_size=6 {number of |mem| words in a fraction noad}
21602 @d small_fam(#)==mem[#].qqqq.b0 {|fam| for ``small'' delimiter}
21603 @d small_char(#)==mem[#].qqqq.b1 {|character| for ``small'' delimiter}
21604 @d large_fam(#)==mem[#].qqqq.b2 {|fam| for ``large'' delimiter}
21605 @d large_char(#)==mem[#].qqqq.b3 {|character| for ``large'' delimiter}
21606 @d thickness==width {|thickness| field in a fraction noad}
21607 @d default_code==@'10000000000 {denotes |default_rule_thickness|}
21608 @d numerator==supscr {|numerator| field in a fraction noad}
21609 @d denominator==subscr {|denominator| field in a fraction noad}
21610
21611 @ The global variable |empty_field| is set up for initialization of empty
21612 fields in new noads. Similarly, |null_delimiter| is for the initialization
21613 of delimiter fields.
21614
21615 @<Glob...@>=
21616 @!empty_field:two_halves;
21617 @!null_delimiter:four_quarters;
21618
21619 @ @<Set init...@>=
21620 empty_field.rh:=empty; empty_field.lh:=null;@/
21621 null_delimiter.b0:=0; null_delimiter.b1:=min_quarterword;@/
21622 null_delimiter.b2:=0; null_delimiter.b3:=min_quarterword;
21623
21624 @ The |new_noad| function creates an |ord_noad| that is completely null.
21625
21626 @p function new_noad:pointer;
21627 var p:pointer;
21628 begin p:=get_node(noad_size);
21629 type(p):=ord_noad; subtype(p):=normal;
21630 mem[nucleus(p)].hh:=empty_field;
21631 mem[subscr(p)].hh:=empty_field;
21632 mem[supscr(p)].hh:=empty_field;
21633 new_noad:=p;
21634 end;
21635
21636 @ A few more kinds of noads will complete the set: An |under_noad| has its
21637 nucleus underlined; an |over_noad| has it overlined. An |accent_noad| places
21638 an accent over its nucleus; the accent character appears as
21639 |fam(accent_chr(p))| and |character(accent_chr(p))|. A |vcenter_noad|
21640 centers its nucleus vertically with respect to the axis of the formula;
21641 in such noads we always have |math_type(nucleus(p))=sub_box|.
21642
21643 And finally, we have |left_noad| and |right_noad| types, to implement
21644 \TeX's \.{\\left} and \.{\\right} as well as \eTeX's \.{\\middle}.
21645 The |nucleus| of such noads is
21646 replaced by a |delimiter| field; thus, for example, `\.{\\left(}' produces
21647 a |left_noad| such that |delimiter(p)| holds the family and character
21648 codes for all left parentheses. A |left_noad| never appears in an mlist
21649 except as the first element, and a |right_noad| never appears in an mlist
21650 except as the last element; furthermore, we either have both a |left_noad|
21651 and a |right_noad|, or neither one is present. The |subscr| and |supscr|
21652 fields are always |empty| in a |left_noad| and a |right_noad|.
21653
21654 @d under_noad=fraction_noad+1 {|type| of a noad for underlining}
21655 @d over_noad=under_noad+1 {|type| of a noad for overlining}
21656 @d accent_noad=over_noad+1 {|type| of a noad for accented subformulas}
21657 @d accent_noad_size=5 {number of |mem| words in an accent noad}
21658 @d accent_chr(#)==#+4 {the |accent_chr| field of an accent noad}
21659 @d vcenter_noad=accent_noad+1 {|type| of a noad for \.{\\vcenter}}
21660 @d left_noad=vcenter_noad+1 {|type| of a noad for \.{\\left}}
21661 @d right_noad=left_noad+1 {|type| of a noad for \.{\\right}}
21662 @d delimiter==nucleus {|delimiter| field in left and right noads}
21663 @d middle_noad==1 {|subtype| of right noad representing \.{\\middle}}
21664 @d scripts_allowed(#)==(type(#)>=ord_noad)and(type(#)<left_noad)
21665
21666 @ Math formulas can also contain instructions like \.{\\textstyle} that
21667 override \TeX's normal style rules. A |style_node| is inserted into the
21668 data structure to record such instructions; it is three words long, so it
21669 is considered a node instead of a noad. The |subtype| is either |display_style|
21670 or |text_style| or |script_style| or |script_script_style|. The
21671 second and third words of a |style_node| are not used, but they are
21672 present because a |choice_node| is converted to a |style_node|.
21673
21674 \TeX\ uses even numbers 0, 2, 4, 6 to encode the basic styles
21675 |display_style|, \dots, |script_script_style|, and adds~1 to get the
21676 ``cramped'' versions of these styles. This gives a numerical order that
21677 is backwards from the convention of Appendix~G in {\sl The \TeX book\/};
21678 i.e., a smaller style has a larger numerical value.
21679 @:TeXbook}{\sl The \TeX book@>
21680
21681 @d style_node=unset_node+1 {|type| of a style node}
21682 @d style_node_size=3 {number of words in a style node}
21683 @d display_style=0 {|subtype| for \.{\\displaystyle}}
21684 @d text_style=2 {|subtype| for \.{\\textstyle}}
21685 @d script_style=4 {|subtype| for \.{\\scriptstyle}}
21686 @d script_script_style=6 {|subtype| for \.{\\scriptscriptstyle}}
21687 @d cramped=1 {add this to an uncramped style if you want to cramp it}
21688
21689 @p function new_style(@!s:small_number):pointer; {create a style node}
21690 var p:pointer; {the new node}
21691 begin p:=get_node(style_node_size); type(p):=style_node;
21692 subtype(p):=s; width(p):=0; depth(p):=0; {the |width| and |depth| are not used}
21693 new_style:=p;
21694 end;
21695
21696 @ Finally, the \.{\\mathchoice} primitive creates a |choice_node|, which
21697 has special subfields |display_mlist|, |text_mlist|, |script_mlist|,
21698 and |script_script_mlist| pointing to the mlists for each style.
21699
21700 @d choice_node=unset_node+2 {|type| of a choice node}
21701 @d display_mlist(#)==info(#+1) {mlist to be used in display style}
21702 @d text_mlist(#)==link(#+1) {mlist to be used in text style}
21703 @d script_mlist(#)==info(#+2) {mlist to be used in script style}
21704 @d script_script_mlist(#)==link(#+2) {mlist to be used in scriptscript style}
21705
21706 @p function new_choice:pointer; {create a choice node}
21707 var p:pointer; {the new node}
21708 begin p:=get_node(style_node_size); type(p):=choice_node;
21709 subtype(p):=0; {the |subtype| is not used}
21710 display_mlist(p):=null; text_mlist(p):=null; script_mlist(p):=null;
21711 script_script_mlist(p):=null;
21712 new_choice:=p;
21713 end;
21714
21715 @ Let's consider now the previously unwritten part of |show_node_list|
21716 that displays the things that can only be present in mlists; this
21717 program illustrates how to access the data structures just defined.
21718
21719 In the context of the following program, |p| points to a node or noad that
21720 should be displayed, and the current string contains the ``recursion history''
21721 that leads to this point. The recursion history consists of a dot for each
21722 outer level in which |p| is subsidiary to some node, or in which |p| is
21723 subsidiary to the |nucleus| field of some noad; the dot is replaced by
21724 `\.\_' or `\.\^' or `\./' or `\.\\' if |p| is descended from the |subscr|
21725 or |supscr| or |denominator| or |numerator| fields of noads. For example,
21726 the current string would be `\.{.\^.\_/}' if |p| points to the |ord_noad| for
21727 |x| in the (ridiculous) formula
21728 `\.{\$\\sqrt\{a\^\{\\mathinner\{b\_\{c\\over x+y\}\}\}\}\$}'.
21729
21730 @<Cases of |show_node_list| that arise...@>=
21731 style_node:print_style(subtype(p));
21732 choice_node:@<Display choice node |p|@>;
21733 ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
21734 radical_noad,over_noad,under_noad,vcenter_noad,accent_noad,
21735 left_noad,right_noad:@<Display normal noad |p|@>;
21736 fraction_noad:@<Display fraction noad |p|@>;
21737
21738 @ Here are some simple routines used in the display of noads.
21739
21740 @<Declare procedures needed for displaying the elements of mlists@>=
21741 procedure print_fam_and_char(@!p:pointer); {prints family and character}
21742 begin print_esc("fam"); print_int(fam(p)); print_char(" ");
21743 print_ASCII(qo(character(p)));
21744 end;
21745 @#
21746 procedure print_delimiter(@!p:pointer); {prints a delimiter as 24-bit hex value}
21747 var a:integer; {accumulator}
21748 begin a:=small_fam(p)*256+qo(small_char(p));
21749 a:=a*@"1000+large_fam(p)*256+qo(large_char(p));
21750 if a<0 then print_int(a) {this should never happen}
21751 else print_hex(a);
21752 end;
21753
21754 @ The next subroutine will descend to another level of recursion when a
21755 subsidiary mlist needs to be displayed. The parameter |c| indicates what
21756 character is to become part of the recursion history. An empty mlist is
21757 distinguished from a field with |math_type(p)=empty|, because these are
21758 not equivalent (as explained above).
21759 @^recursion@>
21760
21761 @<Declare procedures needed for displaying...@>=
21762 procedure@?show_info; forward;@t\2@>@?{|show_node_list(info(temp_ptr))|}
21763 procedure print_subsidiary_data(@!p:pointer;@!c:ASCII_code);
21764 {display a noad field}
21765 begin if cur_length>=depth_threshold then
21766 begin if math_type(p)<>empty then print(" []");
21767 end
21768 else begin append_char(c); {include |c| in the recursion history}
21769 temp_ptr:=p; {prepare for |show_info| if recursion is needed}
21770 case math_type(p) of
21771 math_char: begin print_ln; print_current_string; print_fam_and_char(p);
21772 end;
21773 sub_box: show_info; {recursive call}
21774 sub_mlist: if info(p)=null then
21775 begin print_ln; print_current_string; print("{}");
21776 end
21777 else show_info; {recursive call}
21778 othercases do_nothing {|empty|}
21779 endcases;@/
21780 flush_char; {remove |c| from the recursion history}
21781 end;
21782 end;
21783
21784 @ The inelegant introduction of |show_info| in the code above seems better
21785 than the alternative of using \PASCAL's strange |forward| declaration for a
21786 procedure with parameters. The \PASCAL\ convention about dropping parameters
21787 from a post-|forward| procedure is, frankly, so intolerable to the author
21788 of \TeX\ that he would rather stoop to communication via a global temporary
21789 variable. (A similar stupidity occurred with respect to |hlist_out| and
21790 |vlist_out| above, and it will occur with respect to |mlist_to_hlist| below.)
21791 @^Knuth, Donald Ervin@>
21792 @:PASCAL}{\PASCAL@>
21793
21794 @p procedure show_info; {the reader will kindly forgive this}
21795 begin show_node_list(info(temp_ptr));
21796 end;
21797
21798 @ @<Declare procedures needed for displaying...@>=
21799 procedure print_style(@!c:integer);
21800 begin case c div 2 of
21801 0: print_esc("displaystyle"); {|display_style=0|}
21802 1: print_esc("textstyle"); {|text_style=2|}
21803 2: print_esc("scriptstyle"); {|script_style=4|}
21804 3: print_esc("scriptscriptstyle"); {|script_script_style=6|}
21805 othercases print("Unknown style!")
21806 endcases;
21807 end;
21808
21809 @ @<Display choice node |p|@>=
21810 begin print_esc("mathchoice");
21811 append_char("D"); show_node_list(display_mlist(p)); flush_char;
21812 append_char("T"); show_node_list(text_mlist(p)); flush_char;
21813 append_char("S"); show_node_list(script_mlist(p)); flush_char;
21814 append_char("s"); show_node_list(script_script_mlist(p)); flush_char;
21815 end
21816
21817 @ @<Display normal noad |p|@>=
21818 begin case type(p) of
21819 ord_noad: print_esc("mathord");
21820 op_noad: print_esc("mathop");
21821 bin_noad: print_esc("mathbin");
21822 rel_noad: print_esc("mathrel");
21823 open_noad: print_esc("mathopen");
21824 close_noad: print_esc("mathclose");
21825 punct_noad: print_esc("mathpunct");
21826 inner_noad: print_esc("mathinner");
21827 over_noad: print_esc("overline");
21828 under_noad: print_esc("underline");
21829 vcenter_noad: print_esc("vcenter");
21830 radical_noad: begin print_esc("radical"); print_delimiter(left_delimiter(p));
21831 end;
21832 accent_noad: begin print_esc("accent"); print_fam_and_char(accent_chr(p));
21833 end;
21834 left_noad: begin print_esc("left"); print_delimiter(delimiter(p));
21835 end;
21836 right_noad: begin if subtype(p)=normal then print_esc("right")
21837 else print_esc("middle");
21838 print_delimiter(delimiter(p));
21839 end;
21840 end;
21841 if type(p)<left_noad then
21842 begin if subtype(p)<>normal then
21843 if subtype(p)=limits then print_esc("limits")
21844 else print_esc("nolimits");
21845 print_subsidiary_data(nucleus(p),".");
21846 end;
21847 print_subsidiary_data(supscr(p),"^");
21848 print_subsidiary_data(subscr(p),"_");
21849 end
21850
21851 @ @<Display fraction noad |p|@>=
21852 begin print_esc("fraction, thickness ");
21853 if thickness(p)=default_code then print("= default")
21854 else print_scaled(thickness(p));
21855 if (small_fam(left_delimiter(p))<>0)or@+
21856 (small_char(left_delimiter(p))<>min_quarterword)or@|
21857 (large_fam(left_delimiter(p))<>0)or@|
21858 (large_char(left_delimiter(p))<>min_quarterword) then
21859 begin print(", left-delimiter "); print_delimiter(left_delimiter(p));
21860 end;
21861 if (small_fam(right_delimiter(p))<>0)or@|
21862 (small_char(right_delimiter(p))<>min_quarterword)or@|
21863 (large_fam(right_delimiter(p))<>0)or@|
21864 (large_char(right_delimiter(p))<>min_quarterword) then
21865 begin print(", right-delimiter "); print_delimiter(right_delimiter(p));
21866 end;
21867 print_subsidiary_data(numerator(p),"\");
21868 print_subsidiary_data(denominator(p),"/");
21869 end
21870
21871 @ That which can be displayed can also be destroyed.
21872
21873 @<Cases of |flush_node_list| that arise...@>=
21874 style_node: begin free_node(p,style_node_size); goto done;
21875 end;
21876 choice_node:begin flush_node_list(display_mlist(p));
21877 flush_node_list(text_mlist(p));
21878 flush_node_list(script_mlist(p));
21879 flush_node_list(script_script_mlist(p));
21880 free_node(p,style_node_size); goto done;
21881 end;
21882 ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
21883 radical_noad,over_noad,under_noad,vcenter_noad,accent_noad:@t@>@;@/
21884 begin if math_type(nucleus(p))>=sub_box then
21885 flush_node_list(info(nucleus(p)));
21886 if math_type(supscr(p))>=sub_box then
21887 flush_node_list(info(supscr(p)));
21888 if math_type(subscr(p))>=sub_box then
21889 flush_node_list(info(subscr(p)));
21890 if type(p)=radical_noad then free_node(p,radical_noad_size)
21891 else if type(p)=accent_noad then free_node(p,accent_noad_size)
21892 else free_node(p,noad_size);
21893 goto done;
21894 end;
21895 left_noad,right_noad: begin free_node(p,noad_size); goto done;
21896 end;
21897 fraction_noad: begin flush_node_list(info(numerator(p)));
21898 flush_node_list(info(denominator(p)));
21899 free_node(p,fraction_noad_size); goto done;
21900 end;
21901
21902 @* \[35] Subroutines for math mode.
21903 In order to convert mlists to hlists, i.e., noads to nodes, we need several
21904 subroutines that are conveniently dealt with now.
21905
21906 Let us first introduce the macros that make it easy to get at the parameters and
21907 other font information. A size code, which is a multiple of 16, is added to a
21908 family number to get an index into the table of internal font numbers
21909 for each combination of family and size. (Be alert: Size codes get
21910 larger as the type gets smaller.)
21911
21912 @d text_size=0 {size code for the largest size in a family}
21913 @d script_size=16 {size code for the medium size in a family}
21914 @d script_script_size=32 {size code for the smallest size in a family}
21915
21916 @<Basic printing procedures@>=
21917 procedure print_size(@!s:integer);
21918 begin if s=text_size then print_esc("textfont")
21919 else if s=script_size then print_esc("scriptfont")
21920 else print_esc("scriptscriptfont");
21921 end;
21922
21923 @ Before an mlist is converted to an hlist, \TeX\ makes sure that
21924 the fonts in family~2 have enough parameters to be math-symbol
21925 fonts, and that the fonts in family~3 have enough parameters to be
21926 math-extension fonts. The math-symbol parameters are referred to by using the
21927 following macros, which take a size code as their parameter; for example,
21928 |num1(cur_size)| gives the value of the |num1| parameter for the current size.
21929 @^parameters for symbols@>
21930 @^font parameters@>
21931
21932 @d mathsy_end(#)==fam_fnt(2+#)]].sc
21933 @d mathsy(#)==font_info[#+param_base[mathsy_end
21934 @d math_x_height==mathsy(5) {height of `\.x'}
21935 @d math_quad==mathsy(6) {\.{18mu}}
21936 @d num1==mathsy(8) {numerator shift-up in display styles}
21937 @d num2==mathsy(9) {numerator shift-up in non-display, non-\.{\\atop}}
21938 @d num3==mathsy(10) {numerator shift-up in non-display \.{\\atop}}
21939 @d denom1==mathsy(11) {denominator shift-down in display styles}
21940 @d denom2==mathsy(12) {denominator shift-down in non-display styles}
21941 @d sup1==mathsy(13) {superscript shift-up in uncramped display style}
21942 @d sup2==mathsy(14) {superscript shift-up in uncramped non-display}
21943 @d sup3==mathsy(15) {superscript shift-up in cramped styles}
21944 @d sub1==mathsy(16) {subscript shift-down if superscript is absent}
21945 @d sub2==mathsy(17) {subscript shift-down if superscript is present}
21946 @d sup_drop==mathsy(18) {superscript baseline below top of large box}
21947 @d sub_drop==mathsy(19) {subscript baseline below bottom of large box}
21948 @d delim1==mathsy(20) {size of \.{\\atopwithdelims} delimiters
21949 in display styles}
21950 @d delim2==mathsy(21) {size of \.{\\atopwithdelims} delimiters in non-displays}
21951 @d axis_height==mathsy(22) {height of fraction lines above the baseline}
21952 @d total_mathsy_params=22
21953
21954 @ The math-extension parameters have similar macros, but the size code is
21955 omitted (since it is always |cur_size| when we refer to such parameters).
21956 @^parameters for symbols@>
21957 @^font parameters@>
21958
21959 @d mathex(#)==font_info[#+param_base[fam_fnt(3+cur_size)]].sc
21960 @d default_rule_thickness==mathex(8) {thickness of \.{\\over} bars}
21961 @d big_op_spacing1==mathex(9) {minimum clearance above a displayed op}
21962 @d big_op_spacing2==mathex(10) {minimum clearance below a displayed op}
21963 @d big_op_spacing3==mathex(11) {minimum baselineskip above displayed op}
21964 @d big_op_spacing4==mathex(12) {minimum baselineskip below displayed op}
21965 @d big_op_spacing5==mathex(13) {padding above and below displayed limits}
21966 @d total_mathex_params=13
21967
21968 @ We also need to compute the change in style between mlists and their
21969 subsidiaries. The following macros define the subsidiary style for
21970 an overlined nucleus (|cramped_style|), for a subscript or a superscript
21971 (|sub_style| or |sup_style|), or for a numerator or denominator (|num_style|
21972 or |denom_style|).
21973
21974 @d cramped_style(#)==2*(# div 2)+cramped {cramp the style}
21975 @d sub_style(#)==2*(# div 4)+script_style+cramped {smaller and cramped}
21976 @d sup_style(#)==2*(# div 4)+script_style+(# mod 2) {smaller}
21977 @d num_style(#)==#+2-2*(# div 6) {smaller unless already script-script}
21978 @d denom_style(#)==2*(# div 2)+cramped+2-2*(# div 6) {smaller, cramped}
21979
21980 @ When the style changes, the following piece of program computes associated
21981 information:
21982
21983 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>=
21984 begin if cur_style<script_style then cur_size:=text_size
21985 else cur_size:=16*((cur_style-text_style) div 2);
21986 cur_mu:=x_over_n(math_quad(cur_size),18);
21987 end
21988
21989 @ Here is a function that returns a pointer to a rule node having a given
21990 thickness |t|. The rule will extend horizontally to the boundary of the vlist
21991 that eventually contains it.
21992
21993 @p function fraction_rule(@!t:scaled):pointer;
21994 {construct the bar for a fraction}
21995 var p:pointer; {the new node}
21996 begin p:=new_rule; height(p):=t; depth(p):=0; fraction_rule:=p;
21997 end;
21998
21999 @ The |overbar| function returns a pointer to a vlist box that consists of
22000 a given box |b|, above which has been placed a kern of height |k| under a
22001 fraction rule of thickness |t| under additional space of height |t|.
22002
22003 @p function overbar(@!b:pointer;@!k,@!t:scaled):pointer;
22004 var p,@!q:pointer; {nodes being constructed}
22005 begin p:=new_kern(k); link(p):=b; q:=fraction_rule(t); link(q):=p;
22006 p:=new_kern(t); link(p):=q; overbar:=vpack(p,natural);
22007 end;
22008
22009 @ The |var_delimiter| function, which finds or constructs a sufficiently
22010 large delimiter, is the most interesting of the auxiliary functions that
22011 currently concern us. Given a pointer |d| to a delimiter field in some noad,
22012 together with a size code |s| and a vertical distance |v|, this function
22013 returns a pointer to a box that contains the smallest variant of |d| whose
22014 height plus depth is |v| or more. (And if no variant is large enough, it
22015 returns the largest available variant.) In particular, this routine will
22016 construct arbitrarily large delimiters from extensible components, if
22017 |d| leads to such characters.
22018
22019 The value returned is a box whose |shift_amount| has been set so that
22020 the box is vertically centered with respect to the axis in the given size.
22021 If a built-up symbol is returned, the height of the box before shifting
22022 will be the height of its topmost component.
22023
22024 @p@t\4@>@<Declare subprocedures for |var_delimiter|@>
22025 function var_delimiter(@!d:pointer;@!s:small_number;@!v:scaled):pointer;
22026 label found,continue;
22027 var b:pointer; {the box that will be constructed}
22028 @!f,@!g: internal_font_number; {best-so-far and tentative font codes}
22029 @!c,@!x,@!y: quarterword; {best-so-far and tentative character codes}
22030 @!m,@!n: integer; {the number of extensible pieces}
22031 @!u: scaled; {height-plus-depth of a tentative character}
22032 @!w: scaled; {largest height-plus-depth so far}
22033 @!q: four_quarters; {character info}
22034 @!hd: eight_bits; {height-depth byte}
22035 @!r: four_quarters; {extensible pieces}
22036 @!z: small_number; {runs through font family members}
22037 @!large_attempt: boolean; {are we trying the ``large'' variant?}
22038 begin f:=null_font; w:=0; large_attempt:=false;
22039 z:=small_fam(d); x:=small_char(d);
22040 loop@+ begin @<Look at the variants of |(z,x)|; set |f| and |c| whenever
22041 a better character is found; |goto found| as soon as a
22042 large enough variant is encountered@>;
22043 if large_attempt then goto found; {there were none large enough}
22044 large_attempt:=true; z:=large_fam(d); x:=large_char(d);
22045 end;
22046 found: if f<>null_font then
22047 @<Make variable |b| point to a box for |(f,c)|@>
22048 else begin b:=new_null_box;
22049 width(b):=null_delimiter_space; {use this width if no delimiter was found}
22050 end;
22051 shift_amount(b):=half(height(b)-depth(b)) - axis_height(s);
22052 var_delimiter:=b;
22053 end;
22054
22055 @ The search process is complicated slightly by the facts that some of the
22056 characters might not be present in some of the fonts, and they might not
22057 be probed in increasing order of height.
22058
22059 @<Look at the variants of |(z,x)|; set |f| and |c|...@>=
22060 if (z<>0)or(x<>min_quarterword) then
22061 begin z:=z+s+16;
22062 repeat z:=z-16; g:=fam_fnt(z);
22063 if g<>null_font then
22064 @<Look at the list of characters starting with |x| in
22065 font |g|; set |f| and |c| whenever
22066 a better character is found; |goto found| as soon as a
22067 large enough variant is encountered@>;
22068 until z<16;
22069 end
22070
22071 @ @<Look at the list of characters starting with |x|...@>=
22072 begin y:=x;
22073 if (qo(y)>=font_bc[g])and(qo(y)<=font_ec[g]) then
22074 begin continue: q:=char_info(g)(y);
22075 if char_exists(q) then
22076 begin if char_tag(q)=ext_tag then
22077 begin f:=g; c:=y; goto found;
22078 end;
22079 hd:=height_depth(q);
22080 u:=char_height(g)(hd)+char_depth(g)(hd);
22081 if u>w then
22082 begin f:=g; c:=y; w:=u;
22083 if u>=v then goto found;
22084 end;
22085 if char_tag(q)=list_tag then
22086 begin y:=rem_byte(q); goto continue;
22087 end;
22088 end;
22089 end;
22090 end
22091
22092 @ Here is a subroutine that creates a new box, whose list contains a
22093 single character, and whose width includes the italic correction for
22094 that character. The height or depth of the box will be negative, if
22095 the height or depth of the character is negative; thus, this routine
22096 may deliver a slightly different result than |hpack| would produce.
22097
22098 @<Declare subprocedures for |var_delimiter|@>=
22099 function char_box(@!f:internal_font_number;@!c:quarterword):pointer;
22100 var q:four_quarters;
22101 @!hd:eight_bits; {|height_depth| byte}
22102 @!b,@!p:pointer; {the new box and its character node}
22103 begin q:=char_info(f)(c); hd:=height_depth(q);
22104 b:=new_null_box; width(b):=char_width(f)(q)+char_italic(f)(q);
22105 height(b):=char_height(f)(hd); depth(b):=char_depth(f)(hd);
22106 p:=get_avail; character(p):=c; font(p):=f; list_ptr(b):=p; char_box:=b;
22107 end;
22108
22109 @ When the following code is executed, |char_tag(q)| will be equal to
22110 |ext_tag| if and only if a built-up symbol is supposed to be returned.
22111
22112 @<Make variable |b| point to a box for |(f,c)|@>=
22113 if char_tag(q)=ext_tag then
22114 @<Construct an extensible character in a new box |b|,
22115 using recipe |rem_byte(q)| and font |f|@>
22116 else b:=char_box(f,c)
22117
22118 @ When we build an extensible character, it's handy to have the
22119 following subroutine, which puts a given character on top
22120 of the characters already in box |b|:
22121
22122 @<Declare subprocedures for |var_delimiter|@>=
22123 procedure stack_into_box(@!b:pointer;@!f:internal_font_number;
22124 @!c:quarterword);
22125 var p:pointer; {new node placed into |b|}
22126 begin p:=char_box(f,c); link(p):=list_ptr(b); list_ptr(b):=p;
22127 height(b):=height(p);
22128 end;
22129
22130 @ Another handy subroutine computes the height plus depth of
22131 a given character:
22132
22133 @<Declare subprocedures for |var_delimiter|@>=
22134 function height_plus_depth(@!f:internal_font_number;@!c:quarterword):scaled;
22135 var q:four_quarters;
22136 @!hd:eight_bits; {|height_depth| byte}
22137 begin q:=char_info(f)(c); hd:=height_depth(q);
22138 height_plus_depth:=char_height(f)(hd)+char_depth(f)(hd);
22139 end;
22140
22141 @ @<Construct an extensible...@>=
22142 begin b:=new_null_box;
22143 type(b):=vlist_node;
22144 r:=font_info[exten_base[f]+rem_byte(q)].qqqq;@/
22145 @<Compute the minimum suitable height, |w|, and the corresponding
22146 number of extension steps, |n|; also set |width(b)|@>;
22147 c:=ext_bot(r);
22148 if c<>min_quarterword then stack_into_box(b,f,c);
22149 c:=ext_rep(r);
22150 for m:=1 to n do stack_into_box(b,f,c);
22151 c:=ext_mid(r);
22152 if c<>min_quarterword then
22153 begin stack_into_box(b,f,c); c:=ext_rep(r);
22154 for m:=1 to n do stack_into_box(b,f,c);
22155 end;
22156 c:=ext_top(r);
22157 if c<>min_quarterword then stack_into_box(b,f,c);
22158 depth(b):=w-height(b);
22159 end
22160
22161 @ The width of an extensible character is the width of the repeatable
22162 module. If this module does not have positive height plus depth,
22163 we don't use any copies of it, otherwise we use as few as possible
22164 (in groups of two if there is a middle part).
22165
22166 @<Compute the minimum suitable height, |w|, and...@>=
22167 c:=ext_rep(r); u:=height_plus_depth(f,c);
22168 w:=0; q:=char_info(f)(c); width(b):=char_width(f)(q)+char_italic(f)(q);@/
22169 c:=ext_bot(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
22170 c:=ext_mid(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
22171 c:=ext_top(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
22172 n:=0;
22173 if u>0 then while w<v do
22174 begin w:=w+u; incr(n);
22175 if ext_mid(r)<>min_quarterword then w:=w+u;
22176 end
22177
22178 @ The next subroutine is much simpler; it is used for numerators and
22179 denominators of fractions as well as for displayed operators and
22180 their limits above and below. It takes a given box~|b| and
22181 changes it so that the new box is centered in a box of width~|w|.
22182 The centering is done by putting \.{\\hss} glue at the left and right
22183 of the list inside |b|, then packaging the new box; thus, the
22184 actual box might not really be centered, if it already contains
22185 infinite glue.
22186
22187 The given box might contain a single character whose italic correction
22188 has been added to the width of the box; in this case a compensating
22189 kern is inserted.
22190
22191 @p function rebox(@!b:pointer;@!w:scaled):pointer;
22192 var p:pointer; {temporary register for list manipulation}
22193 @!f:internal_font_number; {font in a one-character box}
22194 @!v:scaled; {width of a character without italic correction}
22195 begin if (width(b)<>w)and(list_ptr(b)<>null) then
22196 begin if type(b)=vlist_node then b:=hpack(b,natural);
22197 p:=list_ptr(b);
22198 if (is_char_node(p))and(link(p)=null) then
22199 begin f:=font(p); v:=char_width(f)(char_info(f)(character(p)));
22200 if v<>width(b) then link(p):=new_kern(width(b)-v);
22201 end;
22202 free_node(b,box_node_size);
22203 b:=new_glue(ss_glue); link(b):=p;
22204 while link(p)<>null do p:=link(p);
22205 link(p):=new_glue(ss_glue);
22206 rebox:=hpack(b,w,exactly);
22207 end
22208 else begin width(b):=w; rebox:=b;
22209 end;
22210 end;
22211
22212 @ Here is a subroutine that creates a new glue specification from another
22213 one that is expressed in `\.{mu}', given the value of the math unit.
22214
22215 @d mu_mult(#)==nx_plus_y(n,#,xn_over_d(#,f,@'200000))
22216
22217 @p function math_glue(@!g:pointer;@!m:scaled):pointer;
22218 var p:pointer; {the new glue specification}
22219 @!n:integer; {integer part of |m|}
22220 @!f:scaled; {fraction part of |m|}
22221 begin n:=x_over_n(m,@'200000); f:=remainder;@/
22222 if f<0 then
22223 begin decr(n); f:=f+@'200000;
22224 end;
22225 p:=get_node(glue_spec_size);
22226 width(p):=mu_mult(width(g)); {convert \.{mu} to \.{pt}}
22227 stretch_order(p):=stretch_order(g);
22228 if stretch_order(p)=normal then stretch(p):=mu_mult(stretch(g))
22229 else stretch(p):=stretch(g);
22230 shrink_order(p):=shrink_order(g);
22231 if shrink_order(p)=normal then shrink(p):=mu_mult(shrink(g))
22232 else shrink(p):=shrink(g);
22233 math_glue:=p;
22234 end;
22235
22236 @ The |math_kern| subroutine removes |mu_glue| from a kern node, given
22237 the value of the math unit.
22238
22239 @p procedure math_kern(@!p:pointer;@!m:scaled);
22240 var @!n:integer; {integer part of |m|}
22241 @!f:scaled; {fraction part of |m|}
22242 begin if subtype(p)=mu_glue then
22243 begin n:=x_over_n(m,@'200000); f:=remainder;@/
22244 if f<0 then
22245 begin decr(n); f:=f+@'200000;
22246 end;
22247 width(p):=mu_mult(width(p)); subtype(p):=explicit;
22248 end;
22249 end;
22250
22251 @ Sometimes it is necessary to destroy an mlist. The following
22252 subroutine empties the current list, assuming that |abs(mode)=mmode|.
22253
22254 @p procedure flush_math;
22255 begin flush_node_list(link(head)); flush_node_list(incompleat_noad);
22256 link(head):=null; tail:=head; incompleat_noad:=null;
22257 end;
22258
22259 @* \[36] Typesetting math formulas.
22260 \TeX's most important routine for dealing with formulas is called
22261 |mlist_to_hlist|. After a formula has been scanned and represented as an
22262 mlist, this routine converts it to an hlist that can be placed into a box
22263 or incorporated into the text of a paragraph. There are three implicit
22264 parameters, passed in global variables: |cur_mlist| points to the first
22265 node or noad in the given mlist (and it might be |null|); |cur_style| is a
22266 style code; and |mlist_penalties| is |true| if penalty nodes for potential
22267 line breaks are to be inserted into the resulting hlist. After
22268 |mlist_to_hlist| has acted, |link(temp_head)| points to the translated hlist.
22269
22270 Since mlists can be inside mlists, the procedure is recursive. And since this
22271 is not part of \TeX's inner loop, the program has been written in a manner
22272 that stresses compactness over efficiency.
22273 @^recursion@>
22274
22275 @<Glob...@>=
22276 @!cur_mlist:pointer; {beginning of mlist to be translated}
22277 @!cur_style:small_number; {style code at current place in the list}
22278 @!cur_size:small_number; {size code corresponding to |cur_style|}
22279 @!cur_mu:scaled; {the math unit width corresponding to |cur_size|}
22280 @!mlist_penalties:boolean; {should |mlist_to_hlist| insert penalties?}
22281
22282 @ The recursion in |mlist_to_hlist| is due primarily to a subroutine
22283 called |clean_box| that puts a given noad field into a box using a given
22284 math style; |mlist_to_hlist| can call |clean_box|, which can call
22285 |mlist_to_hlist|.
22286 @^recursion@>
22287
22288 The box returned by |clean_box| is ``clean'' in the
22289 sense that its |shift_amount| is zero.
22290
22291 @p procedure@?mlist_to_hlist; forward;@t\2@>@/
22292 function clean_box(@!p:pointer;@!s:small_number):pointer;
22293 label found;
22294 var q:pointer; {beginning of a list to be boxed}
22295 @!save_style:small_number; {|cur_style| to be restored}
22296 @!x:pointer; {box to be returned}
22297 @!r:pointer; {temporary pointer}
22298 begin case math_type(p) of
22299 math_char: begin cur_mlist:=new_noad; mem[nucleus(cur_mlist)]:=mem[p];
22300 end;
22301 sub_box: begin q:=info(p); goto found;
22302 end;
22303 sub_mlist: cur_mlist:=info(p);
22304 othercases begin q:=new_null_box; goto found;
22305 end
22306 endcases;@/
22307 save_style:=cur_style; cur_style:=s; mlist_penalties:=false;@/
22308 mlist_to_hlist; q:=link(temp_head); {recursive call}
22309 cur_style:=save_style; {restore the style}
22310 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
22311 found: if is_char_node(q)or(q=null) then x:=hpack(q,natural)
22312 else if (link(q)=null)and(type(q)<=vlist_node)and(shift_amount(q)=0) then
22313 x:=q {it's already clean}
22314 else x:=hpack(q,natural);
22315 @<Simplify a trivial box@>;
22316 clean_box:=x;
22317 end;
22318
22319 @ Here we save memory space in a common case.
22320
22321 @<Simplify a trivial box@>=
22322 q:=list_ptr(x);
22323 if is_char_node(q) then
22324 begin r:=link(q);
22325 if r<>null then if link(r)=null then if not is_char_node(r) then
22326 if type(r)=kern_node then {unneeded italic correction}
22327 begin free_node(r,small_node_size); link(q):=null;
22328 end;
22329 end
22330
22331 @ It is convenient to have a procedure that converts a |math_char|
22332 field to an ``unpacked'' form. The |fetch| routine sets |cur_f|, |cur_c|,
22333 and |cur_i| to the font code, character code, and character information bytes of
22334 a given noad field. It also takes care of issuing error messages for
22335 nonexistent characters; in such cases, |char_exists(cur_i)| will be |false|
22336 after |fetch| has acted, and the field will also have been reset to |empty|.
22337
22338 @p procedure fetch(@!a:pointer); {unpack the |math_char| field |a|}
22339 begin cur_c:=character(a); cur_f:=fam_fnt(fam(a)+cur_size);
22340 if cur_f=null_font then
22341 @<Complain about an undefined family and set |cur_i| null@>
22342 else begin if (qo(cur_c)>=font_bc[cur_f])and(qo(cur_c)<=font_ec[cur_f]) then
22343 cur_i:=char_info(cur_f)(cur_c)
22344 else cur_i:=null_character;
22345 if not(char_exists(cur_i)) then
22346 begin char_warning(cur_f,qo(cur_c));
22347 math_type(a):=empty; cur_i:=null_character;
22348 end;
22349 end;
22350 end;
22351
22352 @ @<Complain about an undefined family...@>=
22353 begin print_err(""); print_size(cur_size); print_char(" ");
22354 print_int(fam(a)); print(" is undefined (character ");
22355 print_ASCII(qo(cur_c)); print_char(")");
22356 help4("Somewhere in the math formula just ended, you used the")@/
22357 ("stated character from an undefined font family. For example,")@/
22358 ("plain TeX doesn't allow \it or \sl in subscripts. Proceed,")@/
22359 ("and I'll try to forget that I needed that character.");
22360 error; cur_i:=null_character; math_type(a):=empty;
22361 end
22362
22363 @ The outputs of |fetch| are placed in global variables.
22364
22365 @<Glob...@>=
22366 @!cur_f:internal_font_number; {the |font| field of a |math_char|}
22367 @!cur_c:quarterword; {the |character| field of a |math_char|}
22368 @!cur_i:four_quarters; {the |char_info| of a |math_char|,
22369 or a lig/kern instruction}
22370
22371 @ We need to do a lot of different things, so |mlist_to_hlist| makes two
22372 passes over the given mlist.
22373
22374 The first pass does most of the processing: It removes ``mu'' spacing from
22375 glue, it recursively evaluates all subsidiary mlists so that only the
22376 top-level mlist remains to be handled, it puts fractions and square roots
22377 and such things into boxes, it attaches subscripts and superscripts, and
22378 it computes the overall height and depth of the top-level mlist so that
22379 the size of delimiters for a |left_noad| and a |right_noad| will be known.
22380 The hlist resulting from each noad is recorded in that noad's |new_hlist|
22381 field, an integer field that replaces the |nucleus| or |thickness|.
22382 @^recursion@>
22383
22384 The second pass eliminates all noads and inserts the correct glue and
22385 penalties between nodes.
22386
22387 @d new_hlist(#)==mem[nucleus(#)].int {the translation of an mlist}
22388
22389 @ Here is the overall plan of |mlist_to_hlist|, and the list of its
22390 local variables.
22391
22392 @d done_with_noad=80 {go here when a noad has been fully translated}
22393 @d done_with_node=81 {go here when a node has been fully converted}
22394 @d check_dimensions=82 {go here to update |max_h| and |max_d|}
22395 @d delete_q=83 {go here to delete |q| and move to the next node}
22396
22397 @p@t\4@>@<Declare math construction procedures@>
22398 procedure mlist_to_hlist;
22399 label reswitch, check_dimensions, done_with_noad, done_with_node, delete_q,
22400 done;
22401 var mlist:pointer; {beginning of the given list}
22402 @!penalties:boolean; {should penalty nodes be inserted?}
22403 @!style:small_number; {the given style}
22404 @!save_style:small_number; {holds |cur_style| during recursion}
22405 @!q:pointer; {runs through the mlist}
22406 @!r:pointer; {the most recent noad preceding |q|}
22407 @!r_type:small_number; {the |type| of noad |r|, or |op_noad| if |r=null|}
22408 @!t:small_number; {the effective |type| of noad |q| during the second pass}
22409 @!p,@!x,@!y,@!z: pointer; {temporary registers for list construction}
22410 @!pen:integer; {a penalty to be inserted}
22411 @!s:small_number; {the size of a noad to be deleted}
22412 @!max_h,@!max_d:scaled; {maximum height and depth of the list translated so far}
22413 @!delta:scaled; {offset between subscript and superscript}
22414 begin mlist:=cur_mlist; penalties:=mlist_penalties;
22415 style:=cur_style; {tuck global parameters away as local variables}
22416 q:=mlist; r:=null; r_type:=op_noad; max_h:=0; max_d:=0;
22417 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
22418 while q<>null do @<Process node-or-noad |q| as much as possible in preparation
22419 for the second pass of |mlist_to_hlist|, then move to the next
22420 item in the mlist@>;
22421 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
22422 @<Make a second pass over the mlist, removing all noads and inserting the
22423 proper spacing and penalties@>;
22424 end;
22425
22426 @ We use the fact that no character nodes appear in an mlist, hence
22427 the field |type(q)| is always present.
22428
22429 @<Process node-or-noad...@>=
22430 begin @<Do first-pass processing based on |type(q)|; |goto done_with_noad|
22431 if a noad has been fully processed, |goto check_dimensions| if it
22432 has been translated into |new_hlist(q)|, or |goto done_with_node|
22433 if a node has been fully processed@>;
22434 check_dimensions: z:=hpack(new_hlist(q),natural);
22435 if height(z)>max_h then max_h:=height(z);
22436 if depth(z)>max_d then max_d:=depth(z);
22437 free_node(z,box_node_size);
22438 done_with_noad: r:=q; r_type:=type(r);
22439 if r_type=right_noad then
22440 begin r_type:=left_noad; cur_style:=style; @<Set up the values...@>;
22441 end;
22442 done_with_node: q:=link(q);
22443 end
22444
22445 @ One of the things we must do on the first pass is change a |bin_noad| to
22446 an |ord_noad| if the |bin_noad| is not in the context of a binary operator.
22447 The values of |r| and |r_type| make this fairly easy.
22448
22449 @<Do first-pass processing...@>=
22450 reswitch: delta:=0;
22451 case type(q) of
22452 bin_noad: case r_type of
22453 bin_noad,op_noad,rel_noad,open_noad,punct_noad,left_noad:
22454 begin type(q):=ord_noad; goto reswitch;
22455 end;
22456 othercases do_nothing
22457 endcases;
22458 rel_noad,close_noad,punct_noad,right_noad: begin@t@>@;@/
22459 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
22460 if type(q)=right_noad then goto done_with_noad;
22461 end;
22462 @t\4@>@<Cases for noads that can follow a |bin_noad|@>@;
22463 @t\4@>@<Cases for nodes that can appear in an mlist, after which we
22464 |goto done_with_node|@>@;
22465 othercases confusion("mlist1")
22466 @:this can't happen mlist1}{\quad mlist1@>
22467 endcases;@/
22468 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>
22469
22470 @ @<Convert \(a)a final |bin_noad| to an |ord_noad|@>=
22471 if r_type=bin_noad then type(r):=ord_noad
22472
22473 @ @<Cases for nodes that can appear in an mlist...@>=
22474 style_node: begin cur_style:=subtype(q);
22475 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
22476 goto done_with_node;
22477 end;
22478 choice_node: @<Change this node to a style node followed by the correct choice,
22479 then |goto done_with_node|@>;
22480 ins_node,mark_node,adjust_node,
22481 whatsit_node,penalty_node,disc_node: goto done_with_node;
22482 rule_node: begin if height(q)>max_h then max_h:=height(q);
22483 if depth(q)>max_d then max_d:=depth(q); goto done_with_node;
22484 end;
22485 glue_node: begin @<Convert \(m)math glue to ordinary glue@>;
22486 goto done_with_node;
22487 end;
22488 kern_node: begin math_kern(q,cur_mu); goto done_with_node;
22489 end;
22490
22491 @ @d choose_mlist(#)==begin p:=#(q); #(q):=null;@+end
22492
22493 @<Change this node to a style node...@>=
22494 begin case cur_style div 2 of
22495 0: choose_mlist(display_mlist); {|display_style=0|}
22496 1: choose_mlist(text_mlist); {|text_style=2|}
22497 2: choose_mlist(script_mlist); {|script_style=4|}
22498 3: choose_mlist(script_script_mlist); {|script_script_style=6|}
22499 end; {there are no other cases}
22500 flush_node_list(display_mlist(q));
22501 flush_node_list(text_mlist(q));
22502 flush_node_list(script_mlist(q));
22503 flush_node_list(script_script_mlist(q));@/
22504 type(q):=style_node; subtype(q):=cur_style; width(q):=0; depth(q):=0;
22505 if p<>null then
22506 begin z:=link(q); link(q):=p;
22507 while link(p)<>null do p:=link(p);
22508 link(p):=z;
22509 end;
22510 goto done_with_node;
22511 end
22512
22513 @ Conditional math glue (`\.{\\nonscript}') results in a |glue_node|
22514 pointing to |zero_glue|, with |subtype(q)=cond_math_glue|; in such a case
22515 the node following will be eliminated if it is a glue or kern node and if the
22516 current size is different from |text_size|. Unconditional math glue
22517 (`\.{\\muskip}') is converted to normal glue by multiplying the dimensions
22518 by |cur_mu|.
22519 @!@:non_script_}{\.{\\nonscript} primitive@>
22520
22521 @<Convert \(m)math glue to ordinary glue@>=
22522 if subtype(q)=mu_glue then
22523 begin x:=glue_ptr(q);
22524 y:=math_glue(x,cur_mu); delete_glue_ref(x); glue_ptr(q):=y;
22525 subtype(q):=normal;
22526 end
22527 else if (cur_size<>text_size)and(subtype(q)=cond_math_glue) then
22528 begin p:=link(q);
22529 if p<>null then if (type(p)=glue_node)or(type(p)=kern_node) then
22530 begin link(q):=link(p); link(p):=null; flush_node_list(p);
22531 end;
22532 end
22533
22534 @ @<Cases for noads that can follow a |bin_noad|@>=
22535 left_noad: goto done_with_noad;
22536 fraction_noad: begin make_fraction(q); goto check_dimensions;
22537 end;
22538 op_noad: begin delta:=make_op(q);
22539 if subtype(q)=limits then goto check_dimensions;
22540 end;
22541 ord_noad: make_ord(q);
22542 open_noad,inner_noad: do_nothing;
22543 radical_noad: make_radical(q);
22544 over_noad: make_over(q);
22545 under_noad: make_under(q);
22546 accent_noad: make_math_accent(q);
22547 vcenter_noad: make_vcenter(q);
22548
22549 @ Most of the actual construction work of |mlist_to_hlist| is done
22550 by procedures with names
22551 like |make_fraction|, |make_radical|, etc. To illustrate
22552 the general setup of such procedures, let's begin with a couple of
22553 simple ones.
22554
22555 @<Declare math...@>=
22556 procedure make_over(@!q:pointer);
22557 begin info(nucleus(q)):=@|
22558 overbar(clean_box(nucleus(q),cramped_style(cur_style)),@|
22559 3*default_rule_thickness,default_rule_thickness);
22560 math_type(nucleus(q)):=sub_box;
22561 end;
22562
22563 @ @<Declare math...@>=
22564 procedure make_under(@!q:pointer);
22565 var p,@!x,@!y: pointer; {temporary registers for box construction}
22566 @!delta:scaled; {overall height plus depth}
22567 begin x:=clean_box(nucleus(q),cur_style);
22568 p:=new_kern(3*default_rule_thickness); link(x):=p;
22569 link(p):=fraction_rule(default_rule_thickness);
22570 y:=vpack(x,natural);
22571 delta:=height(y)+depth(y)+default_rule_thickness;
22572 height(y):=height(x); depth(y):=delta-height(y);
22573 info(nucleus(q)):=y; math_type(nucleus(q)):=sub_box;
22574 end;
22575
22576 @ @<Declare math...@>=
22577 procedure make_vcenter(@!q:pointer);
22578 var v:pointer; {the box that should be centered vertically}
22579 @!delta:scaled; {its height plus depth}
22580 begin v:=info(nucleus(q));
22581 if type(v)<>vlist_node then confusion("vcenter");
22582 @:this can't happen vcenter}{\quad vcenter@>
22583 delta:=height(v)+depth(v);
22584 height(v):=axis_height(cur_size)+half(delta);
22585 depth(v):=delta-height(v);
22586 end;
22587
22588 @ According to the rules in the \.{DVI} file specifications, we ensure alignment
22589 @^square roots@>
22590 between a square root sign and the rule above its nucleus by assuming that the
22591 baseline of the square-root symbol is the same as the bottom of the rule. The
22592 height of the square-root symbol will be the thickness of the rule, and the
22593 depth of the square-root symbol should exceed or equal the height-plus-depth
22594 of the nucleus plus a certain minimum clearance~|clr|. The symbol will be
22595 placed so that the actual clearance is |clr| plus half the excess.
22596
22597 @<Declare math...@>=
22598 procedure make_radical(@!q:pointer);
22599 var x,@!y:pointer; {temporary registers for box construction}
22600 @!delta,@!clr:scaled; {dimensions involved in the calculation}
22601 begin x:=clean_box(nucleus(q),cramped_style(cur_style));
22602 if cur_style<text_style then {display style}
22603 clr:=default_rule_thickness+(abs(math_x_height(cur_size)) div 4)
22604 else begin clr:=default_rule_thickness; clr:=clr + (abs(clr) div 4);
22605 end;
22606 y:=var_delimiter(left_delimiter(q),cur_size,height(x)+depth(x)+clr+
22607 default_rule_thickness);
22608 delta:=depth(y)-(height(x)+depth(x)+clr);
22609 if delta>0 then clr:=clr+half(delta); {increase the actual clearance}
22610 shift_amount(y):=-(height(x)+clr);
22611 link(y):=overbar(x,clr,height(y));
22612 info(nucleus(q)):=hpack(y,natural); math_type(nucleus(q)):=sub_box;
22613 end;
22614
22615 @ Slants are not considered when placing accents in math mode. The accenter is
22616 centered over the accentee, and the accent width is treated as zero with
22617 respect to the size of the final box.
22618
22619 @<Declare math...@>=
22620 procedure make_math_accent(@!q:pointer);
22621 label done,done1;
22622 var p,@!x,@!y:pointer; {temporary registers for box construction}
22623 @!a:integer; {address of lig/kern instruction}
22624 @!c:quarterword; {accent character}
22625 @!f:internal_font_number; {its font}
22626 @!i:four_quarters; {its |char_info|}
22627 @!s:scaled; {amount to skew the accent to the right}
22628 @!h:scaled; {height of character being accented}
22629 @!delta:scaled; {space to remove between accent and accentee}
22630 @!w:scaled; {width of the accentee, not including sub/superscripts}
22631 begin fetch(accent_chr(q));
22632 if char_exists(cur_i) then
22633 begin i:=cur_i; c:=cur_c; f:=cur_f;@/
22634 @<Compute the amount of skew@>;
22635 x:=clean_box(nucleus(q),cramped_style(cur_style)); w:=width(x); h:=height(x);
22636 @<Switch to a larger accent if available and appropriate@>;
22637 if h<x_height(f) then delta:=h@+else delta:=x_height(f);
22638 if (math_type(supscr(q))<>empty)or(math_type(subscr(q))<>empty) then
22639 if math_type(nucleus(q))=math_char then
22640 @<Swap the subscript and superscript into box |x|@>;
22641 y:=char_box(f,c);
22642 shift_amount(y):=s+half(w-width(y));
22643 width(y):=0; p:=new_kern(-delta); link(p):=x; link(y):=p;
22644 y:=vpack(y,natural); width(y):=width(x);
22645 if height(y)<h then @<Make the height of box |y| equal to |h|@>;
22646 info(nucleus(q)):=y;
22647 math_type(nucleus(q)):=sub_box;
22648 end;
22649 end;
22650
22651 @ @<Make the height of box |y|...@>=
22652 begin p:=new_kern(h-height(y)); link(p):=list_ptr(y); list_ptr(y):=p;
22653 height(y):=h;
22654 end
22655
22656 @ @<Switch to a larger accent if available and appropriate@>=
22657 loop@+ begin if char_tag(i)<>list_tag then goto done;
22658 y:=rem_byte(i);
22659 i:=char_info(f)(y);
22660 if not char_exists(i) then goto done;
22661 if char_width(f)(i)>w then goto done;
22662 c:=y;
22663 end;
22664 done:
22665
22666 @ @<Compute the amount of skew@>=
22667 s:=0;
22668 if math_type(nucleus(q))=math_char then
22669 begin fetch(nucleus(q));
22670 if char_tag(cur_i)=lig_tag then
22671 begin a:=lig_kern_start(cur_f)(cur_i);
22672 cur_i:=font_info[a].qqqq;
22673 if skip_byte(cur_i)>stop_flag then
22674 begin a:=lig_kern_restart(cur_f)(cur_i);
22675 cur_i:=font_info[a].qqqq;
22676 end;
22677 loop@+ begin if qo(next_char(cur_i))=skew_char[cur_f] then
22678 begin if op_byte(cur_i)>=kern_flag then
22679 if skip_byte(cur_i)<=stop_flag then s:=char_kern(cur_f)(cur_i);
22680 goto done1;
22681 end;
22682 if skip_byte(cur_i)>=stop_flag then goto done1;
22683 a:=a+qo(skip_byte(cur_i))+1;
22684 cur_i:=font_info[a].qqqq;
22685 end;
22686 end;
22687 end;
22688 done1:
22689
22690 @ @<Swap the subscript and superscript into box |x|@>=
22691 begin flush_node_list(x); x:=new_noad;
22692 mem[nucleus(x)]:=mem[nucleus(q)];
22693 mem[supscr(x)]:=mem[supscr(q)];
22694 mem[subscr(x)]:=mem[subscr(q)];@/
22695 mem[supscr(q)].hh:=empty_field;
22696 mem[subscr(q)].hh:=empty_field;@/
22697 math_type(nucleus(q)):=sub_mlist; info(nucleus(q)):=x;
22698 x:=clean_box(nucleus(q),cur_style); delta:=delta+height(x)-h; h:=height(x);
22699 end
22700
22701 @ The |make_fraction| procedure is a bit different because it sets
22702 |new_hlist(q)| directly rather than making a sub-box.
22703
22704 @<Declare math...@>=
22705 procedure make_fraction(@!q:pointer);
22706 var p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
22707 @!delta,@!delta1,@!delta2,@!shift_up,@!shift_down,@!clr:scaled;
22708 {dimensions for box calculations}
22709 begin if thickness(q)=default_code then thickness(q):=default_rule_thickness;
22710 @<Create equal-width boxes |x| and |z| for the numerator and denominator,
22711 and compute the default amounts |shift_up| and |shift_down| by which they
22712 are displaced from the baseline@>;
22713 if thickness(q)=0 then @<Adjust \(s)|shift_up| and |shift_down| for the case
22714 of no fraction line@>
22715 else @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>;
22716 @<Construct a vlist box for the fraction, according to |shift_up| and
22717 |shift_down|@>;
22718 @<Put the \(f)fraction into a box with its delimiters, and make |new_hlist(q)|
22719 point to it@>;
22720 end;
22721
22722 @ @<Create equal-width boxes |x| and |z| for the numerator and denom...@>=
22723 x:=clean_box(numerator(q),num_style(cur_style));
22724 z:=clean_box(denominator(q),denom_style(cur_style));
22725 if width(x)<width(z) then x:=rebox(x,width(z))
22726 else z:=rebox(z,width(x));
22727 if cur_style<text_style then {display style}
22728 begin shift_up:=num1(cur_size); shift_down:=denom1(cur_size);
22729 end
22730 else begin shift_down:=denom2(cur_size);
22731 if thickness(q)<>0 then shift_up:=num2(cur_size)
22732 else shift_up:=num3(cur_size);
22733 end
22734
22735 @ The numerator and denominator must be separated by a certain minimum
22736 clearance, called |clr| in the following program. The difference between
22737 |clr| and the actual clearance is twice |delta|.
22738
22739 @<Adjust \(s)|shift_up| and |shift_down| for the case of no fraction line@>=
22740 begin if cur_style<text_style then clr:=7*default_rule_thickness
22741 else clr:=3*default_rule_thickness;
22742 delta:=half(clr-((shift_up-depth(x))-(height(z)-shift_down)));
22743 if delta>0 then
22744 begin shift_up:=shift_up+delta;
22745 shift_down:=shift_down+delta;
22746 end;
22747 end
22748
22749 @ In the case of a fraction line, the minimum clearance depends on the actual
22750 thickness of the line.
22751
22752 @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>=
22753 begin if cur_style<text_style then clr:=3*thickness(q)
22754 else clr:=thickness(q);
22755 delta:=half(thickness(q));
22756 delta1:=clr-((shift_up-depth(x))-(axis_height(cur_size)+delta));
22757 delta2:=clr-((axis_height(cur_size)-delta)-(height(z)-shift_down));
22758 if delta1>0 then shift_up:=shift_up+delta1;
22759 if delta2>0 then shift_down:=shift_down+delta2;
22760 end
22761
22762 @ @<Construct a vlist box for the fraction...@>=
22763 v:=new_null_box; type(v):=vlist_node;
22764 height(v):=shift_up+height(x); depth(v):=depth(z)+shift_down;
22765 width(v):=width(x); {this also equals |width(z)|}
22766 if thickness(q)=0 then
22767 begin p:=new_kern((shift_up-depth(x))-(height(z)-shift_down));
22768 link(p):=z;
22769 end
22770 else begin y:=fraction_rule(thickness(q));@/
22771 p:=new_kern((axis_height(cur_size)-delta)-@|(height(z)-shift_down));@/
22772 link(y):=p; link(p):=z;@/
22773 p:=new_kern((shift_up-depth(x))-(axis_height(cur_size)+delta));
22774 link(p):=y;
22775 end;
22776 link(x):=p; list_ptr(v):=x
22777
22778 @ @<Put the \(f)fraction into a box with its delimiters...@>=
22779 if cur_style<text_style then delta:=delim1(cur_size)
22780 else delta:=delim2(cur_size);
22781 x:=var_delimiter(left_delimiter(q), cur_size, delta); link(x):=v;@/
22782 z:=var_delimiter(right_delimiter(q), cur_size, delta); link(v):=z;@/
22783 new_hlist(q):=hpack(x,natural)
22784
22785 @ If the nucleus of an |op_noad| is a single character, it is to be
22786 centered vertically with respect to the axis, after first being enlarged
22787 (via a character list in the font) if we are in display style. The normal
22788 convention for placing displayed limits is to put them above and below the
22789 operator in display style.
22790
22791 The italic correction is removed from the character if there is a subscript
22792 and the limits are not being displayed. The |make_op|
22793 routine returns the value that should be used as an offset between
22794 subscript and superscript.
22795
22796 After |make_op| has acted, |subtype(q)| will be |limits| if and only if
22797 the limits have been set above and below the operator. In that case,
22798 |new_hlist(q)| will already contain the desired final box.
22799
22800 @<Declare math...@>=
22801 function make_op(@!q:pointer):scaled;
22802 var delta:scaled; {offset between subscript and superscript}
22803 @!p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
22804 @!c:quarterword;@+@!i:four_quarters; {registers for character examination}
22805 @!shift_up,@!shift_down:scaled; {dimensions for box calculation}
22806 begin if (subtype(q)=normal)and(cur_style<text_style) then
22807 subtype(q):=limits;
22808 if math_type(nucleus(q))=math_char then
22809 begin fetch(nucleus(q));
22810 if (cur_style<text_style)and(char_tag(cur_i)=list_tag) then {make it larger}
22811 begin c:=rem_byte(cur_i); i:=char_info(cur_f)(c);
22812 if char_exists(i) then
22813 begin cur_c:=c; cur_i:=i; character(nucleus(q)):=c;
22814 end;
22815 end;
22816 delta:=char_italic(cur_f)(cur_i); x:=clean_box(nucleus(q),cur_style);
22817 if (math_type(subscr(q))<>empty)and(subtype(q)<>limits) then
22818 width(x):=width(x)-delta; {remove italic correction}
22819 shift_amount(x):=half(height(x)-depth(x)) - axis_height(cur_size);
22820 {center vertically}
22821 math_type(nucleus(q)):=sub_box; info(nucleus(q)):=x;
22822 end
22823 else delta:=0;
22824 if subtype(q)=limits then
22825 @<Construct a box with limits above and below it, skewed by |delta|@>;
22826 make_op:=delta;
22827 end;
22828
22829 @ The following program builds a vlist box |v| for displayed limits. The
22830 width of the box is not affected by the fact that the limits may be skewed.
22831
22832 @<Construct a box with limits above and below it...@>=
22833 begin x:=clean_box(supscr(q),sup_style(cur_style));
22834 y:=clean_box(nucleus(q),cur_style);
22835 z:=clean_box(subscr(q),sub_style(cur_style));
22836 v:=new_null_box; type(v):=vlist_node; width(v):=width(y);
22837 if width(x)>width(v) then width(v):=width(x);
22838 if width(z)>width(v) then width(v):=width(z);
22839 x:=rebox(x,width(v)); y:=rebox(y,width(v)); z:=rebox(z,width(v));@/
22840 shift_amount(x):=half(delta); shift_amount(z):=-shift_amount(x);
22841 height(v):=height(y); depth(v):=depth(y);
22842 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)| to
22843 account for their presence@>;
22844 new_hlist(q):=v;
22845 end
22846
22847 @ We use |shift_up| and |shift_down| in the following program for the
22848 amount of glue between the displayed operator |y| and its limits |x| and
22849 |z|. The vlist inside box |v| will consist of |x| followed by |y| followed
22850 by |z|, with kern nodes for the spaces between and around them.
22851
22852 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)|...@>=
22853 if math_type(supscr(q))=empty then
22854 begin free_node(x,box_node_size); list_ptr(v):=y;
22855 end
22856 else begin shift_up:=big_op_spacing3-depth(x);
22857 if shift_up<big_op_spacing1 then shift_up:=big_op_spacing1;
22858 p:=new_kern(shift_up); link(p):=y; link(x):=p;@/
22859 p:=new_kern(big_op_spacing5); link(p):=x; list_ptr(v):=p;
22860 height(v):=height(v)+big_op_spacing5+height(x)+depth(x)+shift_up;
22861 end;
22862 if math_type(subscr(q))=empty then free_node(z,box_node_size)
22863 else begin shift_down:=big_op_spacing4-height(z);
22864 if shift_down<big_op_spacing2 then shift_down:=big_op_spacing2;
22865 p:=new_kern(shift_down); link(y):=p; link(p):=z;@/
22866 p:=new_kern(big_op_spacing5); link(z):=p;
22867 depth(v):=depth(v)+big_op_spacing5+height(z)+depth(z)+shift_down;
22868 end
22869
22870 @ A ligature found in a math formula does not create a |ligature_node|, because
22871 there is no question of hyphenation afterwards; the ligature will simply be
22872 stored in an ordinary |char_node|, after residing in an |ord_noad|.
22873
22874 The |math_type| is converted to |math_text_char| here if we would not want to
22875 apply an italic correction to the current character unless it belongs
22876 to a math font (i.e., a font with |space=0|).
22877
22878 No boundary characters enter into these ligatures.
22879
22880 @<Declare math...@>=
22881 procedure make_ord(@!q:pointer);
22882 label restart,exit;
22883 var a:integer; {address of lig/kern instruction}
22884 @!p,@!r:pointer; {temporary registers for list manipulation}
22885 begin restart:@t@>@;@/
22886 if math_type(subscr(q))=empty then if math_type(supscr(q))=empty then
22887 if math_type(nucleus(q))=math_char then
22888 begin p:=link(q);
22889 if p<>null then if (type(p)>=ord_noad)and(type(p)<=punct_noad) then
22890 if math_type(nucleus(p))=math_char then
22891 if fam(nucleus(p))=fam(nucleus(q)) then
22892 begin math_type(nucleus(q)):=math_text_char;
22893 fetch(nucleus(q));
22894 if char_tag(cur_i)=lig_tag then
22895 begin a:=lig_kern_start(cur_f)(cur_i);
22896 cur_c:=character(nucleus(p));
22897 cur_i:=font_info[a].qqqq;
22898 if skip_byte(cur_i)>stop_flag then
22899 begin a:=lig_kern_restart(cur_f)(cur_i);
22900 cur_i:=font_info[a].qqqq;
22901 end;
22902 loop@+ begin @<If instruction |cur_i| is a kern with |cur_c|, attach
22903 the kern after~|q|; or if it is a ligature with |cur_c|, combine
22904 noads |q| and~|p| appropriately; then |return| if the cursor has
22905 moved past a noad, or |goto restart|@>;
22906 if skip_byte(cur_i)>=stop_flag then return;
22907 a:=a+qo(skip_byte(cur_i))+1;
22908 cur_i:=font_info[a].qqqq;
22909 end;
22910 end;
22911 end;
22912 end;
22913 exit:end;
22914
22915 @ Note that a ligature between an |ord_noad| and another kind of noad
22916 is replaced by an |ord_noad|, when the two noads collapse into one.
22917 But we could make a parenthesis (say) change shape when it follows
22918 certain letters. Presumably a font designer will define such
22919 ligatures only when this convention makes sense.
22920
22921 \chardef\?='174 % vertical line to indicate character retention
22922
22923 @<If instruction |cur_i| is a kern with |cur_c|, ...@>=
22924 if next_char(cur_i)=cur_c then if skip_byte(cur_i)<=stop_flag then
22925 if op_byte(cur_i)>=kern_flag then
22926 begin p:=new_kern(char_kern(cur_f)(cur_i));
22927 link(p):=link(q); link(q):=p; return;
22928 end
22929 else begin check_interrupt; {allow a way out of infinite ligature loop}
22930 case op_byte(cur_i) of
22931 qi(1),qi(5): character(nucleus(q)):=rem_byte(cur_i); {\.{=:\?}, \.{=:\?>}}
22932 qi(2),qi(6): character(nucleus(p)):=rem_byte(cur_i); {\.{\?=:}, \.{\?=:>}}
22933 qi(3),qi(7),qi(11):begin r:=new_noad; {\.{\?=:\?}, \.{\?=:\?>}, \.{\?=:\?>>}}
22934 character(nucleus(r)):=rem_byte(cur_i);
22935 fam(nucleus(r)):=fam(nucleus(q));@/
22936 link(q):=r; link(r):=p;
22937 if op_byte(cur_i)<qi(11) then math_type(nucleus(r)):=math_char
22938 else math_type(nucleus(r)):=math_text_char; {prevent combination}
22939 end;
22940 othercases begin link(q):=link(p);
22941 character(nucleus(q)):=rem_byte(cur_i); {\.{=:}}
22942 mem[subscr(q)]:=mem[subscr(p)]; mem[supscr(q)]:=mem[supscr(p)];@/
22943 free_node(p,noad_size);
22944 end
22945 endcases;
22946 if op_byte(cur_i)>qi(3) then return;
22947 math_type(nucleus(q)):=math_char; goto restart;
22948 end
22949
22950 @ When we get to the following part of the program, we have ``fallen through''
22951 from cases that did not lead to |check_dimensions| or |done_with_noad| or
22952 |done_with_node|. Thus, |q|~points to a noad whose nucleus may need to be
22953 converted to an hlist, and whose subscripts and superscripts need to be
22954 appended if they are present.
22955
22956 If |nucleus(q)| is not a |math_char|, the variable |delta| is the amount
22957 by which a superscript should be moved right with respect to a subscript
22958 when both are present.
22959 @^subscripts@>
22960 @^superscripts@>
22961
22962 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>=
22963 case math_type(nucleus(q)) of
22964 math_char, math_text_char:
22965 @<Create a character node |p| for |nucleus(q)|, possibly followed
22966 by a kern node for the italic correction, and set |delta| to the
22967 italic correction if a subscript is present@>;
22968 empty: p:=null;
22969 sub_box: p:=info(nucleus(q));
22970 sub_mlist: begin cur_mlist:=info(nucleus(q)); save_style:=cur_style;
22971 mlist_penalties:=false; mlist_to_hlist; {recursive call}
22972 @^recursion@>
22973 cur_style:=save_style; @<Set up the values...@>;
22974 p:=hpack(link(temp_head),natural);
22975 end;
22976 othercases confusion("mlist2")
22977 @:this can't happen mlist2}{\quad mlist2@>
22978 endcases;@/
22979 new_hlist(q):=p;
22980 if (math_type(subscr(q))=empty)and(math_type(supscr(q))=empty) then
22981 goto check_dimensions;
22982 make_scripts(q,delta)
22983
22984 @ @<Create a character node |p| for |nucleus(q)|...@>=
22985 begin fetch(nucleus(q));
22986 if char_exists(cur_i) then
22987 begin delta:=char_italic(cur_f)(cur_i); p:=new_character(cur_f,qo(cur_c));
22988 if (math_type(nucleus(q))=math_text_char)and(space(cur_f)<>0) then
22989 delta:=0; {no italic correction in mid-word of text font}
22990 if (math_type(subscr(q))=empty)and(delta<>0) then
22991 begin link(p):=new_kern(delta); delta:=0;
22992 end;
22993 end
22994 else p:=null;
22995 end
22996
22997 @ The purpose of |make_scripts(q,delta)| is to attach the subscript and/or
22998 superscript of noad |q| to the list that starts at |new_hlist(q)|,
22999 given that the subscript and superscript aren't both empty. The superscript
23000 will appear to the right of the subscript by a given distance |delta|.
23001
23002 We set |shift_down| and |shift_up| to the minimum amounts to shift the
23003 baseline of subscripts and superscripts based on the given nucleus.
23004
23005 @<Declare math...@>=
23006 procedure make_scripts(@!q:pointer;@!delta:scaled);
23007 var p,@!x,@!y,@!z:pointer; {temporary registers for box construction}
23008 @!shift_up,@!shift_down,@!clr:scaled; {dimensions in the calculation}
23009 @!t:small_number; {subsidiary size code}
23010 begin p:=new_hlist(q);
23011 if is_char_node(p) then
23012 begin shift_up:=0; shift_down:=0;
23013 end
23014 else begin z:=hpack(p,natural);
23015 if cur_style<script_style then t:=script_size@+else t:=script_script_size;
23016 shift_up:=height(z)-sup_drop(t);
23017 shift_down:=depth(z)+sub_drop(t);
23018 free_node(z,box_node_size);
23019 end;
23020 if math_type(supscr(q))=empty then
23021 @<Construct a subscript box |x| when there is no superscript@>
23022 else begin @<Construct a superscript box |x|@>;
23023 if math_type(subscr(q))=empty then shift_amount(x):=-shift_up
23024 else @<Construct a sub/superscript combination box |x|, with the
23025 superscript offset by |delta|@>;
23026 end;
23027 if new_hlist(q)=null then new_hlist(q):=x
23028 else begin p:=new_hlist(q);
23029 while link(p)<>null do p:=link(p);
23030 link(p):=x;
23031 end;
23032 end;
23033
23034 @ When there is a subscript without a superscript, the top of the subscript
23035 should not exceed the baseline plus four-fifths of the x-height.
23036
23037 @<Construct a subscript box |x| when there is no superscript@>=
23038 begin x:=clean_box(subscr(q),sub_style(cur_style));
23039 width(x):=width(x)+script_space;
23040 if shift_down<sub1(cur_size) then shift_down:=sub1(cur_size);
23041 clr:=height(x)-(abs(math_x_height(cur_size)*4) div 5);
23042 if shift_down<clr then shift_down:=clr;
23043 shift_amount(x):=shift_down;
23044 end
23045
23046 @ The bottom of a superscript should never descend below the baseline plus
23047 one-fourth of the x-height.
23048
23049 @<Construct a superscript box |x|@>=
23050 begin x:=clean_box(supscr(q),sup_style(cur_style));
23051 width(x):=width(x)+script_space;
23052 if odd(cur_style) then clr:=sup3(cur_size)
23053 else if cur_style<text_style then clr:=sup1(cur_size)
23054 else clr:=sup2(cur_size);
23055 if shift_up<clr then shift_up:=clr;
23056 clr:=depth(x)+(abs(math_x_height(cur_size)) div 4);
23057 if shift_up<clr then shift_up:=clr;
23058 end
23059
23060 @ When both subscript and superscript are present, the subscript must be
23061 separated from the superscript by at least four times |default_rule_thickness|.
23062 If this condition would be violated, the subscript moves down, after which
23063 both subscript and superscript move up so that the bottom of the superscript
23064 is at least as high as the baseline plus four-fifths of the x-height.
23065
23066 @<Construct a sub/superscript combination box |x|...@>=
23067 begin y:=clean_box(subscr(q),sub_style(cur_style));
23068 width(y):=width(y)+script_space;
23069 if shift_down<sub2(cur_size) then shift_down:=sub2(cur_size);
23070 clr:=4*default_rule_thickness-
23071 ((shift_up-depth(x))-(height(y)-shift_down));
23072 if clr>0 then
23073 begin shift_down:=shift_down+clr;
23074 clr:=(abs(math_x_height(cur_size)*4) div 5)-(shift_up-depth(x));
23075 if clr>0 then
23076 begin shift_up:=shift_up+clr;
23077 shift_down:=shift_down-clr;
23078 end;
23079 end;
23080 shift_amount(x):=delta; {superscript is |delta| to the right of the subscript}
23081 p:=new_kern((shift_up-depth(x))-(height(y)-shift_down)); link(x):=p; link(p):=y;
23082 x:=vpack(x,natural); shift_amount(x):=shift_down;
23083 end
23084
23085 @ We have now tied up all the loose ends of the first pass of |mlist_to_hlist|.
23086 The second pass simply goes through and hooks everything together with the
23087 proper glue and penalties. It also handles the |left_noad| and |right_noad| that
23088 might be present, since |max_h| and |max_d| are now known. Variable |p| points
23089 to a node at the current end of the final hlist.
23090
23091 @<Make a second pass over the mlist, ...@>=
23092 p:=temp_head; link(p):=null; q:=mlist; r_type:=0; cur_style:=style;
23093 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
23094 while q<>null do
23095 begin @<If node |q| is a style node, change the style and |goto delete_q|;
23096 otherwise if it is not a noad, put it into the hlist,
23097 advance |q|, and |goto done|; otherwise set |s| to the size
23098 of noad |q|, set |t| to the associated type (|ord_noad..
23099 inner_noad|), and set |pen| to the associated penalty@>;
23100 @<Append inter-element spacing based on |r_type| and |t|@>;
23101 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>;
23102 if type(q)=right_noad then t:=open_noad;
23103 r_type:=t;
23104 delete_q: r:=q; q:=link(q); free_node(r,s);
23105 done: end
23106
23107 @ Just before doing the big |case| switch in the second pass, the program
23108 sets up default values so that most of the branches are short.
23109
23110 @<If node |q| is a style node, change the style...@>=
23111 t:=ord_noad; s:=noad_size; pen:=inf_penalty;
23112 case type(q) of
23113 op_noad,open_noad,close_noad,punct_noad,inner_noad: t:=type(q);
23114 bin_noad: begin t:=bin_noad; pen:=bin_op_penalty;
23115 end;
23116 rel_noad: begin t:=rel_noad; pen:=rel_penalty;
23117 end;
23118 ord_noad,vcenter_noad,over_noad,under_noad: do_nothing;
23119 radical_noad: s:=radical_noad_size;
23120 accent_noad: s:=accent_noad_size;
23121 fraction_noad: s:=fraction_noad_size;
23122 left_noad,right_noad: t:=make_left_right(q,style,max_d,max_h);
23123 style_node: @<Change the current style and |goto delete_q|@>;
23124 whatsit_node,penalty_node,rule_node,disc_node,adjust_node,ins_node,mark_node,
23125 glue_node,kern_node:@t@>@;@/
23126 begin link(p):=q; p:=q; q:=link(q); link(p):=null; goto done;
23127 end;
23128 othercases confusion("mlist3")
23129 @:this can't happen mlist3}{\quad mlist3@>
23130 endcases
23131
23132 @ The |make_left_right| function constructs a left or right delimiter of
23133 the required size and returns the value |open_noad| or |close_noad|. The
23134 |right_noad| and |left_noad| will both be based on the original |style|,
23135 so they will have consistent sizes.
23136
23137 We use the fact that |right_noad-left_noad=close_noad-open_noad|.
23138
23139 @<Declare math...@>=
23140 function make_left_right(@!q:pointer;@!style:small_number;
23141 @!max_d,@!max_h:scaled):small_number;
23142 var delta,@!delta1,@!delta2:scaled; {dimensions used in the calculation}
23143 begin cur_style:=style; @<Set up the values...@>;
23144 delta2:=max_d+axis_height(cur_size);
23145 delta1:=max_h+max_d-delta2;
23146 if delta2>delta1 then delta1:=delta2; {|delta1| is max distance from axis}
23147 delta:=(delta1 div 500)*delimiter_factor;
23148 delta2:=delta1+delta1-delimiter_shortfall;
23149 if delta<delta2 then delta:=delta2;
23150 new_hlist(q):=var_delimiter(delimiter(q),cur_size,delta);
23151 make_left_right:=type(q)-(left_noad-open_noad); {|open_noad| or |close_noad|}
23152 end;
23153
23154 @ @<Change the current style and |goto delete_q|@>=
23155 begin cur_style:=subtype(q); s:=style_node_size;
23156 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
23157 goto delete_q;
23158 end
23159
23160 @ The inter-element spacing in math formulas depends on an $8\times8$ table that
23161 \TeX\ preloads as a 64-digit string. The elements of this string have the
23162 following significance:
23163 $$\vbox{\halign{#\hfil\cr
23164 \.0 means no space;\cr
23165 \.1 means a conditional thin space (\.{\\nonscript\\mskip\\thinmuskip});\cr
23166 \.2 means a thin space (\.{\\mskip\\thinmuskip});\cr
23167 \.3 means a conditional medium space
23168 (\.{\\nonscript\\mskip\\medmuskip});\cr
23169 \.4 means a conditional thick space
23170 (\.{\\nonscript\\mskip\\thickmuskip});\cr
23171 \.* means an impossible case.\cr}}$$
23172 This is all pretty cryptic, but {\sl The \TeX book\/} explains what is
23173 supposed to happen, and the string makes it happen.
23174 @:TeXbook}{\sl The \TeX book@>
23175
23176 A global variable |magic_offset| is computed so that if |a| and |b| are
23177 in the range |ord_noad..inner_noad|, then |str_pool[a*8+b+magic_offset]|
23178 is the digit for spacing between noad types |a| and |b|.
23179
23180 If \PASCAL\ had provided a good way to preload constant arrays, this part of
23181 the program would not have been so strange.
23182 @:PASCAL}{\PASCAL@>
23183
23184 @d math_spacing=@;@/
23185 @t\hskip-35pt@>
23186 "0234000122*4000133**3**344*0400400*000000234000111*1111112341011"
23187 @t$ \hskip-35pt$@>
23188
23189 @<Glob...@>=
23190 @!magic_offset:integer; {used to find inter-element spacing}
23191
23192 @ @<Compute the magic offset@>=
23193 magic_offset:=str_start[math_spacing]-9*ord_noad
23194
23195 @ @<Append inter-element spacing based on |r_type| and |t|@>=
23196 if r_type>0 then {not the first noad}
23197 begin case so(str_pool[r_type*8+t+magic_offset]) of
23198 "0": x:=0;
23199 "1": if cur_style<script_style then x:=thin_mu_skip_code@+else x:=0;
23200 "2": x:=thin_mu_skip_code;
23201 "3": if cur_style<script_style then x:=med_mu_skip_code@+else x:=0;
23202 "4": if cur_style<script_style then x:=thick_mu_skip_code@+else x:=0;
23203 othercases confusion("mlist4")
23204 @:this can't happen mlist4}{\quad mlist4@>
23205 endcases;
23206 if x<>0 then
23207 begin y:=math_glue(glue_par(x),cur_mu);
23208 z:=new_glue(y); glue_ref_count(y):=null; link(p):=z; p:=z;@/
23209 subtype(z):=x+1; {store a symbolic subtype}
23210 end;
23211 end
23212
23213 @ We insert a penalty node after the hlist entries of noad |q| if |pen|
23214 is not an ``infinite'' penalty, and if the node immediately following |q|
23215 is not a penalty node or a |rel_noad| or absent entirely.
23216
23217 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>=
23218 if new_hlist(q)<>null then
23219 begin link(p):=new_hlist(q);
23220 repeat p:=link(p);
23221 until link(p)=null;
23222 end;
23223 if penalties then if link(q)<>null then if pen<inf_penalty then
23224 begin r_type:=type(link(q));
23225 if r_type<>penalty_node then if r_type<>rel_noad then
23226 begin z:=new_penalty(pen); link(p):=z; p:=z;
23227 end;
23228 end
23229
23230 @* \[37] Alignment.
23231 It's sort of a miracle whenever \.{\\halign} and \.{\\valign} work, because
23232 they cut across so many of the control structures of \TeX.
23233
23234 Therefore the
23235 present page is probably not the best place for a beginner to start reading
23236 this program; it is better to master everything else first.
23237
23238 Let us focus our thoughts on an example of what the input might be, in order
23239 to get some idea about how the alignment miracle happens. The example doesn't
23240 do anything useful, but it is sufficiently general to indicate all of the
23241 special cases that must be dealt with; please do not be disturbed by its
23242 apparent complexity and meaninglessness.
23243 $$\vbox{\halign{\.{#}\hfil\cr
23244 {}\\tabskip 2pt plus 3pt\cr
23245 {}\\halign to 300pt\{u1\#v1\&\cr
23246 \hskip 50pt\\tabskip 1pt plus 1fil u2\#v2\&\cr
23247 \hskip 50pt u3\#v3\\cr\cr
23248 \hskip 25pt a1\&\\omit a2\&\\vrule\\cr\cr
23249 \hskip 25pt \\noalign\{\\vskip 3pt\}\cr
23250 \hskip 25pt b1\\span b2\\cr\cr
23251 \hskip 25pt \\omit\&c2\\span\\omit\\cr\}\cr}}$$
23252 Here's what happens:
23253
23254 \yskip
23255 (0) When `\.{\\halign to 300pt\{}' is scanned, the |scan_spec| routine
23256 places the 300pt dimension onto the |save_stack|, and an |align_group|
23257 code is placed above it. This will make it possible to complete the alignment
23258 when the matching `\.\}' is found.
23259
23260 (1) The preamble is scanned next. Macros in the preamble are not expanded,
23261 @^preamble@>
23262 except as part of a tabskip specification. For example, if \.{u2} had been
23263 a macro in the preamble above, it would have been expanded, since \TeX\
23264 must look for `\.{minus...}' as part of the tabskip glue. A ``preamble list''
23265 is constructed based on the user's preamble; in our case it contains the
23266 following seven items:
23267 $$\vbox{\halign{\.{#}\hfil\qquad&(#)\hfil\cr
23268 {}\\glue 2pt plus 3pt&the tabskip preceding column 1\cr
23269 {}\\alignrecord, width $-\infty$&preamble info for column 1\cr
23270 {}\\glue 2pt plus 3pt&the tabskip between columns 1 and 2\cr
23271 {}\\alignrecord, width $-\infty$&preamble info for column 2\cr
23272 {}\\glue 1pt plus 1fil&the tabskip between columns 2 and 3\cr
23273 {}\\alignrecord, width $-\infty$&preamble info for column 3\cr
23274 {}\\glue 1pt plus 1fil&the tabskip following column 3\cr}}$$
23275 These ``alignrecord'' entries have the same size as an |unset_node|,
23276 since they will later be converted into such nodes. However, at the
23277 moment they have no |type| or |subtype| fields; they have |info| fields
23278 instead, and these |info| fields are initially set to the value |end_span|,
23279 for reasons explained below. Furthermore, the alignrecord nodes have no
23280 |height| or |depth| fields; these are renamed |u_part| and |v_part|,
23281 and they point to token lists for the templates of the alignment.
23282 For example, the |u_part| field in the first alignrecord points to the
23283 token list `\.{u1}', i.e., the template preceding the `\.\#' for column~1.
23284
23285 (2) \TeX\ now looks at what follows the \.{\\cr} that ended the preamble.
23286 It is not `\.{\\noalign}' or `\.{\\omit}', so this input is put back to
23287 be read again, and the template `\.{u1}' is fed to the scanner. Just
23288 before reading `\.{u1}', \TeX\ goes into restricted horizontal mode.
23289 Just after reading `\.{u1}', \TeX\ will see `\.{a1}', and then (when the
23290 {\.\&} is sensed) \TeX\ will see `\.{v1}'. Then \TeX\ scans an |endv|
23291 token, indicating the end of a column. At this point an |unset_node| is
23292 created, containing the contents of the current hlist (i.e., `\.{u1a1v1}').
23293 The natural width of this unset node replaces the |width| field of the
23294 alignrecord for column~1; in general, the alignrecords will record the
23295 maximum natural width that has occurred so far in a given column.
23296
23297 (3) Since `\.{\\omit}' follows the `\.\&', the templates for column~2
23298 are now bypassed. Again \TeX\ goes into restricted horizontal mode and
23299 makes an |unset_node| from the resulting hlist; but this time the
23300 hlist contains simply `\.{a2}'. The natural width of the new unset box
23301 is remembered in the |width| field of the alignrecord for column~2.
23302
23303 (4) A third |unset_node| is created for column 3, using essentially the
23304 mechanism that worked for column~1; this unset box contains `\.{u3\\vrule
23305 v3}'. The vertical rule in this case has running dimensions that will later
23306 extend to the height and depth of the whole first row, since each |unset_node|
23307 in a row will eventually inherit the height and depth of its enclosing box.
23308
23309 (5) The first row has now ended; it is made into a single unset box
23310 comprising the following seven items:
23311 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
23312 {}\\glue 2pt plus 3pt\cr
23313 {}\\unsetbox for 1 column: u1a1v1\cr
23314 {}\\glue 2pt plus 3pt\cr
23315 {}\\unsetbox for 1 column: a2\cr
23316 {}\\glue 1pt plus 1fil\cr
23317 {}\\unsetbox for 1 column: u3\\vrule v3\cr
23318 {}\\glue 1pt plus 1fil\cr}}$$
23319 The width of this unset row is unimportant, but it has the correct height
23320 and depth, so the correct baselineskip glue will be computed as the row
23321 is inserted into a vertical list.
23322
23323 (6) Since `\.{\\noalign}' follows the current \.{\\cr}, \TeX\ appends
23324 additional material (in this case \.{\\vskip 3pt}) to the vertical list.
23325 While processing this material, \TeX\ will be in internal vertical
23326 mode, and |no_align_group| will be on |save_stack|.
23327
23328 (7) The next row produces an unset box that looks like this:
23329 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
23330 {}\\glue 2pt plus 3pt\cr
23331 {}\\unsetbox for 2 columns: u1b1v1u2b2v2\cr
23332 {}\\glue 1pt plus 1fil\cr
23333 {}\\unsetbox for 1 column: {\rm(empty)}\cr
23334 {}\\glue 1pt plus 1fil\cr}}$$
23335 The natural width of the unset box that spans columns 1~and~2 is stored
23336 in a ``span node,'' which we will explain later; the |info| field of the
23337 alignrecord for column~1 now points to the new span node, and the |info|
23338 of the span node points to |end_span|.
23339
23340 (8) The final row produces the unset box
23341 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
23342 {}\\glue 2pt plus 3pt\cr
23343 {}\\unsetbox for 1 column: {\rm(empty)}\cr
23344 {}\\glue 2pt plus 3pt\cr
23345 {}\\unsetbox for 2 columns: u2c2v2\cr
23346 {}\\glue 1pt plus 1fil\cr}}$$
23347 A new span node is attached to the alignrecord for column 2.
23348
23349 (9) The last step is to compute the true column widths and to change all the
23350 unset boxes to hboxes, appending the whole works to the vertical list that
23351 encloses the \.{\\halign}. The rules for deciding on the final widths of
23352 each unset column box will be explained below.
23353
23354 \yskip\noindent
23355 Note that as \.{\\halign} is being processed, we fearlessly give up control
23356 to the rest of \TeX. At critical junctures, an alignment routine is
23357 called upon to step in and do some little action, but most of the time
23358 these routines just lurk in the background. It's something like
23359 post-hypnotic suggestion.
23360
23361 @ We have mentioned that alignrecords contain no |height| or |depth| fields.
23362 Their |glue_sign| and |glue_order| are pre-empted as well, since it
23363 is necessary to store information about what to do when a template ends.
23364 This information is called the |extra_info| field.
23365
23366 @d u_part(#)==mem[#+height_offset].int {pointer to \<u_j> token list}
23367 @d v_part(#)==mem[#+depth_offset].int {pointer to \<v_j> token list}
23368 @d extra_info(#)==info(#+list_offset) {info to remember during template}
23369
23370 @ Alignments can occur within alignments, so a small stack is used to access
23371 the alignrecord information. At each level we have a |preamble| pointer,
23372 indicating the beginning of the preamble list; a |cur_align| pointer,
23373 indicating the current position in the preamble list; a |cur_span| pointer,
23374 indicating the value of |cur_align| at the beginning of a sequence of
23375 spanned columns; a |cur_loop| pointer, indicating the tabskip glue before
23376 an alignrecord that should be copied next if the current list is extended;
23377 and the |align_state| variable, which indicates the nesting of braces so
23378 that \.{\\cr} and \.{\\span} and tab marks are properly intercepted.
23379 There also are pointers |cur_head| and |cur_tail| to the head and tail
23380 of a list of adjustments being moved out from horizontal mode to
23381 vertical~mode.
23382
23383 The current values of these seven quantities appear in global variables;
23384 when they have to be pushed down, they are stored in 5-word nodes, and
23385 |align_ptr| points to the topmost such node.
23386
23387 @d preamble==link(align_head) {the current preamble list}
23388 @d align_stack_node_size=6 {number of |mem| words to save alignment states}
23389
23390 @<Glob...@>=
23391 @!cur_align:pointer; {current position in preamble list}
23392 @!cur_span:pointer; {start of currently spanned columns in preamble list}
23393 @!cur_loop:pointer; {place to copy when extending a periodic preamble}
23394 @!align_ptr:pointer; {most recently pushed-down alignment stack node}
23395 @!cur_head,@!cur_tail:pointer; {adjustment list pointers}
23396 @!cur_pre_head,@!cur_pre_tail:pointer; {pre-adjustment list pointers}
23397
23398 @ The |align_state| and |preamble| variables are initialized elsewhere.
23399
23400 @<Set init...@>=
23401 align_ptr:=null; cur_align:=null; cur_span:=null; cur_loop:=null;
23402 cur_head:=null; cur_tail:=null;
23403 cur_pre_head:=null; cur_pre_tail:=null;
23404
23405 @ Alignment stack maintenance is handled by a pair of trivial routines
23406 called |push_alignment| and |pop_alignment|.
23407
23408 @p procedure push_alignment;
23409 var p:pointer; {the new alignment stack node}
23410 begin p:=get_node(align_stack_node_size);
23411 link(p):=align_ptr; info(p):=cur_align;
23412 llink(p):=preamble; rlink(p):=cur_span;
23413 mem[p+2].int:=cur_loop; mem[p+3].int:=align_state;
23414 info(p+4):=cur_head; link(p+4):=cur_tail;
23415 info(p+5):=cur_pre_head; link(p+5):=cur_pre_tail;
23416 align_ptr:=p;
23417 cur_head:=get_avail;
23418 cur_pre_head:=get_avail;
23419 end;
23420 @#
23421 procedure pop_alignment;
23422 var p:pointer; {the top alignment stack node}
23423 begin free_avail(cur_head);
23424 free_avail(cur_pre_head);
23425 p:=align_ptr;
23426 cur_tail:=link(p+4); cur_head:=info(p+4);
23427 cur_pre_tail:=link(p+5); cur_pre_head:=info(p+5);
23428 align_state:=mem[p+3].int; cur_loop:=mem[p+2].int;
23429 cur_span:=rlink(p); preamble:=llink(p);
23430 cur_align:=info(p); align_ptr:=link(p);
23431 free_node(p,align_stack_node_size);
23432 end;
23433
23434 @ \TeX\ has eight procedures that govern alignments: |init_align| and
23435 |fin_align| are used at the very beginning and the very end; |init_row| and
23436 |fin_row| are used at the beginning and end of individual rows; |init_span|
23437 is used at the beginning of a sequence of spanned columns (possibly involving
23438 only one column); |init_col| and |fin_col| are used at the beginning and
23439 end of individual columns; and |align_peek| is used after \.{\\cr} to see
23440 whether the next item is \.{\\noalign}.
23441
23442 We shall consider these routines in the order they are first used during
23443 the course of a complete \.{\\halign}, namely |init_align|, |align_peek|,
23444 |init_row|, |init_span|, |init_col|, |fin_col|, |fin_row|, |fin_align|.
23445
23446 @ When \.{\\halign} or \.{\\valign} has been scanned in an appropriate
23447 mode, \TeX\ calls |init_align|, whose task is to get everything off to a
23448 good start. This mostly involves scanning the preamble and putting its
23449 information into the preamble list.
23450 @^preamble@>
23451
23452 @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/
23453 procedure@?align_peek; forward;@t\2@>@/
23454 procedure@?normal_paragraph; forward;@t\2@>@/
23455 procedure init_align;
23456 label done, done1, done2, continue;
23457 var save_cs_ptr:pointer; {|warning_index| value for error messages}
23458 @!p:pointer; {for short-term temporary use}
23459 begin save_cs_ptr:=cur_cs; {\.{\\halign} or \.{\\valign}, usually}
23460 push_alignment; align_state:=-1000000; {enter a new alignment level}
23461 @<Check for improper alignment in displayed math@>;
23462 push_nest; {enter a new semantic level}
23463 @<Change current mode to |-vmode| for \.{\\halign}, |-hmode| for \.{\\valign}@>;
23464 scan_spec(align_group,false);@/
23465 @<Scan the preamble and record it in the |preamble| list@>;
23466 new_save_level(align_group);
23467 if every_cr<>null then begin_token_list(every_cr,every_cr_text);
23468 align_peek; {look for \.{\\noalign} or \.{\\omit}}
23469 end;
23470
23471 @ In vertical modes, |prev_depth| already has the correct value. But
23472 if we are in |mmode| (displayed formula mode), we reach out to the
23473 enclosing vertical mode for the |prev_depth| value that produces the
23474 correct baseline calculations.
23475
23476 @<Change current mode...@>=
23477 if mode=mmode then
23478 begin mode:=-vmode; prev_depth:=nest[nest_ptr-2].aux_field.sc;
23479 end
23480 else if mode>0 then negate(mode)
23481
23482 @ When \.{\\halign} is used as a displayed formula, there should be
23483 no other pieces of mlists present.
23484
23485 @<Check for improper alignment in displayed math@>=
23486 if (mode=mmode)and((tail<>head)or(incompleat_noad<>null)) then
23487 begin print_err("Improper "); print_esc("halign"); print(" inside $$'s");
23488 @.Improper \\halign...@>
23489 help3("Displays can use special alignments (like \eqalignno)")@/
23490 ("only if nothing but the alignment itself is between $$'s.")@/
23491 ("So I've deleted the formulas that preceded this alignment.");
23492 error; flush_math;
23493 end
23494
23495 @ @<Scan the preamble and record it in the |preamble| list@>=
23496 preamble:=null; cur_align:=align_head; cur_loop:=null; scanner_status:=aligning;
23497 warning_index:=save_cs_ptr; align_state:=-1000000;
23498 {at this point, |cur_cmd=left_brace|}
23499 loop@+ begin @<Append the current tabskip glue to the preamble list@>;
23500 if cur_cmd=car_ret then goto done; {\.{\\cr} ends the preamble}
23501 @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|,
23502 looking for changes in the tabskip glue; append an
23503 alignrecord to the preamble list@>;
23504 end;
23505 done: scanner_status:=normal
23506
23507 @ @<Append the current tabskip glue to the preamble list@>=
23508 link(cur_align):=new_param_glue(tab_skip_code);
23509 cur_align:=link(cur_align)
23510
23511 @ @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|...@>=
23512 @<Scan the template \<u_j>, putting the resulting token list in |hold_head|@>;
23513 link(cur_align):=new_null_box; cur_align:=link(cur_align); {a new alignrecord}
23514 info(cur_align):=end_span; width(cur_align):=null_flag;
23515 u_part(cur_align):=link(hold_head);
23516 @<Scan the template \<v_j>, putting the resulting token list in |hold_head|@>;
23517 v_part(cur_align):=link(hold_head)
23518
23519 @ We enter `\.{\\span}' into |eqtb| with |tab_mark| as its command code,
23520 and with |span_code| as the command modifier. This makes \TeX\ interpret it
23521 essentially the same as an alignment delimiter like `\.\&', yet it is
23522 recognizably different when we need to distinguish it from a normal delimiter.
23523 It also turns out to be useful to give a special |cr_code| to `\.{\\cr}',
23524 and an even larger |cr_cr_code| to `\.{\\crcr}'.
23525
23526 The end of a template is represented by two ``frozen'' control sequences
23527 called \.{\\endtemplate}. The first has the command code |end_template|, which
23528 is |>outer_call|, so it will not easily disappear in the presence of errors.
23529 The |get_x_token| routine converts the first into the second, which has |endv|
23530 as its command code.
23531
23532 @d span_code=256 {distinct from any character}
23533 @d cr_code=257 {distinct from |span_code| and from any character}
23534 @d cr_cr_code=cr_code+1 {this distinguishes \.{\\crcr} from \.{\\cr}}
23535 @d end_template_token==cs_token_flag+frozen_end_template
23536
23537 @<Put each of \TeX's primitives into the hash table@>=
23538 primitive("span",tab_mark,span_code);@/
23539 @!@:span_}{\.{\\span} primitive@>
23540 primitive("cr",car_ret,cr_code);
23541 @!@:cr_}{\.{\\cr} primitive@>
23542 text(frozen_cr):="cr"; eqtb[frozen_cr]:=eqtb[cur_val];@/
23543 primitive("crcr",car_ret,cr_cr_code);
23544 @!@:cr_cr_}{\.{\\crcr} primitive@>
23545 text(frozen_end_template):="endtemplate"; text(frozen_endv):="endtemplate";
23546 @.endtemplate@>
23547 eq_type(frozen_endv):=endv; equiv(frozen_endv):=null_list;
23548 eq_level(frozen_endv):=level_one;@/
23549 eqtb[frozen_end_template]:=eqtb[frozen_endv];
23550 eq_type(frozen_end_template):=end_template;
23551
23552 @ @<Cases of |print_cmd_chr|...@>=
23553 tab_mark: if chr_code=span_code then print_esc("span")
23554 else chr_cmd("alignment tab character ");
23555 car_ret: if chr_code=cr_code then print_esc("cr")
23556 else print_esc("crcr");
23557
23558 @ The preamble is copied directly, except that \.{\\tabskip} causes a change
23559 to the tabskip glue, thereby possibly expanding macros that immediately
23560 follow it. An appearance of \.{\\span} also causes such an expansion.
23561
23562 Note that if the preamble contains `\.{\\global\\tabskip}', the `\.{\\global}'
23563 token survives in the preamble and the `\.{\\tabskip}' defines new
23564 tabskip glue (locally).
23565
23566 @<Declare the procedure called |get_preamble_token|@>=
23567 procedure get_preamble_token;
23568 label restart;
23569 begin restart: get_token;
23570 while (cur_chr=span_code)and(cur_cmd=tab_mark) do
23571 begin get_token; {this token will be expanded once}
23572 if cur_cmd>max_command then
23573 begin expand; get_token;
23574 end;
23575 end;
23576 if cur_cmd=endv then
23577 fatal_error("(interwoven alignment preambles are not allowed)");
23578 @.interwoven alignment preambles...@>
23579 if (cur_cmd=assign_glue)and(cur_chr=glue_base+tab_skip_code) then
23580 begin scan_optional_equals; scan_glue(glue_val);
23581 if global_defs>0 then geq_define(glue_base+tab_skip_code,glue_ref,cur_val)
23582 else eq_define(glue_base+tab_skip_code,glue_ref,cur_val);
23583 goto restart;
23584 end;
23585 end;
23586
23587 @ Spaces are eliminated from the beginning of a template.
23588
23589 @<Scan the template \<u_j>...@>=
23590 p:=hold_head; link(p):=null;
23591 loop@+ begin get_preamble_token;
23592 if cur_cmd=mac_param then goto done1;
23593 if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
23594 if (p=hold_head)and(cur_loop=null)and(cur_cmd=tab_mark)
23595 then cur_loop:=cur_align
23596 else begin print_err("Missing # inserted in alignment preamble");
23597 @.Missing \# inserted...@>
23598 help3("There should be exactly one # between &'s, when an")@/
23599 ("\halign or \valign is being set up. In this case you had")@/
23600 ("none, so I've put one in; maybe that will work.");
23601 back_error; goto done1;
23602 end
23603 else if (cur_cmd<>spacer)or(p<>hold_head) then
23604 begin link(p):=get_avail; p:=link(p); info(p):=cur_tok;
23605 end;
23606 end;
23607 done1:
23608
23609 @ @<Scan the template \<v_j>...@>=
23610 p:=hold_head; link(p):=null;
23611 loop@+ begin continue: get_preamble_token;
23612 if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
23613 goto done2;
23614 if cur_cmd=mac_param then
23615 begin print_err("Only one # is allowed per tab");
23616 @.Only one \# is allowed...@>
23617 help3("There should be exactly one # between &'s, when an")@/
23618 ("\halign or \valign is being set up. In this case you had")@/
23619 ("more than one, so I'm ignoring all but the first.");
23620 error; goto continue;
23621 end;
23622 link(p):=get_avail; p:=link(p); info(p):=cur_tok;
23623 end;
23624 done2: link(p):=get_avail; p:=link(p);
23625 info(p):=end_template_token {put \.{\\endtemplate} at the end}
23626
23627 @ The tricky part about alignments is getting the templates into the
23628 scanner at the right time, and recovering control when a row or column
23629 is finished.
23630
23631 We usually begin a row after each \.{\\cr} has been sensed, unless that
23632 \.{\\cr} is followed by \.{\\noalign} or by the right brace that terminates
23633 the alignment. The |align_peek| routine is used to look ahead and do
23634 the right thing; it either gets a new row started, or gets a \.{\\noalign}
23635 started, or finishes off the alignment.
23636
23637 @<Declare the procedure called |align_peek|@>=
23638 procedure align_peek;
23639 label restart;
23640 begin restart: align_state:=1000000;
23641 repeat get_x_or_protected;
23642 until cur_cmd<>spacer;
23643 if cur_cmd=no_align then
23644 begin scan_left_brace; new_save_level(no_align_group);
23645 if mode=-vmode then normal_paragraph;
23646 end
23647 else if cur_cmd=right_brace then fin_align
23648 else if (cur_cmd=car_ret)and(cur_chr=cr_cr_code) then
23649 goto restart {ignore \.{\\crcr}}
23650 else begin init_row; {start a new row}
23651 init_col; {start a new column and replace what we peeked at}
23652 end;
23653 end;
23654
23655 @ To start a row (i.e., a `row' that rhymes with `dough' but not with `bough'),
23656 we enter a new semantic level, copy the first tabskip glue, and change
23657 from internal vertical mode to restricted horizontal mode or vice versa.
23658 The |space_factor| and |prev_depth| are not used on this semantic level,
23659 but we clear them to zero just to be tidy.
23660
23661 @p @t\4@>@<Declare the procedure called |init_span|@>@t@>@/
23662 procedure init_row;
23663 begin push_nest; mode:=(-hmode-vmode)-mode;
23664 if mode=-hmode then space_factor:=0 @+else prev_depth:=0;
23665 tail_append(new_glue(glue_ptr(preamble)));
23666 subtype(tail):=tab_skip_code+1;@/
23667 cur_align:=link(preamble); cur_tail:=cur_head; cur_pre_tail:=cur_pre_head;
23668 init_span(cur_align);
23669 end;
23670
23671 @ The parameter to |init_span| is a pointer to the alignrecord where the
23672 next column or group of columns will begin. A new semantic level is
23673 entered, so that the columns will generate a list for subsequent packaging.
23674
23675 @<Declare the procedure called |init_span|@>=
23676 procedure init_span(@!p:pointer);
23677 begin push_nest;
23678 if mode=-hmode then space_factor:=1000
23679 else begin prev_depth:=pdf_ignored_dimen; normal_paragraph;
23680 end;
23681 cur_span:=p;
23682 end;
23683
23684 @ When a column begins, we assume that |cur_cmd| is either |omit| or else
23685 the current token should be put back into the input until the \<u_j>
23686 template has been scanned. (Note that |cur_cmd| might be |tab_mark| or
23687 |car_ret|.) We also assume that |align_state| is approximately 1000000 at
23688 this time. We remain in the same mode, and start the template if it is
23689 called for.
23690
23691 @p procedure init_col;
23692 begin extra_info(cur_align):=cur_cmd;
23693 if cur_cmd=omit then align_state:=0
23694 else begin back_input; begin_token_list(u_part(cur_align),u_template);
23695 end; {now |align_state=1000000|}
23696 end;
23697
23698 @ The scanner sets |align_state| to zero when the \<u_j> template ends. When
23699 a subsequent \.{\\cr} or \.{\\span} or tab mark occurs with |align_state=0|,
23700 the scanner activates the following code, which fires up the \<v_j> template.
23701 We need to remember the |cur_chr|, which is either |cr_cr_code|, |cr_code|,
23702 |span_code|, or a character code, depending on how the column text has ended.
23703
23704 This part of the program had better not be activated when the preamble
23705 to another alignment is being scanned, or when no alignment preamble is active.
23706
23707 @<Insert the \(v)\<v_j>...@>=
23708 begin if (scanner_status=aligning) or (cur_align=null) then
23709 fatal_error("(interwoven alignment preambles are not allowed)");
23710 @.interwoven alignment preambles...@>
23711 cur_cmd:=extra_info(cur_align); extra_info(cur_align):=cur_chr;
23712 if cur_cmd=omit then begin_token_list(omit_template,v_template)
23713 else begin_token_list(v_part(cur_align),v_template);
23714 align_state:=1000000; goto restart;
23715 end
23716
23717 @ The token list |omit_template| just referred to is a constant token
23718 list that contains the special control sequence \.{\\endtemplate} only.
23719
23720 @<Initialize the special...@>=
23721 info(omit_template):=end_template_token; {|link(omit_template)=null|}
23722
23723 @ When the |endv| command at the end of a \<v_j> template comes through the
23724 scanner, things really start to happen; and it is the |fin_col| routine
23725 that makes them happen. This routine returns |true| if a row as well as a
23726 column has been finished.
23727
23728 @p function fin_col:boolean;
23729 label exit;
23730 var p:pointer; {the alignrecord after the current one}
23731 @!q,@!r:pointer; {temporary pointers for list manipulation}
23732 @!s:pointer; {a new span node}
23733 @!u:pointer; {a new unset box}
23734 @!w:scaled; {natural width}
23735 @!o:glue_ord; {order of infinity}
23736 @!n:halfword; {span counter}
23737 begin if cur_align=null then confusion("endv");
23738 q:=link(cur_align);@+if q=null then confusion("endv");
23739 @:this can't happen endv}{\quad endv@>
23740 if align_state<500000 then
23741 fatal_error("(interwoven alignment preambles are not allowed)");
23742 @.interwoven alignment preambles...@>
23743 p:=link(q);
23744 @<If the preamble list has been traversed, check that the row has ended@>;
23745 if extra_info(cur_align)<>span_code then
23746 begin unsave; new_save_level(align_group);@/
23747 @<Package an unset box for the current column and record its width@>;
23748 @<Copy the tabskip glue between columns@>;
23749 if extra_info(cur_align)>=cr_code then
23750 begin fin_col:=true; return;
23751 end;
23752 init_span(p);
23753 end;
23754 align_state:=1000000;
23755 repeat get_x_or_protected;
23756 until cur_cmd<>spacer;
23757 cur_align:=p;
23758 init_col; fin_col:=false;
23759 exit: end;
23760
23761 @ @<If the preamble list has been traversed, check that the row has ended@>=
23762 if (p=null)and(extra_info(cur_align)<cr_code) then
23763 if cur_loop<>null then @<Lengthen the preamble periodically@>
23764 else begin print_err("Extra alignment tab has been changed to ");
23765 @.Extra alignment tab...@>
23766 print_esc("cr");
23767 help3("You have given more \span or & marks than there were")@/
23768 ("in the preamble to the \halign or \valign now in progress.")@/
23769 ("So I'll assume that you meant to type \cr instead.");
23770 extra_info(cur_align):=cr_code; error;
23771 end
23772
23773 @ @<Lengthen the preamble...@>=
23774 begin link(q):=new_null_box; p:=link(q); {a new alignrecord}
23775 info(p):=end_span; width(p):=null_flag; cur_loop:=link(cur_loop);
23776 @<Copy the templates from node |cur_loop| into node |p|@>;
23777 cur_loop:=link(cur_loop);
23778 link(p):=new_glue(glue_ptr(cur_loop));
23779 subtype(link(p)):=tab_skip_code+1;
23780 end
23781
23782 @ @<Copy the templates from node |cur_loop| into node |p|@>=
23783 q:=hold_head; r:=u_part(cur_loop);
23784 while r<>null do
23785 begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
23786 end;
23787 link(q):=null; u_part(p):=link(hold_head);
23788 q:=hold_head; r:=v_part(cur_loop);
23789 while r<>null do
23790 begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
23791 end;
23792 link(q):=null; v_part(p):=link(hold_head)
23793
23794 @ @<Copy the tabskip glue...@>=
23795 tail_append(new_glue(glue_ptr(link(cur_align))));
23796 subtype(tail):=tab_skip_code+1
23797
23798 @ @<Package an unset...@>=
23799 begin if mode=-hmode then
23800 begin adjust_tail:=cur_tail; pre_adjust_tail:=cur_pre_tail;
23801 u:=hpack(link(head),natural); w:=width(u);
23802 cur_tail:=adjust_tail; adjust_tail:=null;
23803 cur_pre_tail:=pre_adjust_tail; pre_adjust_tail:=null;
23804 end
23805 else begin u:=vpackage(link(head),natural,0); w:=height(u);
23806 end;
23807 n:=min_quarterword; {this represents a span count of 1}
23808 if cur_span<>cur_align then @<Update width entry for spanned columns@>
23809 else if w>width(cur_align) then width(cur_align):=w;
23810 type(u):=unset_node; span_count(u):=n;@/
23811 @<Determine the stretch order@>;
23812 glue_order(u):=o; glue_stretch(u):=total_stretch[o];@/
23813 @<Determine the shrink order@>;
23814 glue_sign(u):=o; glue_shrink(u):=total_shrink[o];@/
23815 pop_nest; link(tail):=u; tail:=u;
23816 end
23817
23818 @ A span node is a 2-word record containing |width|, |info|, and |link|
23819 fields. The |link| field is not really a link, it indicates the number of
23820 spanned columns; the |info| field points to a span node for the same
23821 starting column, having a greater extent of spanning, or to |end_span|,
23822 which has the largest possible |link| field; the |width| field holds the
23823 largest natural width corresponding to a particular set of spanned columns.
23824
23825 A list of the maximum widths so far, for spanned columns starting at a
23826 given column, begins with the |info| field of the alignrecord for that
23827 column.
23828
23829 @d span_node_size=2 {number of |mem| words for a span node}
23830
23831 @<Initialize the special list heads...@>=
23832 link(end_span):=max_quarterword+1; info(end_span):=null;
23833
23834 @ @<Update width entry for spanned columns@>=
23835 begin q:=cur_span;
23836 repeat incr(n); q:=link(link(q));
23837 until q=cur_align;
23838 if n>max_quarterword then confusion("256 spans"); {this can happen, but won't}
23839 @^system dependencies@>
23840 @:this can't happen 256 spans}{\quad 256 spans@>
23841 q:=cur_span; while link(info(q))<n do q:=info(q);
23842 if link(info(q))>n then
23843 begin s:=get_node(span_node_size); info(s):=info(q); link(s):=n;
23844 info(q):=s; width(s):=w;
23845 end
23846 else if width(info(q))<w then width(info(q)):=w;
23847 end
23848
23849 @ At the end of a row, we append an unset box to the current vlist (for
23850 \.{\\halign}) or the current hlist (for \.{\\valign}). This unset box
23851 contains the unset boxes for the columns, separated by the tabskip glue.
23852 Everything will be set later.
23853
23854 @p procedure fin_row;
23855 var p:pointer; {the new unset box}
23856 begin if mode=-hmode then
23857 begin p:=hpack(link(head),natural);
23858 pop_nest;
23859 if cur_pre_head <> cur_pre_tail then
23860 append_list(cur_pre_head)(cur_pre_tail);
23861 append_to_vlist(p);
23862 if cur_head <> cur_tail then
23863 append_list(cur_head)(cur_tail);
23864 end
23865 else begin p:=vpack(link(head),natural); pop_nest;
23866 link(tail):=p; tail:=p; space_factor:=1000;
23867 end;
23868 type(p):=unset_node; glue_stretch(p):=0;
23869 if every_cr<>null then begin_token_list(every_cr,every_cr_text);
23870 align_peek;
23871 end; {note that |glue_shrink(p)=0| since |glue_shrink==shift_amount|}
23872
23873 @ Finally, we will reach the end of the alignment, and we can breathe a
23874 sigh of relief that memory hasn't overflowed. All the unset boxes will now be
23875 set so that the columns line up, taking due account of spanned columns.
23876
23877 @p procedure@?do_assignments; forward;@t\2@>@/
23878 procedure@?resume_after_display; forward;@t\2@>@/
23879 procedure@?build_page; forward;@t\2@>@/
23880 procedure fin_align;
23881 var @!p,@!q,@!r,@!s,@!u,@!v: pointer; {registers for the list operations}
23882 @!t,@!w:scaled; {width of column}
23883 @!o:scaled; {shift offset for unset boxes}
23884 @!n:halfword; {matching span amount}
23885 @!rule_save:scaled; {temporary storage for |overfull_rule|}
23886 @!aux_save:memory_word; {temporary storage for |aux|}
23887 begin if cur_group<>align_group then confusion("align1");
23888 @:this can't happen align}{\quad align@>
23889 unsave; {that |align_group| was for individual entries}
23890 if cur_group<>align_group then confusion("align0");
23891 unsave; {that |align_group| was for the whole alignment}
23892 if nest[nest_ptr-1].mode_field=mmode then o:=display_indent
23893 else o:=0;
23894 @<Go through the preamble list, determining the column widths and
23895 changing the alignrecords to dummy unset boxes@>;
23896 @<Package the preamble list, to determine the actual tabskip glue amounts,
23897 and let |p| point to this prototype box@>;
23898 @<Set the glue in all the unset boxes of the current list@>;
23899 flush_node_list(p); pop_alignment;
23900 @<Insert the \(c)current list into its environment@>;
23901 end;@/
23902 @t\4@>@<Declare the procedure called |align_peek|@>
23903
23904 @ It's time now to dismantle the preamble list and to compute the column
23905 widths. Let $w_{ij}$ be the maximum of the natural widths of all entries
23906 that span columns $i$ through $j$, inclusive. The alignrecord for column~$i$
23907 contains $w_{ii}$ in its |width| field, and there is also a linked list of
23908 the nonzero $w_{ij}$ for increasing $j$, accessible via the |info| field;
23909 these span nodes contain the value $j-i+|min_quarterword|$ in their
23910 |link| fields. The values of $w_{ii}$ were initialized to |null_flag|, which
23911 we regard as $-\infty$.
23912
23913 The final column widths are defined by the formula
23914 $$w_j=\max_{1\L i\L j}\biggl( w_{ij}-\sum_{i\L k<j}(t_k+w_k)\biggr),$$
23915 where $t_k$ is the natural width of the tabskip glue between columns
23916 $k$ and~$k+1$. However, if $w_{ij}=-\infty$ for all |i| in the range
23917 |1<=i<=j| (i.e., if every entry that involved column~|j| also involved
23918 column~|j+1|), we let $w_j=0$, and we zero out the tabskip glue after
23919 column~|j|.
23920
23921 \TeX\ computes these values by using the following scheme: First $w_1=w_{11}$.
23922 Then replace $w_{2j}$ by $\max(w_{2j},w_{1j}-t_1-w_1)$, for all $j>1$.
23923 Then $w_2=w_{22}$. Then replace $w_{3j}$ by $\max(w_{3j},w_{2j}-t_2-w_2)$
23924 for all $j>2$; and so on. If any $w_j$ turns out to be $-\infty$, its
23925 value is changed to zero and so is the next tabskip.
23926
23927 @<Go through the preamble list,...@>=
23928 q:=link(preamble);
23929 repeat flush_list(u_part(q)); flush_list(v_part(q));
23930 p:=link(link(q));
23931 if width(q)=null_flag then
23932 @<Nullify |width(q)| and the tabskip glue following this column@>;
23933 if info(q)<>end_span then
23934 @<Merge the widths in the span nodes of |q| with those of |p|,
23935 destroying the span nodes of |q|@>;
23936 type(q):=unset_node; span_count(q):=min_quarterword; height(q):=0;
23937 depth(q):=0; glue_order(q):=normal; glue_sign(q):=normal;
23938 glue_stretch(q):=0; glue_shrink(q):=0; q:=p;
23939 until q=null
23940
23941 @ @<Nullify |width(q)| and the tabskip glue following this column@>=
23942 begin width(q):=0; r:=link(q); s:=glue_ptr(r);
23943 if s<>zero_glue then
23944 begin add_glue_ref(zero_glue); delete_glue_ref(s);
23945 glue_ptr(r):=zero_glue;
23946 end;
23947 end
23948
23949 @ Merging of two span-node lists is a typical exercise in the manipulation of
23950 linearly linked data structures. The essential invariant in the following
23951 |repeat| loop is that we want to dispense with node |r|, in |q|'s list,
23952 and |u| is its successor; all nodes of |p|'s list up to and including |s|
23953 have been processed, and the successor of |s| matches |r| or precedes |r|
23954 or follows |r|, according as |link(r)=n| or |link(r)>n| or |link(r)<n|.
23955
23956 @<Merge the widths...@>=
23957 begin t:=width(q)+width(glue_ptr(link(q)));
23958 r:=info(q); s:=end_span; info(s):=p; n:=min_quarterword+1;
23959 repeat width(r):=width(r)-t; u:=info(r);
23960 while link(r)>n do
23961 begin s:=info(s); n:=link(info(s))+1;
23962 end;
23963 if link(r)<n then
23964 begin info(r):=info(s); info(s):=r; decr(link(r)); s:=r;
23965 end
23966 else begin if width(r)>width(info(s)) then width(info(s)):=width(r);
23967 free_node(r,span_node_size);
23968 end;
23969 r:=u;
23970 until r=end_span;
23971 end
23972
23973 @ Now the preamble list has been converted to a list of alternating unset
23974 boxes and tabskip glue, where the box widths are equal to the final
23975 column sizes. In case of \.{\\valign}, we change the widths to heights,
23976 so that a correct error message will be produced if the alignment is
23977 overfull or underfull.
23978
23979 @<Package the preamble list...@>=
23980 save_ptr:=save_ptr-2; pack_begin_line:=-mode_line;
23981 if mode=-vmode then
23982 begin rule_save:=overfull_rule;
23983 overfull_rule:=0; {prevent rule from being packaged}
23984 p:=hpack(preamble,saved(1),saved(0)); overfull_rule:=rule_save;
23985 end
23986 else begin q:=link(preamble);
23987 repeat height(q):=width(q); width(q):=0; q:=link(link(q));
23988 until q=null;
23989 p:=vpack(preamble,saved(1),saved(0));
23990 q:=link(preamble);
23991 repeat width(q):=height(q); height(q):=0; q:=link(link(q));
23992 until q=null;
23993 end;
23994 pack_begin_line:=0
23995
23996 @ @<Set the glue in all the unset...@>=
23997 q:=link(head); s:=head;
23998 while q<>null do
23999 begin if not is_char_node(q) then
24000 if type(q)=unset_node then
24001 @<Set the unset box |q| and the unset boxes in it@>
24002 else if type(q)=rule_node then
24003 @<Make the running dimensions in rule |q| extend to the
24004 boundaries of the alignment@>;
24005 s:=q; q:=link(q);
24006 end
24007
24008 @ @<Make the running dimensions in rule |q| extend...@>=
24009 begin if is_running(width(q)) then width(q):=width(p);
24010 if is_running(height(q)) then height(q):=height(p);
24011 if is_running(depth(q)) then depth(q):=depth(p);
24012 if o<>0 then
24013 begin r:=link(q); link(q):=null; q:=hpack(q,natural);
24014 shift_amount(q):=o; link(q):=r; link(s):=q;
24015 end;
24016 end
24017
24018 @ The unset box |q| represents a row that contains one or more unset boxes,
24019 depending on how soon \.{\\cr} occurred in that row.
24020
24021 @<Set the unset box |q| and the unset boxes in it@>=
24022 begin if mode=-vmode then
24023 begin type(q):=hlist_node; width(q):=width(p);
24024 if nest[nest_ptr-1].mode_field=mmode then set_box_lr(q)(dlist); {for |ship_out|}
24025 end
24026 else begin type(q):=vlist_node; height(q):=height(p);
24027 end;
24028 glue_order(q):=glue_order(p); glue_sign(q):=glue_sign(p);
24029 glue_set(q):=glue_set(p); shift_amount(q):=o;
24030 r:=link(list_ptr(q)); s:=link(list_ptr(p));
24031 repeat @<Set the glue in node |r| and change it from an unset node@>;
24032 r:=link(link(r)); s:=link(link(s));
24033 until r=null;
24034 end
24035
24036 @ A box made from spanned columns will be followed by tabskip glue nodes and
24037 by empty boxes as if there were no spanning. This permits perfect alignment
24038 of subsequent entries, and it prevents values that depend on floating point
24039 arithmetic from entering into the dimensions of any boxes.
24040
24041 @<Set the glue in node |r|...@>=
24042 n:=span_count(r); t:=width(s); w:=t; u:=hold_head;
24043 set_box_lr(r)(0); {for |ship_out|}
24044 while n>min_quarterword do
24045 begin decr(n);
24046 @<Append tabskip glue and an empty box to list |u|,
24047 and update |s| and |t| as the prototype nodes are passed@>;
24048 end;
24049 if mode=-vmode then
24050 @<Make the unset node |r| into an |hlist_node| of width |w|,
24051 setting the glue as if the width were |t|@>
24052 else @<Make the unset node |r| into a |vlist_node| of height |w|,
24053 setting the glue as if the height were |t|@>;
24054 shift_amount(r):=0;
24055 if u<>hold_head then {append blank boxes to account for spanned nodes}
24056 begin link(u):=link(r); link(r):=link(hold_head); r:=u;
24057 end
24058
24059 @ @<Append tabskip glue and an empty box to list |u|...@>=
24060 s:=link(s); v:=glue_ptr(s); link(u):=new_glue(v); u:=link(u);
24061 subtype(u):=tab_skip_code+1; t:=t+width(v);
24062 if glue_sign(p)=stretching then
24063 begin if stretch_order(v)=glue_order(p) then
24064 t:=t+round(float(glue_set(p))*stretch(v));
24065 @^real multiplication@>
24066 end
24067 else if glue_sign(p)=shrinking then
24068 begin if shrink_order(v)=glue_order(p) then
24069 t:=t-round(float(glue_set(p))*shrink(v));
24070 end;
24071 s:=link(s); link(u):=new_null_box; u:=link(u); t:=t+width(s);
24072 if mode=-vmode then width(u):=width(s)@+else
24073 begin type(u):=vlist_node; height(u):=width(s);
24074 end
24075
24076 @ @<Make the unset node |r| into an |hlist_node| of width |w|...@>=
24077 begin height(r):=height(q); depth(r):=depth(q);
24078 if t=width(r) then
24079 begin glue_sign(r):=normal; glue_order(r):=normal;
24080 set_glue_ratio_zero(glue_set(r));
24081 end
24082 else if t>width(r) then
24083 begin glue_sign(r):=stretching;
24084 if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
24085 else glue_set(r):=unfloat((t-width(r))/glue_stretch(r));
24086 @^real division@>
24087 end
24088 else begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
24089 if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
24090 else if (glue_order(r)=normal)and(width(r)-t>glue_shrink(r)) then
24091 set_glue_ratio_one(glue_set(r))
24092 else glue_set(r):=unfloat((width(r)-t)/glue_shrink(r));
24093 end;
24094 width(r):=w; type(r):=hlist_node;
24095 end
24096
24097 @ @<Make the unset node |r| into a |vlist_node| of height |w|...@>=
24098 begin width(r):=width(q);
24099 if t=height(r) then
24100 begin glue_sign(r):=normal; glue_order(r):=normal;
24101 set_glue_ratio_zero(glue_set(r));
24102 end
24103 else if t>height(r) then
24104 begin glue_sign(r):=stretching;
24105 if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
24106 else glue_set(r):=unfloat((t-height(r))/glue_stretch(r));
24107 @^real division@>
24108 end
24109 else begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
24110 if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
24111 else if (glue_order(r)=normal)and(height(r)-t>glue_shrink(r)) then
24112 set_glue_ratio_one(glue_set(r))
24113 else glue_set(r):=unfloat((height(r)-t)/glue_shrink(r));
24114 end;
24115 height(r):=w; type(r):=vlist_node;
24116 end
24117
24118 @ We now have a completed alignment, in the list that starts at |head|
24119 and ends at |tail|. This list will be merged with the one that encloses
24120 it. (In case the enclosing mode is |mmode|, for displayed formulas,
24121 we will need to insert glue before and after the display; that part of the
24122 program will be deferred until we're more familiar with such operations.)
24123
24124 In restricted horizontal mode, the |clang| part of |aux| is undefined;
24125 an over-cautious \PASCAL\ runtime system may complain about this.
24126 @^dirty \PASCAL@>
24127
24128 @<Insert the \(c)current list into its environment@>=
24129 aux_save:=aux; p:=link(head); q:=tail; pop_nest;
24130 if mode=mmode then @<Finish an alignment in a display@>
24131 else begin aux:=aux_save; link(tail):=p;
24132 if p<>null then tail:=q;
24133 if mode=vmode then build_page;
24134 end
24135
24136 @* \[38] Breaking paragraphs into lines.
24137 We come now to what is probably the most interesting algorithm of \TeX:
24138 the mechanism for choosing the ``best possible'' breakpoints that yield
24139 the individual lines of a paragraph. \TeX's line-breaking algorithm takes
24140 a given horizontal list and converts it to a sequence of boxes that are
24141 appended to the current vertical list. In the course of doing this, it
24142 creates a special data structure containing three kinds of records that are
24143 not used elsewhere in \TeX. Such nodes are created while a paragraph is
24144 being processed, and they are destroyed afterwards; thus, the other parts
24145 of \TeX\ do not need to know anything about how line-breaking is done.
24146
24147 The method used here is based on an approach devised by Michael F. Plass and
24148 @^Plass, Michael Frederick@>
24149 @^Knuth, Donald Ervin@>
24150 the author in 1977, subsequently generalized and improved by the same two
24151 people in 1980. A detailed discussion appears in {\sl Software---Practice
24152 and Experience \bf11} (1981), 1119--1184, where it is shown that the
24153 line-breaking problem can be regarded as a special case of the problem of
24154 computing the shortest path in an acyclic network. The cited paper includes
24155 numerous examples and describes the history of line breaking as it has been
24156 practiced by printers through the ages. The present implementation adds two
24157 new ideas to the algorithm of 1980: Memory space requirements are considerably
24158 reduced by using smaller records for inactive nodes than for active ones,
24159 and arithmetic overflow is avoided by using ``delta distances'' instead of
24160 keeping track of the total distance from the beginning of the paragraph to the
24161 current point.
24162
24163 @ The |line_break| procedure should be invoked only in horizontal mode; it
24164 leaves that mode and places its output into the current vlist of the
24165 enclosing vertical mode (or internal vertical mode).
24166 There is one explicit parameter: |d| is true for partial paragraphs
24167 preceding display math mode; in this case the amount of additional
24168 penalty inserted before the final line is |display_widow_penalty|
24169 instead of |widow_penalty|.
24170
24171 There are also a number of implicit parameters: The hlist to be broken
24172 starts at |link(head)|, and it is nonempty. The value of |prev_graf| in the
24173 enclosing semantic level tells where the paragraph should begin in the
24174 sequence of line numbers, in case hanging indentation or \.{\\parshape}
24175 is in use; |prev_graf| is zero unless this paragraph is being continued
24176 after a displayed formula. Other implicit parameters, such as the
24177 |par_shape_ptr| and various penalties to use for hyphenation, etc., appear
24178 in |eqtb|.
24179
24180 After |line_break| has acted, it will have updated the current vlist and the
24181 value of |prev_graf|. Furthermore, the global variable |just_box| will
24182 point to the final box created by |line_break|, so that the width of this
24183 line can be ascertained when it is necessary to decide whether to use
24184 |above_display_skip| or |above_display_short_skip| before a displayed formula.
24185
24186 @<Glob...@>=
24187 @!just_box:pointer; {the |hlist_node| for the last line of the new paragraph}
24188
24189 @ Since |line_break| is a rather lengthy procedure---sort of a small world unto
24190 itself---we must build it up little by little, somewhat more cautiously
24191 than we have done with the simpler procedures of \TeX. Here is the
24192 general outline.
24193
24194 @p@t\4@>@<Declare subprocedures for |line_break|@>
24195 procedure line_break(@!d:boolean);
24196 label done,done1,done2,done3,done4,done5,continue;
24197 var @<Local variables for line breaking@>@;
24198 begin pack_begin_line:=mode_line; {this is for over/underfull box messages}
24199 @<Get ready to start line breaking@>;
24200 @<Find optimal breakpoints@>;
24201 @<Break the paragraph at the chosen breakpoints, justify the resulting lines
24202 to the correct widths, and append them to the current vertical list@>;
24203 @<Clean up the memory by removing the break nodes@>;
24204 pack_begin_line:=0;
24205 end;
24206 @#
24207 @t\4@>@<Declare \eTeX\ procedures for use by |main_control|@>
24208
24209 @ The first task is to move the list from |head| to |temp_head| and go
24210 into the enclosing semantic level. We also append the \.{\\parfillskip}
24211 glue to the end of the paragraph, removing a space (or other glue node) if
24212 it was there, since spaces usually precede blank lines and instances of
24213 `\.{\$\$}'. The |par_fill_skip| is preceded by an infinite penalty, so
24214 it will never be considered as a potential breakpoint.
24215
24216 This code assumes that a |glue_node| and a |penalty_node| occupy the
24217 same number of |mem|~words.
24218 @^data structure assumptions@>
24219
24220 @<Get ready to start...@>=
24221 link(temp_head):=link(head);
24222 if is_char_node(tail) then tail_append(new_penalty(inf_penalty))
24223 else if type(tail)<>glue_node then tail_append(new_penalty(inf_penalty))
24224 else begin type(tail):=penalty_node; delete_glue_ref(glue_ptr(tail));
24225 flush_node_list(leader_ptr(tail)); penalty(tail):=inf_penalty;
24226 end;
24227 link(tail):=new_param_glue(par_fill_skip_code);
24228 last_line_fill:=link(tail);
24229 init_cur_lang:=prev_graf mod @'200000;
24230 init_l_hyf:=prev_graf div @'20000000;
24231 init_r_hyf:=(prev_graf div @'200000) mod @'100;
24232 pop_nest;
24233
24234 @ When looking for optimal line breaks, \TeX\ creates a ``break node'' for
24235 each break that is {\sl feasible}, in the sense that there is a way to end
24236 a line at the given place without requiring any line to stretch more than
24237 a given tolerance. A break node is characterized by three things: the position
24238 of the break (which is a pointer to a |glue_node|, |math_node|, |penalty_node|,
24239 or |disc_node|); the ordinal number of the line that will follow this
24240 breakpoint; and the fitness classification of the line that has just
24241 ended, i.e., |tight_fit|, |decent_fit|, |loose_fit|, or |very_loose_fit|.
24242
24243 @d tight_fit=3 {fitness classification for lines shrinking 0.5 to 1.0 of their
24244 shrinkability}
24245 @d loose_fit=1 {fitness classification for lines stretching 0.5 to 1.0 of their
24246 stretchability}
24247 @d very_loose_fit=0 {fitness classification for lines stretching more than
24248 their stretchability}
24249 @d decent_fit=2 {fitness classification for all other lines}
24250
24251 @ The algorithm essentially determines the best possible way to achieve
24252 each feasible combination of position, line, and fitness. Thus, it answers
24253 questions like, ``What is the best way to break the opening part of the
24254 paragraph so that the fourth line is a tight line ending at such-and-such
24255 a place?'' However, the fact that all lines are to be the same length
24256 after a certain point makes it possible to regard all sufficiently large
24257 line numbers as equivalent, when the looseness parameter is zero, and this
24258 makes it possible for the algorithm to save space and time.
24259
24260 An ``active node'' and a ``passive node'' are created in |mem| for each
24261 feasible breakpoint that needs to be considered. Active nodes are three
24262 words long and passive nodes are two words long. We need active nodes only
24263 for breakpoints near the place in the paragraph that is currently being
24264 examined, so they are recycled within a comparatively short time after
24265 they are created.
24266
24267 @ An active node for a given breakpoint contains six fields:
24268
24269 \yskip\hang|link| points to the next node in the list of active nodes; the
24270 last active node has |link=last_active|.
24271
24272 \yskip\hang|break_node| points to the passive node associated with this
24273 breakpoint.
24274
24275 \yskip\hang|line_number| is the number of the line that follows this
24276 breakpoint.
24277
24278 \yskip\hang|fitness| is the fitness classification of the line ending at this
24279 breakpoint.
24280
24281 \yskip\hang|type| is either |hyphenated| or |unhyphenated|, depending on
24282 whether this breakpoint is a |disc_node|.
24283
24284 \yskip\hang|total_demerits| is the minimum possible sum of demerits over all
24285 lines leading from the beginning of the paragraph to this breakpoint.
24286
24287 \yskip\noindent
24288 The value of |link(active)| points to the first active node on a linked list
24289 of all currently active nodes. This list is in order by |line_number|,
24290 except that nodes with |line_number>easy_line| may be in any order relative
24291 to each other.
24292
24293 @d active_node_size_normal=3 {number of words in normal active nodes}
24294 @d fitness==subtype {|very_loose_fit..tight_fit| on final line for this break}
24295 @d break_node==rlink {pointer to the corresponding passive node}
24296 @d line_number==llink {line that begins at this breakpoint}
24297 @d total_demerits(#)==mem[#+2].int {the quantity that \TeX\ minimizes}
24298 @d unhyphenated=0 {the |type| of a normal active break node}
24299 @d hyphenated=1 {the |type| of an active node that breaks at a |disc_node|}
24300 @d last_active==active {the active list ends where it begins}
24301
24302 @ @<Initialize the special list heads...@>=
24303 type(last_active):=hyphenated; line_number(last_active):=max_halfword;
24304 subtype(last_active):=0; {the |subtype| is never examined by the algorithm}
24305
24306 @ The passive node for a given breakpoint contains only four fields:
24307
24308 \yskip\hang|link| points to the passive node created just before this one,
24309 if any, otherwise it is |null|.
24310
24311 \yskip\hang|cur_break| points to the position of this breakpoint in the
24312 horizontal list for the paragraph being broken.
24313
24314 \yskip\hang|prev_break| points to the passive node that should precede this
24315 one in an optimal path to this breakpoint.
24316
24317 \yskip\hang|serial| is equal to |n| if this passive node is the |n|th
24318 one created during the current pass. (This field is used only when
24319 printing out detailed statistics about the line-breaking calculations.)
24320
24321 \yskip\noindent
24322 There is a global variable called |passive| that points to the most
24323 recently created passive node. Another global variable, |printed_node|,
24324 is used to help print out the paragraph when detailed information about
24325 the line-breaking computation is being displayed.
24326
24327 @d passive_node_size=2 {number of words in passive nodes}
24328 @d cur_break==rlink {in passive node, points to position of this breakpoint}
24329 @d prev_break==llink {points to passive node that should precede this one}
24330 @d serial==info {serial number for symbolic identification}
24331
24332 @<Glob...@>=
24333 @!passive:pointer; {most recent node on passive list}
24334 @!printed_node:pointer; {most recent node that has been printed}
24335 @!pass_number:halfword; {the number of passive nodes allocated on this pass}
24336
24337 @ The active list also contains ``delta'' nodes that help the algorithm
24338 compute the badness of individual lines. Such nodes appear only between two
24339 active nodes, and they have |type=delta_node|. If |p| and |r| are active nodes
24340 and if |q| is a delta node between them, so that |link(p)=q| and |link(q)=r|,
24341 then |q| tells the space difference between lines in the horizontal list that
24342 start after breakpoint |p| and lines that start after breakpoint |r|. In
24343 other words, if we know the length of the line that starts after |p| and
24344 ends at our current position, then the corresponding length of the line that
24345 starts after |r| is obtained by adding the amounts in node~|q|. A delta node
24346 contains six scaled numbers, since it must record the net change in glue
24347 stretchability with respect to all orders of infinity. The natural width
24348 difference appears in |mem[q+1].sc|; the stretch differences in units of
24349 pt, fil, fill, and filll appear in |mem[q+2..q+5].sc|; and the shrink difference
24350 appears in |mem[q+6].sc|. The |subtype| field of a delta node is not used.
24351
24352 @d delta_node_size=9 {number of words in a delta node}
24353 @d delta_node=2 {|type| field in a delta node}
24354
24355 @ As the algorithm runs, it maintains a set of six delta-like registers
24356 for the length of the line following the first active breakpoint to the
24357 current position in the given hlist. When it makes a pass through the
24358 active list, it also maintains a similar set of six registers for the
24359 length following the active breakpoint of current interest. A third set
24360 holds the length of an empty line (namely, the sum of \.{\\leftskip} and
24361 \.{\\rightskip}); and a fourth set is used to create new delta nodes.
24362
24363 When we pass a delta node we want to do operations like
24364 $$\hbox{\ignorespaces|for
24365 k:=1 to 6 do cur_active_width[k]:=cur_active_width[k]+mem[q+k].sc|};$$ and we
24366 want to do this without the overhead of |for| loops. The |do_all_six|
24367 macro makes such six-tuples convenient.
24368
24369 @d do_all_six(#)==#(1);#(2);#(3);#(4);#(5);#(6)
24370
24371 @d do_seven_eight(#) == if pdf_adjust_spacing > 1 then begin #(7);#(8); end
24372 @d do_all_eight(#) == do_all_six(#); do_seven_eight(#)
24373 @d do_one_seven_eight(#) == #(1); do_seven_eight(#)
24374
24375 @d total_font_stretch == cur_active_width[7]
24376 @d total_font_shrink == cur_active_width[8]
24377
24378 @d save_active_width(#) == prev_active_width[#] := active_width[#]
24379 @d restore_active_width(#) == active_width[#] := prev_active_width[#]
24380
24381 @<Glob...@>=
24382 @!active_width:array[1..8] of scaled;
24383 {distance from first active node to~|cur_p|}
24384 @!cur_active_width:array[1..8] of scaled; {distance from current active node}
24385 @!background:array[1..8] of scaled; {length of an ``empty'' line}
24386 @!break_width:array[1..8] of scaled; {length being computed after current break}
24387 @#
24388 @!auto_breaking: boolean; {make |auto_breaking| accessible out of |line_break|}
24389 @!prev_p: pointer; {make |prev_p| accessible out of |line_break|}
24390 @!first_p: pointer; {to access the first node of the paragraph}
24391 @!prev_char_p: pointer; {pointer to the previous char of an implicit kern}
24392 @!next_char_p: pointer; {pointer to the next char of an implicit kern}
24393 @#
24394 @!try_prev_break: boolean; {force break at the previous legal breakpoint?}
24395 @!prev_legal: pointer; {the previous legal breakpoint}
24396 @!prev_prev_legal: pointer; {to save |prev_p| corresponding to |prev_legal|}
24397 @!prev_auto_breaking: boolean; {to save |auto_breaking| corresponding to |prev_legal|}
24398 @!prev_active_width: array[1..8] of scaled; {to save |active_width| corresponding to |prev_legal|}
24399 @!rejected_cur_p: pointer; {the last |cur_p| that has been rejected}
24400 @!before_rejected_cur_p: boolean; {|cur_p| is still before |rejected_cur_p|?}
24401 @#
24402 @!max_stretch_ratio: integer; {maximal stretch ratio of expanded fonts}
24403 @!max_shrink_ratio: integer; {maximal shrink ratio of expanded fonts}
24404 @!cur_font_step: integer; {the current step of expanded fonts}
24405
24406 @ Let's state the principles of the delta nodes more precisely and concisely,
24407 so that the following programs will be less obscure. For each legal
24408 breakpoint~|p| in the paragraph, we define two quantities $\alpha(p)$ and
24409 $\beta(p)$ such that the length of material in a line from breakpoint~|p|
24410 to breakpoint~|q| is $\gamma+\beta(q)-\alpha(p)$, for some fixed $\gamma$.
24411 Intuitively, $\alpha(p)$ and $\beta(q)$ are the total length of material from
24412 the beginning of the paragraph to a point ``after'' a break at |p| and to a
24413 point ``before'' a break at |q|; and $\gamma$ is the width of an empty line,
24414 namely the length contributed by \.{\\leftskip} and \.{\\rightskip}.
24415
24416 Suppose, for example, that the paragraph consists entirely of alternating
24417 boxes and glue skips; let the boxes have widths $x_1\ldots x_n$ and
24418 let the skips have widths $y_1\ldots y_n$, so that the paragraph can be
24419 represented by $x_1y_1\ldots x_ny_n$. Let $p_i$ be the legal breakpoint
24420 at $y_i$; then $\alpha(p_i)=x_1+y_1+\cdots+x_i+y_i$, and $\beta(p_i)=
24421 x_1+y_1+\cdots+x_i$. To check this, note that the length of material from
24422 $p_2$ to $p_5$, say, is $\gamma+x_3+y_3+x_4+y_4+x_5=\gamma+\beta(p_5)
24423 -\alpha(p_2)$.
24424
24425 The quantities $\alpha$, $\beta$, $\gamma$ involve glue stretchability and
24426 shrinkability as well as a natural width. If we were to compute $\alpha(p)$
24427 and $\beta(p)$ for each |p|, we would need multiple precision arithmetic, and
24428 the multiprecise numbers would have to be kept in the active nodes.
24429 \TeX\ avoids this problem by working entirely with relative differences
24430 or ``deltas.'' Suppose, for example, that the active list contains
24431 $a_1\,\delta_1\,a_2\,\delta_2\,a_3$, where the |a|'s are active breakpoints
24432 and the $\delta$'s are delta nodes. Then $\delta_1=\alpha(a_1)-\alpha(a_2)$
24433 and $\delta_2=\alpha(a_2)-\alpha(a_3)$. If the line breaking algorithm is
24434 currently positioned at some other breakpoint |p|, the |active_width| array
24435 contains the value $\gamma+\beta(p)-\alpha(a_1)$. If we are scanning through
24436 the list of active nodes and considering a tentative line that runs from
24437 $a_2$ to~|p|, say, the |cur_active_width| array will contain the value
24438 $\gamma+\beta(p)-\alpha(a_2)$. Thus, when we move from $a_2$ to $a_3$,
24439 we want to add $\alpha(a_2)-\alpha(a_3)$ to |cur_active_width|; and this
24440 is just $\delta_2$, which appears in the active list between $a_2$ and
24441 $a_3$. The |background| array contains $\gamma$. The |break_width| array
24442 will be used to calculate values of new delta nodes when the active
24443 list is being updated.
24444
24445 @ Glue nodes in a horizontal list that is being paragraphed are not supposed to
24446 include ``infinite'' shrinkability; that is why the algorithm maintains
24447 four registers for stretching but only one for shrinking. If the user tries to
24448 introduce infinite shrinkability, the shrinkability will be reset to finite
24449 and an error message will be issued. A boolean variable |no_shrink_error_yet|
24450 prevents this error message from appearing more than once per paragraph.
24451
24452 @d check_shrinkage(#)==if (shrink_order(#)<>normal)and(shrink(#)<>0) then
24453 begin #:=finite_shrink(#);
24454 end
24455
24456 @<Glob...@>=
24457 @!no_shrink_error_yet:boolean; {have we complained about infinite shrinkage?}
24458
24459 @ @<Declare subprocedures for |line_break|@>=
24460 function finite_shrink(@!p:pointer):pointer; {recovers from infinite shrinkage}
24461 var q:pointer; {new glue specification}
24462 begin if no_shrink_error_yet then
24463 begin no_shrink_error_yet:=false;
24464 @!stat if tracing_paragraphs>0 then end_diagnostic(true);@+tats@;
24465 print_err("Infinite glue shrinkage found in a paragraph");
24466 @.Infinite glue shrinkage...@>
24467 help5("The paragraph just ended includes some glue that has")@/
24468 ("infinite shrinkability, e.g., `\hskip 0pt minus 1fil'.")@/
24469 ("Such glue doesn't belong there---it allows a paragraph")@/
24470 ("of any length to fit on one line. But it's safe to proceed,")@/
24471 ("since the offensive shrinkability has been made finite.");
24472 error;
24473 @!stat if tracing_paragraphs>0 then begin_diagnostic;@+tats@;
24474 end;
24475 q:=new_spec(p); shrink_order(q):=normal;
24476 delete_glue_ref(p); finite_shrink:=q;
24477 end;
24478
24479 @ @<Get ready to start...@>=
24480 no_shrink_error_yet:=true;@/
24481 check_shrinkage(left_skip); check_shrinkage(right_skip);@/
24482 q:=left_skip; r:=right_skip; background[1]:=width(q)+width(r);@/
24483 background[2]:=0; background[3]:=0; background[4]:=0; background[5]:=0;@/
24484 background[2+stretch_order(q)]:=stretch(q);@/
24485 background[2+stretch_order(r)]:=@|background[2+stretch_order(r)]+stretch(r);@/
24486 background[6]:=shrink(q)+shrink(r);
24487 if pdf_adjust_spacing > 1 then begin
24488 background[7] := 0;
24489 background[8] := 0;
24490 max_stretch_ratio := -1;
24491 max_shrink_ratio := -1;
24492 cur_font_step := -1;
24493 prev_char_p := null;
24494 end;
24495 @<Check for special treatment of last line of paragraph@>;
24496
24497 @ A pointer variable |cur_p| runs through the given horizontal list as we look
24498 for breakpoints. This variable is global, since it is used both by |line_break|
24499 and by its subprocedure |try_break|.
24500
24501 Another global variable called |threshold| is used to determine the feasibility
24502 of individual lines: Breakpoints are feasible if there is a way to reach
24503 them without creating lines whose badness exceeds |threshold|. (The
24504 badness is compared to |threshold| before penalties are added, so that
24505 penalty values do not affect the feasibility of breakpoints, except that
24506 no break is allowed when the penalty is 10000 or more.) If |threshold|
24507 is 10000 or more, all legal breaks are considered feasible, since the
24508 |badness| function specified above never returns a value greater than~10000.
24509
24510 Up to three passes might be made through the paragraph in an attempt to find at
24511 least one set of feasible breakpoints. On the first pass, we have
24512 |threshold=pretolerance| and |second_pass=final_pass=false|.
24513 If this pass fails to find a
24514 feasible solution, |threshold| is set to |tolerance|, |second_pass| is set
24515 |true|, and an attempt is made to hyphenate as many words as possible.
24516 If that fails too, we add |emergency_stretch| to the background
24517 stretchability and set |final_pass=true|.
24518
24519 @<Glob...@>=
24520 @!cur_p:pointer; {the current breakpoint under consideration}
24521 @!second_pass:boolean; {is this our second attempt to break this paragraph?}
24522 @!final_pass:boolean; {is this our final attempt to break this paragraph?}
24523 @!threshold:integer; {maximum badness on feasible lines}
24524
24525 @ The heart of the line-breaking procedure is `|try_break|', a subroutine
24526 that tests if the current breakpoint |cur_p| is feasible, by running
24527 through the active list to see what lines of text can be made from active
24528 nodes to~|cur_p|. If feasible breaks are possible, new break nodes are
24529 created. If |cur_p| is too far from an active node, that node is
24530 deactivated.
24531
24532 The parameter |pi| to |try_break| is the penalty associated
24533 with a break at |cur_p|; we have |pi=eject_penalty| if the break is forced,
24534 and |pi=inf_penalty| if the break is illegal.
24535
24536 The other parameter, |break_type|, is set to |hyphenated| or |unhyphenated|,
24537 depending on whether or not the current break is at a |disc_node|. The
24538 end of a paragraph is also regarded as `|hyphenated|'; this case is
24539 distinguishable by the condition |cur_p=null|.
24540
24541 @d copy_to_cur_active(#)==cur_active_width[#]:=active_width[#]
24542 @d deactivate=60 {go here when node |r| should be deactivated}
24543
24544 @d cp_skipable(#) == {skipable nodes at the margins during character protrusion}
24545 (
24546 not is_char_node(#) and
24547 (
24548 (type(#) = ins_node)
24549 or (type(#) = mark_node)
24550 or (type(#) = adjust_node)
24551 or (type(#) = penalty_node)
24552 or ((type(#) = whatsit_node) and
24553 (subtype(#) <> pdf_refximage_node) and
24554 (subtype(#) <> pdf_refxform_node)) {reference to an image or XObject form}
24555 or ((type(#) = disc_node) and
24556 (pre_break(#) = null) and
24557 (post_break(#) = null) and
24558 (replace_count(#) = 0)) {an empty |disc_node|}
24559 or ((type(#) = math_node) and (width(#) = 0))
24560 or ((type(#) = kern_node) and
24561 ((width(#) = 0) or (subtype(#) = normal)
24562 or (subtype(#) = auto_kern)))
24563 or ((type(#) = glue_node) and (glue_ptr(#) = zero_glue))
24564 or ((type(#) = hlist_node) and (width(#) = 0) and (height(#) = 0) and
24565 (depth(#) = 0) and (list_ptr(#) = null))
24566 )
24567 )
24568
24569
24570 @<Declare subprocedures for |line_break|@>=
24571 procedure push_node(p: pointer);
24572 begin
24573 if hlist_stack_level > max_hlist_stack then
24574 pdf_error("push_node", "stack overflow");
24575 hlist_stack[hlist_stack_level] := p;
24576 hlist_stack_level := hlist_stack_level + 1;
24577 end;
24578
24579 function pop_node: pointer;
24580 begin
24581 hlist_stack_level := hlist_stack_level - 1;
24582 if hlist_stack_level < 0 then {would point to some bug}
24583 pdf_error("pop_node", "stack underflow (internal error)");
24584 pop_node := hlist_stack[hlist_stack_level];
24585 end;
24586
24587 function find_protchar_left(l: pointer; d: boolean): pointer;
24588 {searches left to right from list head |l|, returns 1st non-skipable item}
24589 var t: pointer;
24590 run: boolean;
24591 begin
24592 if (link(l) <> null) and (type(l) = hlist_node) and (width(l) = 0)
24593 and (height(l) = 0) and (depth(l) = 0) and (list_ptr(l) = null) then
24594 l := link(l) {for paragraph start with \.{\\parindent = 0pt}}
24595 else if d then
24596 while (link(l) <> null) and (not (is_char_node(l) or non_discardable(l))) do
24597 l := link(l); {std.\ discardables at line break, \TeX book, p 95}
24598 hlist_stack_level := 0;
24599 run := true;
24600 repeat
24601 t := l;
24602 while run and (type(l) = hlist_node) and (list_ptr(l) <> null) do begin
24603 push_node(l);
24604 l := list_ptr(l);
24605 end;
24606 while run and cp_skipable(l) do begin
24607 while (link(l) = null) and (hlist_stack_level > 0) do begin
24608 l := pop_node; {don't visit this node again}
24609 end;
24610 if link(l) <> null then
24611 l := link(l)
24612 else if hlist_stack_level = 0 then run := false
24613 end;
24614 until t = l;
24615 find_protchar_left := l;
24616 end;
24617
24618 function find_protchar_right(l, r: pointer): pointer;
24619 {searches right to left from list tail |r| to head |l|, returns 1st non-skipable item}
24620 var t: pointer;
24621 run: boolean;
24622 begin
24623 find_protchar_right := null;
24624 if r = null then return;
24625 hlist_stack_level := 0;
24626 run := true;
24627 repeat
24628 t := r;
24629 while run and (type(r) = hlist_node) and (list_ptr(r) <> null) do begin
24630 push_node(l);
24631 push_node(r);
24632 l := list_ptr(r);
24633 r := l;
24634 while link(r) <> null do
24635 r := link(r);
24636 end;
24637 while run and cp_skipable(r) do begin
24638 while (r = l) and (hlist_stack_level > 0) do begin
24639 r := pop_node; {don't visit this node again}
24640 l := pop_node;
24641 end;
24642 if (r <> l) and (r <> null) then
24643 r := prev_rightmost(l, r)
24644 else if (r = l) and (hlist_stack_level = 0) then run := false
24645 end;
24646 until t = r;
24647 find_protchar_right := r;
24648 end;
24649
24650 function total_pw(q, p: pointer): scaled;
24651 {returns the total width of character protrusion of a line;
24652 |cur_break(break_node(q))| and |p| is the leftmost resp. rightmost node in the
24653 horizontal list representing the actual line}
24654 var l, r: pointer;
24655 n: integer;
24656 begin
24657 if break_node(q) = null then
24658 l := first_p
24659 else
24660 l := cur_break(break_node(q));
24661 r := prev_rightmost(prev_p, p); {get |link(r)=p|}
24662 {let's look at the right margin first}
24663 @{
24664 short_display_n(r, 2);
24665 print("&");
24666 short_display_n(p, 2);
24667 print_ln;
24668 @}
24669 if (p <> null) and (type(p) = disc_node) and (pre_break(p) <> null) then
24670 {a |disc_node| with non-empty |pre_break|, protrude the last char of |pre_break|}
24671 begin
24672 r := pre_break(p);
24673 while link(r) <> null do
24674 r := link(r);
24675 end else r := find_protchar_right(l, r);
24676 {now the left margin}
24677 @{
24678 short_display_n(l, 2);
24679 print_ln;
24680 breadth_max := 10;
24681 depth_threshold := 2;
24682 show_node_list(l);
24683 print_ln;
24684 @}
24685 if (l <> null) and (type(l) = disc_node) then begin
24686 if post_break(l) <> null then begin
24687 l := post_break(l); {protrude the first char}
24688 goto done;
24689 end else {discard |replace_count(l)| nodes}
24690 begin
24691 n := replace_count(l);
24692 l := link(l);
24693 while n > 0 do begin
24694 if link(l) <> null then
24695 l := link(l);
24696 decr(n);
24697 end;
24698 end;
24699 end;
24700 l := find_protchar_left(l, true);
24701 done:
24702 total_pw := left_pw(l) + right_pw(r);
24703 end;
24704
24705 procedure try_break(@!pi:integer;@!break_type:small_number);
24706 label exit,done,done1,continue,deactivate,found,not_found;
24707 var r:pointer; {runs through the active list}
24708 @!margin_kern_stretch: scaled;
24709 @!margin_kern_shrink: scaled;
24710 @!lp, rp, cp: pointer;
24711 @!prev_r:pointer; {stays a step behind |r|}
24712 @!old_l:halfword; {maximum line number in current equivalence class of lines}
24713 @!no_break_yet:boolean; {have we found a feasible break at |cur_p|?}
24714 @<Other local variables for |try_break|@>@;
24715 begin @<Make sure that |pi| is in the proper range@>;
24716 no_break_yet:=true; prev_r:=active; old_l:=0;
24717 do_all_eight(copy_to_cur_active);
24718 loop@+ begin continue: r:=link(prev_r);
24719 @<If node |r| is of type |delta_node|, update |cur_active_width|,
24720 set |prev_r| and |prev_prev_r|, then |goto continue|@>;
24721 @<If a line number class has ended, create new active nodes for
24722 the best feasible breaks in that class; then |return|
24723 if |r=last_active|, otherwise compute the new |line_width|@>;
24724 @<Consider the demerits for a line from |r| to |cur_p|;
24725 deactivate node |r| if it should no longer be active;
24726 then |goto continue| if a line from |r| to |cur_p| is infeasible,
24727 otherwise record a new feasible break@>;
24728 end;
24729 exit: @!stat @<Update the value of |printed_node| for
24730 symbolic displays@>@+tats@;
24731 end;
24732
24733 @ @<Other local variables for |try_break|@>=
24734 @!prev_prev_r:pointer; {a step behind |prev_r|, if |type(prev_r)=delta_node|}
24735 @!s:pointer; {runs through nodes ahead of |cur_p|}
24736 @!q:pointer; {points to a new node being created}
24737 @!v:pointer; {points to a glue specification or a node ahead of |cur_p|}
24738 @!t:integer; {node count, if |cur_p| is a discretionary node}
24739 @!f:internal_font_number; {used in character width calculation}
24740 @!l:halfword; {line number of current active node}
24741 @!node_r_stays_active:boolean; {should node |r| remain in the active list?}
24742 @!line_width:scaled; {the current line will be justified to this width}
24743 @!fit_class:very_loose_fit..tight_fit; {possible fitness class of test line}
24744 @!b:halfword; {badness of test line}
24745 @!d:integer; {demerits of test line}
24746 @!artificial_demerits:boolean; {has |d| been forced to zero?}
24747 @!save_link:pointer; {temporarily holds value of |link(cur_p)|}
24748 @!shortfall:scaled; {used in badness calculations}
24749
24750 @ @<Make sure that |pi| is in the proper range@>=
24751 if abs(pi)>=inf_penalty then
24752 if pi>0 then return {this breakpoint is inhibited by infinite penalty}
24753 else pi:=eject_penalty {this breakpoint will be forced}
24754
24755 @ The following code uses the fact that |type(last_active)<>delta_node|.
24756
24757 @d update_width(#)==@|
24758 cur_active_width[#]:=cur_active_width[#]+mem[r+#].sc
24759
24760 @<If node |r|...@>=
24761 @^inner loop@>
24762 if type(r)=delta_node then
24763 begin do_all_eight(update_width);
24764 prev_prev_r:=prev_r; prev_r:=r; goto continue;
24765 end
24766
24767 @ As we consider various ways to end a line at |cur_p|, in a given line number
24768 class, we keep track of the best total demerits known, in an array with
24769 one entry for each of the fitness classifications. For example,
24770 |minimal_demerits[tight_fit]| contains the fewest total demerits of feasible
24771 line breaks ending at |cur_p| with a |tight_fit| line; |best_place[tight_fit]|
24772 points to the passive node for the break before~|cur_p| that achieves such
24773 an optimum; and |best_pl_line[tight_fit]| is the |line_number| field in the
24774 active node corresponding to |best_place[tight_fit]|. When no feasible break
24775 sequence is known, the |minimal_demerits| entries will be equal to
24776 |awful_bad|, which is $2^{30}-1$. Another variable, |minimum_demerits|,
24777 keeps track of the smallest value in the |minimal_demerits| array.
24778
24779 @d awful_bad==@'7777777777 {more than a billion demerits}
24780
24781 @<Global...@>=
24782 @!minimal_demerits:array[very_loose_fit..tight_fit] of integer; {best total
24783 demerits known for current line class and position, given the fitness}
24784 @!minimum_demerits:integer; {best total demerits known for current line class
24785 and position}
24786 @!best_place:array[very_loose_fit..tight_fit] of pointer; {how to achieve
24787 |minimal_demerits|}
24788 @!best_pl_line:array[very_loose_fit..tight_fit] of halfword; {corresponding
24789 line number}
24790
24791 @ @<Get ready to start...@>=
24792 minimum_demerits:=awful_bad;
24793 minimal_demerits[tight_fit]:=awful_bad;
24794 minimal_demerits[decent_fit]:=awful_bad;
24795 minimal_demerits[loose_fit]:=awful_bad;
24796 minimal_demerits[very_loose_fit]:=awful_bad;
24797
24798 @ The first part of the following code is part of \TeX's inner loop, so
24799 we don't want to waste any time. The current active node, namely node |r|,
24800 contains the line number that will be considered next. At the end of the
24801 list we have arranged the data structure so that |r=last_active| and
24802 |line_number(last_active)>old_l|.
24803 @^inner loop@>
24804
24805 @<If a line number class...@>=
24806 begin l:=line_number(r);
24807 if l>old_l then
24808 begin {now we are no longer in the inner loop}
24809 if (minimum_demerits<awful_bad)and@|
24810 ((old_l<>easy_line)or(r=last_active)) then
24811 @<Create new active nodes for the best feasible breaks
24812 just found@>;
24813 if r=last_active then return;
24814 @<Compute the new line width@>;
24815 end;
24816 end
24817
24818 @ It is not necessary to create new active nodes having |minimal_demerits|
24819 greater than
24820 |minimum_demerits+abs(adj_demerits)|, since such active nodes will never
24821 be chosen in the final paragraph breaks. This observation allows us to
24822 omit a substantial number of feasible breakpoints from further consideration.
24823
24824 @<Create new active nodes...@>=
24825 begin if no_break_yet then @<Compute the values of |break_width|@>;
24826 @<Insert a delta node to prepare for breaks at |cur_p|@>;
24827 if abs(adj_demerits)>=awful_bad-minimum_demerits then
24828 minimum_demerits:=awful_bad-1
24829 else minimum_demerits:=minimum_demerits+abs(adj_demerits);
24830 for fit_class:=very_loose_fit to tight_fit do
24831 begin if minimal_demerits[fit_class]<=minimum_demerits then
24832 @<Insert a new active node
24833 from |best_place[fit_class]| to |cur_p|@>;
24834 minimal_demerits[fit_class]:=awful_bad;
24835 end;
24836 minimum_demerits:=awful_bad;
24837 @<Insert a delta node to prepare for the next active node@>;
24838 end
24839
24840 @ When we insert a new active node for a break at |cur_p|, suppose this
24841 new node is to be placed just before active node |a|; then we essentially
24842 want to insert `$\delta\,|cur_p|\,\delta^\prime$' before |a|, where
24843 $\delta=\alpha(a)-\alpha(|cur_p|)$ and $\delta^\prime=\alpha(|cur_p|)-\alpha(a)$
24844 in the notation explained above. The |cur_active_width| array now holds
24845 $\gamma+\beta(|cur_p|)-\alpha(a)$; so $\delta$ can be obtained by
24846 subtracting |cur_active_width| from the quantity $\gamma+\beta(|cur_p|)-
24847 \alpha(|cur_p|)$. The latter quantity can be regarded as the length of a
24848 line ``from |cur_p| to |cur_p|''; we call it the |break_width| at |cur_p|.
24849
24850 The |break_width| is usually negative, since it consists of the background
24851 (which is normally zero) minus the width of nodes following~|cur_p| that are
24852 eliminated after a break. If, for example, node |cur_p| is a glue node, the
24853 width of this glue is subtracted from the background; and we also look
24854 ahead to eliminate all subsequent glue and penalty and kern and math
24855 nodes, subtracting their widths as well.
24856
24857 Kern nodes do not disappear at a line break unless they are |explicit|.
24858
24859 @d set_break_width_to_background(#)==break_width[#]:=background[#]
24860
24861 @<Compute the values of |break...@>=
24862 begin no_break_yet:=false; do_all_eight(set_break_width_to_background);
24863 s:=cur_p;
24864 if break_type>unhyphenated then if cur_p<>null then
24865 @<Compute the discretionary |break_width| values@>;
24866 while s<>null do
24867 begin if is_char_node(s) then goto done;
24868 case type(s) of
24869 glue_node:@<Subtract glue from |break_width|@>;
24870 penalty_node: do_nothing;
24871 math_node: break_width[1]:=break_width[1]-width(s);
24872 kern_node: if subtype(s)<>explicit then goto done
24873 else break_width[1]:=break_width[1]-width(s);
24874 othercases goto done
24875 endcases;@/
24876 s:=link(s);
24877 end;
24878 done: end
24879
24880 @ @<Subtract glue from |break...@>=
24881 begin v:=glue_ptr(s); break_width[1]:=break_width[1]-width(v);
24882 break_width[2+stretch_order(v)]:=break_width[2+stretch_order(v)]-stretch(v);
24883 break_width[6]:=break_width[6]-shrink(v);
24884 end
24885
24886 @ When |cur_p| is a discretionary break, the length of a line ``from |cur_p| to
24887 |cur_p|'' has to be defined properly so that the other calculations work out.
24888 Suppose that the pre-break text at |cur_p| has length $l_0$, the post-break
24889 text has length $l_1$, and the replacement text has length |l|. Suppose
24890 also that |q| is the node following the replacement text. Then length of a
24891 line from |cur_p| to |q| will be computed as $\gamma+\beta(q)-\alpha(|cur_p|)$,
24892 where $\beta(q)=\beta(|cur_p|)-l_0+l$. The actual length will be the background
24893 plus $l_1$, so the length from |cur_p| to |cur_p| should be $\gamma+l_0+l_1-l$.
24894 If the post-break text of the discretionary is empty, a break may also
24895 discard~|q|; in that unusual case we subtract the length of~|q| and any
24896 other nodes that will be discarded after the discretionary break.
24897
24898 The value of $l_0$ need not be computed, since |line_break| will put
24899 it into the global variable |disc_width| before calling |try_break|.
24900
24901 @d reset_disc_width(#) == disc_width[#] := 0
24902
24903 @d add_disc_width_to_break_width(#) ==
24904 break_width[#] := break_width[#] + disc_width[#]
24905
24906 @d add_disc_width_to_active_width(#) ==
24907 active_width[#] := active_width[#] + disc_width[#]
24908
24909 @d sub_disc_width_from_active_width(#) ==
24910 active_width[#] := active_width[#] - disc_width[#]
24911
24912 @d add_char_stretch_end(#) == char_stretch(f, #)
24913 @d add_char_stretch(#) == # := # + add_char_stretch_end
24914
24915 @d add_char_shrink_end(#) == char_shrink(f, #)
24916 @d add_char_shrink(#) == # := # + add_char_shrink_end
24917
24918 @d sub_char_stretch_end(#) == char_stretch(f, #)
24919 @d sub_char_stretch(#) == # := # - sub_char_stretch_end
24920
24921 @d sub_char_shrink_end(#) == char_shrink(f, #)
24922 @d sub_char_shrink(#) == # := # - sub_char_shrink_end
24923
24924 @d add_kern_stretch_end(#) == kern_stretch(#)
24925 @d add_kern_stretch(#) == # := # + add_kern_stretch_end
24926
24927 @d add_kern_shrink_end(#) == kern_shrink(#)
24928 @d add_kern_shrink(#) == # := # + add_kern_shrink_end
24929
24930 @d sub_kern_stretch_end(#) == kern_stretch(#)
24931 @d sub_kern_stretch(#) == # := # - sub_kern_stretch_end
24932
24933 @d sub_kern_shrink_end(#) == kern_shrink(#)
24934 @d sub_kern_shrink(#) == # := # - sub_kern_shrink_end
24935
24936 @<Glob...@>=
24937 @!disc_width: array[1..8] of scaled; {the length of discretionary material preceding a break}
24938
24939 @ @<Compute the discretionary |break...@>=
24940 begin t:=replace_count(cur_p); v:=cur_p; s:=post_break(cur_p);
24941 while t>0 do
24942 begin decr(t); v:=link(v);
24943 @<Subtract the width of node |v| from |break_width|@>;
24944 end;
24945 while s<>null do
24946 begin @<Add the width of node |s| to |break_width|@>;
24947 s:=link(s);
24948 end;
24949 do_one_seven_eight(add_disc_width_to_break_width);
24950 if post_break(cur_p)=null then s:=link(v);
24951 {nodes may be discardable after the break}
24952 end
24953
24954 @ Replacement texts and discretionary texts are supposed to contain
24955 only character nodes, kern nodes, ligature nodes, and box or rule nodes.
24956
24957 @<Subtract the width of node |v|...@>=
24958 if is_char_node(v) then
24959 begin f:=font(v);
24960 break_width[1]:=break_width[1]-char_width(f)(char_info(f)(character(v)));
24961 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
24962 prev_char_p := v;
24963 sub_char_stretch(break_width[7])(character(v));
24964 sub_char_shrink(break_width[8])(character(v));
24965 end;
24966 end
24967 else case type(v) of
24968 ligature_node: begin f:=font(lig_char(v));@/
24969 break_width[1]:=@|break_width[1]-
24970 char_width(f)(char_info(f)(character(lig_char(v))));
24971 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
24972 prev_char_p := v;
24973 sub_char_stretch(break_width[7])(character(lig_char(v)));
24974 sub_char_shrink(break_width[8])(character(lig_char(v)));
24975 end;
24976 end;
24977 hlist_node,vlist_node,rule_node,kern_node: begin
24978 break_width[1]:=break_width[1]-width(v);
24979 if (type(v) = kern_node) and
24980 (pdf_adjust_spacing > 1) and (subtype(v) = normal)
24981 then begin
24982 sub_kern_stretch(break_width[7])(v);
24983 sub_kern_shrink(break_width[8])(v);
24984 end;
24985 end;
24986 othercases confusion("disc1")
24987 @:this can't happen disc1}{\quad disc1@>
24988 endcases
24989
24990 @ @<Add the width of node |s| to |b...@>=
24991 if is_char_node(s) then
24992 begin f:=font(s);
24993 break_width[1]:=@|break_width[1]+char_width(f)(char_info(f)(character(s)));
24994 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
24995 prev_char_p := s;
24996 add_char_stretch(break_width[7])(character(s));
24997 add_char_shrink(break_width[8])(character(s));
24998 end;
24999 end
25000 else case type(s) of
25001 ligature_node: begin f:=font(lig_char(s));
25002 break_width[1]:=break_width[1]+
25003 char_width(f)(char_info(f)(character(lig_char(s))));
25004 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
25005 prev_char_p := s;
25006 add_char_stretch(break_width[7])(character(lig_char(s)));
25007 add_char_shrink(break_width[8])(character(lig_char(s)));
25008 end;
25009 end;
25010 hlist_node,vlist_node,rule_node,kern_node: begin
25011 break_width[1]:=break_width[1]+width(s);
25012 if (type(s) = kern_node) and
25013 (pdf_adjust_spacing > 1) and (subtype(s) = normal)
25014 then begin
25015 add_kern_stretch(break_width[7])(s);
25016 add_kern_shrink(break_width[8])(s);
25017 end;
25018 end;
25019 othercases confusion("disc2")
25020 @:this can't happen disc2}{\quad disc2@>
25021 endcases
25022
25023 @ We use the fact that |type(active)<>delta_node|.
25024
25025 @d convert_to_break_width(#)==@|
25026 mem[prev_r+#].sc:=@|@t\hskip10pt@>mem[prev_r+#].sc
25027 -cur_active_width[#]+break_width[#]
25028 @d store_break_width(#)==active_width[#]:=break_width[#]
25029 @d new_delta_to_break_width(#)==@|
25030 mem[q+#].sc:=break_width[#]-cur_active_width[#]
25031
25032 @<Insert a delta node to prepare for breaks at |cur_p|@>=
25033 if type(prev_r)=delta_node then {modify an existing delta node}
25034 begin do_all_eight(convert_to_break_width);
25035 end
25036 else if prev_r=active then {no delta node needed at the beginning}
25037 begin do_all_eight(store_break_width);
25038 end
25039 else begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
25040 subtype(q):=0; {the |subtype| is not used}
25041 do_all_eight(new_delta_to_break_width);
25042 link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
25043 end
25044
25045 @ When the following code is performed, we will have just inserted at
25046 least one active node before |r|, so |type(prev_r)<>delta_node|.
25047
25048 @d new_delta_from_break_width(#)==@|mem[q+#].sc:=
25049 cur_active_width[#]-break_width[#]
25050
25051 @<Insert a delta node to prepare for the next active node@>=
25052 if r<>last_active then
25053 begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
25054 subtype(q):=0; {the |subtype| is not used}
25055 do_all_eight(new_delta_from_break_width);
25056 link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
25057 end
25058
25059 @ When we create an active node, we also create the corresponding
25060 passive node.
25061
25062 @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>=
25063 begin q:=get_node(passive_node_size);
25064 link(q):=passive; passive:=q; cur_break(q):=cur_p;
25065 @!stat incr(pass_number); serial(q):=pass_number;@+tats@;@/
25066 prev_break(q):=best_place[fit_class];@/
25067 q:=get_node(active_node_size); break_node(q):=passive;
25068 line_number(q):=best_pl_line[fit_class]+1;
25069 fitness(q):=fit_class; type(q):=break_type;
25070 total_demerits(q):=minimal_demerits[fit_class];
25071 if do_last_line_fit then
25072 @<Store \(a)additional data in the new active node@>;
25073 link(q):=r; link(prev_r):=q; prev_r:=q;
25074 @!stat if tracing_paragraphs>0 then
25075 @<Print a symbolic description of the new break node@>;
25076 tats@;@/
25077 end
25078
25079 @ @<Print a symbolic description of the new break node@>=
25080 begin print_nl("@@@@"); print_int(serial(passive));
25081 @.\AT!\AT!@>
25082 print(": line "); print_int(line_number(q)-1);
25083 print_char("."); print_int(fit_class);
25084 if break_type=hyphenated then print_char("-");
25085 print(" t="); print_int(total_demerits(q));
25086 if do_last_line_fit then @<Print additional data in the new active node@>;
25087 print(" -> @@@@");
25088 if prev_break(passive)=null then print_char("0")
25089 else print_int(serial(prev_break(passive)));
25090 end
25091
25092 @ The length of lines depends on whether the user has specified
25093 \.{\\parshape} or \.{\\hangindent}. If |par_shape_ptr| is not null, it
25094 points to a $(2n+1)$-word record in |mem|, where the |info| in the first
25095 word contains the value of |n|, and the other $2n$ words contain the left
25096 margins and line lengths for the first |n| lines of the paragraph; the
25097 specifications for line |n| apply to all subsequent lines. If
25098 |par_shape_ptr=null|, the shape of the paragraph depends on the value of
25099 |n=hang_after|; if |n>=0|, hanging indentation takes place on lines |n+1|,
25100 |n+2|, \dots, otherwise it takes place on lines 1, \dots, $\vert
25101 n\vert$. When hanging indentation is active, the left margin is
25102 |hang_indent|, if |hang_indent>=0|, else it is 0; the line length is
25103 $|hsize|-\vert|hang_indent|\vert$. The normal setting is
25104 |par_shape_ptr=null|, |hang_after=1|, and |hang_indent=0|.
25105 Note that if |hang_indent=0|, the value of |hang_after| is irrelevant.
25106 @^length of lines@> @^hanging indentation@>
25107
25108 @<Glob...@>=
25109 @!easy_line:halfword; {line numbers |>easy_line| are equivalent in break nodes}
25110 @!last_special_line:halfword; {line numbers |>last_special_line| all have
25111 the same width}
25112 @!first_width:scaled; {the width of all lines |<=last_special_line|, if
25113 no \.{\\parshape} has been specified}
25114 @!second_width:scaled; {the width of all lines |>last_special_line|}
25115 @!first_indent:scaled; {left margin to go with |first_width|}
25116 @!second_indent:scaled; {left margin to go with |second_width|}
25117
25118 @ We compute the values of |easy_line| and the other local variables relating
25119 to line length when the |line_break| procedure is initializing itself.
25120
25121 @<Get ready to start...@>=
25122 if par_shape_ptr=null then
25123 if hang_indent=0 then
25124 begin last_special_line:=0; second_width:=hsize;
25125 second_indent:=0;
25126 end
25127 else @<Set line length parameters in preparation for hanging indentation@>
25128 else begin last_special_line:=info(par_shape_ptr)-1;
25129 second_width:=mem[par_shape_ptr+2*(last_special_line+1)].sc;
25130 second_indent:=mem[par_shape_ptr+2*last_special_line+1].sc;
25131 end;
25132 if looseness=0 then easy_line:=last_special_line
25133 else easy_line:=max_halfword
25134
25135 @ @<Set line length parameters in preparation for hanging indentation@>=
25136 begin last_special_line:=abs(hang_after);
25137 if hang_after<0 then
25138 begin first_width:=hsize-abs(hang_indent);
25139 if hang_indent>=0 then first_indent:=hang_indent
25140 else first_indent:=0;
25141 second_width:=hsize; second_indent:=0;
25142 end
25143 else begin first_width:=hsize; first_indent:=0;
25144 second_width:=hsize-abs(hang_indent);
25145 if hang_indent>=0 then second_indent:=hang_indent
25146 else second_indent:=0;
25147 end;
25148 end
25149
25150 @ When we come to the following code, we have just encountered the first
25151 active node~|r| whose |line_number| field contains |l|. Thus we want to
25152 compute the length of the $l\mskip1mu$th line of the current paragraph. Furthermore,
25153 we want to set |old_l| to the last number in the class of line numbers
25154 equivalent to~|l|.
25155
25156 @<Compute the new line width@>=
25157 if l>easy_line then
25158 begin line_width:=second_width; old_l:=max_halfword-1;
25159 end
25160 else begin old_l:=l;
25161 if l>last_special_line then line_width:=second_width
25162 else if par_shape_ptr=null then line_width:=first_width
25163 else line_width:=mem[par_shape_ptr+2*l@,].sc;
25164 end
25165
25166 @ The remaining part of |try_break| deals with the calculation of
25167 demerits for a break from |r| to |cur_p|.
25168
25169 The first thing to do is calculate the badness, |b|. This value will always
25170 be between zero and |inf_bad+1|; the latter value occurs only in the
25171 case of lines from |r| to |cur_p| that cannot shrink enough to fit the necessary
25172 width. In such cases, node |r| will be deactivated.
25173 We also deactivate node~|r| when a break at~|cur_p| is forced, since future
25174 breaks must go through a forced break.
25175
25176 @<Consider the demerits for a line from |r| to |cur_p|...@>=
25177 begin artificial_demerits:=false;@/
25178 @^inner loop@>
25179 shortfall:=line_width-cur_active_width[1]; {we're this much too short}
25180
25181 @{
25182 if pdf_output > 2 then begin
25183 print_ln;
25184 if (r <> null) and (break_node(r) <> null) then
25185 short_display_n(cur_break(break_node(r)), 5);
25186 print_ln;
25187 short_display_n(cur_p, 5);
25188 print_ln;
25189 end;
25190 @}
25191
25192 if pdf_protrude_chars > 1 then
25193 shortfall := shortfall + total_pw(r, cur_p);
25194 if (pdf_adjust_spacing > 1) and (shortfall <> 0) then begin
25195 margin_kern_stretch := 0;
25196 margin_kern_shrink := 0;
25197 if pdf_protrude_chars > 1 then
25198 @<Calculate variations of marginal kerns@>;
25199 if (shortfall > 0) and ((total_font_stretch + margin_kern_stretch) > 0)
25200 then begin
25201 if (total_font_stretch + margin_kern_stretch) > shortfall then
25202 shortfall := ((total_font_stretch + margin_kern_stretch) div
25203 (max_stretch_ratio div cur_font_step)) div 2
25204 else
25205 shortfall := shortfall - (total_font_stretch + margin_kern_stretch);
25206 end
25207 else if (shortfall < 0) and ((total_font_shrink + margin_kern_shrink) > 0)
25208 then begin
25209 if (total_font_shrink + margin_kern_shrink) > -shortfall then
25210 shortfall := -((total_font_shrink + margin_kern_shrink) div
25211 (max_shrink_ratio div cur_font_step)) div 2
25212 else
25213 shortfall := shortfall + (total_font_shrink + margin_kern_shrink);
25214 end;
25215 end;
25216 if shortfall>0 then
25217 @<Set the value of |b| to the badness for stretching the line,
25218 and compute the corresponding |fit_class|@>
25219 else @<Set the value of |b| to the badness for shrinking the line,
25220 and compute the corresponding |fit_class|@>;
25221 if do_last_line_fit then @<Adjust \(t)the additional data for last line@>;
25222 found:
25223 if (b>inf_bad)or(pi=eject_penalty) then
25224 @<Prepare to deactivate node~|r|, and |goto deactivate| unless
25225 there is a reason to consider lines of text from |r| to |cur_p|@>
25226 else begin prev_r:=r;
25227 if b>threshold then goto continue;
25228 node_r_stays_active:=true;
25229 end;
25230 @<Record a new feasible break@>;
25231 if node_r_stays_active then goto continue; {|prev_r| has been set to |r|}
25232 deactivate: @<Deactivate node |r|@>;
25233 end
25234
25235 @ When a line must stretch, the available stretchability can be found in the
25236 subarray |cur_active_width[2..5]|, in units of points, fil, fill, and filll.
25237
25238 The present section is part of \TeX's inner loop, and it is most often performed
25239 when the badness is infinite; therefore it is worth while to make a quick
25240 test for large width excess and small stretchability, before calling the
25241 |badness| subroutine.
25242 @^inner loop@>
25243
25244 @<Set the value of |b| to the badness for stretching...@>=
25245 if (cur_active_width[3]<>0)or(cur_active_width[4]<>0)or@|
25246 (cur_active_width[5]<>0) then
25247 begin if do_last_line_fit then
25248 begin if cur_p=null then {the last line of a paragraph}
25249 @<Perform computations for last line and |goto found|@>;
25250 shortfall:=0;
25251 end;
25252 b:=0; fit_class:=decent_fit; {infinite stretch}
25253 end
25254 else begin if shortfall>7230584 then if cur_active_width[2]<1663497 then
25255 begin b:=inf_bad; fit_class:=very_loose_fit; goto done1;
25256 end;
25257 b:=badness(shortfall,cur_active_width[2]);
25258 if b>12 then
25259 if b>99 then fit_class:=very_loose_fit
25260 else fit_class:=loose_fit
25261 else fit_class:=decent_fit;
25262 done1:
25263 end
25264
25265 @ Shrinkability is never infinite in a paragraph;
25266 we can shrink the line from |r| to |cur_p| by at most |cur_active_width[6]|.
25267
25268 @<Set the value of |b| to the badness for shrinking...@>=
25269 begin if -shortfall>cur_active_width[6] then b:=inf_bad+1
25270 else b:=badness(-shortfall,cur_active_width[6]);
25271 if b>12 then fit_class:=tight_fit@+else fit_class:=decent_fit;
25272 end
25273
25274 @ During the final pass, we dare not lose all active nodes, lest we lose
25275 touch with the line breaks already found. The code shown here makes sure
25276 that such a catastrophe does not happen, by permitting overfull boxes as
25277 a last resort. This particular part of \TeX\ was a source of several subtle
25278 bugs before the correct program logic was finally discovered; readers
25279 who seek to ``improve'' \TeX\ should therefore think thrice before daring
25280 to make any changes here.
25281 @^overfull boxes@>
25282
25283 @<Prepare to deactivate node~|r|, and |goto deactivate| unless...@>=
25284 begin if final_pass and (minimum_demerits=awful_bad) and@|
25285 (link(r)=last_active) and
25286 (prev_r=active) then
25287 artificial_demerits:=true {set demerits zero, this break is forced}
25288 else if b>threshold then goto deactivate;
25289 node_r_stays_active:=false;
25290 end
25291
25292 @ When we get to this part of the code, the line from |r| to |cur_p| is
25293 feasible, its badness is~|b|, and its fitness classification is |fit_class|.
25294 We don't want to make an active node for this break yet, but we will
25295 compute the total demerits and record them in the |minimal_demerits| array,
25296 if such a break is the current champion among all ways to get to |cur_p|
25297 in a given line-number class and fitness class.
25298
25299 @<Record a new feasible break@>=
25300 if artificial_demerits then d:=0
25301 else @<Compute the demerits, |d|, from |r| to |cur_p|@>;
25302 @!stat if tracing_paragraphs>0 then
25303 @<Print a symbolic description of this feasible break@>;
25304 tats@;@/
25305 d:=d+total_demerits(r); {this is the minimum total demerits
25306 from the beginning to |cur_p| via |r|}
25307 if d<=minimal_demerits[fit_class] then
25308 begin minimal_demerits[fit_class]:=d;
25309 best_place[fit_class]:=break_node(r); best_pl_line[fit_class]:=l;
25310 if do_last_line_fit then
25311 @<Store \(a)additional data for this feasible break@>;
25312 if d<minimum_demerits then minimum_demerits:=d;
25313 end
25314
25315 @ @<Print a symbolic description of this feasible break@>=
25316 begin if printed_node<>cur_p then
25317 @<Print the list between |printed_node| and |cur_p|,
25318 then set |printed_node:=cur_p|@>;
25319 print_nl("@@");
25320 @.\AT!@>
25321 if cur_p=null then print_esc("par")
25322 else if type(cur_p)<>glue_node then
25323 begin if type(cur_p)=penalty_node then print_esc("penalty")
25324 else if type(cur_p)=disc_node then print_esc("discretionary")
25325 else if type(cur_p)=kern_node then print_esc("kern")
25326 else print_esc("math");
25327 end;
25328 print(" via @@@@");
25329 if break_node(r)=null then print_char("0")
25330 else print_int(serial(break_node(r)));
25331 print(" b=");
25332 if b>inf_bad then print_char("*")@+else print_int(b);
25333 @.*\relax@>
25334 print(" p="); print_int(pi); print(" d=");
25335 if artificial_demerits then print_char("*")@+else print_int(d);
25336 end
25337
25338 @ @<Print the list between |printed_node| and |cur_p|...@>=
25339 begin print_nl("");
25340 if cur_p=null then short_display(link(printed_node))
25341 else begin save_link:=link(cur_p);
25342 link(cur_p):=null; print_nl(""); short_display(link(printed_node));
25343 link(cur_p):=save_link;
25344 end;
25345 printed_node:=cur_p;
25346 end
25347
25348 @ When the data for a discretionary break is being displayed, we will have
25349 printed the |pre_break| and |post_break| lists; we want to skip over the
25350 third list, so that the discretionary data will not appear twice. The
25351 following code is performed at the very end of |try_break|.
25352
25353 @<Update the value of |printed_node|...@>=
25354 if cur_p=printed_node then if cur_p<>null then if type(cur_p)=disc_node then
25355 begin t:=replace_count(cur_p);
25356 while t>0 do
25357 begin decr(t); printed_node:=link(printed_node);
25358 end;
25359 end
25360
25361 @ @<Compute the demerits, |d|, from |r| to |cur_p|@>=
25362 begin d:=line_penalty+b;
25363 if abs(d)>=10000 then d:=100000000@+else d:=d*d;
25364 if pi<>0 then
25365 if pi>0 then d:=d+pi*pi
25366 else if pi>eject_penalty then d:=d-pi*pi;
25367 if (break_type=hyphenated)and(type(r)=hyphenated) then
25368 if cur_p<>null then d:=d+double_hyphen_demerits
25369 else d:=d+final_hyphen_demerits;
25370 if abs(fit_class-fitness(r))>1 then d:=d+adj_demerits;
25371 end
25372
25373 @ When an active node disappears, we must delete an adjacent delta node if the
25374 active node was at the beginning or the end of the active list, or if it
25375 was surrounded by delta nodes. We also must preserve the property that
25376 |cur_active_width| represents the length of material from |link(prev_r)|
25377 to~|cur_p|.
25378
25379 @d combine_two_deltas(#)==@|mem[prev_r+#].sc:=mem[prev_r+#].sc+mem[r+#].sc
25380 @d downdate_width(#)==@|cur_active_width[#]:=cur_active_width[#]-
25381 mem[prev_r+#].sc
25382
25383 @<Deactivate node |r|@>=
25384 link(prev_r):=link(r); free_node(r,active_node_size);
25385 if prev_r=active then @<Update the active widths, since the first active
25386 node has been deleted@>
25387 else if type(prev_r)=delta_node then
25388 begin r:=link(prev_r);
25389 if r=last_active then
25390 begin do_all_eight(downdate_width);
25391 link(prev_prev_r):=last_active;
25392 free_node(prev_r,delta_node_size); prev_r:=prev_prev_r;
25393 end
25394 else if type(r)=delta_node then
25395 begin do_all_eight(update_width);
25396 do_all_eight(combine_two_deltas);
25397 link(prev_r):=link(r); free_node(r,delta_node_size);
25398 end;
25399 end
25400
25401 @ The following code uses the fact that |type(last_active)<>delta_node|. If the
25402 active list has just become empty, we do not need to update the
25403 |active_width| array, since it will be initialized when an active
25404 node is next inserted.
25405
25406 @d update_active(#)==active_width[#]:=active_width[#]+mem[r+#].sc
25407
25408 @<Update the active widths,...@>=
25409 begin r:=link(active);
25410 if type(r)=delta_node then
25411 begin do_all_eight(update_active);
25412 do_all_eight(copy_to_cur_active);
25413 link(active):=link(r); free_node(r,delta_node_size);
25414 end;
25415 end
25416
25417 @* \[39] Breaking paragraphs into lines, continued.
25418 So far we have gotten a little way into the |line_break| routine, having
25419 covered its important |try_break| subroutine. Now let's consider the
25420 rest of the process.
25421
25422 The main loop of |line_break| traverses the given hlist,
25423 starting at |link(temp_head)|, and calls |try_break| at each legal
25424 breakpoint. A variable called |auto_breaking| is set to true except
25425 within math formulas, since glue nodes are not legal breakpoints when
25426 they appear in formulas.
25427
25428 The current node of interest in the hlist is pointed to by |cur_p|. Another
25429 variable, |prev_p|, is usually one step behind |cur_p|, but the real
25430 meaning of |prev_p| is this: If |type(cur_p)=glue_node| then |cur_p| is a legal
25431 breakpoint if and only if |auto_breaking| is true and |prev_p| does not
25432 point to a glue node, penalty node, explicit kern node, or math node.
25433
25434 The following declarations provide for a few other local variables that are
25435 used in special calculations.
25436
25437 @<Local variables for line breaking@>=
25438 @!q,@!r,@!s,@!prev_s:pointer; {miscellaneous nodes of temporary interest}
25439 @!f:internal_font_number; {used when calculating character widths}
25440
25441 @ The `\ignorespaces|loop|\unskip' in the following code is performed at most
25442 thrice per call of |line_break|, since it is actually a pass over the
25443 entire paragraph.
25444
25445 @<Find optimal breakpoints@>=
25446 threshold:=pretolerance;
25447 if threshold>=0 then
25448 begin @!stat if tracing_paragraphs>0 then
25449 begin begin_diagnostic; print_nl("@@firstpass");@+end;@;@+tats@;@/
25450 second_pass:=false; final_pass:=false;
25451 end
25452 else begin threshold:=tolerance; second_pass:=true;
25453 final_pass:=(emergency_stretch<=0);
25454 @!stat if tracing_paragraphs>0 then begin_diagnostic;@+tats@;
25455 end;
25456 loop@+ begin if threshold>inf_bad then threshold:=inf_bad;
25457 if second_pass then @<Initialize for hyphenating a paragraph@>;
25458 @<Create an active breakpoint representing the beginning of the paragraph@>;
25459 cur_p:=link(temp_head); auto_breaking:=true;@/
25460 prev_p:=cur_p; {glue at beginning is not a legal breakpoint}
25461 prev_char_p := null;
25462 prev_legal := null;
25463 rejected_cur_p := null;
25464 try_prev_break := false;
25465 before_rejected_cur_p := false;
25466 first_p := cur_p; {to access the first node of paragraph as the first active
25467 node has |break_node=null|}
25468 while (cur_p<>null)and(link(active)<>last_active) do
25469 @<Call |try_break| if |cur_p| is a legal breakpoint;
25470 on the second pass, also try to hyphenate the next
25471 word, if |cur_p| is a glue node;
25472 then advance |cur_p| to the next node of the paragraph
25473 that could possibly be a legal breakpoint@>;
25474 if cur_p=null then
25475 @<Try the final line break at the end of the paragraph,
25476 and |goto done| if the desired breakpoints have been found@>;
25477 @<Clean up the memory by removing the break nodes@>;
25478 if not second_pass then
25479 begin@!stat if tracing_paragraphs>0 then print_nl("@@secondpass");@;@+tats@/
25480 threshold:=tolerance; second_pass:=true; final_pass:=(emergency_stretch<=0);
25481 end {if at first you don't succeed, \dots}
25482 else begin @!stat if tracing_paragraphs>0 then
25483 print_nl("@@emergencypass");@;@+tats@/
25484 background[2]:=background[2]+emergency_stretch; final_pass:=true;
25485 end;
25486 end;
25487 done: @!stat if tracing_paragraphs>0 then
25488 begin end_diagnostic(true); normalize_selector;
25489 end;@+tats@/
25490 if do_last_line_fit then @<Adjust \(t)the final line of the paragraph@>;
25491
25492 @ The active node that represents the starting point does not need a
25493 corresponding passive node.
25494
25495 @d store_background(#)==active_width[#]:=background[#]
25496
25497 @<Create an active breakpoint representing the beginning of the paragraph@>=
25498 q:=get_node(active_node_size);
25499 type(q):=unhyphenated; fitness(q):=decent_fit;
25500 link(q):=last_active; break_node(q):=null;
25501 line_number(q):=prev_graf+1; total_demerits(q):=0; link(active):=q;
25502 if do_last_line_fit then
25503 @<Initialize additional fields of the first active node@>;
25504 do_all_eight(store_background);@/
25505 passive:=null; printed_node:=temp_head; pass_number:=0;
25506 font_in_short_display:=null_font
25507
25508 @ @<Clean...@>=
25509 q:=link(active);
25510 while q<>last_active do
25511 begin cur_p:=link(q);
25512 if type(q)=delta_node then free_node(q,delta_node_size)
25513 else free_node(q,active_node_size);
25514 q:=cur_p;
25515 end;
25516 q:=passive;
25517 while q<>null do
25518 begin cur_p:=link(q);
25519 free_node(q,passive_node_size);
25520 q:=cur_p;
25521 end
25522
25523 @ Here is the main switch in the |line_break| routine, where legal breaks
25524 are determined. As we move through the hlist, we need to keep the |active_width|
25525 array up to date, so that the badness of individual lines is readily calculated
25526 by |try_break|. It is convenient to use the short name |act_width| for
25527 the component of active width that represents real width as opposed to glue.
25528
25529 @d act_width==active_width[1] {length from first active node to current node}
25530 @d kern_break==begin if not is_char_node(link(cur_p)) and auto_breaking then
25531 if type(link(cur_p))=glue_node then try_break(0,unhyphenated);
25532 act_width:=act_width+width(cur_p);
25533 end
25534
25535 @<Call |try_break| if |cur_p| is a legal breakpoint...@>=
25536 begin if is_char_node(cur_p) then
25537 @<Advance \(c)|cur_p| to the node following the present
25538 string of characters@>;
25539 case type(cur_p) of
25540 hlist_node,vlist_node,rule_node: act_width:=act_width+width(cur_p);
25541 whatsit_node: @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>;
25542 glue_node: begin @<If node |cur_p| is a legal breakpoint, call |try_break|;
25543 then update the active widths by including the glue in |glue_ptr(cur_p)|@>;
25544 if second_pass and auto_breaking then
25545 @<Try to hyphenate the following word@>;
25546 end;
25547 kern_node: if subtype(cur_p)=explicit then kern_break
25548 else begin
25549 act_width:=act_width+width(cur_p);
25550 if (pdf_adjust_spacing > 1) and (subtype(cur_p) = normal) then begin
25551 add_kern_stretch(active_width[7])(cur_p);
25552 add_kern_shrink(active_width[8])(cur_p);
25553 end;
25554 end;
25555 ligature_node: begin f:=font(lig_char(cur_p));
25556 act_width:=act_width+char_width(f)(char_info(f)(character(lig_char(cur_p))));
25557 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
25558 prev_char_p := cur_p;
25559 add_char_stretch(active_width[7])(character(lig_char(cur_p)));
25560 add_char_shrink(active_width[8])(character(lig_char(cur_p)));
25561 end;
25562 end;
25563 disc_node: @<Try to break after a discretionary fragment, then |goto done5|@>;
25564 math_node: begin if subtype(cur_p)<L_code then auto_breaking:=odd(subtype(cur_p));
25565 kern_break;
25566 end;
25567 penalty_node: try_break(penalty(cur_p),unhyphenated);
25568 mark_node,ins_node,adjust_node: do_nothing;
25569 othercases confusion("paragraph")
25570 @:this can't happen paragraph}{\quad paragraph@>
25571 endcases;@/
25572 prev_p:=cur_p; cur_p:=link(cur_p);
25573 done5:end
25574
25575 @ The code that passes over the characters of words in a paragraph is
25576 part of \TeX's inner loop, so it has been streamlined for speed. We use
25577 the fact that `\.{\\parfillskip}' glue appears at the end of each paragraph;
25578 it is therefore unnecessary to check if |link(cur_p)=null| when |cur_p| is a
25579 character node.
25580 @^inner loop@>
25581
25582 @<Advance \(c)|cur_p| to the node following the present string...@>=
25583 begin prev_p:=cur_p;
25584 repeat f:=font(cur_p);
25585 act_width:=act_width+char_width(f)(char_info(f)(character(cur_p)));
25586 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
25587 prev_char_p := cur_p;
25588 add_char_stretch(active_width[7])(character(cur_p));
25589 add_char_shrink(active_width[8])(character(cur_p));
25590 end;
25591 cur_p:=link(cur_p);
25592 until not is_char_node(cur_p);
25593 end
25594
25595 @ When node |cur_p| is a glue node, we look at |prev_p| to see whether or not
25596 a breakpoint is legal at |cur_p|, as explained above.
25597
25598 @<If node |cur_p| is a legal breakpoint, call...@>=
25599 if auto_breaking then
25600 begin if is_char_node(prev_p) then try_break(0,unhyphenated)
25601 else if precedes_break(prev_p) then try_break(0,unhyphenated)
25602 else if (type(prev_p)=kern_node)and(subtype(prev_p)<>explicit) then
25603 try_break(0,unhyphenated);
25604 end;
25605 check_shrinkage(glue_ptr(cur_p)); q:=glue_ptr(cur_p);
25606 act_width:=act_width+width(q);@|
25607 active_width[2+stretch_order(q)]:=@|
25608 active_width[2+stretch_order(q)]+stretch(q);@/
25609 active_width[6]:=active_width[6]+shrink(q)
25610
25611 @ The following code knows that discretionary texts contain
25612 only character nodes, kern nodes, box nodes, rule nodes, and ligature nodes.
25613
25614 @<Try to break after a discretionary fragment...@>=
25615 begin s:=pre_break(cur_p);
25616 do_one_seven_eight(reset_disc_width);
25617 if s=null then try_break(ex_hyphen_penalty,hyphenated)
25618 else begin repeat @<Add the width of node |s| to |disc_width|@>;
25619 s:=link(s);
25620 until s=null;
25621 do_one_seven_eight(add_disc_width_to_active_width);
25622 try_break(hyphen_penalty,hyphenated);
25623 do_one_seven_eight(sub_disc_width_from_active_width);
25624 end;
25625 r:=replace_count(cur_p); s:=link(cur_p);
25626 while r>0 do
25627 begin @<Add the width of node |s| to |act_width|@>;
25628 decr(r); s:=link(s);
25629 end;
25630 prev_p:=cur_p; cur_p:=s; goto done5;
25631 end
25632
25633 @ @<Add the width of node |s| to |disc_width|@>=
25634 if is_char_node(s) then
25635 begin f:=font(s);
25636 disc_width[1]:=disc_width[1]+char_width(f)(char_info(f)(character(s)));
25637 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
25638 prev_char_p := s;
25639 add_char_stretch(disc_width[7])(character(s));
25640 add_char_shrink(disc_width[8])(character(s));
25641 end;
25642 end
25643 else case type(s) of
25644 ligature_node: begin f:=font(lig_char(s));
25645 disc_width[1]:=disc_width[1]+
25646 char_width(f)(char_info(f)(character(lig_char(s))));
25647 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
25648 prev_char_p := s;
25649 add_char_stretch(disc_width[7])(character(lig_char(s)));
25650 add_char_shrink(disc_width[8])(character(lig_char(s)));
25651 end;
25652 end;
25653 hlist_node,vlist_node,rule_node,kern_node: begin
25654 disc_width[1]:=disc_width[1]+width(s);
25655 if (type(s) = kern_node) and
25656 (pdf_adjust_spacing > 1) and (subtype(s) = normal)
25657 then begin
25658 add_kern_stretch(disc_width[7])(s);
25659 add_kern_shrink(disc_width[8])(s);
25660 end;
25661 end;
25662 othercases confusion("disc3")
25663 @:this can't happen disc3}{\quad disc3@>
25664 endcases
25665
25666 @ @<Add the width of node |s| to |act_width|@>=
25667 if is_char_node(s) then
25668 begin f:=font(s);
25669 act_width:=act_width+char_width(f)(char_info(f)(character(s)));
25670 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
25671 prev_char_p := s;
25672 add_char_stretch(active_width[7])(character(s));
25673 add_char_shrink(active_width[8])(character(s));
25674 end;
25675 end
25676 else case type(s) of
25677 ligature_node: begin f:=font(lig_char(s));
25678 act_width:=act_width+
25679 char_width(f)(char_info(f)(character(lig_char(s))));
25680 if (pdf_adjust_spacing > 1) and check_expand_pars(f) then begin
25681 prev_char_p := s;
25682 add_char_stretch(active_width[7])(character(lig_char(s)));
25683 add_char_shrink(active_width[8])(character(lig_char(s)));
25684 end;
25685 end;
25686 hlist_node,vlist_node,rule_node,kern_node: begin
25687 act_width:=act_width+width(s);
25688 if (type(s) = kern_node) and
25689 (pdf_adjust_spacing > 1) and (subtype(s) = normal)
25690 then begin
25691 add_kern_stretch(active_width[7])(s);
25692 add_kern_shrink(active_width[8])(s);
25693 end;
25694 end;
25695 othercases confusion("disc4")
25696 @:this can't happen disc4}{\quad disc4@>
25697 endcases
25698
25699 @ The forced line break at the paragraph's end will reduce the list of
25700 breakpoints so that all active nodes represent breaks at |cur_p=null|.
25701 On the first pass, we insist on finding an active node that has the
25702 correct ``looseness.'' On the final pass, there will be at least one active
25703 node, and we will match the desired looseness as well as we can.
25704
25705 The global variable |best_bet| will be set to the active node for the best
25706 way to break the paragraph, and a few other variables are used to
25707 help determine what is best.
25708
25709 @<Glob...@>=
25710 @!best_bet:pointer; {use this passive node and its predecessors}
25711 @!fewest_demerits:integer; {the demerits associated with |best_bet|}
25712 @!best_line:halfword; {line number following the last line of the new paragraph}
25713 @!actual_looseness:integer; {the difference between |line_number(best_bet)|
25714 and the optimum |best_line|}
25715 @!line_diff:integer; {the difference between the current line number and
25716 the optimum |best_line|}
25717
25718 @ @<Try the final line break at the end of the paragraph...@>=
25719 begin try_break(eject_penalty,hyphenated);
25720 if link(active)<>last_active then
25721 begin @<Find an active node with fewest demerits@>;
25722 if looseness=0 then goto done;
25723 @<Find the best active node for the desired looseness@>;
25724 if (actual_looseness=looseness)or final_pass then goto done;
25725 end;
25726 end
25727
25728 @ @<Find an active node...@>=
25729 r:=link(active); fewest_demerits:=awful_bad;
25730 repeat if type(r)<>delta_node then if total_demerits(r)<fewest_demerits then
25731 begin fewest_demerits:=total_demerits(r); best_bet:=r;
25732 end;
25733 r:=link(r);
25734 until r=last_active;
25735 best_line:=line_number(best_bet)
25736
25737 @ The adjustment for a desired looseness is a slightly more complicated
25738 version of the loop just considered. Note that if a paragraph is broken
25739 into segments by displayed equations, each segment will be subject to the
25740 looseness calculation, independently of the other segments.
25741
25742 @<Find the best active node...@>=
25743 begin r:=link(active); actual_looseness:=0;
25744 repeat if type(r)<>delta_node then
25745 begin line_diff:=line_number(r)-best_line;
25746 if ((line_diff<actual_looseness)and(looseness<=line_diff))or@|
25747 ((line_diff>actual_looseness)and(looseness>=line_diff)) then
25748 begin best_bet:=r; actual_looseness:=line_diff;
25749 fewest_demerits:=total_demerits(r);
25750 end
25751 else if (line_diff=actual_looseness)and@|
25752 (total_demerits(r)<fewest_demerits) then
25753 begin best_bet:=r; fewest_demerits:=total_demerits(r);
25754 end;
25755 end;
25756 r:=link(r);
25757 until r=last_active;
25758 best_line:=line_number(best_bet);
25759 end
25760
25761 @ Once the best sequence of breakpoints has been found (hurray), we call on the
25762 procedure |post_line_break| to finish the remainder of the work.
25763 (By introducing this subprocedure, we are able to keep |line_break|
25764 from getting extremely long.)
25765
25766 @<Break the paragraph at the chosen...@>=
25767 post_line_break(d)
25768
25769 @ The total number of lines that will be set by |post_line_break|
25770 is |best_line-prev_graf-1|. The last breakpoint is specified by
25771 |break_node(best_bet)|, and this passive node points to the other breakpoints
25772 via the |prev_break| links. The finishing-up phase starts by linking the
25773 relevant passive nodes in forward order, changing |prev_break| to
25774 |next_break|. (The |next_break| fields actually reside in the same memory
25775 space as the |prev_break| fields did, but we give them a new name because
25776 of their new significance.) Then the lines are justified, one by one.
25777
25778 @d next_break==prev_break {new name for |prev_break| after links are reversed}
25779
25780 @<Declare subprocedures for |line_break|@>=
25781 procedure post_line_break(@!d:boolean);
25782 label done,done1;
25783 var q,@!r,@!s:pointer; {temporary registers for list manipulation}
25784 p, k: pointer;
25785 w: scaled;
25786 glue_break: boolean; {was a break at glue?}
25787 ptmp: pointer;
25788 @!disc_break:boolean; {was the current break at a discretionary node?}
25789 @!post_disc_break:boolean; {and did it have a nonempty post-break part?}
25790 @!cur_width:scaled; {width of line number |cur_line|}
25791 @!cur_indent:scaled; {left margin of line number |cur_line|}
25792 @!t:quarterword; {used for replacement counts in discretionary nodes}
25793 @!pen:integer; {use when calculating penalties between lines}
25794 @!cur_line: halfword; {the current line number being justified}
25795 @!LR_ptr:pointer; {stack of LR codes}
25796 begin LR_ptr:=LR_save;
25797 @<Reverse the links of the relevant passive nodes, setting |cur_p| to the
25798 first breakpoint@>;
25799 cur_line:=prev_graf+1;
25800 repeat @<Justify the line ending at breakpoint |cur_p|, and append it to the
25801 current vertical list, together with associated penalties and other
25802 insertions@>;
25803 incr(cur_line); cur_p:=next_break(cur_p);
25804 if cur_p<>null then if not post_disc_break then
25805 @<Prune unwanted nodes at the beginning of the next line@>;
25806 until cur_p=null;
25807 if (cur_line<>best_line)or(link(temp_head)<>null) then
25808 confusion("line breaking");
25809 @:this can't happen line breaking}{\quad line breaking@>
25810 prev_graf:=best_line-1;
25811 LR_save:=LR_ptr;
25812 end;
25813
25814 @ The job of reversing links in a list is conveniently regarded as the job
25815 of taking items off one stack and putting them on another. In this case we
25816 take them off a stack pointed to by |q| and having |prev_break| fields;
25817 we put them on a stack pointed to by |cur_p| and having |next_break| fields.
25818 Node |r| is the passive node being moved from stack to stack.
25819
25820 @<Reverse the links of the relevant passive nodes...@>=
25821 q:=break_node(best_bet); cur_p:=null;
25822 repeat r:=q; q:=prev_break(q); next_break(r):=cur_p; cur_p:=r;
25823 until q=null
25824
25825 @ Glue and penalty and kern and math nodes are deleted at the beginning of
25826 a line, except in the anomalous case that the node to be deleted is actually
25827 one of the chosen breakpoints. Otherwise
25828 the pruning done here is designed to match
25829 the lookahead computation in |try_break|, where the |break_width| values
25830 are computed for non-discretionary breakpoints.
25831
25832 @<Prune unwanted nodes at the beginning of the next line@>=
25833 begin r:=temp_head;
25834 loop@+ begin q:=link(r);
25835 if q=cur_break(cur_p) then goto done1;
25836 {|cur_break(cur_p)| is the next breakpoint}
25837 {now |q| cannot be |null|}
25838 if is_char_node(q) then goto done1;
25839 if non_discardable(q) then goto done1;
25840 if type(q)=kern_node then if subtype(q)<>explicit then goto done1;
25841 r:=q; {now |type(q)=glue_node|, |kern_node|, |math_node|, or |penalty_node|}
25842 if type(q)=math_node then if TeXXeT_en then
25843 @<Adjust \(t)the LR stack for the |post_line_break| routine@>;
25844 end;
25845 done1: if r<>temp_head then
25846 begin link(r):=null; flush_node_list(link(temp_head));
25847 link(temp_head):=q;
25848 end;
25849 end
25850
25851 @ The current line to be justified appears in a horizontal list starting
25852 at |link(temp_head)| and ending at |cur_break(cur_p)|. If |cur_break(cur_p)| is
25853 a glue node, we reset the glue to equal the |right_skip| glue; otherwise
25854 we append the |right_skip| glue at the right. If |cur_break(cur_p)| is a
25855 discretionary node, we modify the list so that the discretionary break
25856 is compulsory, and we set |disc_break| to |true|. We also append
25857 the |left_skip| glue at the left of the line, unless it is zero.
25858
25859 @<Justify the line ending at breakpoint |cur_p|, and append it...@>=
25860 if TeXXeT_en then
25861 @<Insert LR nodes at the beginning of the current line and adjust
25862 the LR stack based on LR nodes in this line@>;
25863 @<Modify the end of the line to reflect the nature of the break and to include
25864 \.{\\rightskip}; also set the proper value of |disc_break|@>;
25865 if TeXXeT_en then @<Insert LR nodes at the end of the current line@>;
25866 @<Put the \(l)\.{\\leftskip} glue at the left and detach this line@>;
25867 @<Call the packaging subroutine, setting |just_box| to the justified box@>;
25868 @<Append the new box to the current vertical list, followed by the list of
25869 special nodes taken out of the box by the packager@>;
25870 @<Append a penalty node, if a nonzero penalty is appropriate@>
25871
25872 @ At the end of the following code, |q| will point to the final node on the
25873 list about to be justified.
25874
25875 @<Modify the end of the line...@>=
25876 q:=cur_break(cur_p); disc_break:=false; post_disc_break:=false;
25877 glue_break := false;
25878 if q<>null then {|q| cannot be a |char_node|}
25879 if type(q)=glue_node then
25880 begin delete_glue_ref(glue_ptr(q));
25881 glue_ptr(q):=right_skip;
25882 subtype(q):=right_skip_code+1; add_glue_ref(right_skip);
25883 glue_break := true;
25884 goto done;
25885 end
25886 else begin if type(q)=disc_node then
25887 @<Change discretionary to compulsory and set
25888 |disc_break:=true|@>
25889 else if type(q)=kern_node then width(q):=0
25890 else if type(q)=math_node then
25891 begin width(q):=0;
25892 if TeXXeT_en then @<Adjust \(t)the LR stack for the |p...@>;
25893 end;
25894 end
25895 else begin q:=temp_head;
25896 while link(q)<>null do q:=link(q);
25897 end;
25898 done:
25899
25900 {at this point |q| is the rightmost breakpoint; the only exception is the case
25901 of a discretionary break with non-empty |pre_break|, then |q| has been changed
25902 to the last node of the |pre_break| list}
25903
25904 if pdf_protrude_chars > 0 then begin
25905 if disc_break and (is_char_node(q) or (type(q) <> disc_node))
25906 {|q| has been reset to the last node of |pre_break|}
25907 then begin
25908 p := q;
25909 ptmp := p;
25910 end else begin
25911 p := prev_rightmost(link(temp_head), q); {get |link(p) = q|}
25912 ptmp := p;
25913 p := find_protchar_right(link(temp_head), p);
25914 end;
25915 @{
25916 short_display_n(p, 1);
25917 print_ln;
25918 @}
25919 w := right_pw(p);
25920 if w <> 0 then {we have found a marginal kern, append it after |ptmp|}
25921 begin
25922 k := new_margin_kern(-w, last_rightmost_char, right_side);
25923 link(k) := link(ptmp);
25924 link(ptmp) := k;
25925 if (ptmp = q) then
25926 q := link(q);
25927 end;
25928 end;
25929
25930 {if |q| was not a breakpoint at glue and has been reset to |rightskip| then
25931 we append |rightskip| after |q| now}
25932 if not glue_break then begin
25933 @<Put the \(r)\.{\\rightskip} glue after node |q|@>;
25934 end;
25935
25936 @ @<Change discretionary to compulsory...@>=
25937 begin t:=replace_count(q);
25938 @<Destroy the |t| nodes following |q|, and
25939 make |r| point to the following node@>;
25940 if post_break(q)<>null then @<Transplant the post-break list@>;
25941 if pre_break(q)<>null then @<Transplant the pre-break list@>;
25942 link(q):=r; disc_break:=true;
25943 end
25944
25945 @ @<Destroy the |t| nodes following |q|...@>=
25946 if t=0 then r:=link(q)
25947 else begin r:=q;
25948 while t>1 do
25949 begin r:=link(r); decr(t);
25950 end;
25951 s:=link(r);
25952 r:=link(s); link(s):=null;
25953 flush_node_list(link(q)); replace_count(q):=0;
25954 end
25955
25956 @ We move the post-break list from inside node |q| to the main list by
25957 re\-attaching it just before the present node |r|, then resetting |r|.
25958
25959 @<Transplant the post-break list@>=
25960 begin s:=post_break(q);
25961 while link(s)<>null do s:=link(s);
25962 link(s):=r; r:=post_break(q); post_break(q):=null; post_disc_break:=true;
25963 end
25964
25965 @ We move the pre-break list from inside node |q| to the main list by
25966 re\-attaching it just after the present node |q|, then resetting |q|.
25967
25968 @<Transplant the pre-break list@>=
25969 begin s:=pre_break(q); link(q):=s;
25970 while link(s)<>null do s:=link(s);
25971 pre_break(q):=null; q:=s;
25972 end
25973
25974 @ @<Put the \(r)\.{\\rightskip} glue after node |q|@>=
25975 r:=new_param_glue(right_skip_code); link(r):=link(q); link(q):=r; q:=r
25976
25977 @ The following code begins with |q| at the end of the list to be
25978 justified. It ends with |q| at the beginning of that list, and with
25979 |link(temp_head)| pointing to the remainder of the paragraph, if any.
25980
25981 @<Put the \(l)\.{\\leftskip} glue at the left...@>=
25982 r:=link(q); link(q):=null; q:=link(temp_head); link(temp_head):=r;
25983 {at this point |q| is the leftmost node; all discardable nodes have been discarded}
25984 if pdf_protrude_chars > 0 then begin
25985 p := q;
25986 p := find_protchar_left(p, false); {no more discardables}
25987 w := left_pw(p);
25988 if w <> 0 then begin
25989 k := new_margin_kern(-w, last_leftmost_char, left_side);
25990 link(k) := q;
25991 q := k;
25992 end;
25993 end;
25994 if left_skip<>zero_glue then
25995 begin r:=new_param_glue(left_skip_code);
25996 link(r):=q; q:=r;
25997 end
25998
25999 @ @<Initialize table entries...@>=
26000 pdf_ignored_dimen := ignore_depth;
26001 pdf_each_line_height := pdf_ignored_dimen;
26002 pdf_each_line_depth := pdf_ignored_dimen;
26003 pdf_first_line_height := pdf_ignored_dimen;
26004 pdf_last_line_depth := pdf_ignored_dimen;
26005
26006 @ @<Append the new box to the current vertical list...@>=
26007 if pdf_each_line_height <> pdf_ignored_dimen then
26008 height(just_box) := pdf_each_line_height;
26009 if pdf_each_line_depth <> pdf_ignored_dimen then
26010 depth(just_box) := pdf_each_line_depth;
26011 if (pdf_first_line_height <> pdf_ignored_dimen) and (cur_line = prev_graf + 1) then
26012 height(just_box) := pdf_first_line_height;
26013 if (pdf_last_line_depth <> pdf_ignored_dimen) and (cur_line + 1 = best_line) then
26014 depth(just_box) := pdf_last_line_depth;
26015 if pre_adjust_head <> pre_adjust_tail then
26016 append_list(pre_adjust_head)(pre_adjust_tail);
26017 pre_adjust_tail := null;
26018 append_to_vlist(just_box);
26019 if adjust_head <> adjust_tail then
26020 append_list(adjust_head)(adjust_tail);
26021 adjust_tail := null
26022
26023 @ Now |q| points to the hlist that represents the current line of the
26024 paragraph. We need to compute the appropriate line width, pack the
26025 line into a box of this size, and shift the box by the appropriate
26026 amount of indentation.
26027
26028 @<Call the packaging subroutine...@>=
26029 if cur_line>last_special_line then
26030 begin cur_width:=second_width; cur_indent:=second_indent;
26031 end
26032 else if par_shape_ptr=null then
26033 begin cur_width:=first_width; cur_indent:=first_indent;
26034 end
26035 else begin cur_width:=mem[par_shape_ptr+2*cur_line].sc;
26036 cur_indent:=mem[par_shape_ptr+2*cur_line-1].sc;
26037 end;
26038 adjust_tail:=adjust_head;
26039 pre_adjust_tail := pre_adjust_head;
26040 if pdf_adjust_spacing > 0 then
26041 just_box := hpack(q, cur_width, cal_expand_ratio)
26042 else
26043 just_box := hpack(q, cur_width, exactly);
26044 shift_amount(just_box):=cur_indent
26045
26046 @ Penalties between the lines of a paragraph come from club and widow lines,
26047 from the |inter_line_penalty| parameter, and from lines that end at
26048 discretionary breaks. Breaking between lines of a two-line paragraph gets
26049 both club-line and widow-line penalties. The local variable |pen| will
26050 be set to the sum of all relevant penalties for the current line, except
26051 that the final line is never penalized.
26052
26053 @<Append a penalty node, if a nonzero penalty is appropriate@>=
26054 if cur_line+1<>best_line then
26055 begin q:=inter_line_penalties_ptr;
26056 if q<>null then
26057 begin r:=cur_line;
26058 if r>penalty(q) then r:=penalty(q);
26059 pen:=penalty(q+r);
26060 end
26061 else pen:=inter_line_penalty;
26062 q:=club_penalties_ptr;
26063 if q<>null then
26064 begin r:=cur_line-prev_graf;
26065 if r>penalty(q) then r:=penalty(q);
26066 pen:=pen+penalty(q+r);
26067 end
26068 else if cur_line=prev_graf+1 then pen:=pen+club_penalty;
26069 if d then q:=display_widow_penalties_ptr
26070 else q:=widow_penalties_ptr;
26071 if q<>null then
26072 begin r:=best_line-cur_line-1;
26073 if r>penalty(q) then r:=penalty(q);
26074 pen:=pen+penalty(q+r);
26075 end
26076 else if cur_line+2=best_line then
26077 if d then pen:=pen+display_widow_penalty
26078 else pen:=pen+widow_penalty;
26079 if disc_break then pen:=pen+broken_penalty;
26080 if pen<>0 then
26081 begin r:=new_penalty(pen);
26082 link(tail):=r; tail:=r;
26083 end;
26084 end
26085
26086 @* \[40] Pre-hyphenation.
26087 When the line-breaking routine is unable to find a feasible sequence of
26088 breakpoints, it makes a second pass over the paragraph, attempting to
26089 hyphenate the hyphenatable words. The goal of hyphenation is to insert
26090 discretionary material into the paragraph so that there are more
26091 potential places to break.
26092
26093 The general rules for hyphenation are somewhat complex and technical,
26094 because we want to be able to hyphenate words that are preceded or
26095 followed by punctuation marks, and because we want the rules to work
26096 for languages other than English. We also must contend with the fact
26097 that hyphens might radically alter the ligature and kerning structure
26098 of a word.
26099
26100 A sequence of characters will be considered for hyphenation only if it
26101 belongs to a ``potentially hyphenatable part'' of the current paragraph.
26102 This is a sequence of nodes $p_0p_1\ldots p_m$ where $p_0$ is a glue node,
26103 $p_1\ldots p_{m-1}$ are either character or ligature or whatsit or
26104 implicit kern or text direction nodes, and $p_m$ is a glue or penalty or
26105 insertion or adjust
26106 or mark or whatsit or explicit kern node. (Therefore hyphenation is
26107 disabled by boxes, math formulas, and discretionary nodes already inserted
26108 by the user.) The ligature nodes among $p_1\ldots p_{m-1}$ are effectively
26109 expanded into the original non-ligature characters; the kern nodes and
26110 whatsits are ignored. Each character |c| is now classified as either a
26111 nonletter (if |lc_code(c)=0|), a lowercase letter (if
26112 |lc_code(c)=c|), or an uppercase letter (otherwise); an uppercase letter
26113 is treated as if it were |lc_code(c)| for purposes of hyphenation. The
26114 characters generated by $p_1\ldots p_{m-1}$ may begin with nonletters; let
26115 $c_1$ be the first letter that is not in the middle of a ligature. Whatsit
26116 nodes preceding $c_1$ are ignored; a whatsit found after $c_1$ will be the
26117 terminating node $p_m$. All characters that do not have the same font as
26118 $c_1$ will be treated as nonletters. The |hyphen_char| for that font
26119 must be between 0 and 255, otherwise hyphenation will not be attempted.
26120 \TeX\ looks ahead for as many consecutive letters $c_1\ldots c_n$ as
26121 possible; however, |n| must be less than 64, so a character that would
26122 otherwise be $c_{64}$ is effectively not a letter. Furthermore $c_n$ must
26123 not be in the middle of a ligature. In this way we obtain a string of
26124 letters $c_1\ldots c_n$ that are generated by nodes $p_a\ldots p_b$, where
26125 |1<=a<=b+1<=m|. If |n>=l_hyf+r_hyf|, this string qualifies for hyphenation;
26126 however, |uc_hyph| must be positive, if $c_1$ is uppercase.
26127
26128 The hyphenation process takes place in three stages. First, the candidate
26129 sequence $c_1\ldots c_n$ is found; then potential positions for hyphens
26130 are determined by referring to hyphenation tables; and finally, the nodes
26131 $p_a\ldots p_b$ are replaced by a new sequence of nodes that includes the
26132 discretionary breaks found.
26133
26134 Fortunately, we do not have to do all this calculation very often, because
26135 of the way it has been taken out of \TeX's inner loop. For example, when
26136 the second edition of the author's 700-page book {\sl Seminumerical
26137 Algorithms} was typeset by \TeX, only about 1.2 hyphenations needed to be
26138 @^Knuth, Donald Ervin@>
26139 tried per paragraph, since the line breaking algorithm needed to use two
26140 passes on only about 5 per cent of the paragraphs.
26141
26142 @<Initialize for hyphenating...@>=
26143 begin @!init if trie_not_ready then init_trie;@+tini@;@/
26144 cur_lang:=init_cur_lang; l_hyf:=init_l_hyf; r_hyf:=init_r_hyf;
26145 set_hyph_index;
26146 end
26147
26148 @ The letters $c_1\ldots c_n$ that are candidates for hyphenation are placed
26149 into an array called |hc|; the number |n| is placed into |hn|; pointers to
26150 nodes $p_{a-1}$ and~$p_b$ in the description above are placed into variables
26151 |ha| and |hb|; and the font number is placed into |hf|.
26152
26153 @<Glob...@>=
26154 @!hc:array[0..65] of 0..256; {word to be hyphenated}
26155 @!hn:0..64; {the number of positions occupied in |hc|;
26156 not always a |small_number|}
26157 @!ha,@!hb:pointer; {nodes |ha..hb| should be replaced by the hyphenated result}
26158 @!hf:internal_font_number; {font number of the letters in |hc|}
26159 @!hu:array[0..63] of 0..256; {like |hc|, before conversion to lowercase}
26160 @!hyf_char:integer; {hyphen character of the relevant font}
26161 @!cur_lang,@!init_cur_lang:ASCII_code; {current hyphenation table of interest}
26162 @!l_hyf,@!r_hyf,@!init_l_hyf,@!init_r_hyf:integer; {limits on fragment sizes}
26163 @!hyf_bchar:halfword; {boundary character after $c_n$}
26164
26165 @ Hyphenation routines need a few more local variables.
26166
26167 @<Local variables for line...@>=
26168 @!j:small_number; {an index into |hc| or |hu|}
26169 @!c:0..255; {character being considered for hyphenation}
26170
26171 @ When the following code is activated, the |line_break| procedure is in its
26172 second pass, and |cur_p| points to a glue node.
26173
26174 @<Try to hyphenate...@>=
26175 begin prev_s:=cur_p; s:=link(prev_s);
26176 if s<>null then
26177 begin @<Skip to node |ha|, or |goto done1| if no hyphenation
26178 should be attempted@>;
26179 if l_hyf+r_hyf>63 then goto done1;
26180 @<Skip to node |hb|, putting letters into |hu| and |hc|@>;
26181 @<Check that the nodes following |hb| permit hyphenation and that at least
26182 |l_hyf+r_hyf| letters have been found, otherwise |goto done1|@>;
26183 hyphenate;
26184 end;
26185 done1: end
26186
26187 @ @<Declare subprocedures for |line_break|@>=
26188 @t\4@>@<Declare the function called |reconstitute|@>
26189 procedure hyphenate;
26190 label common_ending,done,found,found1,found2,not_found,exit;
26191 var @<Local variables for hyphenation@>@;
26192 begin @<Find hyphen locations for the word in |hc|, or |return|@>;
26193 @<If no hyphens were found, |return|@>;
26194 @<Replace nodes |ha..hb| by a sequence of nodes that includes
26195 the discretionary hyphens@>;
26196 exit:end;
26197
26198 @ The first thing we need to do is find the node |ha| just before the
26199 first letter.
26200
26201 @<Skip to node |ha|, or |goto done1|...@>=
26202 loop@+ begin if is_char_node(s) then
26203 begin c:=qo(character(s)); hf:=font(s);
26204 end
26205 else if type(s)=ligature_node then
26206 if lig_ptr(s)=null then goto continue
26207 else begin q:=lig_ptr(s); c:=qo(character(q)); hf:=font(q);
26208 end
26209 else if (type(s)=kern_node)and(subtype(s)=normal) then goto continue
26210 else if (type(s)=math_node)and(subtype(s)>=L_code) then goto continue
26211 else if type(s)=whatsit_node then
26212 begin @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>;
26213 goto continue;
26214 end
26215 else goto done1;
26216 set_lc_code(c);
26217 if hc[0]<>0 then
26218 if (hc[0]=c)or(uc_hyph>0) then goto done2
26219 else goto done1;
26220 continue: prev_s:=s; s:=link(prev_s);
26221 end;
26222 done2: hyf_char:=hyphen_char[hf];
26223 if hyf_char<0 then goto done1;
26224 if hyf_char>255 then goto done1;
26225 ha:=prev_s
26226
26227 @ The word to be hyphenated is now moved to the |hu| and |hc| arrays.
26228
26229 @<Skip to node |hb|, putting letters...@>=
26230 hn:=0;
26231 loop@+ begin if is_char_node(s) then
26232 begin if font(s)<>hf then goto done3;
26233 hyf_bchar:=character(s); c:=qo(hyf_bchar);
26234 set_lc_code(c);
26235 if hc[0]=0 then goto done3;
26236 if hn=63 then goto done3;
26237 hb:=s; incr(hn); hu[hn]:=c; hc[hn]:=hc[0]; hyf_bchar:=non_char;
26238 end
26239 else if type(s)=ligature_node then
26240 @<Move the characters of a ligature node to |hu| and |hc|;
26241 but |goto done3| if they are not all letters@>
26242 else if (type(s)=kern_node)and(subtype(s)=normal) then
26243 begin hb:=s;
26244 hyf_bchar:=font_bchar[hf];
26245 end
26246 else goto done3;
26247 s:=link(s);
26248 end;
26249 done3:
26250
26251 @ We let |j| be the index of the character being stored when a ligature node
26252 is being expanded, since we do not want to advance |hn| until we are sure
26253 that the entire ligature consists of letters. Note that it is possible
26254 to get to |done3| with |hn=0| and |hb| not set to any value.
26255
26256 @<Move the characters of a ligature node to |hu| and |hc|...@>=
26257 begin if font(lig_char(s))<>hf then goto done3;
26258 j:=hn; q:=lig_ptr(s);@+if q>null then hyf_bchar:=character(q);
26259 while q>null do
26260 begin c:=qo(character(q));
26261 set_lc_code(c);
26262 if hc[0]=0 then goto done3;
26263 if j=63 then goto done3;
26264 incr(j); hu[j]:=c; hc[j]:=hc[0];@/
26265 q:=link(q);
26266 end;
26267 hb:=s; hn:=j;
26268 if odd(subtype(s)) then hyf_bchar:=font_bchar[hf]@+else hyf_bchar:=non_char;
26269 end
26270
26271 @ @<Check that the nodes following |hb| permit hyphenation...@>=
26272 if hn<l_hyf+r_hyf then goto done1; {|l_hyf| and |r_hyf| are |>=1|}
26273 loop@+ begin if not(is_char_node(s)) then
26274 case type(s) of
26275 ligature_node: do_nothing;
26276 kern_node: if subtype(s)<>normal then goto done4;
26277 whatsit_node,glue_node,penalty_node,ins_node,adjust_node,mark_node:
26278 goto done4;
26279 math_node: if subtype(s)>=L_code then goto done4@+else goto done1;
26280 othercases goto done1
26281 endcases;
26282 s:=link(s);
26283 end;
26284 done4:
26285
26286 @* \[41] Post-hyphenation.
26287 If a hyphen may be inserted between |hc[j]| and |hc[j+1]|, the hyphenation
26288 procedure will set |hyf[j]| to some small odd number. But before we look
26289 at \TeX's hyphenation procedure, which is independent of the rest of the
26290 line-breaking algorithm, let us consider what we will do with the hyphens
26291 it finds, since it is better to work on this part of the program before
26292 forgetting what |ha| and |hb|, etc., are all about.
26293
26294 @<Glob...@>=
26295 @!hyf:array [0..64] of 0..9; {odd values indicate discretionary hyphens}
26296 @!init_list:pointer; {list of punctuation characters preceding the word}
26297 @!init_lig:boolean; {does |init_list| represent a ligature?}
26298 @!init_lft:boolean; {if so, did the ligature involve a left boundary?}
26299
26300 @ @<Local variables for hyphenation@>=
26301 @!i,@!j,@!l:0..65; {indices into |hc| or |hu|}
26302 @!q,@!r,@!s:pointer; {temporary registers for list manipulation}
26303 @!bchar:halfword; {boundary character of hyphenated word, or |non_char|}
26304
26305 @ \TeX\ will never insert a hyphen that has fewer than
26306 \.{\\lefthyphenmin} letters before it or fewer than
26307 \.{\\righthyphenmin} after it; hence, a short word has
26308 comparatively little chance of being hyphenated. If no hyphens have
26309 been found, we can save time by not having to make any changes to the
26310 paragraph.
26311
26312 @<If no hyphens were found, |return|@>=
26313 for j:=l_hyf to hn-r_hyf do if odd(hyf[j]) then goto found1;
26314 return;
26315 found1:
26316
26317 @ If hyphens are in fact going to be inserted, \TeX\ first deletes the
26318 subsequence of nodes between |ha| and~|hb|. An attempt is made to
26319 preserve the effect that implicit boundary characters and punctuation marks
26320 had on ligatures inside the hyphenated word, by storing a left boundary or
26321 preceding character in |hu[0]| and by storing a possible right boundary
26322 in |bchar|. We set |j:=0| if |hu[0]| is to be part of the reconstruction;
26323 otherwise |j:=1|.
26324 The variable |s| will point to the tail of the current hlist, and
26325 |q| will point to the node following |hb|, so that
26326 things can be hooked up after we reconstitute the hyphenated word.
26327
26328 @<Replace nodes |ha..hb| by a sequence of nodes...@>=
26329 q:=link(hb); link(hb):=null; r:=link(ha); link(ha):=null; bchar:=hyf_bchar;
26330 if is_char_node(ha) then
26331 if font(ha)<>hf then goto found2
26332 else begin init_list:=ha; init_lig:=false; hu[0]:=qo(character(ha));
26333 end
26334 else if type(ha)=ligature_node then
26335 if font(lig_char(ha))<>hf then goto found2
26336 else begin init_list:=lig_ptr(ha); init_lig:=true; init_lft:=(subtype(ha)>1);
26337 hu[0]:=qo(character(lig_char(ha)));
26338 if init_list=null then if init_lft then
26339 begin hu[0]:=256; init_lig:=false;
26340 end; {in this case a ligature will be reconstructed from scratch}
26341 free_node(ha,small_node_size);
26342 end
26343 else begin {no punctuation found; look for left boundary}
26344 if not is_char_node(r) then if type(r)=ligature_node then
26345 if subtype(r)>1 then goto found2;
26346 j:=1; s:=ha; init_list:=null; goto common_ending;
26347 end;
26348 s:=cur_p; {we have |cur_p<>ha| because |type(cur_p)=glue_node|}
26349 while link(s)<>ha do s:=link(s);
26350 j:=0; goto common_ending;
26351 found2: s:=ha; j:=0; hu[0]:=256; init_lig:=false; init_list:=null;
26352 common_ending: flush_node_list(r);
26353 @<Reconstitute nodes for the hyphenated word, inserting discretionary hyphens@>;
26354 flush_list(init_list)
26355
26356 @ We must now face the fact that the battle is not over, even though the
26357 {\def\!{\kern-1pt}%
26358 hyphens have been found: The process of reconstituting a word can be nontrivial
26359 because ligatures might change when a hyphen is present. {\sl The \TeX book\/}
26360 discusses the difficulties of the word ``difficult'', and
26361 the discretionary material surrounding a
26362 hyphen can be considerably more complex than that. Suppose
26363 \.{abcdef} is a word in a font for which the only ligatures are \.{b\!c},
26364 \.{c\!d}, \.{d\!e}, and \.{e\!f}. If this word permits hyphenation
26365 between \.b and \.c, the two patterns with and without hyphenation are
26366 $\.a\,\.b\,\.-\,\.{c\!d}\,\.{e\!f}$ and $\.a\,\.{b\!c}\,\.{d\!e}\,\.f$.
26367 Thus the insertion of a hyphen might cause effects to ripple arbitrarily
26368 far into the rest of the word. A further complication arises if additional
26369 hyphens appear together with such rippling, e.g., if the word in the
26370 example just given could also be hyphenated between \.c and \.d; \TeX\
26371 avoids this by simply ignoring the additional hyphens in such weird cases.}
26372
26373 Still further complications arise in the presence of ligatures that do not
26374 delete the original characters. When punctuation precedes the word being
26375 hyphenated, \TeX's method is not perfect under all possible scenarios,
26376 because punctuation marks and letters can propagate information back and forth.
26377 For example, suppose the original pre-hyphenation pair
26378 \.{*a} changes to \.{*y} via a \.{\?=:} ligature, which changes to \.{xy}
26379 via a \.{=:\?} ligature; if $p_{a-1}=\.x$ and $p_a=\.y$, the reconstitution
26380 procedure isn't smart enough to obtain \.{xy} again. In such cases the
26381 font designer should include a ligature that goes from \.{xa} to \.{xy}.
26382
26383 @ The processing is facilitated by a subroutine called |reconstitute|. Given
26384 a string of characters $x_j\ldots x_n$, there is a smallest index $m\ge j$
26385 such that the ``translation'' of $x_j\ldots x_n$ by ligatures and kerning
26386 has the form $y_1\ldots y_t$ followed by the translation of $x_{m+1}\ldots x_n$,
26387 where $y_1\ldots y_t$ is some nonempty sequence of character, ligature, and
26388 kern nodes. We call $x_j\ldots x_m$ a ``cut prefix'' of $x_j\ldots x_n$.
26389 For example, if $x_1x_2x_3=\.{fly}$, and if the font contains `fl' as a
26390 ligature and a kern between `fl' and `y', then $m=2$, $t=2$, and $y_1$ will
26391 be a ligature node for `fl' followed by an appropriate kern node~$y_2$.
26392 In the most common case, $x_j$~forms no ligature with $x_{j+1}$ and we
26393 simply have $m=j$, $y_1=x_j$. If $m<n$ we can repeat the procedure on
26394 $x_{m+1}\ldots x_n$ until the entire translation has been found.
26395
26396 The |reconstitute| function returns the integer $m$ and puts the nodes
26397 $y_1\ldots y_t$ into a linked list starting at |link(hold_head)|,
26398 getting the input $x_j\ldots x_n$ from the |hu| array. If $x_j=256$,
26399 we consider $x_j$ to be an implicit left boundary character; in this
26400 case |j| must be strictly less than~|n|. There is a
26401 parameter |bchar|, which is either 256 or an implicit right boundary character
26402 assumed to be present just following~$x_n$. (The value |hu[n+1]| is never
26403 explicitly examined, but the algorithm imagines that |bchar| is there.)
26404
26405 If there exists an index |k| in the range $j\le k\le m$ such that |hyf[k]|
26406 is odd and such that the result of |reconstitute| would have been different
26407 if $x_{k+1}$ had been |hchar|, then |reconstitute| sets |hyphen_passed|
26408 to the smallest such~|k|. Otherwise it sets |hyphen_passed| to zero.
26409
26410 A special convention is used in the case |j=0|: Then we assume that the
26411 translation of |hu[0]| appears in a special list of charnodes starting at
26412 |init_list|; moreover, if |init_lig| is |true|, then |hu[0]| will be
26413 a ligature character, involving a left boundary if |init_lft| is |true|.
26414 This facility is provided for cases when a hyphenated
26415 word is preceded by punctuation (like single or double quotes) that might
26416 affect the translation of the beginning of the word.
26417
26418 @<Glob...@>=
26419 @!hyphen_passed:small_number; {first hyphen in a ligature, if any}
26420
26421 @ @<Declare the function called |reconstitute|@>=
26422 function reconstitute(@!j,@!n:small_number;@!bchar,@!hchar:halfword):
26423 small_number;
26424 label continue,done;
26425 var @!p:pointer; {temporary register for list manipulation}
26426 @!t:pointer; {a node being appended to}
26427 @!q:four_quarters; {character information or a lig/kern instruction}
26428 @!cur_rh:halfword; {hyphen character for ligature testing}
26429 @!test_char:halfword; {hyphen or other character for ligature testing}
26430 @!w:scaled; {amount of kerning}
26431 @!k:font_index; {position of current lig/kern instruction}
26432 begin hyphen_passed:=0; t:=hold_head; w:=0; link(hold_head):=null;
26433 {at this point |ligature_present=lft_hit=rt_hit=false|}
26434 @<Set up data structures with the cursor following position |j|@>;
26435 continue:@<If there's a ligature or kern at the cursor position, update the data
26436 structures, possibly advancing~|j|; continue until the cursor moves@>;
26437 @<Append a ligature and/or kern to the translation;
26438 |goto continue| if the stack of inserted ligatures is nonempty@>;
26439 reconstitute:=j;
26440 end;
26441
26442 @ The reconstitution procedure shares many of the global data structures
26443 by which \TeX\ has processed the words before they were hyphenated.
26444 There is an implied ``cursor'' between characters |cur_l| and |cur_r|;
26445 these characters will be tested for possible ligature activity. If
26446 |ligature_present| then |cur_l| is a ligature character formed from the
26447 original characters following |cur_q| in the current translation list.
26448 There is a ``ligature stack'' between the cursor and character |j+1|,
26449 consisting of pseudo-ligature nodes linked together by their |link| fields.
26450 This stack is normally empty unless a ligature command has created a new
26451 character that will need to be processed later. A pseudo-ligature is
26452 a special node having a |character| field that represents a potential
26453 ligature and a |lig_ptr| field that points to a |char_node| or is |null|.
26454 We have
26455 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
26456 |qi(hu[j+1])|,&if |lig_stack=null| and |j<n|;\cr
26457 bchar,&if |lig_stack=null| and |j=n|.\cr}$$
26458
26459 @<Glob...@>=
26460 @!cur_l,@!cur_r:halfword; {characters before and after the cursor}
26461 @!cur_q:pointer; {where a ligature should be detached}
26462 @!lig_stack:pointer; {unfinished business to the right of the cursor}
26463 @!ligature_present:boolean; {should a ligature node be made for |cur_l|?}
26464 @!lft_hit,@!rt_hit:boolean; {did we hit a ligature with a boundary character?}
26465
26466 @ @d append_charnode_to_t(#)== begin link(t):=get_avail; t:=link(t);
26467 font(t):=hf; character(t):=#;
26468 end
26469 @d set_cur_r==begin if j<n then cur_r:=qi(hu[j+1])@+else cur_r:=bchar;
26470 if odd(hyf[j]) then cur_rh:=hchar@+else cur_rh:=non_char;
26471 end
26472
26473 @<Set up data structures with the cursor following position |j|@>=
26474 cur_l:=qi(hu[j]); cur_q:=t;
26475 if j=0 then
26476 begin ligature_present:=init_lig; p:=init_list;
26477 if ligature_present then lft_hit:=init_lft;
26478 while p>null do
26479 begin append_charnode_to_t(character(p)); p:=link(p);
26480 end;
26481 end
26482 else if cur_l<non_char then append_charnode_to_t(cur_l);
26483 lig_stack:=null; set_cur_r
26484
26485 @ We may want to look at the lig/kern program twice, once for a hyphen
26486 and once for a normal letter. (The hyphen might appear after the letter
26487 in the program, so we'd better not try to look for both at once.)
26488
26489 @<If there's a ligature or kern at the cursor position, update...@>=
26490 if cur_l=non_char then
26491 begin k:=bchar_label[hf];
26492 if k=non_address then goto done@+else q:=font_info[k].qqqq;
26493 end
26494 else begin q:=char_info(hf)(cur_l);
26495 if char_tag(q)<>lig_tag then goto done;
26496 k:=lig_kern_start(hf)(q); q:=font_info[k].qqqq;
26497 if skip_byte(q)>stop_flag then
26498 begin k:=lig_kern_restart(hf)(q); q:=font_info[k].qqqq;
26499 end;
26500 end; {now |k| is the starting address of the lig/kern program}
26501 if cur_rh<non_char then test_char:=cur_rh@+else test_char:=cur_r;
26502 loop@+begin if next_char(q)=test_char then if skip_byte(q)<=stop_flag then
26503 if cur_rh<non_char then
26504 begin hyphen_passed:=j; hchar:=non_char; cur_rh:=non_char;
26505 goto continue;
26506 end
26507 else begin if hchar<non_char then if odd(hyf[j]) then
26508 begin hyphen_passed:=j; hchar:=non_char;
26509 end;
26510 if op_byte(q)<kern_flag then
26511 @<Carry out a ligature replacement, updating the cursor structure
26512 and possibly advancing~|j|; |goto continue| if the cursor doesn't
26513 advance, otherwise |goto done|@>;
26514 w:=char_kern(hf)(q); goto done; {this kern will be inserted below}
26515 end;
26516 if skip_byte(q)>=stop_flag then
26517 if cur_rh=non_char then goto done
26518 else begin cur_rh:=non_char; goto continue;
26519 end;
26520 k:=k+qo(skip_byte(q))+1; q:=font_info[k].qqqq;
26521 end;
26522 done:
26523
26524 @ @d wrap_lig(#)==if ligature_present then
26525 begin p:=new_ligature(hf,cur_l,link(cur_q));
26526 if lft_hit then
26527 begin subtype(p):=2; lft_hit:=false;
26528 end;
26529 if # then if lig_stack=null then
26530 begin incr(subtype(p)); rt_hit:=false;
26531 end;
26532 link(cur_q):=p; t:=p; ligature_present:=false;
26533 end
26534 @d pop_lig_stack==begin if lig_ptr(lig_stack)>null then
26535 begin link(t):=lig_ptr(lig_stack); {this is a charnode for |hu[j+1]|}
26536 t:=link(t); incr(j);
26537 end;
26538 p:=lig_stack; lig_stack:=link(p); free_node(p,small_node_size);
26539 if lig_stack=null then set_cur_r@+else cur_r:=character(lig_stack);
26540 end {if |lig_stack| isn't |null| we have |cur_rh=non_char|}
26541
26542 @<Append a ligature and/or kern to the translation...@>=
26543 wrap_lig(rt_hit);
26544 if w<>0 then
26545 begin link(t):=new_kern(w); t:=link(t); w:=0;
26546 end;
26547 if lig_stack>null then
26548 begin cur_q:=t; cur_l:=character(lig_stack); ligature_present:=true;
26549 pop_lig_stack; goto continue;
26550 end
26551
26552 @ @<Carry out a ligature replacement, updating the cursor structure...@>=
26553 begin if cur_l=non_char then lft_hit:=true;
26554 if j=n then if lig_stack=null then rt_hit:=true;
26555 check_interrupt; {allow a way out in case there's an infinite ligature loop}
26556 case op_byte(q) of
26557 qi(1),qi(5):begin cur_l:=rem_byte(q); {\.{=:\?}, \.{=:\?>}}
26558 ligature_present:=true;
26559 end;
26560 qi(2),qi(6):begin cur_r:=rem_byte(q); {\.{\?=:}, \.{\?=:>}}
26561 if lig_stack>null then character(lig_stack):=cur_r
26562 else begin lig_stack:=new_lig_item(cur_r);
26563 if j=n then bchar:=non_char
26564 else begin p:=get_avail; lig_ptr(lig_stack):=p;
26565 character(p):=qi(hu[j+1]); font(p):=hf;
26566 end;
26567 end;
26568 end;
26569 qi(3):begin cur_r:=rem_byte(q); {\.{\?=:\?}}
26570 p:=lig_stack; lig_stack:=new_lig_item(cur_r); link(lig_stack):=p;
26571 end;
26572 qi(7),qi(11):begin wrap_lig(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
26573 cur_q:=t; cur_l:=rem_byte(q); ligature_present:=true;
26574 end;
26575 othercases begin cur_l:=rem_byte(q); ligature_present:=true; {\.{=:}}
26576 if lig_stack>null then pop_lig_stack
26577 else if j=n then goto done
26578 else begin append_charnode_to_t(cur_r); incr(j); set_cur_r;
26579 end;
26580 end
26581 endcases;
26582 if op_byte(q)>qi(4) then if op_byte(q)<>qi(7) then goto done;
26583 goto continue;
26584 end
26585
26586 @ Okay, we're ready to insert the potential hyphenations that were found.
26587 When the following program is executed, we want to append the word
26588 |hu[1..hn]| after node |ha|, and node |q| should be appended to the result.
26589 During this process, the variable |i| will be a temporary
26590 index into |hu|; the variable |j| will be an index to our current position
26591 in |hu|; the variable |l| will be the counterpart of |j|, in a discretionary
26592 branch; the variable |r| will point to new nodes being created; and
26593 we need a few new local variables:
26594
26595 @<Local variables for hyph...@>=
26596 @!major_tail,@!minor_tail:pointer; {the end of lists in the main and
26597 discretionary branches being reconstructed}
26598 @!c:ASCII_code; {character temporarily replaced by a hyphen}
26599 @!c_loc:0..63; {where that character came from}
26600 @!r_count:integer; {replacement count for discretionary}
26601 @!hyf_node:pointer; {the hyphen, if it exists}
26602
26603 @ When the following code is performed, |hyf[0]| and |hyf[hn]| will be zero.
26604
26605 @<Reconstitute nodes for the hyphenated word...@>=
26606 repeat l:=j; j:=reconstitute(j,hn,bchar,qi(hyf_char))+1;
26607 if hyphen_passed=0 then
26608 begin link(s):=link(hold_head);
26609 while link(s)>null do s:=link(s);
26610 if odd(hyf[j-1]) then
26611 begin l:=j; hyphen_passed:=j-1; link(hold_head):=null;
26612 end;
26613 end;
26614 if hyphen_passed>0 then
26615 @<Create and append a discretionary node as an alternative to the
26616 unhyphenated word, and continue to develop both branches until they
26617 become equivalent@>;
26618 until j>hn;
26619 link(s):=q
26620
26621 @ In this repeat loop we will insert another discretionary if |hyf[j-1]| is
26622 odd, when both branches of the previous discretionary end at position |j-1|.
26623 Strictly speaking, we aren't justified in doing this, because we don't know
26624 that a hyphen after |j-1| is truly independent of those branches. But in almost
26625 all applications we would rather not lose a potentially valuable hyphenation
26626 point. (Consider the word `difficult', where the letter `c' is in position |j|.)
26627
26628 @d advance_major_tail==begin major_tail:=link(major_tail); incr(r_count);
26629 end
26630
26631 @<Create and append a discretionary node as an alternative...@>=
26632 repeat r:=get_node(small_node_size);
26633 link(r):=link(hold_head); type(r):=disc_node;
26634 major_tail:=r; r_count:=0;
26635 while link(major_tail)>null do advance_major_tail;
26636 i:=hyphen_passed; hyf[i]:=0;
26637 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>;
26638 @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|, appending to this
26639 list and to |major_tail| until synchronization has been achieved@>;
26640 @<Move pointer |s| to the end of the current list, and set |replace_count(r)|
26641 appropriately@>;
26642 hyphen_passed:=j-1; link(hold_head):=null;
26643 until not odd(hyf[j-1])
26644
26645 @ The new hyphen might combine with the previous character via ligature
26646 or kern. At this point we have |l-1<=i<j| and |i<hn|.
26647
26648 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>=
26649 minor_tail:=null; pre_break(r):=null; hyf_node:=new_character(hf,hyf_char);
26650 if hyf_node<>null then
26651 begin incr(i); c:=hu[i]; hu[i]:=hyf_char; free_avail(hyf_node);
26652 end;
26653 while l<=i do
26654 begin l:=reconstitute(l,i,font_bchar[hf],non_char)+1;
26655 if link(hold_head)>null then
26656 begin if minor_tail=null then pre_break(r):=link(hold_head)
26657 else link(minor_tail):=link(hold_head);
26658 minor_tail:=link(hold_head);
26659 while link(minor_tail)>null do minor_tail:=link(minor_tail);
26660 end;
26661 end;
26662 if hyf_node<>null then
26663 begin hu[i]:=c; {restore the character in the hyphen position}
26664 l:=i; decr(i);
26665 end
26666
26667 @ The synchronization algorithm begins with |l=i+1<=j|.
26668
26669 @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|...@>=
26670 minor_tail:=null; post_break(r):=null; c_loc:=0;
26671 if bchar_label[hf]<>non_address then {put left boundary at beginning of new line}
26672 begin decr(l); c:=hu[l]; c_loc:=l; hu[l]:=256;
26673 end;
26674 while l<j do
26675 begin repeat l:=reconstitute(l,hn,bchar,non_char)+1;
26676 if c_loc>0 then
26677 begin hu[c_loc]:=c; c_loc:=0;
26678 end;
26679 if link(hold_head)>null then
26680 begin if minor_tail=null then post_break(r):=link(hold_head)
26681 else link(minor_tail):=link(hold_head);
26682 minor_tail:=link(hold_head);
26683 while link(minor_tail)>null do minor_tail:=link(minor_tail);
26684 end;
26685 until l>=j;
26686 while l>j do
26687 @<Append characters of |hu[j..@,]| to |major_tail|, advancing~|j|@>;
26688 end
26689
26690 @ @<Append characters of |hu[j..@,]|...@>=
26691 begin j:=reconstitute(j,hn,bchar,non_char)+1;
26692 link(major_tail):=link(hold_head);
26693 while link(major_tail)>null do advance_major_tail;
26694 end
26695
26696 @ Ligature insertion can cause a word to grow exponentially in size. Therefore
26697 we must test the size of |r_count| here, even though the hyphenated text
26698 was at most 63 characters long.
26699
26700 @<Move pointer |s| to the end of the current list...@>=
26701 if r_count>127 then {we have to forget the discretionary hyphen}
26702 begin link(s):=link(r); link(r):=null; flush_node_list(r);
26703 end
26704 else begin link(s):=r; replace_count(r):=r_count;
26705 end;
26706 s:=major_tail
26707
26708 @* \[42] Hyphenation.
26709 When a word |hc[1..hn]| has been set up to contain a candidate for hyphenation,
26710 \TeX\ first looks to see if it is in the user's exception dictionary. If not,
26711 hyphens are inserted based on patterns that appear within the given word,
26712 using an algorithm due to Frank~M. Liang.
26713 @^Liang, Franklin Mark@>
26714
26715 Let's consider Liang's method first, since it is much more interesting than the
26716 exception-lookup routine. The algorithm begins by setting |hyf[j]| to zero
26717 for all |j|, and invalid characters are inserted into |hc[0]|
26718 and |hc[hn+1]| to serve as delimiters. Then a reasonably fast method is
26719 used to see which of a given set of patterns occurs in the word
26720 |hc[0..(hn+1)]|. Each pattern $p_1\ldots p_k$ of length |k| has an associated
26721 sequence of |k+1| numbers $n_0\ldots n_k$; and if the pattern occurs in
26722 |hc[(j+1)..(j+k)]|, \TeX\ will set |hyf[j+i]:=@tmax@>(hyf[j+i],@t$n_i$@>)| for
26723 |0<=i<=k|. After this has been done for each pattern that occurs, a
26724 discretionary hyphen will be inserted between |hc[j]| and |hc[j+1]| when
26725 |hyf[j]| is odd, as we have already seen.
26726
26727 The set of patterns $p_1\ldots p_k$ and associated numbers $n_0\ldots n_k$
26728 depends, of course, on the language whose words are being hyphenated, and
26729 on the degree of hyphenation that is desired. A method for finding
26730 appropriate |p|'s and |n|'s, from a given dictionary of words and acceptable
26731 hyphenations, is discussed in Liang's Ph.D. thesis (Stanford University,
26732 1983); \TeX\ simply starts with the patterns and works from there.
26733
26734 @ The patterns are stored in a compact table that is also efficient for
26735 retrieval, using a variant of ``trie memory'' [cf.\ {\sl The Art of
26736 Computer Programming \bf3} (1973), 481--505]. We can find each pattern
26737 $p_1\ldots p_k$ by letting $z_0$ be one greater than the relevant language
26738 index and then, for |1<=i<=k|,
26739 setting |@t$z_i$@>:=trie_link@t$(z_{i-1})+p_i$@>|; the pattern will be
26740 identified by the number $z_k$. Since all the pattern information is
26741 packed together into a single |trie_link| array, it is necessary to
26742 prevent confusion between the data from inequivalent patterns, so another
26743 table is provided such that |trie_char@t$(z_i)=p_i$@>| for all |i|. There
26744 is also a table |trie_op|$(z_k)$ to identify the numbers $n_0\ldots n_k$
26745 associated with $p_1\ldots p_k$.
26746
26747 Comparatively few different number sequences $n_0\ldots n_k$ actually occur,
26748 since most of the |n|'s are generally zero. Therefore the number sequences
26749 are encoded in such a way that |trie_op|$(z_k)$ is only one byte long.
26750 If |trie_op(@t$z_k$@>)<>min_quarterword|, when $p_1\ldots p_k$ has matched
26751 the letters in |hc[(l-k+1)..l@,]| of language |t|,
26752 we perform all of the required operations
26753 for this pattern by carrying out the following little program: Set
26754 |v:=trie_op(@t$z_k$@>)|. Then set |v:=v+op_start[t]|,
26755 |hyf[l-hyf_distance[v]]:=@tmax@>(hyf[l-hyf_distance[v]], hyf_num[v])|,
26756 and |v:=hyf_next[v]|; repeat, if necessary, until |v=min_quarterword|.
26757
26758 @<Types...@>=
26759 @!trie_pointer=0..trie_size; {an index into |trie|}
26760
26761 @ @d trie_link(#)==trie[#].rh {``downward'' link in a trie}
26762 @d trie_char(#)==trie[#].b1 {character matched at this trie location}
26763 @d trie_op(#)==trie[#].b0 {program for hyphenation at this trie location}
26764
26765 @<Glob...@>=
26766 @!trie:array[trie_pointer] of two_halves; {|trie_link|, |trie_char|, |trie_op|}
26767 @!hyf_distance:array[1..trie_op_size] of small_number; {position |k-j| of $n_j$}
26768 @!hyf_num:array[1..trie_op_size] of small_number; {value of $n_j$}
26769 @!hyf_next:array[1..trie_op_size] of quarterword; {continuation code}
26770 @!op_start:array[ASCII_code] of 0..trie_op_size; {offset for current language}
26771
26772 @ @<Local variables for hyph...@>=
26773 @!z:trie_pointer; {an index into |trie|}
26774 @!v:integer; {an index into |hyf_distance|, etc.}
26775
26776 @ Assuming that these auxiliary tables have been set up properly, the
26777 hyphenation algorithm is quite short. In the following code we set |hc[hn+2]|
26778 to the impossible value 256, in order to guarantee that |hc[hn+3]| will
26779 never be fetched.
26780
26781 @<Find hyphen locations for the word in |hc|...@>=
26782 for j:=0 to hn do hyf[j]:=0;
26783 @<Look for the word |hc[1..hn]| in the exception table, and |goto found| (with
26784 |hyf| containing the hyphens) if an entry is found@>;
26785 if trie_char(cur_lang+1)<>qi(cur_lang) then return; {no patterns for |cur_lang|}
26786 hc[0]:=0; hc[hn+1]:=0; hc[hn+2]:=256; {insert delimiters}
26787 for j:=0 to hn-r_hyf+1 do
26788 begin z:=trie_link(cur_lang+1)+hc[j]; l:=j;
26789 while hc[l]=qo(trie_char(z)) do
26790 begin if trie_op(z)<>min_quarterword then
26791 @<Store \(m)maximum values in the |hyf| table@>;
26792 incr(l); z:=trie_link(z)+hc[l];
26793 end;
26794 end;
26795 found: for j:=0 to l_hyf-1 do hyf[j]:=0;
26796 for j:=0 to r_hyf-1 do hyf[hn-j]:=0
26797
26798 @ @<Store \(m)maximum values in the |hyf| table@>=
26799 begin v:=trie_op(z);
26800 repeat v:=v+op_start[cur_lang]; i:=l-hyf_distance[v];
26801 if hyf_num[v]>hyf[i] then hyf[i]:=hyf_num[v];
26802 v:=hyf_next[v];
26803 until v=min_quarterword;
26804 end
26805
26806 @ The exception table that is built by \TeX's \.{\\hyphenation} primitive is
26807 organized as an ordered hash table [cf.\ Amble and Knuth, {\sl The Computer
26808 @^Amble, Ole@> @^Knuth, Donald Ervin@>
26809 Journal\/ \bf17} (1974), 135--142] using linear probing. If $\alpha$ and
26810 $\beta$ are words, we will say that $\alpha<\beta$ if $\vert\alpha\vert<
26811 \vert\beta\vert$ or if $\vert\alpha\vert=\vert\beta\vert$ and
26812 $\alpha$ is lexicographically smaller than $\beta$. (The notation $\vert
26813 \alpha\vert$ stands for the length of $\alpha$.) The idea of ordered hashing
26814 is to arrange the table so that a given word $\alpha$ can be sought by computing
26815 a hash address $h=h(\alpha)$ and then looking in table positions |h|, |h-1|,
26816 \dots, until encountering the first word $\L\alpha$. If this word is
26817 different from $\alpha$, we can conclude that $\alpha$ is not in the table.
26818
26819 The words in the table point to lists in |mem| that specify hyphen positions
26820 in their |info| fields. The list for $c_1\ldots c_n$ contains the number |k| if
26821 the word $c_1\ldots c_n$ has a discretionary hyphen between $c_k$ and
26822 $c_{k+1}$.
26823
26824 @<Types...@>=
26825 @!hyph_pointer=0..hyph_size; {an index into the ordered hash table}
26826
26827 @ @<Glob...@>=
26828 @!hyph_word:array[hyph_pointer] of str_number; {exception words}
26829 @!hyph_list:array[hyph_pointer] of pointer; {lists of hyphen positions}
26830 @!hyph_count:hyph_pointer; {the number of words in the exception dictionary}
26831
26832 @ @<Local variables for init...@>=
26833 @!z:hyph_pointer; {runs through the exception dictionary}
26834
26835 @ @<Set init...@>=
26836 for z:=0 to hyph_size do
26837 begin hyph_word[z]:=0; hyph_list[z]:=null;
26838 end;
26839 hyph_count:=0;
26840
26841 @ The algorithm for exception lookup is quite simple, as soon as we have
26842 a few more local variables to work with.
26843
26844 @<Local variables for hyph...@>=
26845 @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
26846 @!k:str_number; {an index into |str_start|}
26847 @!u:pool_pointer; {an index into |str_pool|}
26848
26849 @ First we compute the hash code |h|, then we search until we either
26850 find the word or we don't. Words from different languages are kept
26851 separate by appending the language code to the string.
26852
26853 @<Look for the word |hc[1...@>=
26854 h:=hc[1]; incr(hn); hc[hn]:=cur_lang;
26855 for j:=2 to hn do h:=(h+h+hc[j]) mod hyph_size;
26856 loop@+ begin @<If the string |hyph_word[h]| is less than \(hc)|hc[1..hn]|,
26857 |goto not_found|; but if the two strings are equal,
26858 set |hyf| to the hyphen positions and |goto found|@>;
26859 if h>0 then decr(h)@+else h:=hyph_size;
26860 end;
26861 not_found: decr(hn)
26862
26863 @ @<If the string |hyph_word[h]| is less than \(hc)...@>=
26864 k:=hyph_word[h]; if k=0 then goto not_found;
26865 if length(k)<hn then goto not_found;
26866 if length(k)=hn then
26867 begin j:=1; u:=str_start[k];
26868 repeat if so(str_pool[u])<hc[j] then goto not_found;
26869 if so(str_pool[u])>hc[j] then goto done;
26870 incr(j); incr(u);
26871 until j>hn;
26872 @<Insert hyphens as specified in |hyph_list[h]|@>;
26873 decr(hn); goto found;
26874 end;
26875 done:
26876
26877 @ @<Insert hyphens as specified...@>=
26878 s:=hyph_list[h];
26879 while s<>null do
26880 begin hyf[info(s)]:=1; s:=link(s);
26881 end
26882
26883 @ @<Search |hyph_list| for pointers to |p|@>=
26884 for q:=0 to hyph_size do
26885 begin if hyph_list[q]=p then
26886 begin print_nl("HYPH("); print_int(q); print_char(")");
26887 end;
26888 end
26889
26890 @ We have now completed the hyphenation routine, so the |line_break| procedure
26891 is finished at last. Since the hyphenation exception table is fresh in our
26892 minds, it's a good time to deal with the routine that adds new entries to it.
26893
26894 When \TeX\ has scanned `\.{\\hyphenation}', it calls on a procedure named
26895 |new_hyph_exceptions| to do the right thing.
26896
26897 @d set_cur_lang==if language<=0 then cur_lang:=0
26898 else if language>255 then cur_lang:=0
26899 else cur_lang:=language
26900
26901 @p procedure new_hyph_exceptions; {enters new exceptions}
26902 label reswitch, exit, found, not_found, not_found1;
26903 var n:0..64; {length of current word; not always a |small_number|}
26904 @!j:0..64; {an index into |hc|}
26905 @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
26906 @!k:str_number; {an index into |str_start|}
26907 @!p:pointer; {head of a list of hyphen positions}
26908 @!q:pointer; {used when creating a new node for list |p|}
26909 @!s,@!t:str_number; {strings being compared or stored}
26910 @!u,@!v:pool_pointer; {indices into |str_pool|}
26911 begin scan_left_brace; {a left brace must follow \.{\\hyphenation}}
26912 set_cur_lang;
26913 @!init if trie_not_ready then
26914 begin hyph_index:=0; goto not_found1;
26915 end;
26916 tini@/
26917 set_hyph_index;
26918 not_found1:
26919 @<Enter as many hyphenation exceptions as are listed,
26920 until coming to a right brace; then |return|@>;
26921 exit:end;
26922
26923 @ @<Enter as many...@>=
26924 n:=0; p:=null;
26925 loop@+ begin get_x_token;
26926 reswitch: case cur_cmd of
26927 letter,other_char,char_given:@<Append a new letter or hyphen@>;
26928 char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
26929 goto reswitch;
26930 end;
26931 spacer,right_brace: begin if n>1 then @<Enter a hyphenation exception@>;
26932 if cur_cmd=right_brace then return;
26933 n:=0; p:=null;
26934 end;
26935 othercases @<Give improper \.{\\hyphenation} error@>
26936 endcases;
26937 end
26938
26939 @ @<Give improper \.{\\hyph...@>=
26940 begin print_err("Improper "); print_esc("hyphenation");
26941 @.Improper \\hyphenation...@>
26942 print(" will be flushed");
26943 help2("Hyphenation exceptions must contain only letters")@/
26944 ("and hyphens. But continue; I'll forgive and forget.");
26945 error;
26946 end
26947
26948 @ @<Append a new letter or hyphen@>=
26949 if cur_chr="-" then @<Append the value |n| to list |p|@>
26950 else begin set_lc_code(cur_chr);
26951 if hc[0]=0 then
26952 begin print_err("Not a letter");
26953 @.Not a letter@>
26954 help2("Letters in \hyphenation words must have \lccode>0.")@/
26955 ("Proceed; I'll ignore the character I just read.");
26956 error;
26957 end
26958 else if n<63 then
26959 begin incr(n); hc[n]:=hc[0];
26960 end;
26961 end
26962
26963 @ @<Append the value |n| to list |p|@>=
26964 begin if n<63 then
26965 begin q:=get_avail; link(q):=p; info(q):=n; p:=q;
26966 end;
26967 end
26968
26969 @ @<Enter a hyphenation exception@>=
26970 begin incr(n); hc[n]:=cur_lang; str_room(n); h:=0;
26971 for j:=1 to n do
26972 begin h:=(h+h+hc[j]) mod hyph_size;
26973 append_char(hc[j]);
26974 end;
26975 s:=make_string;
26976 @<Insert the \(p)pair |(s,p)| into the exception table@>;
26977 end
26978
26979 @ @<Insert the \(p)pair |(s,p)|...@>=
26980 if hyph_count=hyph_size then overflow("exception dictionary",hyph_size);
26981 @:TeX capacity exceeded exception dictionary}{\quad exception dictionary@>
26982 incr(hyph_count);
26983 while hyph_word[h]<>0 do
26984 begin @<If the string |hyph_word[h]| is less than \(or)or equal to
26985 |s|, interchange |(hyph_word[h],hyph_list[h])| with |(s,p)|@>;
26986 if h>0 then decr(h)@+else h:=hyph_size;
26987 end;
26988 hyph_word[h]:=s; hyph_list[h]:=p
26989
26990 @ @<If the string |hyph_word[h]| is less than \(or)...@>=
26991 k:=hyph_word[h];
26992 if length(k)<length(s) then goto found;
26993 if length(k)>length(s) then goto not_found;
26994 u:=str_start[k]; v:=str_start[s];
26995 repeat if str_pool[u]<str_pool[v] then goto found;
26996 if str_pool[u]>str_pool[v] then goto not_found;
26997 incr(u); incr(v);
26998 until u=str_start[k+1];
26999 found:q:=hyph_list[h]; hyph_list[h]:=p; p:=q;@/
27000 t:=hyph_word[h]; hyph_word[h]:=s; s:=t;
27001 not_found:
27002
27003 @* \[43] Initializing the hyphenation tables.
27004 The trie for \TeX's hyphenation algorithm is built from a sequence of
27005 patterns following a \.{\\patterns} specification. Such a specification
27006 is allowed only in \.{INITEX}, since the extra memory for auxiliary tables
27007 and for the initialization program itself would only clutter up the
27008 production version of \TeX\ with a lot of deadwood.
27009
27010 The first step is to build a trie that is linked, instead of packed
27011 into sequential storage, so that insertions are readily made.
27012 After all patterns have been processed, \.{INITEX}
27013 compresses the linked trie by identifying common subtries. Finally the
27014 trie is packed into the efficient sequential form that the hyphenation
27015 algorithm actually uses.
27016
27017 @<Declare subprocedures for |line_break|@>=
27018 @!init @<Declare procedures for preprocessing hyphenation patterns@>@;
27019 tini
27020
27021 @ Before we discuss trie building in detail, let's consider the simpler
27022 problem of creating the |hyf_distance|, |hyf_num|, and |hyf_next| arrays.
27023
27024 Suppose, for example, that \TeX\ reads the pattern `\.{ab2cde1}'. This is
27025 a pattern of length 5, with $n_0\ldots n_5=0\,0\,2\,0\,0\,1$ in the
27026 notation above. We want the corresponding |trie_op| code |v| to have
27027 |hyf_distance[v]=3|, |hyf_num[v]=2|, and |hyf_next[v]=@t$v^\prime$@>|,
27028 where the auxiliary |trie_op| code $v^\prime$ has
27029 |hyf_distance[@t$v^\prime$@>]=0|, |hyf_num[@t$v^\prime$@>]=1|, and
27030 |hyf_next[@t$v^\prime$@>]=min_quarterword|.
27031
27032 \TeX\ computes an appropriate value |v| with the |new_trie_op| subroutine
27033 below, by setting
27034 $$\hbox{|@t$v^\prime$@>:=new_trie_op(0,1,min_quarterword)|,\qquad
27035 |v:=new_trie_op(3,2,@t$v^\prime$@>)|.}$$
27036 This subroutine looks up its three
27037 parameters in a special hash table, assigning a new value only if these
27038 three have not appeared before for the current language.
27039
27040 The hash table is called |trie_op_hash|, and the number of entries it contains
27041 is |trie_op_ptr|.
27042
27043 @<Glob...@>=
27044 @!init @!trie_op_hash:array[-trie_op_size..trie_op_size] of 0..trie_op_size;
27045 {trie op codes for quadruples}
27046 @!trie_used:array[ASCII_code] of quarterword;
27047 {largest opcode used so far for this language}
27048 @!trie_op_lang:array[1..trie_op_size] of ASCII_code;
27049 {language part of a hashed quadruple}
27050 @!trie_op_val:array[1..trie_op_size] of quarterword;
27051 {opcode corresponding to a hashed quadruple}
27052 @!trie_op_ptr:0..trie_op_size; {number of stored ops so far}
27053 tini
27054
27055 @ It's tempting to remove the |overflow| stops in the following procedure;
27056 |new_trie_op| could return |min_quarterword| (thereby simply ignoring
27057 part of a hyphenation pattern) instead of aborting the job. However, that would
27058 lead to different hyphenation results on different installations of \TeX\
27059 using the same patterns. The |overflow| stops are necessary for portability
27060 of patterns.
27061
27062 @<Declare procedures for preprocessing hyph...@>=
27063 function new_trie_op(@!d,@!n:small_number;@!v:quarterword):quarterword;
27064 label exit;
27065 var h:-trie_op_size..trie_op_size; {trial hash location}
27066 @!u:quarterword; {trial op code}
27067 @!l:0..trie_op_size; {pointer to stored data}
27068 begin h:=abs(n+313*d+361*v+1009*cur_lang) mod (trie_op_size+trie_op_size)
27069 - trie_op_size;
27070 loop@+ begin l:=trie_op_hash[h];
27071 if l=0 then {empty position found for a new op}
27072 begin if trie_op_ptr=trie_op_size then
27073 overflow("pattern memory ops",trie_op_size);
27074 u:=trie_used[cur_lang];
27075 if u=max_quarterword then
27076 overflow("pattern memory ops per language",
27077 max_quarterword-min_quarterword);
27078 incr(trie_op_ptr); incr(u); trie_used[cur_lang]:=u;
27079 hyf_distance[trie_op_ptr]:=d;
27080 hyf_num[trie_op_ptr]:=n; hyf_next[trie_op_ptr]:=v;
27081 trie_op_lang[trie_op_ptr]:=cur_lang; trie_op_hash[h]:=trie_op_ptr;
27082 trie_op_val[trie_op_ptr]:=u; new_trie_op:=u; return;
27083 end;
27084 if (hyf_distance[l]=d)and(hyf_num[l]=n)and(hyf_next[l]=v)
27085 and(trie_op_lang[l]=cur_lang) then
27086 begin new_trie_op:=trie_op_val[l]; return;
27087 end;
27088 if h>-trie_op_size then decr(h)@+else h:=trie_op_size;
27089 end;
27090 exit:end;
27091
27092 @ After |new_trie_op| has compressed the necessary opcode information,
27093 plenty of information is available to unscramble the data into the
27094 final form needed by our hyphenation algorithm.
27095
27096 @<Sort \(t)the hyphenation op tables into proper order@>=
27097 op_start[0]:=-min_quarterword;
27098 for j:=1 to 255 do op_start[j]:=op_start[j-1]+qo(trie_used[j-1]);
27099 for j:=1 to trie_op_ptr do
27100 trie_op_hash[j]:=op_start[trie_op_lang[j]]+trie_op_val[j]; {destination}
27101 for j:=1 to trie_op_ptr do while trie_op_hash[j]>j do
27102 begin k:=trie_op_hash[j];@/
27103 t:=hyf_distance[k]; hyf_distance[k]:=hyf_distance[j]; hyf_distance[j]:=t;@/
27104 t:=hyf_num[k]; hyf_num[k]:=hyf_num[j]; hyf_num[j]:=t;@/
27105 t:=hyf_next[k]; hyf_next[k]:=hyf_next[j]; hyf_next[j]:=t;@/
27106 trie_op_hash[j]:=trie_op_hash[k]; trie_op_hash[k]:=k;
27107 end
27108
27109 @ Before we forget how to initialize the data structures that have been
27110 mentioned so far, let's write down the code that gets them started.
27111
27112 @<Initialize table entries...@>=
27113 for k:=-trie_op_size to trie_op_size do trie_op_hash[k]:=0;
27114 for k:=0 to 255 do trie_used[k]:=min_quarterword;
27115 trie_op_ptr:=0;
27116
27117 @ The linked trie that is used to preprocess hyphenation patterns appears
27118 in several global arrays. Each node represents an instruction of the form
27119 ``if you see character |c|, then perform operation |o|, move to the
27120 next character, and go to node |l|; otherwise go to node |r|.''
27121 The four quantities |c|, |o|, |l|, and |r| are stored in four arrays
27122 |trie_c|, |trie_o|, |trie_l|, and |trie_r|. The root of the trie
27123 is |trie_l[0]|, and the number of nodes is |trie_ptr|. Null trie
27124 pointers are represented by zero. To initialize the trie, we simply
27125 set |trie_l[0]| and |trie_ptr| to zero. We also set |trie_c[0]| to some
27126 arbitrary value, since the algorithm may access it.
27127
27128 The algorithms maintain the condition
27129 $$\hbox{|trie_c[trie_r[z]]>trie_c[z]|\qquad
27130 whenever |z<>0| and |trie_r[z]<>0|};$$ in other words, sibling nodes are
27131 ordered by their |c| fields.
27132
27133 @d trie_root==trie_l[0] {root of the linked trie}
27134
27135 @<Glob...@>=
27136 @!init @!trie_c:packed array[trie_pointer] of packed_ASCII_code;
27137 {characters to match}
27138 @t\hskip10pt@>@!trie_o:packed array[trie_pointer] of quarterword;
27139 {operations to perform}
27140 @t\hskip10pt@>@!trie_l:packed array[trie_pointer] of trie_pointer;
27141 {left subtrie links}
27142 @t\hskip10pt@>@!trie_r:packed array[trie_pointer] of trie_pointer;
27143 {right subtrie links}
27144 @t\hskip10pt@>@!trie_ptr:trie_pointer; {the number of nodes in the trie}
27145 @t\hskip10pt@>@!trie_hash:packed array[trie_pointer] of trie_pointer;
27146 {used to identify equivalent subtries}
27147 tini
27148
27149 @ Let us suppose that a linked trie has already been constructed.
27150 Experience shows that we can often reduce its size by recognizing common
27151 subtries; therefore another hash table is introduced for this purpose,
27152 somewhat similar to |trie_op_hash|. The new hash table will be
27153 initialized to zero.
27154
27155 The function |trie_node(p)| returns |p| if |p| is distinct from other nodes
27156 that it has seen, otherwise it returns the number of the first equivalent
27157 node that it has seen.
27158
27159 Notice that we might make subtries equivalent even if they correspond to
27160 patterns for different languages, in which the trie ops might mean quite
27161 different things. That's perfectly all right.
27162
27163 @<Declare procedures for preprocessing hyph...@>=
27164 function trie_node(@!p:trie_pointer):trie_pointer; {converts
27165 to a canonical form}
27166 label exit;
27167 var h:trie_pointer; {trial hash location}
27168 @!q:trie_pointer; {trial trie node}
27169 begin h:=abs(trie_c[p]+1009*trie_o[p]+@|
27170 2718*trie_l[p]+3142*trie_r[p]) mod trie_size;
27171 loop@+ begin q:=trie_hash[h];
27172 if q=0 then
27173 begin trie_hash[h]:=p; trie_node:=p; return;
27174 end;
27175 if (trie_c[q]=trie_c[p])and(trie_o[q]=trie_o[p])and@|
27176 (trie_l[q]=trie_l[p])and(trie_r[q]=trie_r[p]) then
27177 begin trie_node:=q; return;
27178 end;
27179 if h>0 then decr(h)@+else h:=trie_size;
27180 end;
27181 exit:end;
27182
27183 @ A neat recursive procedure is now able to compress a trie by
27184 traversing it and applying |trie_node| to its nodes in ``bottom up''
27185 fashion. We will compress the entire trie by clearing |trie_hash| to
27186 zero and then saying `|trie_root:=compress_trie(trie_root)|'.
27187 @^recursion@>
27188
27189 @<Declare procedures for preprocessing hyph...@>=
27190 function compress_trie(@!p:trie_pointer):trie_pointer;
27191 begin if p=0 then compress_trie:=0
27192 else begin trie_l[p]:=compress_trie(trie_l[p]);
27193 trie_r[p]:=compress_trie(trie_r[p]);
27194 compress_trie:=trie_node(p);
27195 end;
27196 end;
27197
27198 @ The compressed trie will be packed into the |trie| array using a
27199 ``top-down first-fit'' procedure. This is a little tricky, so the reader
27200 should pay close attention: The |trie_hash| array is cleared to zero
27201 again and renamed |trie_ref| for this phase of the operation; later on,
27202 |trie_ref[p]| will be nonzero only if the linked trie node |p| is the
27203 smallest character
27204 in a family and if the characters |c| of that family have been allocated to
27205 locations |trie_ref[p]+c| in the |trie| array. Locations of |trie| that
27206 are in use will have |trie_link=0|, while the unused holes in |trie|
27207 will be doubly linked with |trie_link| pointing to the next larger vacant
27208 location and |trie_back| pointing to the next smaller one. This double
27209 linking will have been carried out only as far as |trie_max|, where
27210 |trie_max| is the largest index of |trie| that will be needed.
27211 To save time at the low end of the trie, we maintain array entries
27212 |trie_min[c]| pointing to the smallest hole that is greater than~|c|.
27213 Another array |trie_taken| tells whether or not a given location is
27214 equal to |trie_ref[p]| for some |p|; this array is used to ensure that
27215 distinct nodes in the compressed trie will have distinct |trie_ref|
27216 entries.
27217
27218 @d trie_ref==trie_hash {where linked trie families go into |trie|}
27219 @d trie_back(#)==trie[#].lh {backward links in |trie| holes}
27220
27221 @<Glob...@>=
27222 @!init @!trie_taken:packed array[1..trie_size] of boolean;
27223 {does a family start here?}
27224 @t\hskip10pt@>@!trie_min:array[ASCII_code] of trie_pointer;
27225 {the first possible slot for each character}
27226 @t\hskip10pt@>@!trie_max:trie_pointer; {largest location used in |trie|}
27227 @t\hskip10pt@>@!trie_not_ready:boolean; {is the trie still in linked form?}
27228 tini
27229
27230 @ Each time \.{\\patterns} appears, it contributes further patterns to
27231 the future trie, which will be built only when hyphenation is attempted or
27232 when a format file is dumped. The boolean variable |trie_not_ready|
27233 will change to |false| when the trie is compressed; this will disable
27234 further patterns.
27235
27236 @<Initialize table entries...@>=
27237 trie_not_ready:=true; trie_root:=0; trie_c[0]:=si(0); trie_ptr:=0;
27238
27239 @ Here is how the trie-compression data structures are initialized.
27240 If storage is tight, it would be possible to overlap |trie_op_hash|,
27241 |trie_op_lang|, and |trie_op_val| with |trie|, |trie_hash|, and |trie_taken|,
27242 because we finish with the former just before we need the latter.
27243
27244 @<Get ready to compress the trie@>=
27245 @<Sort \(t)the hyphenation...@>;
27246 for p:=0 to trie_size do trie_hash[p]:=0;
27247 hyph_root:=compress_trie(hyph_root);
27248 trie_root:=compress_trie(trie_root); {identify equivalent subtries}
27249 for p:=0 to trie_ptr do trie_ref[p]:=0;
27250 for p:=0 to 255 do trie_min[p]:=p+1;
27251 trie_link(0):=1; trie_max:=0
27252
27253 @ The |first_fit| procedure finds the smallest hole |z| in |trie| such that
27254 a trie family starting at a given node |p| will fit into vacant positions
27255 starting at |z|. If |c=trie_c[p]|, this means that location |z-c| must
27256 not already be taken by some other family, and that |z-c+@t$c^\prime$@>|
27257 must be vacant for all characters $c^\prime$ in the family. The procedure
27258 sets |trie_ref[p]| to |z-c| when the first fit has been found.
27259
27260 @<Declare procedures for preprocessing hyph...@>=
27261 procedure first_fit(@!p:trie_pointer); {packs a family into |trie|}
27262 label not_found,found;
27263 var h:trie_pointer; {candidate for |trie_ref[p]|}
27264 @!z:trie_pointer; {runs through holes}
27265 @!q:trie_pointer; {runs through the family starting at |p|}
27266 @!c:ASCII_code; {smallest character in the family}
27267 @!l,@!r:trie_pointer; {left and right neighbors}
27268 @!ll:1..256; {upper limit of |trie_min| updating}
27269 begin c:=so(trie_c[p]);
27270 z:=trie_min[c]; {get the first conceivably good hole}
27271 loop@+ begin h:=z-c;@/
27272 @<Ensure that |trie_max>=h+256|@>;
27273 if trie_taken[h] then goto not_found;
27274 @<If all characters of the family fit relative to |h|, then
27275 |goto found|,\30\ otherwise |goto not_found|@>;
27276 not_found: z:=trie_link(z); {move to the next hole}
27277 end;
27278 found: @<Pack the family into |trie| relative to |h|@>;
27279 end;
27280
27281 @ By making sure that |trie_max| is at least |h+256|, we can be sure that
27282 |trie_max>z|, since |h=z-c|. It follows that location |trie_max| will
27283 never be occupied in |trie|, and we will have |trie_max>=trie_link(z)|.
27284
27285 @<Ensure that |trie_max>=h+256|@>=
27286 if trie_max<h+256 then
27287 begin if trie_size<=h+256 then overflow("pattern memory",trie_size);
27288 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
27289 repeat incr(trie_max); trie_taken[trie_max]:=false;
27290 trie_link(trie_max):=trie_max+1; trie_back(trie_max):=trie_max-1;
27291 until trie_max=h+256;
27292 end
27293
27294 @ @<If all characters of the family fit relative to |h|...@>=
27295 q:=trie_r[p];
27296 while q>0 do
27297 begin if trie_link(h+so(trie_c[q]))=0 then goto not_found;
27298 q:=trie_r[q];
27299 end;
27300 goto found
27301
27302 @ @<Pack the family into |trie| relative to |h|@>=
27303 trie_taken[h]:=true; trie_ref[p]:=h; q:=p;
27304 repeat z:=h+so(trie_c[q]); l:=trie_back(z); r:=trie_link(z);
27305 trie_back(r):=l; trie_link(l):=r; trie_link(z):=0;
27306 if l<256 then
27307 begin if z<256 then ll:=z @+else ll:=256;
27308 repeat trie_min[l]:=r; incr(l);
27309 until l=ll;
27310 end;
27311 q:=trie_r[q];
27312 until q=0
27313
27314 @ To pack the entire linked trie, we use the following recursive procedure.
27315 @^recursion@>
27316
27317 @<Declare procedures for preprocessing hyph...@>=
27318 procedure trie_pack(@!p:trie_pointer); {pack subtries of a family}
27319 var q:trie_pointer; {a local variable that need not be saved on recursive calls}
27320 begin repeat q:=trie_l[p];
27321 if (q>0)and(trie_ref[q]=0) then
27322 begin first_fit(q); trie_pack(q);
27323 end;
27324 p:=trie_r[p];
27325 until p=0;
27326 end;
27327
27328 @ When the whole trie has been allocated into the sequential table, we
27329 must go through it once again so that |trie| contains the correct
27330 information. Null pointers in the linked trie will be represented by the
27331 value~0, which properly implements an ``empty'' family.
27332
27333 @<Move the data into |trie|@>=
27334 h.rh:=0; h.b0:=min_quarterword; h.b1:=min_quarterword; {|trie_link:=0|,
27335 |trie_op:=min_quarterword|, |trie_char:=qi(0)|}
27336 if trie_max=0 then {no patterns were given}
27337 begin for r:=0 to 256 do trie[r]:=h;
27338 trie_max:=256;
27339 end
27340 else begin if hyph_root>0 then trie_fix(hyph_root);
27341 if trie_root>0 then trie_fix(trie_root); {this fixes the non-holes in |trie|}
27342 r:=0; {now we will zero out all the holes}
27343 repeat s:=trie_link(r); trie[r]:=h; r:=s;
27344 until r>trie_max;
27345 end;
27346 trie_char(0):=qi("?"); {make |trie_char(c)<>c| for all |c|}
27347
27348 @ The fixing-up procedure is, of course, recursive. Since the linked trie
27349 usually has overlapping subtries, the same data may be moved several
27350 times; but that causes no harm, and at most as much work is done as it
27351 took to build the uncompressed trie.
27352 @^recursion@>
27353
27354 @<Declare procedures for preprocessing hyph...@>=
27355 procedure trie_fix(@!p:trie_pointer); {moves |p| and its siblings into |trie|}
27356 var q:trie_pointer; {a local variable that need not be saved on recursive calls}
27357 @!c:ASCII_code; {another one that need not be saved}
27358 @!z:trie_pointer; {|trie| reference; this local variable must be saved}
27359 begin z:=trie_ref[p];
27360 repeat q:=trie_l[p]; c:=so(trie_c[p]);
27361 trie_link(z+c):=trie_ref[q]; trie_char(z+c):=qi(c); trie_op(z+c):=trie_o[p];
27362 if q>0 then trie_fix(q);
27363 p:=trie_r[p];
27364 until p=0;
27365 end;
27366
27367 @ Now let's go back to the easier problem, of building the linked
27368 trie. When \.{INITEX} has scanned the `\.{\\patterns}' control
27369 sequence, it calls on |new_patterns| to do the right thing.
27370
27371 @<Declare procedures for preprocessing hyph...@>=
27372 procedure new_patterns; {initializes the hyphenation pattern data}
27373 label done, done1;
27374 var k,@!l:0..64; {indices into |hc| and |hyf|;
27375 not always in |small_number| range}
27376 @!digit_sensed:boolean; {should the next digit be treated as a letter?}
27377 @!v:quarterword; {trie op code}
27378 @!p,@!q:trie_pointer; {nodes of trie traversed during insertion}
27379 @!first_child:boolean; {is |p=trie_l[q]|?}
27380 @!c:ASCII_code; {character being inserted}
27381 begin if trie_not_ready then
27382 begin set_cur_lang; scan_left_brace; {a left brace must follow \.{\\patterns}}
27383 @<Enter all of the patterns into a linked trie, until coming to a right
27384 brace@>;
27385 if saving_hyph_codes>0 then
27386 @<Store hyphenation codes for current language@>;
27387 end
27388 else begin print_err("Too late for "); print_esc("patterns");
27389 help1("All patterns must be given before typesetting begins.");
27390 error; link(garbage):=scan_toks(false,false); flush_list(def_ref);
27391 end;
27392 end;
27393
27394 @ Novices are not supposed to be using \.{\\patterns}, so the error
27395 messages are terse. (Note that all error messages appear in \TeX's string
27396 pool, even if they are used only by \.{INITEX}.)
27397
27398 @<Enter all of the patterns into a linked trie...@>=
27399 k:=0; hyf[0]:=0; digit_sensed:=false;
27400 loop@+ begin get_x_token;
27401 case cur_cmd of
27402 letter,other_char:@<Append a new letter or a hyphen level@>;
27403 spacer,right_brace: begin if k>0 then
27404 @<Insert a new pattern into the linked trie@>;
27405 if cur_cmd=right_brace then goto done;
27406 k:=0; hyf[0]:=0; digit_sensed:=false;
27407 end;
27408 othercases begin print_err("Bad "); print_esc("patterns");
27409 @.Bad \\patterns@>
27410 help1("(See Appendix H.)"); error;
27411 end
27412 endcases;
27413 end;
27414 done:
27415
27416 @ @<Append a new letter or a hyphen level@>=
27417 if digit_sensed or(cur_chr<"0")or(cur_chr>"9") then
27418 begin if cur_chr="." then cur_chr:=0 {edge-of-word delimiter}
27419 else begin cur_chr:=lc_code(cur_chr);
27420 if cur_chr=0 then
27421 begin print_err("Nonletter");
27422 @.Nonletter@>
27423 help1("(See Appendix H.)"); error;
27424 end;
27425 end;
27426 if k<63 then
27427 begin incr(k); hc[k]:=cur_chr; hyf[k]:=0; digit_sensed:=false;
27428 end;
27429 end
27430 else if k<63 then
27431 begin hyf[k]:=cur_chr-"0"; digit_sensed:=true;
27432 end
27433
27434 @ When the following code comes into play, the pattern $p_1\ldots p_k$
27435 appears in |hc[1..k]|, and the corresponding sequence of numbers $n_0\ldots
27436 n_k$ appears in |hyf[0..k]|.
27437
27438 @<Insert a new pattern into the linked trie@>=
27439 begin @<Compute the trie op code, |v|, and set |l:=0|@>;
27440 q:=0; hc[0]:=cur_lang;
27441 while l<=k do
27442 begin c:=hc[l]; incr(l); p:=trie_l[q]; first_child:=true;
27443 while (p>0)and(c>so(trie_c[p])) do
27444 begin q:=p; p:=trie_r[q]; first_child:=false;
27445 end;
27446 if (p=0)or(c<so(trie_c[p])) then
27447 @<Insert a new trie node between |q| and |p|, and
27448 make |p| point to it@>;
27449 q:=p; {now node |q| represents $p_1\ldots p_{l-1}$}
27450 end;
27451 if trie_o[q]<>min_quarterword then
27452 begin print_err("Duplicate pattern");
27453 @.Duplicate pattern@>
27454 help1("(See Appendix H.)"); error;
27455 end;
27456 trie_o[q]:=v;
27457 end
27458
27459 @ @<Insert a new trie node between |q| and |p|...@>=
27460 begin if trie_ptr=trie_size then overflow("pattern memory",trie_size);
27461 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
27462 incr(trie_ptr); trie_r[trie_ptr]:=p; p:=trie_ptr; trie_l[p]:=0;
27463 if first_child then trie_l[q]:=p@+else trie_r[q]:=p;
27464 trie_c[p]:=si(c); trie_o[p]:=min_quarterword;
27465 end
27466
27467 @ @<Compute the trie op code, |v|...@>=
27468 if hc[1]=0 then hyf[0]:=0;
27469 if hc[k]=0 then hyf[k]:=0;
27470 l:=k; v:=min_quarterword;
27471 loop@+ begin if hyf[l]<>0 then v:=new_trie_op(k-l,hyf[l],v);
27472 if l>0 then decr(l)@+else goto done1;
27473 end;
27474 done1:
27475
27476 @ Finally we put everything together: Here is how the trie gets to its
27477 final, efficient form.
27478 The following packing routine is rigged so that the root of the linked
27479 tree gets mapped into location 1 of |trie|, as required by the hyphenation
27480 algorithm. This happens because the first call of |first_fit| will
27481 ``take'' location~1.
27482
27483 @<Declare procedures for preprocessing hyphenation patterns@>=
27484 procedure init_trie;
27485 var @!p:trie_pointer; {pointer for initialization}
27486 @!j,@!k,@!t:integer; {all-purpose registers for initialization}
27487 @!r,@!s:trie_pointer; {used to clean up the packed |trie|}
27488 @!h:two_halves; {template used to zero out |trie|'s holes}
27489 begin @<Get ready to compress the trie@>;
27490 if trie_root<>0 then
27491 begin first_fit(trie_root); trie_pack(trie_root);
27492 end;
27493 if hyph_root<>0 then @<Pack all stored |hyph_codes|@>;
27494 @<Move the data into |trie|@>;
27495 trie_not_ready:=false;
27496 end;
27497
27498 @* \[44] Breaking vertical lists into pages.
27499 The |vsplit| procedure, which implements \TeX's \.{\\vsplit} operation,
27500 is considerably simpler than |line_break| because it doesn't have to
27501 worry about hyphenation, and because its mission is to discover a single
27502 break instead of an optimum sequence of breakpoints. But before we get
27503 into the details of |vsplit|, we need to consider a few more basic things.
27504
27505 @ A subroutine called |prune_page_top| takes a pointer to a vlist and
27506 returns a pointer to a modified vlist in which all glue, kern, and penalty nodes
27507 have been deleted before the first box or rule node. However, the first
27508 box or rule is actually preceded by a newly created glue node designed so that
27509 the topmost baseline will be at distance |split_top_skip| from the top,
27510 whenever this is possible without backspacing.
27511
27512 When the second argument |s| is |false| the deleted nodes are destroyed,
27513 otherwise they are collected in a list starting at |split_disc|.
27514
27515 In this routine and those that follow, we make use of the fact that a
27516 vertical list contains no character nodes, hence the |type| field exists
27517 for each node in the list.
27518 @^data structure assumptions@>
27519
27520 @d discard_or_move = 60
27521 @p function prune_page_top(@!p:pointer;@!s:boolean):pointer;
27522 label discard_or_move;
27523 {adjust top after page break}
27524 var prev_p:pointer; {lags one step behind |p|}
27525 @!q,@!r:pointer; {temporary variables for list manipulation}
27526 begin prev_p:=temp_head; link(temp_head):=p;
27527 while p<>null do
27528 case type(p) of
27529 hlist_node,vlist_node,rule_node:@<Insert glue for |split_top_skip|
27530 and set~|p:=null|@>;
27531 whatsit_node,mark_node,ins_node: begin
27532 if (type(p) = whatsit_node) and
27533 ((subtype(p) = pdf_snapy_node) or
27534 (subtype(p) = pdf_snapy_comp_node)) then
27535 begin
27536 print("snap node being discarded");
27537 goto discard_or_move;
27538 end;
27539 prev_p:=p; p:=link(prev_p);
27540 end;
27541 glue_node,kern_node,penalty_node: begin
27542 discard_or_move:
27543 @{
27544 print("discard_or_move: ");
27545 show_node_list(p);
27546 print_ln;
27547 @}
27548 q:=p; p:=link(q); link(q):=null;
27549 link(prev_p):=p;
27550 if s then
27551 begin if split_disc=null then split_disc:=q@+else link(r):=q;
27552 r:=q;
27553 end
27554 else flush_node_list(q);
27555 end;
27556 othercases confusion("pruning")
27557 @:this can't happen pruning}{\quad pruning@>
27558 endcases;
27559 prune_page_top:=link(temp_head);
27560 end;
27561
27562 @ @<Insert glue for |split_top_skip|...@>=
27563 begin q:=new_skip_param(split_top_skip_code); link(prev_p):=q; link(q):=p;
27564 {now |temp_ptr=glue_ptr(q)|}
27565 if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
27566 else width(temp_ptr):=0;
27567 p:=null;
27568 end
27569
27570 @ The next subroutine finds the best place to break a given vertical list
27571 so as to obtain a box of height~|h|, with maximum depth~|d|.
27572 A pointer to the beginning of the vertical list is given,
27573 and a pointer to the optimum breakpoint is returned. The list is effectively
27574 followed by a forced break, i.e., a penalty node with the |eject_penalty|;
27575 if the best break occurs at this artificial node, the value |null| is returned.
27576
27577 An array of six |scaled| distances is used to keep track of the height
27578 from the beginning of the list to the current place, just as in |line_break|.
27579 In fact, we use one of the same arrays, only changing its name to reflect
27580 its new significance.
27581
27582 @d active_height==active_width {new name for the six distance variables}
27583 @d cur_height==active_height[1] {the natural height}
27584 @d set_height_zero(#)==active_height[#]:=0 {initialize the height to zero}
27585 @#
27586 @d update_heights=90 {go here to record glue in the |active_height| table}
27587
27588 @p function vert_break(@!p:pointer; @!h,@!d:scaled):pointer;
27589 {finds optimum page break}
27590 label done,not_found,update_heights;
27591 var prev_p:pointer; {if |p| is a glue node, |type(prev_p)| determines
27592 whether |p| is a legal breakpoint}
27593 @!q,@!r:pointer; {glue specifications}
27594 @!pi:integer; {penalty value}
27595 @!b:integer; {badness at a trial breakpoint}
27596 @!least_cost:integer; {the smallest badness plus penalties found so far}
27597 @!best_place:pointer; {the most recent break that leads to |least_cost|}
27598 @!prev_dp:scaled; {depth of previous box in the list}
27599 @!t:small_number; {|type| of the node following a kern}
27600 begin prev_p:=p; {an initial glue node is not a legal breakpoint}
27601 least_cost:=awful_bad; do_all_six(set_height_zero); prev_dp:=0;
27602 loop@+ begin @<If node |p| is a legal breakpoint, check if this break is
27603 the best known, and |goto done| if |p| is null or
27604 if the page-so-far is already too full to accept more stuff@>;
27605 prev_p:=p; p:=link(prev_p);
27606 end;
27607 done: vert_break:=best_place;
27608 end;
27609
27610 @ A global variable |best_height_plus_depth| will be set to the natural size
27611 of the box that corresponds to the optimum breakpoint found by |vert_break|.
27612 (This value is used by the insertion-splitting algorithm of the page builder.)
27613
27614 @<Glob...@>=
27615 @!best_height_plus_depth:scaled; {height of the best box, without stretching or
27616 shrinking}
27617
27618 @ A subtle point to be noted here is that the maximum depth~|d| might be
27619 negative, so |cur_height| and |prev_dp| might need to be corrected even
27620 after a glue or kern node.
27621
27622 @<If node |p| is a legal breakpoint, check...@>=
27623 if p=null then pi:=eject_penalty
27624 else @<Use node |p| to update the current height and depth measurements;
27625 if this node is not a legal breakpoint, |goto not_found|
27626 or |update_heights|,
27627 otherwise set |pi| to the associated penalty at the break@>;
27628 @<Check if node |p| is a new champion breakpoint; then \(go)|goto done|
27629 if |p| is a forced break or if the page-so-far is already too full@>;
27630 if (type(p)<glue_node)or(type(p)>kern_node) then goto not_found;
27631 update_heights: @<Update the current height and depth measurements with
27632 respect to a glue or kern node~|p|@>;
27633 not_found: if prev_dp>d then
27634 begin cur_height:=cur_height+prev_dp-d;
27635 prev_dp:=d;
27636 end;
27637
27638 @ @<Use node |p| to update the current height and depth measurements...@>=
27639 case type(p) of
27640 hlist_node,vlist_node,rule_node: begin@t@>@;@/
27641 cur_height:=cur_height+prev_dp+height(p); prev_dp:=depth(p);
27642 goto not_found;
27643 end;
27644 whatsit_node:@<Process whatsit |p| in |vert_break| loop, |goto not_found|@>;
27645 glue_node: if precedes_break(prev_p) then pi:=0
27646 else goto update_heights;
27647 kern_node: begin if link(p)=null then t:=penalty_node
27648 else t:=type(link(p));
27649 if t=glue_node then pi:=0@+else goto update_heights;
27650 end;
27651 penalty_node: pi:=penalty(p);
27652 mark_node,ins_node: goto not_found;
27653 othercases confusion("vertbreak")
27654 @:this can't happen vertbreak}{\quad vertbreak@>
27655 endcases
27656
27657 @ @d deplorable==100000 {more than |inf_bad|, but less than |awful_bad|}
27658
27659 @<Check if node |p| is a new champion breakpoint; then \(go)...@>=
27660 if pi<inf_penalty then
27661 begin @<Compute the badness, |b|, using |awful_bad|
27662 if the box is too full@>;
27663 if b<awful_bad then
27664 if pi<=eject_penalty then b:=pi
27665 else if b<inf_bad then b:=b+pi
27666 else b:=deplorable;
27667 if b<=least_cost then
27668 begin best_place:=p; least_cost:=b;
27669 best_height_plus_depth:=cur_height+prev_dp;
27670 end;
27671 if (b=awful_bad)or(pi<=eject_penalty) then goto done;
27672 end
27673
27674 @ @<Compute the badness, |b|, using |awful_bad| if the box is too full@>=
27675 if cur_height<h then
27676 if (active_height[3]<>0) or (active_height[4]<>0) or
27677 (active_height[5]<>0) then b:=0
27678 else b:=badness(h-cur_height,active_height[2])
27679 else if cur_height-h>active_height[6] then b:=awful_bad
27680 else b:=badness(cur_height-h,active_height[6])
27681
27682 @ Vertical lists that are subject to the |vert_break| procedure should not
27683 contain infinite shrinkability, since that would permit any amount of
27684 information to ``fit'' on one page.
27685
27686 @<Update the current height and depth measurements with...@>=
27687 if type(p)=kern_node then q:=p
27688 else begin q:=glue_ptr(p);
27689 active_height[2+stretch_order(q)]:=@|
27690 active_height[2+stretch_order(q)]+stretch(q);@/
27691 active_height[6]:=active_height[6]+shrink(q);
27692 if (shrink_order(q)<>normal)and(shrink(q)<>0) then
27693 begin@t@>@;@/
27694 if is_bit_set(ignore_primitive_error, 1) then
27695 print_ignored_err("Infinite glue shrinkage found in box being split")
27696 else begin
27697 print_err("Infinite glue shrinkage found in box being split");@/
27698 @.Infinite glue shrinkage...@>
27699 help4("The box you are \vsplitting contains some infinitely")@/
27700 ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
27701 ("Such glue doesn't belong there; but you can safely proceed,")@/
27702 ("since the offensive shrinkability has been made finite.");
27703 error;
27704 end;
27705 r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
27706 glue_ptr(p):=r; q:=r;
27707 end;
27708 end;
27709 cur_height:=cur_height+prev_dp+width(q); prev_dp:=0
27710
27711 @ Now we are ready to consider |vsplit| itself. Most of
27712 its work is accomplished by the two subroutines that we have just considered.
27713
27714 Given the number of a vlist box |n|, and given a desired page height |h|,
27715 the |vsplit| function finds the best initial segment of the vlist and
27716 returns a box for a page of height~|h|. The remainder of the vlist, if
27717 any, replaces the original box, after removing glue and penalties and
27718 adjusting for |split_top_skip|. Mark nodes in the split-off box are used to
27719 set the values of |split_first_mark| and |split_bot_mark|; we use the
27720 fact that |split_first_mark=null| if and only if |split_bot_mark=null|.
27721
27722 The original box becomes ``void'' if and only if it has been entirely
27723 extracted. The extracted box is ``void'' if and only if the original
27724 box was void (or if it was, erroneously, an hlist box).
27725
27726 @p @t\4@>@<Declare the function called |do_marks|@>@;
27727 function vsplit(@!n:halfword; @!h:scaled):pointer;
27728 {extracts a page of height |h| from box |n|}
27729 label exit,done;
27730 var v:pointer; {the box to be split}
27731 p:pointer; {runs through the vlist}
27732 q:pointer; {points to where the break occurs}
27733 begin cur_val:=n; fetch_box(v);
27734 flush_node_list(split_disc); split_disc:=null;
27735 if sa_mark<>null then
27736 if do_marks(vsplit_init,0,sa_mark) then sa_mark:=null;
27737 if split_first_mark<>null then
27738 begin delete_token_ref(split_first_mark); split_first_mark:=null;
27739 delete_token_ref(split_bot_mark); split_bot_mark:=null;
27740 end;
27741 @<Dispense with trivial cases of void or bad boxes@>;
27742 q:=vert_break(list_ptr(v),h,split_max_depth);
27743 @<Look at all the marks in nodes before the break, and set the final
27744 link to |null| at the break@>;
27745 q:=prune_page_top(q,saving_vdiscards>0);
27746 p:=list_ptr(v); free_node(v,box_node_size);
27747 if q<>null then q:=vpack(q,natural);
27748 change_box(q); {the |eq_level| of the box stays the same}
27749 vsplit:=vpackage(p,h,exactly,split_max_depth);
27750 exit: end;
27751
27752 @ @<Dispense with trivial cases of void or bad boxes@>=
27753 if v=null then
27754 begin vsplit:=null; return;
27755 end;
27756 if type(v)<>vlist_node then
27757 begin print_err(""); print_esc("vsplit"); print(" needs a ");
27758 print_esc("vbox");
27759 @:vsplit_}{\.{\\vsplit needs a \\vbox}@>
27760 help2("The box you are trying to split is an \hbox.")@/
27761 ("I can't split such a box, so I'll leave it alone.");
27762 error; vsplit:=null; return;
27763 end
27764
27765 @ It's possible that the box begins with a penalty node that is the
27766 ``best'' break, so we must be careful to handle this special case correctly.
27767
27768 @<Look at all the marks...@>=
27769 p:=list_ptr(v);
27770 if p=q then list_ptr(v):=null
27771 else loop@+begin if type(p)=mark_node then
27772 if mark_class(p)<>0 then @<Update the current marks for |vsplit|@>
27773 else if split_first_mark=null then
27774 begin split_first_mark:=mark_ptr(p);
27775 split_bot_mark:=split_first_mark;
27776 token_ref_count(split_first_mark):=@|
27777 token_ref_count(split_first_mark)+2;
27778 end
27779 else begin delete_token_ref(split_bot_mark);
27780 split_bot_mark:=mark_ptr(p);
27781 add_token_ref(split_bot_mark);
27782 end;
27783 if link(p)=q then
27784 begin link(p):=null; goto done;
27785 end;
27786 p:=link(p);
27787 end;
27788 done:
27789
27790 @* \[45] The page builder.
27791 When \TeX\ appends new material to its main vlist in vertical mode, it uses
27792 a method something like |vsplit| to decide where a page ends, except that
27793 the calculations are done ``on line'' as new items come in.
27794 The main complication in this process is that insertions must be put
27795 into their boxes and removed from the vlist, in a more-or-less optimum manner.
27796
27797 We shall use the term ``current page'' for that part of the main vlist that
27798 is being considered as a candidate for being broken off and sent to the
27799 user's output routine. The current page starts at |link(page_head)|, and
27800 it ends at |page_tail|. We have |page_head=page_tail| if this list is empty.
27801 @^current page@>
27802
27803 Utter chaos would reign if the user kept changing page specifications
27804 while a page is being constructed, so the page builder keeps the pertinent
27805 specifications frozen as soon as the page receives its first box or
27806 insertion. The global variable |page_contents| is |empty| when the
27807 current page contains only mark nodes and content-less whatsit nodes; it
27808 is |inserts_only| if the page contains only insertion nodes in addition to
27809 marks and whatsits. Glue nodes, kern nodes, and penalty nodes are
27810 discarded until a box or rule node appears, at which time |page_contents|
27811 changes to |box_there|. As soon as |page_contents| becomes non-|empty|,
27812 the current |vsize| and |max_depth| are squirreled away into |page_goal|
27813 and |page_max_depth|; the latter values will be used until the page has
27814 been forwarded to the user's output routine. The \.{\\topskip} adjustment
27815 is made when |page_contents| changes to |box_there|.
27816
27817 Although |page_goal| starts out equal to |vsize|, it is decreased by the
27818 scaled natural height-plus-depth of the insertions considered so far, and by
27819 the \.{\\skip} corrections for those insertions. Therefore it represents
27820 the size into which the non-inserted material should fit, assuming that
27821 all insertions in the current page have been made.
27822
27823 The global variables |best_page_break| and |least_page_cost| correspond
27824 respectively to the local variables |best_place| and |least_cost| in the
27825 |vert_break| routine that we have already studied; i.e., they record the
27826 location and value of the best place currently known for breaking the
27827 current page. The value of |page_goal| at the time of the best break is
27828 stored in |best_size|.
27829
27830 @d inserts_only=1
27831 {|page_contents| when an insert node has been contributed, but no boxes}
27832 @d box_there=2 {|page_contents| when a box or rule has been contributed}
27833
27834 @<Glob...@>=
27835 @!page_tail:pointer; {the final node on the current page}
27836 @!page_contents:empty..box_there; {what is on the current page so far?}
27837 @!page_max_depth:scaled; {maximum box depth on page being built}
27838 @!best_page_break:pointer; {break here to get the best page known so far}
27839 @!least_page_cost:integer; {the score for this currently best page}
27840 @!best_size:scaled; {its |page_goal|}
27841
27842 @ The page builder has another data structure to keep track of insertions.
27843 This is a list of four-word nodes, starting and ending at |page_ins_head|.
27844 That is, the first element of the list is node |r@t$_1$@>=link(page_ins_head)|;
27845 node $r_j$ is followed by |r@t$_{j+1}$@>=link(r@t$_j$@>)|; and if there are
27846 |n| items we have |r@t$_{n+1}$@>=page_ins_head|. The |subtype| field of
27847 each node in this list refers to an insertion number; for example, `\.{\\insert
27848 250}' would correspond to a node whose |subtype| is |qi(250)|
27849 (the same as the |subtype| field of the relevant |ins_node|). These |subtype|
27850 fields are in increasing order, and |subtype(page_ins_head)=
27851 qi(255)|, so |page_ins_head| serves as a convenient sentinel
27852 at the end of the list. A record is present for each insertion number that
27853 appears in the current page.
27854
27855 The |type| field in these nodes distinguishes two possibilities that
27856 might occur as we look ahead before deciding on the optimum page break.
27857 If |type(r)=inserting|, then |height(r)| contains the total of the
27858 height-plus-depth dimensions of the box and all its inserts seen so far.
27859 If |type(r)=split_up|, then no more insertions will be made into this box,
27860 because at least one previous insertion was too big to fit on the current
27861 page; |broken_ptr(r)| points to the node where that insertion will be
27862 split, if \TeX\ decides to split it, |broken_ins(r)| points to the
27863 insertion node that was tentatively split, and |height(r)| includes also the
27864 natural height plus depth of the part that would be split off.
27865
27866 In both cases, |last_ins_ptr(r)| points to the last |ins_node|
27867 encountered for box |qo(subtype(r))| that would be at least partially
27868 inserted on the next page; and |best_ins_ptr(r)| points to the last
27869 such |ins_node| that should actually be inserted, to get the page with
27870 minimum badness among all page breaks considered so far. We have
27871 |best_ins_ptr(r)=null| if and only if no insertion for this box should
27872 be made to produce this optimum page.
27873
27874 The data structure definitions here use the fact that the |@!height| field
27875 appears in the fourth word of a box node.
27876 @^data structure assumptions@>
27877
27878 @d page_ins_node_size=4 {number of words for a page insertion node}
27879 @d inserting=0 {an insertion class that has not yet overflowed}
27880 @d split_up=1 {an overflowed insertion class}
27881 @d broken_ptr(#)==link(#+1)
27882 {an insertion for this class will break here if anywhere}
27883 @d broken_ins(#)==info(#+1) {this insertion might break at |broken_ptr|}
27884 @d last_ins_ptr(#)==link(#+2) {the most recent insertion for this |subtype|}
27885 @d best_ins_ptr(#)==info(#+2) {the optimum most recent insertion}
27886
27887 @<Initialize the special list heads...@>=
27888 subtype(page_ins_head):=qi(255);
27889 type(page_ins_head):=split_up; link(page_ins_head):=page_ins_head;
27890
27891 @ An array |page_so_far| records the heights and depths of everything
27892 on the current page. This array contains six |scaled| numbers, like the
27893 similar arrays already considered in |line_break| and |vert_break|; and it
27894 also contains |page_goal| and |page_depth|, since these values are
27895 all accessible to the user via |set_page_dimen| commands. The
27896 value of |page_so_far[1]| is also called |page_total|. The stretch
27897 and shrink components of the \.{\\skip} corrections for each insertion are
27898 included in |page_so_far|, but the natural space components of these
27899 corrections are not, since they have been subtracted from |page_goal|.
27900
27901 The variable |page_depth| records the depth of the current page; it has been
27902 adjusted so that it is at most |page_max_depth|. The variable
27903 |last_glue| points to the glue specification of the most recent node
27904 contributed from the contribution list, if this was a glue node; otherwise
27905 |last_glue=max_halfword|. (If the contribution list is nonempty,
27906 however, the value of |last_glue| is not necessarily accurate.)
27907 The variables |last_penalty|, |last_kern|, and |last_node_type|
27908 are similar. And
27909 finally, |insert_penalties| holds the sum of the penalties associated with
27910 all split and floating insertions.
27911
27912 @d page_goal==page_so_far[0] {desired height of information on page being built}
27913 @d page_total==page_so_far[1] {height of the current page}
27914 @d page_shrink==page_so_far[6] {shrinkability of the current page}
27915 @d page_depth==page_so_far[7] {depth of the current page}
27916
27917 @<Glob...@>=
27918 @!page_so_far:array [0..7] of scaled; {height and glue of the current page}
27919 @!last_glue:pointer; {used to implement \.{\\lastskip}}
27920 @!last_penalty:integer; {used to implement \.{\\lastpenalty}}
27921 @!last_kern:scaled; {used to implement \.{\\lastkern}}
27922 @!last_node_type:integer; {used to implement \.{\\lastnodetype}}
27923 @!insert_penalties:integer; {sum of the penalties for insertions
27924 that were held over}
27925
27926 @ @<Put each...@>=
27927 primitive("pagegoal",set_page_dimen,0);
27928 @!@:page_goal_}{\.{\\pagegoal} primitive@>
27929 primitive("pagetotal",set_page_dimen,1);
27930 @!@:page_total_}{\.{\\pagetotal} primitive@>
27931 primitive("pagestretch",set_page_dimen,2);
27932 @!@:page_stretch_}{\.{\\pagestretch} primitive@>
27933 primitive("pagefilstretch",set_page_dimen,3);
27934 @!@:page_fil_stretch_}{\.{\\pagefilstretch} primitive@>
27935 primitive("pagefillstretch",set_page_dimen,4);
27936 @!@:page_fill_stretch_}{\.{\\pagefillstretch} primitive@>
27937 primitive("pagefilllstretch",set_page_dimen,5);
27938 @!@:page_filll_stretch_}{\.{\\pagefilllstretch} primitive@>
27939 primitive("pageshrink",set_page_dimen,6);
27940 @!@:page_shrink_}{\.{\\pageshrink} primitive@>
27941 primitive("pagedepth",set_page_dimen,7);
27942 @!@:page_depth_}{\.{\\pagedepth} primitive@>
27943
27944 @ @<Cases of |print_cmd_chr|...@>=
27945 set_page_dimen: case chr_code of
27946 0: print_esc("pagegoal");
27947 1: print_esc("pagetotal");
27948 2: print_esc("pagestretch");
27949 3: print_esc("pagefilstretch");
27950 4: print_esc("pagefillstretch");
27951 5: print_esc("pagefilllstretch");
27952 6: print_esc("pageshrink");
27953 othercases print_esc("pagedepth")
27954 endcases;
27955
27956 @ @d print_plus_end(#)==print(#);@+end
27957 @d print_plus(#)==if page_so_far[#]<>0 then
27958 begin print(" plus "); print_scaled(page_so_far[#]); print_plus_end
27959
27960 @p procedure print_totals;
27961 begin print_scaled(page_total);
27962 print_plus(2)("");
27963 print_plus(3)("fil");
27964 print_plus(4)("fill");
27965 print_plus(5)("filll");
27966 if page_shrink<>0 then
27967 begin print(" minus "); print_scaled(page_shrink);
27968 end;
27969 end;
27970
27971 @ @<Show the status of the current page@>=
27972 if page_head<>page_tail then
27973 begin print_nl("### current page:");
27974 if output_active then print(" (held over for next output)");
27975 @.held over for next output@>
27976 show_box(link(page_head));
27977 if page_contents>empty then
27978 begin print_nl("total height "); print_totals;
27979 @:total_height}{\.{total height}@>
27980 print_nl(" goal height "); print_scaled(page_goal);
27981 @.goal height@>
27982 r:=link(page_ins_head);
27983 while r<>page_ins_head do
27984 begin print_ln; print_esc("insert"); t:=qo(subtype(r));
27985 print_int(t); print(" adds ");
27986 if count(t)=1000 then t:=height(r)
27987 else t:=x_over_n(height(r),1000)*count(t);
27988 print_scaled(t);
27989 if type(r)=split_up then
27990 begin q:=page_head; t:=0;
27991 repeat q:=link(q);
27992 if (type(q)=ins_node)and(subtype(q)=subtype(r)) then incr(t);
27993 until q=broken_ins(r);
27994 print(", #"); print_int(t); print(" might split");
27995 end;
27996 r:=link(r);
27997 end;
27998 end;
27999 end
28000
28001 @ Here is a procedure that is called when the |page_contents| is changing
28002 from |empty| to |inserts_only| or |box_there|.
28003
28004 @d set_page_so_far_zero(#)==page_so_far[#]:=0
28005
28006 @p procedure freeze_page_specs(@!s:small_number);
28007 begin page_contents:=s;
28008 page_goal:=vsize; page_max_depth:=max_depth;
28009 page_depth:=0; do_all_six(set_page_so_far_zero);
28010 least_page_cost:=awful_bad;
28011 @!stat if tracing_pages>0 then
28012 begin begin_diagnostic;
28013 print_nl("%% goal height="); print_scaled(page_goal);
28014 @.goal height@>
28015 print(", max depth="); print_scaled(page_max_depth);
28016 end_diagnostic(false);
28017 end;@;@+tats@;@/
28018 end;
28019
28020 @ Pages are built by appending nodes to the current list in \TeX's
28021 vertical mode, which is at the outermost level of the semantic nest. This
28022 vlist is split into two parts; the ``current page'' that we have been
28023 talking so much about already, and the ``contribution list'' that receives
28024 new nodes as they are created. The current page contains everything that
28025 the page builder has accounted for in its data structures, as described
28026 above, while the contribution list contains other things that have been
28027 generated by other parts of \TeX\ but have not yet been
28028 seen by the page builder.
28029 The contribution list starts at |link(contrib_head)|, and it ends at the
28030 current node in \TeX's vertical mode.
28031
28032 When \TeX\ has appended new material in vertical mode, it calls the procedure
28033 |build_page|, which tries to catch up by moving nodes from the contribution
28034 list to the current page. This procedure will succeed in its goal of
28035 emptying the contribution list, unless a page break is discovered, i.e.,
28036 unless the current page has grown to the point where the optimum next
28037 page break has been determined. In the latter case, the nodes after the
28038 optimum break will go back onto the contribution list, and control will
28039 effectively pass to the user's output routine.
28040
28041 We make |type(page_head)=glue_node|, so that an initial glue node on
28042 the current page will not be considered a valid breakpoint.
28043
28044 @<Initialize the special list...@>=
28045 type(page_head):=glue_node; subtype(page_head):=normal;
28046
28047 @ The global variable |output_active| is true during the time the
28048 user's output routine is driving \TeX.
28049
28050 @<Glob...@>=
28051 @!output_active:boolean; {are we in the midst of an output routine?}
28052
28053 @ @<Set init...@>=
28054 output_active:=false; insert_penalties:=0;
28055
28056 @ The page builder is ready to start a fresh page if we initialize
28057 the following state variables. (However, the page insertion list is initialized
28058 elsewhere.)
28059
28060 @<Start a new current page@>=
28061 page_contents:=empty; page_tail:=page_head; link(page_head):=null;@/
28062 last_glue:=max_halfword; last_penalty:=0; last_kern:=0;
28063 last_node_type:=-1;
28064 page_depth:=0; page_max_depth:=0
28065
28066 @ At certain times box 255 is supposed to be void (i.e., |null|),
28067 or an insertion box is supposed to be ready to accept a vertical list.
28068 If not, an error message is printed, and the following subroutine
28069 flushes the unwanted contents, reporting them to the user.
28070
28071 @p procedure box_error(@!n:eight_bits);
28072 begin error; begin_diagnostic;
28073 print_nl("The following box has been deleted:");
28074 @.The following...deleted@>
28075 show_box(box(n)); end_diagnostic(true);
28076 flush_node_list(box(n)); box(n):=null;
28077 end;
28078
28079 @ The following procedure guarantees that a given box register
28080 does not contain an \.{\\hbox}.
28081
28082 @p procedure ensure_vbox(@!n:eight_bits);
28083 var p:pointer; {the box register contents}
28084 begin p:=box(n);
28085 if p<>null then if type(p)=hlist_node then
28086 begin print_err("Insertions can only be added to a vbox");
28087 @.Insertions can only...@>
28088 help3("Tut tut: You're trying to \insert into a")@/
28089 ("\box register that now contains an \hbox.")@/
28090 ("Proceed, and I'll discard its present contents.");
28091 box_error(n);
28092 end;
28093 end;
28094
28095 @ \TeX\ is not always in vertical mode at the time |build_page|
28096 is called; the current mode reflects what \TeX\ should return to, after
28097 the contribution list has been emptied. A call on |build_page| should
28098 be immediately followed by `|goto big_switch|', which is \TeX's central
28099 control point.
28100
28101 @d contribute=80 {go here to link a node into the current page}
28102
28103 @p @t\4@>@<Declare the procedure called |fire_up|@>@;@/
28104 procedure build_page; {append contributions to the current page}
28105 label exit,done,done1,continue,contribute,update_heights;
28106 var p:pointer; {the node being appended}
28107 @!q,@!r:pointer; {nodes being examined}
28108 @!b,@!c:integer; {badness and cost of current page}
28109 @!pi:integer; {penalty to be added to the badness}
28110 @!n:min_quarterword..255; {insertion box number}
28111 @!delta,@!h,@!w:scaled; {sizes used for insertion calculations}
28112 begin if (link(contrib_head)=null)or output_active then return;
28113 repeat continue: p:=link(contrib_head);@/
28114 @<Update the values of |last_glue|, |last_penalty|, and |last_kern|@>;
28115 @<Move node |p| to the current page; if it is time for a page break,
28116 put the nodes following the break back onto the contribution list,
28117 and |return| to the user's output routine if there is one@>;
28118 until link(contrib_head)=null;
28119 @<Make the contribution list empty by setting its tail to |contrib_head|@>;
28120 exit:end;
28121
28122 @ @d contrib_tail==nest[0].tail_field {tail of the contribution list}
28123
28124 @<Make the contribution list empty...@>=
28125 if nest_ptr=0 then tail:=contrib_head {vertical mode}
28126 else contrib_tail:=contrib_head {other modes}
28127
28128 @ @<Update the values of |last_glue|...@>=
28129 if last_glue<>max_halfword then delete_glue_ref(last_glue);
28130 last_penalty:=0; last_kern:=0;
28131 last_node_type:=type(p)+1;
28132 if type(p)=glue_node then
28133 begin last_glue:=glue_ptr(p); add_glue_ref(last_glue);
28134 end
28135 else begin last_glue:=max_halfword;
28136 if type(p)=penalty_node then last_penalty:=penalty(p)
28137 else if type(p)=kern_node then last_kern:=width(p);
28138 end
28139
28140 @ The code here is an example of a many-way switch into routines that
28141 merge together in different places. Some people call this unstructured
28142 programming, but the author doesn't see much wrong with it, as long as
28143 @^Knuth, Donald Ervin@>
28144 the various labels have a well-understood meaning.
28145
28146 @<Move node |p| to the current page; ...@>=
28147 @<If the current page is empty and node |p| is to be deleted, |goto done1|;
28148 otherwise use node |p| to update the state of the current page;
28149 if this node is an insertion, |goto contribute|; otherwise if this node
28150 is not a legal breakpoint, |goto contribute| or |update_heights|;
28151 otherwise set |pi| to the penalty associated with this breakpoint@>;
28152 @<Check if node |p| is a new champion breakpoint; then \(if)if it is time for
28153 a page break, prepare for output, and either fire up the user's
28154 output routine and |return| or ship out the page and |goto done|@>;
28155 if (type(p)<glue_node)or(type(p)>kern_node) then goto contribute;
28156 update_heights:@<Update the current page measurements with respect to the
28157 glue or kern specified by node~|p|@>;
28158 contribute: @<Make sure that |page_max_depth| is not exceeded@>;
28159 @<Link node |p| into the current page and |goto done|@>;
28160 done1:@<Recycle node |p|@>;
28161 done:
28162
28163 @ @<Link node |p| into the current page and |goto done|@>=
28164 link(page_tail):=p; page_tail:=p;
28165 link(contrib_head):=link(p); link(p):=null; goto done
28166
28167 @ @<Recycle node |p|@>=
28168 link(contrib_head):=link(p); link(p):=null;
28169 if saving_vdiscards>0 then
28170 begin if page_disc=null then page_disc:=p@+else link(tail_page_disc):=p;
28171 tail_page_disc:=p;
28172 end
28173 else flush_node_list(p)
28174
28175 @ The title of this section is already so long, it seems best to avoid
28176 making it more accurate but still longer, by mentioning the fact that a
28177 kern node at the end of the contribution list will not be contributed until
28178 we know its successor.
28179
28180 @<If the current page is empty...@>=
28181 case type(p) of
28182 hlist_node,vlist_node,rule_node: if page_contents<box_there then
28183 @<Initialize the current page, insert the \.{\\topskip} glue
28184 ahead of |p|, and |goto continue|@>
28185 else @<Prepare to move a box or rule node to the current page,
28186 then |goto contribute|@>;
28187 whatsit_node: if (page_contents < box_there) and
28188 ((subtype(p) = pdf_snapy_node) or
28189 (subtype(p) = pdf_snapy_comp_node)) then
28190 begin
28191 print("snap node being discarded");
28192 goto done1;
28193 end
28194 else @<Prepare to move whatsit |p| to the current page,
28195 then |goto contribute|@>;
28196 glue_node: if page_contents<box_there then goto done1
28197 else if precedes_break(page_tail) then pi:=0
28198 else goto update_heights;
28199 kern_node: if page_contents<box_there then goto done1
28200 else if link(p)=null then return
28201 else if type(link(p))=glue_node then pi:=0
28202 else goto update_heights;
28203 penalty_node: if page_contents<box_there then goto done1@+else pi:=penalty(p);
28204 mark_node: goto contribute;
28205 ins_node: @<Append an insertion to the current page and |goto contribute|@>;
28206 othercases confusion("page")
28207 @:this can't happen page}{\quad page@>
28208 endcases
28209
28210 @ @<Initialize the current page, insert the \.{\\topskip} glue...@>=
28211 begin if page_contents=empty then freeze_page_specs(box_there)
28212 else page_contents:=box_there;
28213 q:=new_skip_param(top_skip_code); {now |temp_ptr=glue_ptr(q)|}
28214 if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
28215 else width(temp_ptr):=0;
28216 link(q):=p; link(contrib_head):=q; goto continue;
28217 end
28218
28219 @ @<Prepare to move a box or rule node to the current page...@>=
28220 begin page_total:=page_total+page_depth+height(p);
28221 page_depth:=depth(p);
28222 goto contribute;
28223 end
28224
28225 @ @<Make sure that |page_max_depth| is not exceeded@>=
28226 if page_depth>page_max_depth then
28227 begin page_total:=@|
28228 page_total+page_depth-page_max_depth;@/
28229 page_depth:=page_max_depth;
28230 end;
28231
28232 @ @<Update the current page measurements with respect to the glue...@>=
28233 if type(p)=kern_node then q:=p
28234 else begin q:=glue_ptr(p);
28235 page_so_far[2+stretch_order(q)]:=@|
28236 page_so_far[2+stretch_order(q)]+stretch(q);@/
28237 page_shrink:=page_shrink+shrink(q);
28238 if (shrink_order(q)<>normal)and(shrink(q)<>0) then
28239 begin@t@>@;@/
28240 print_err("Infinite glue shrinkage found on current page");@/
28241 @.Infinite glue shrinkage...@>
28242 help4("The page about to be output contains some infinitely")@/
28243 ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
28244 ("Such glue doesn't belong there; but you can safely proceed,")@/
28245 ("since the offensive shrinkability has been made finite.");
28246 error;
28247 r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
28248 glue_ptr(p):=r; q:=r;
28249 end;
28250 end;
28251 page_total:=page_total+page_depth+width(q); page_depth:=0
28252
28253 @ @<Check if node |p| is a new champion breakpoint; then \(if)...@>=
28254 if pi<inf_penalty then
28255 begin @<Compute the badness, |b|, of the current page,
28256 using |awful_bad| if the box is too full@>;
28257 if b<awful_bad then
28258 if pi<=eject_penalty then c:=pi
28259 else if b<inf_bad then c:=b+pi+insert_penalties
28260 else c:=deplorable
28261 else c:=b;
28262 if insert_penalties>=10000 then c:=awful_bad;
28263 @!stat if tracing_pages>0 then @<Display the page break cost@>;@+tats@;@/
28264 if c<=least_page_cost then
28265 begin best_page_break:=p; best_size:=page_goal;
28266 least_page_cost:=c;
28267 r:=link(page_ins_head);
28268 while r<>page_ins_head do
28269 begin best_ins_ptr(r):=last_ins_ptr(r);
28270 r:=link(r);
28271 end;
28272 end;
28273 if (c=awful_bad)or(pi<=eject_penalty) then
28274 begin fire_up(p); {output the current page at the best place}
28275 if output_active then return; {user's output routine will act}
28276 goto done; {the page has been shipped out by default output routine}
28277 end;
28278 end
28279
28280 @ @<Display the page break cost@>=
28281 begin begin_diagnostic; print_nl("%");
28282 print(" t="); print_totals;@/
28283 print(" g="); print_scaled(page_goal);@/
28284 print(" b=");
28285 if b=awful_bad then print_char("*")@+else print_int(b);
28286 @.*\relax@>
28287 print(" p="); print_int(pi);
28288 print(" c=");
28289 if c=awful_bad then print_char("*")@+else print_int(c);
28290 if c<=least_page_cost then print_char("#");
28291 end_diagnostic(false);
28292 end
28293
28294 @ @<Compute the badness, |b|, of the current page...@>=
28295 if page_total<page_goal then
28296 if (page_so_far[3]<>0) or (page_so_far[4]<>0) or@|
28297 (page_so_far[5]<>0) then b:=0
28298 else b:=badness(page_goal-page_total,page_so_far[2])
28299 else if page_total-page_goal>page_shrink then b:=awful_bad
28300 else b:=badness(page_total-page_goal,page_shrink)
28301
28302 @ @<Append an insertion to the current page and |goto contribute|@>=
28303 begin if page_contents=empty then freeze_page_specs(inserts_only);
28304 n:=subtype(p); r:=page_ins_head;
28305 while n>=subtype(link(r)) do r:=link(r);
28306 n:=qo(n);
28307 if subtype(r)<>qi(n) then
28308 @<Create a page insertion node with |subtype(r)=qi(n)|, and
28309 include the glue correction for box |n| in the
28310 current page state@>;
28311 if type(r)=split_up then insert_penalties:=insert_penalties+float_cost(p)
28312 else begin last_ins_ptr(r):=p;
28313 delta:=page_goal-page_total-page_depth+page_shrink;
28314 {this much room is left if we shrink the maximum}
28315 if count(n)=1000 then h:=height(p)
28316 else h:=x_over_n(height(p),1000)*count(n); {this much room is needed}
28317 if ((h<=0)or(h<=delta))and(height(p)+height(r)<=dimen(n)) then
28318 begin page_goal:=page_goal-h; height(r):=height(r)+height(p);
28319 end
28320 else @<Find the best way to split the insertion, and change
28321 |type(r)| to |split_up|@>;
28322 end;
28323 goto contribute;
28324 end
28325
28326 @ We take note of the value of \.{\\skip} |n| and the height plus depth
28327 of \.{\\box}~|n| only when the first \.{\\insert}~|n| node is
28328 encountered for a new page. A user who changes the contents of \.{\\box}~|n|
28329 after that first \.{\\insert}~|n| had better be either extremely careful
28330 or extremely lucky, or both.
28331
28332 @<Create a page insertion node...@>=
28333 begin q:=get_node(page_ins_node_size); link(q):=link(r); link(r):=q; r:=q;
28334 subtype(r):=qi(n); type(r):=inserting; ensure_vbox(n);
28335 if box(n)=null then height(r):=0
28336 else height(r):=height(box(n))+depth(box(n));
28337 best_ins_ptr(r):=null;@/
28338 q:=skip(n);
28339 if count(n)=1000 then h:=height(r)
28340 else h:=x_over_n(height(r),1000)*count(n);
28341 page_goal:=page_goal-h-width(q);@/
28342 page_so_far[2+stretch_order(q)]:=@|page_so_far[2+stretch_order(q)]+stretch(q);@/
28343 page_shrink:=page_shrink+shrink(q);
28344 if (shrink_order(q)<>normal)and(shrink(q)<>0) then
28345 begin print_err("Infinite glue shrinkage inserted from "); print_esc("skip");
28346 @.Infinite glue shrinkage...@>
28347 print_int(n);
28348 help3("The correction glue for page breaking with insertions")@/
28349 ("must have finite shrinkability. But you may proceed,")@/
28350 ("since the offensive shrinkability has been made finite.");
28351 error;
28352 end;
28353 end
28354
28355 @ Here is the code that will split a long footnote between pages, in an
28356 emergency. The current situation deserves to be recapitulated: Node |p|
28357 is an insertion into box |n|; the insertion will not fit, in its entirety,
28358 either because it would make the total contents of box |n| greater than
28359 \.{\\dimen} |n|, or because it would make the incremental amount of growth
28360 |h| greater than the available space |delta|, or both. (This amount |h| has
28361 been weighted by the insertion scaling factor, i.e., by \.{\\count} |n|
28362 over 1000.) Now we will choose the best way to break the vlist of the
28363 insertion, using the same criteria as in the \.{\\vsplit} operation.
28364
28365 @<Find the best way to split the insertion...@>=
28366 begin if count(n)<=0 then w:=max_dimen
28367 else begin w:=page_goal-page_total-page_depth;
28368 if count(n)<>1000 then w:=x_over_n(w,count(n))*1000;
28369 end;
28370 if w>dimen(n)-height(r) then w:=dimen(n)-height(r);
28371 q:=vert_break(ins_ptr(p),w,depth(p));
28372 height(r):=height(r)+best_height_plus_depth;
28373 @!stat if tracing_pages>0 then @<Display the insertion split cost@>;@+tats@;@/
28374 if count(n)<>1000 then
28375 best_height_plus_depth:=x_over_n(best_height_plus_depth,1000)*count(n);
28376 page_goal:=page_goal-best_height_plus_depth;
28377 type(r):=split_up; broken_ptr(r):=q; broken_ins(r):=p;
28378 if q=null then insert_penalties:=insert_penalties+eject_penalty
28379 else if type(q)=penalty_node then insert_penalties:=insert_penalties+penalty(q);
28380 end
28381
28382 @ @<Display the insertion split cost@>=
28383 begin begin_diagnostic; print_nl("% split"); print_int(n);
28384 @.split@>
28385 print(" to "); print_scaled(w);
28386 print_char(","); print_scaled(best_height_plus_depth);@/
28387 print(" p=");
28388 if q=null then print_int(eject_penalty)
28389 else if type(q)=penalty_node then print_int(penalty(q))
28390 else print_char("0");
28391 end_diagnostic(false);
28392 end
28393
28394 @ When the page builder has looked at as much material as could appear before
28395 the next page break, it makes its decision. The break that gave minimum
28396 badness will be used to put a completed ``page'' into box 255, with insertions
28397 appended to their other boxes.
28398
28399 We also set the values of |top_mark|, |first_mark|, and |bot_mark|. The
28400 program uses the fact that |bot_mark<>null| implies |first_mark<>null|;
28401 it also knows that |bot_mark=null| implies |top_mark=first_mark=null|.
28402
28403 The |fire_up| subroutine prepares to output the current page at the best
28404 place; then it fires up the user's output routine, if there is one,
28405 or it simply ships out the page. There is one parameter, |c|, which represents
28406 the node that was being contributed to the page when the decision to
28407 force an output was made.
28408
28409 @<Declare the procedure called |fire_up|@>=
28410 procedure fire_up(@!c:pointer);
28411 label exit;
28412 var p,@!q,@!r,@!s:pointer; {nodes being examined and/or changed}
28413 @!prev_p:pointer; {predecessor of |p|}
28414 @!n:min_quarterword..255; {insertion box number}
28415 @!wait:boolean; {should the present insertion be held over?}
28416 @!save_vbadness:integer; {saved value of |vbadness|}
28417 @!save_vfuzz: scaled; {saved value of |vfuzz|}
28418 @!save_split_top_skip: pointer; {saved value of |split_top_skip|}
28419 begin @<Set the value of |output_penalty|@>;
28420 if sa_mark<>null then
28421 if do_marks(fire_up_init,0,sa_mark) then sa_mark:=null;
28422 if bot_mark<>null then
28423 begin if top_mark<>null then delete_token_ref(top_mark);
28424 top_mark:=bot_mark; add_token_ref(top_mark);
28425 delete_token_ref(first_mark); first_mark:=null;
28426 end;
28427 @<Put the \(o)optimal current page into box 255, update |first_mark| and
28428 |bot_mark|, append insertions to their boxes, and put the
28429 remaining nodes back on the contribution list@>;
28430 if sa_mark<>null then
28431 if do_marks(fire_up_done,0,sa_mark) then sa_mark:=null;
28432 if (top_mark<>null)and(first_mark=null) then
28433 begin first_mark:=top_mark; add_token_ref(top_mark);
28434 end;
28435 if output_routine<>null then
28436 if dead_cycles>=max_dead_cycles then
28437 @<Explain that too many dead cycles have occurred in a row@>
28438 else @<Fire up the user's output routine and |return|@>;
28439 @<Perform the default output routine@>;
28440 exit:end;
28441
28442 @ @<Set the value of |output_penalty|@>=
28443 if type(best_page_break)=penalty_node then
28444 begin geq_word_define(int_base+output_penalty_code,penalty(best_page_break));
28445 penalty(best_page_break):=inf_penalty;
28446 end
28447 else geq_word_define(int_base+output_penalty_code,inf_penalty)
28448
28449 @ As the page is finally being prepared for output,
28450 pointer |p| runs through the vlist, with |prev_p| trailing behind;
28451 pointer |q| is the tail of a list of insertions that
28452 are being held over for a subsequent page.
28453
28454 @<Put the \(o)optimal current page into box 255...@>=
28455 if c=best_page_break then best_page_break:=null; {|c| not yet linked in}
28456 @<Ensure that box 255 is empty before output@>;
28457 insert_penalties:=0; {this will count the number of insertions held over}
28458 save_split_top_skip:=split_top_skip;
28459 if holding_inserts<=0 then
28460 @<Prepare all the boxes involved in insertions to act as queues@>;
28461 q:=hold_head; link(q):=null; prev_p:=page_head; p:=link(prev_p);
28462 while p<>best_page_break do
28463 begin if type(p)=ins_node then
28464 begin if holding_inserts<=0 then
28465 @<Either insert the material specified by node |p| into the
28466 appropriate box, or hold it for the next page;
28467 also delete node |p| from the current page@>;
28468 end
28469 else if type(p)=mark_node then
28470 if mark_class(p)<>0 then @<Update the current marks for |fire_up|@>
28471 else @<Update the values of
28472 |first_mark| and |bot_mark|@>;
28473 prev_p:=p; p:=link(prev_p);
28474 end;
28475 split_top_skip:=save_split_top_skip;
28476 @<Break the current page at node |p|, put it in box~255,
28477 and put the remaining nodes on the contribution list@>;
28478 @<Delete \(t)the page-insertion nodes@>
28479
28480 @ @<Ensure that box 255 is empty before output@>=
28481 if box(255)<>null then
28482 begin print_err(""); print_esc("box"); print("255 is not void");
28483 @:box255}{\.{\\box255 is not void}@>
28484 help2("You shouldn't use \box255 except in \output routines.")@/
28485 ("Proceed, and I'll discard its present contents.");
28486 box_error(255);
28487 end
28488
28489 @ @<Update the values of |first_mark| and |bot_mark|@>=
28490 begin if first_mark=null then
28491 begin first_mark:=mark_ptr(p);
28492 add_token_ref(first_mark);
28493 end;
28494 if bot_mark<>null then delete_token_ref(bot_mark);
28495 bot_mark:=mark_ptr(p); add_token_ref(bot_mark);
28496 end
28497
28498 @ When the following code is executed, the current page runs from node
28499 |link(page_head)| to node |prev_p|, and the nodes from |p| to |page_tail|
28500 are to be placed back at the front of the contribution list. Furthermore
28501 the heldover insertions appear in a list from |link(hold_head)| to |q|; we
28502 will put them into the current page list for safekeeping while the user's
28503 output routine is active. We might have |q=hold_head|; and |p=null| if
28504 and only if |prev_p=page_tail|. Error messages are suppressed within
28505 |vpackage|, since the box might appear to be overfull or underfull simply
28506 because the stretch and shrink from the \.{\\skip} registers for inserts
28507 are not actually present in the box.
28508
28509 @<Break the current page at node |p|, put it...@>=
28510 if p<>null then
28511 begin if link(contrib_head)=null then
28512 if nest_ptr=0 then tail:=page_tail
28513 else contrib_tail:=page_tail;
28514 link(page_tail):=link(contrib_head);
28515 link(contrib_head):=p;
28516 link(prev_p):=null;
28517 end;
28518 save_vbadness:=vbadness; vbadness:=inf_bad;
28519 save_vfuzz:=vfuzz; vfuzz:=max_dimen; {inhibit error messages}
28520 box(255):=vpackage(link(page_head),best_size,exactly,page_max_depth);
28521 vbadness:=save_vbadness; vfuzz:=save_vfuzz;
28522 if last_glue<>max_halfword then delete_glue_ref(last_glue);
28523 @<Start a new current page@>; {this sets |last_glue:=max_halfword|}
28524 if q<>hold_head then
28525 begin link(page_head):=link(hold_head); page_tail:=q;
28526 end
28527
28528 @ If many insertions are supposed to go into the same box, we want to know
28529 the position of the last node in that box, so that we don't need to waste time
28530 when linking further information into it. The |last_ins_ptr| fields of the
28531 page insertion nodes are therefore used for this purpose during the
28532 packaging phase.
28533
28534 @<Prepare all the boxes involved in insertions to act as queues@>=
28535 begin r:=link(page_ins_head);
28536 while r<>page_ins_head do
28537 begin if best_ins_ptr(r)<>null then
28538 begin n:=qo(subtype(r)); ensure_vbox(n);
28539 if box(n)=null then box(n):=new_null_box;
28540 p:=box(n)+list_offset;
28541 while link(p)<>null do p:=link(p);
28542 last_ins_ptr(r):=p;
28543 end;
28544 r:=link(r);
28545 end;
28546 end
28547
28548 @ @<Delete \(t)the page-insertion nodes@>=
28549 r:=link(page_ins_head);
28550 while r<>page_ins_head do
28551 begin q:=link(r); free_node(r,page_ins_node_size); r:=q;
28552 end;
28553 link(page_ins_head):=page_ins_head
28554
28555 @ We will set |best_ins_ptr:=null| and package the box corresponding to
28556 insertion node~|r|, just after making the final insertion into that box.
28557 If this final insertion is `|split_up|', the remainder after splitting
28558 and pruning (if any) will be carried over to the next page.
28559
28560 @<Either insert the material specified by node |p| into...@>=
28561 begin r:=link(page_ins_head);
28562 while subtype(r)<>subtype(p) do r:=link(r);
28563 if best_ins_ptr(r)=null then wait:=true
28564 else begin wait:=false; s:=last_ins_ptr(r); link(s):=ins_ptr(p);
28565 if best_ins_ptr(r)=p then
28566 @<Wrap up the box specified by node |r|, splitting node |p| if
28567 called for; set |wait:=true| if node |p| holds a remainder after
28568 splitting@>
28569 else begin while link(s)<>null do s:=link(s);
28570 last_ins_ptr(r):=s;
28571 end;
28572 end;
28573 @<Either append the insertion node |p| after node |q|, and remove it
28574 from the current page, or delete |node(p)|@>;
28575 end
28576
28577 @ @<Wrap up the box specified by node |r|, splitting node |p| if...@>=
28578 begin if type(r)=split_up then
28579 if (broken_ins(r)=p)and(broken_ptr(r)<>null) then
28580 begin while link(s)<>broken_ptr(r) do s:=link(s);
28581 link(s):=null;
28582 split_top_skip:=split_top_ptr(p);
28583 ins_ptr(p):=prune_page_top(broken_ptr(r),false);
28584 if ins_ptr(p)<>null then
28585 begin temp_ptr:=vpack(ins_ptr(p),natural);
28586 height(p):=height(temp_ptr)+depth(temp_ptr);
28587 free_node(temp_ptr,box_node_size); wait:=true;
28588 end;
28589 end;
28590 best_ins_ptr(r):=null;
28591 n:=qo(subtype(r));
28592 temp_ptr:=list_ptr(box(n));
28593 free_node(box(n),box_node_size);
28594 box(n):=vpack(temp_ptr,natural);
28595 end
28596
28597 @ @<Either append the insertion node |p|...@>=
28598 link(prev_p):=link(p); link(p):=null;
28599 if wait then
28600 begin link(q):=p; q:=p; incr(insert_penalties);
28601 end
28602 else begin delete_glue_ref(split_top_ptr(p));
28603 free_node(p,ins_node_size);
28604 end;
28605 p:=prev_p
28606
28607 @ The list of heldover insertions, running from |link(page_head)| to
28608 |page_tail|, must be moved to the contribution list when the user has
28609 specified no output routine.
28610
28611 @<Perform the default output routine@>=
28612 begin if link(page_head)<>null then
28613 begin if link(contrib_head)=null then
28614 if nest_ptr=0 then tail:=page_tail@+else contrib_tail:=page_tail
28615 else link(page_tail):=link(contrib_head);
28616 link(contrib_head):=link(page_head);
28617 link(page_head):=null; page_tail:=page_head;
28618 end;
28619 flush_node_list(page_disc); page_disc:=null;
28620 ship_out(box(255)); box(255):=null;
28621 end
28622
28623 @ @<Explain that too many dead cycles have occurred in a row@>=
28624 begin print_err("Output loop---"); print_int(dead_cycles);
28625 @.Output loop...@>
28626 print(" consecutive dead cycles");
28627 help3("I've concluded that your \output is awry; it never does a")@/
28628 ("\shipout, so I'm shipping \box255 out myself. Next time")@/
28629 ("increase \maxdeadcycles if you want me to be more patient!"); error;
28630 end
28631
28632 @ @<Fire up the user's output routine and |return|@>=
28633 begin output_active:=true;
28634 incr(dead_cycles);
28635 push_nest; mode:=-vmode; prev_depth:=pdf_ignored_dimen; mode_line:=-line;
28636 begin_token_list(output_routine,output_text);
28637 new_save_level(output_group); normal_paragraph;
28638 scan_left_brace;
28639 return;
28640 end
28641
28642 @ When the user's output routine finishes, it has constructed a vlist
28643 in internal vertical mode, and \TeX\ will do the following:
28644
28645 @<Resume the page builder after an output routine has come to an end@>=
28646 begin if (loc<>null) or
28647 ((token_type<>output_text)and(token_type<>backed_up)) then
28648 @<Recover from an unbalanced output routine@>;
28649 end_token_list; {conserve stack space in case more outputs are triggered}
28650 end_graf; unsave; output_active:=false; insert_penalties:=0;@/
28651 @<Ensure that box 255 is empty after output@>;
28652 if tail<>head then {current list goes after heldover insertions}
28653 begin link(page_tail):=link(head);
28654 page_tail:=tail;
28655 end;
28656 if link(page_head)<>null then {and both go before heldover contributions}
28657 begin if link(contrib_head)=null then contrib_tail:=page_tail;
28658 link(page_tail):=link(contrib_head);
28659 link(contrib_head):=link(page_head);
28660 link(page_head):=null; page_tail:=page_head;
28661 end;
28662 flush_node_list(page_disc); page_disc:=null;
28663 pop_nest; build_page;
28664 end
28665
28666 @ @<Recover from an unbalanced output routine@>=
28667 begin print_err("Unbalanced output routine");
28668 @.Unbalanced output routine@>
28669 help2("Your sneaky output routine has problematic {'s and/or }'s.")@/
28670 ("I can't handle that very well; good luck."); error;
28671 repeat get_token;
28672 until loc=null;
28673 end {loops forever if reading from a file, since |null=min_halfword<=0|}
28674
28675 @ @<Ensure that box 255 is empty after output@>=
28676 if box(255)<>null then
28677 begin print_err("Output routine didn't use all of ");
28678 print_esc("box"); print_int(255);
28679 @.Output routine didn't use...@>
28680 help3("Your \output commands should empty \box255,")@/
28681 ("e.g., by saying `\shipout\box255'.")@/
28682 ("Proceed; I'll discard its present contents.");
28683 box_error(255);
28684 end
28685
28686 @* \[46] The chief executive.
28687 We come now to the |main_control| routine, which contains the master
28688 switch that causes all the various pieces of \TeX\ to do their things,
28689 in the right order.
28690
28691 In a sense, this is the grand climax of the program: It applies all the
28692 tools that we have worked so hard to construct. In another sense, this is
28693 the messiest part of the program: It necessarily refers to other pieces
28694 of code all over the place, so that a person can't fully understand what is
28695 going on without paging back and forth to be reminded of conventions that
28696 are defined elsewhere. We are now at the hub of the web, the central nervous
28697 system that touches most of the other parts and ties them together.
28698 @^brain@>
28699
28700 The structure of |main_control| itself is quite simple. There's a label
28701 called |big_switch|, at which point the next token of input is fetched
28702 using |get_x_token|. Then the program branches at high speed into one of
28703 about 100 possible directions, based on the value of the current
28704 mode and the newly fetched command code; the sum |abs(mode)+cur_cmd|
28705 indicates what to do next. For example, the case `|vmode+letter|' arises
28706 when a letter occurs in vertical mode (or internal vertical mode); this
28707 case leads to instructions that initialize a new paragraph and enter
28708 horizontal mode.
28709
28710 The big |case| statement that contains this multiway switch has been labeled
28711 |reswitch|, so that the program can |goto reswitch| when the next token
28712 has already been fetched. Most of the cases are quite short; they call
28713 an ``action procedure'' that does the work for that case, and then they
28714 either |goto reswitch| or they ``fall through'' to the end of the |case|
28715 statement, which returns control back to |big_switch|. Thus, |main_control|
28716 is not an extremely large procedure, in spite of the multiplicity of things
28717 it must do; it is small enough to be handled by \PASCAL\ compilers that put
28718 severe restrictions on procedure size.
28719 @!@^action procedure@>
28720
28721 One case is singled out for special treatment, because it accounts for most
28722 of \TeX's activities in typical applications. The process of reading simple
28723 text and converting it into |char_node| records, while looking for ligatures
28724 and kerns, is part of \TeX's ``inner loop''; the whole program runs
28725 efficiently when its inner loop is fast, so this part has been written
28726 with particular care.
28727
28728 @ We shall concentrate first on the inner loop of |main_control|, deferring
28729 consideration of the other cases until later.
28730 @^inner loop@>
28731
28732 @d big_switch=60 {go here to branch on the next token of input}
28733 @d main_loop=70 {go here to typeset a string of consecutive characters}
28734 @d main_loop_wrapup=80 {go here to finish a character or ligature}
28735 @d main_loop_move=90 {go here to advance the ligature cursor}
28736 @d main_loop_move_lig=95 {same, when advancing past a generated ligature}
28737 @d main_loop_lookahead=100 {go here to bring in another character, if any}
28738 @d main_lig_loop=110 {go here to check for ligatures or kerning}
28739 @d append_normal_space=120 {go here to append a normal space between words}
28740
28741 @p @t\4@>@<Declare action procedures for use by |main_control|@>@;
28742 @t\4@>@<Declare the procedure called |handle_right_brace|@>@;
28743 procedure main_control; {governs \TeX's activities}
28744 label big_switch,reswitch,main_loop,main_loop_wrapup,
28745 main_loop_move,main_loop_move+1,main_loop_move+2,main_loop_move_lig,
28746 main_loop_lookahead,main_loop_lookahead+1,
28747 main_lig_loop,main_lig_loop+1,main_lig_loop+2,
28748 append_normal_space,exit;
28749 var@!t:integer; {general-purpose temporary variable}
28750 tmp_k1, tmp_k2: pointer; {for testing whether an auto kern should be inserted}
28751 begin if every_job<>null then begin_token_list(every_job,every_job_text);
28752 big_switch: get_x_token;@/
28753 reswitch: @<Give diagnostic information, if requested@>;
28754 case abs(mode)+cur_cmd of
28755 hmode+letter,hmode+other_char,hmode+char_given: goto main_loop;
28756 hmode+char_num: begin scan_char_num; cur_chr:=cur_val; goto main_loop;@+end;
28757 hmode+no_boundary: begin get_x_token;
28758 if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given)or
28759 (cur_cmd=char_num) then cancel_boundary:=true;
28760 goto reswitch;
28761 end;
28762 hmode+spacer:
28763 if (space_factor = 1000) or (pdf_adjust_interword_glue > 0) then
28764 goto append_normal_space
28765 else app_space;
28766 hmode+ex_space,mmode+ex_space: goto append_normal_space;
28767 @t\4@>@<Cases of |main_control| that are not part of the inner loop@>@;
28768 end; {of the big |case| statement}
28769 goto big_switch;
28770 main_loop:@<Append character |cur_chr| and the following characters (if~any)
28771 to the current hlist in the current font; |goto reswitch| when
28772 a non-character has been fetched@>;
28773 append_normal_space:@<Append a normal inter-word space to the current list,
28774 then |goto big_switch|@>;
28775 exit:end;
28776
28777 @ When a new token has just been fetched at |big_switch|, we have an
28778 ideal place to monitor \TeX's activity.
28779 @^debugging@>
28780
28781 @<Give diagnostic information, if requested@>=
28782 if interrupt<>0 then if OK_to_interrupt then
28783 begin back_input; check_interrupt; goto big_switch;
28784 end;
28785 @!debug if panicking then check_mem(false);@+@;@+gubed
28786 if tracing_commands>0 then show_cur_cmd_chr
28787
28788 @ The following part of the program was first written in a structured
28789 manner, according to the philosophy that ``premature optimization is
28790 the root of all evil.'' Then it was rearranged into pieces of
28791 spaghetti so that the most common actions could proceed with little or
28792 no redundancy.
28793
28794 The original unoptimized form of this algorithm resembles the
28795 |reconstitute| procedure, which was described earlier in connection with
28796 hyphenation. Again we have an implied ``cursor'' between characters
28797 |cur_l| and |cur_r|. The main difference is that the |lig_stack| can now
28798 contain a charnode as well as pseudo-ligatures; that stack is now
28799 usually nonempty, because the next character of input (if any) has been
28800 appended to it. In |main_control| we have
28801 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
28802 |font_bchar[cur_font]|,&otherwise;\cr}$$
28803 except when |character(lig_stack)=font_false_bchar[cur_font]|.
28804 Several additional global variables are needed.
28805
28806 @<Glob...@>=
28807 @!main_f:internal_font_number; {the current font}
28808 @!main_i:four_quarters; {character information bytes for |cur_l|}
28809 @!main_j:four_quarters; {ligature/kern command}
28810 @!main_k:font_index; {index into |font_info|}
28811 @!main_p:pointer; {temporary register for list manipulation}
28812 @!main_s:integer; {space factor value}
28813 @!bchar:halfword; {boundary character of current font, or |non_char|}
28814 @!false_bchar:halfword; {nonexistent character matching |bchar|, or |non_char|}
28815 @!cancel_boundary:boolean; {should the left boundary be ignored?}
28816 @!ins_disc:boolean; {should we insert a discretionary node?}
28817
28818 @ The boolean variables of the main loop are normally false, and always reset
28819 to false before the loop is left. That saves us the extra work of initializing
28820 each time.
28821
28822 @<Set init...@>=
28823 ligature_present:=false; cancel_boundary:=false; lft_hit:=false; rt_hit:=false;
28824 ins_disc:=false;
28825
28826 @ We leave the |space_factor| unchanged if |sf_code(cur_chr)=0|; otherwise we
28827 set it equal to |sf_code(cur_chr)|, except that it should never change
28828 from a value less than 1000 to a value exceeding 1000. The most common
28829 case is |sf_code(cur_chr)=1000|, so we want that case to be fast.
28830
28831 The overall structure of the main loop is presented here. Some program labels
28832 are inside the individual sections.
28833 @^inner loop@>
28834
28835 @d adjust_space_factor==@t@>@;@/
28836 main_s:=sf_code(cur_chr);
28837 if main_s=1000 then space_factor:=1000
28838 else if main_s<1000 then
28839 begin if main_s>0 then space_factor:=main_s;
28840 end
28841 else if space_factor<1000 then space_factor:=1000
28842 else space_factor:=main_s
28843
28844 @<Append character |cur_chr|...@>=
28845 adjust_space_factor;@/
28846 save_tail := null;
28847 main_f:=cur_font;
28848 bchar:=font_bchar[main_f]; false_bchar:=font_false_bchar[main_f];
28849 if mode>0 then if language<>clang then fix_language;
28850 fast_get_avail(lig_stack); font(lig_stack):=main_f; cur_l:=qi(cur_chr);
28851 character(lig_stack):=cur_l;@/
28852 cur_q:=tail;
28853 tmp_k1 := get_auto_kern(main_f, non_char, cur_l);
28854 @<If |tmp_k1| is not null then append that kern@>;
28855 if cancel_boundary then
28856 begin cancel_boundary:=false; main_k:=non_address;
28857 end
28858 else main_k:=bchar_label[main_f];
28859 if main_k=non_address then goto main_loop_move+2; {no left boundary processing}
28860 cur_r:=cur_l; cur_l:=non_char;
28861 goto main_lig_loop+1; {begin with cursor after left boundary}
28862 @#
28863 main_loop_wrapup:@<Make a ligature node, if |ligature_present|;
28864 insert a null discretionary, if appropriate@>;
28865 main_loop_move:@<If the cursor is immediately followed by the right boundary,
28866 |goto reswitch|; if it's followed by an invalid character, |goto big_switch|;
28867 otherwise move the cursor one step to the right and |goto main_lig_loop|@>;
28868 main_loop_lookahead:@<Look ahead for another character, or leave |lig_stack|
28869 empty if there's none there@>;
28870 main_lig_loop:@<If there's a ligature/kern command relevant to |cur_l| and
28871 |cur_r|, adjust the text appropriately; exit to |main_loop_wrapup|@>;
28872 main_loop_move_lig:@<Move the cursor past a pseudo-ligature, then
28873 |goto main_loop_lookahead| or |main_lig_loop|@>
28874
28875 @ If |link(cur_q)| is nonnull when |wrapup| is invoked, |cur_q| points to
28876 the list of characters that were consumed while building the ligature
28877 character~|cur_l|.
28878
28879 A discretionary break is not inserted for an explicit hyphen when we are in
28880 restricted horizontal mode. In particular, this avoids putting discretionary
28881 nodes inside of other discretionaries.
28882 @^inner loop@>
28883
28884 @d pack_lig(#)== {the parameter is either |rt_hit| or |false|}
28885 begin main_p:=new_ligature(main_f,cur_l,link(cur_q));
28886 if lft_hit then
28887 begin subtype(main_p):=2; lft_hit:=false;
28888 end;
28889 if # then if lig_stack=null then
28890 begin incr(subtype(main_p)); rt_hit:=false;
28891 end;
28892 if pdf_prepend_kern > 0 then
28893 tmp_k2 := get_auto_kern(main_f, non_char, cur_l)
28894 else
28895 tmp_k2 := null;
28896 if tmp_k2 = null then begin
28897 link(cur_q):=main_p; tail:=main_p; ligature_present:=false;
28898 end
28899 else begin
28900 link(cur_q) := tmp_k2;
28901 link(tmp_k2) := main_p;
28902 tail := main_p;
28903 ligature_present := false;
28904 end
28905 end
28906
28907 @d wrapup(#)==if cur_l<non_char then
28908 begin if link(cur_q)>null then
28909 if character(tail)=qi(hyphen_char[main_f]) then ins_disc:=true;
28910 if ligature_present then pack_lig(#);
28911 if ins_disc then
28912 begin ins_disc:=false;
28913 if mode>0 then tail_append(new_disc);
28914 end;
28915 end
28916
28917 @<Make a ligature node, if |ligature_present|;...@>=
28918 wrapup(rt_hit)
28919
28920 @ @<If the cursor is immediately followed by the right boundary...@>=
28921 @^inner loop@>
28922 if lig_stack=null then goto reswitch;
28923 cur_q:=tail; cur_l:=character(lig_stack);
28924 main_loop_move+1:if not is_char_node(lig_stack) then goto main_loop_move_lig;
28925 main_loop_move+2:if(cur_chr<font_bc[main_f])or(cur_chr>font_ec[main_f]) then
28926 begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
28927 end;
28928 main_i:=char_info(main_f)(cur_l);
28929 if not char_exists(main_i) then
28930 begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
28931 end;
28932 link(tail):=lig_stack; tail:=lig_stack {|main_loop_lookahead| is next}
28933
28934 @ Here we are at |main_loop_move_lig|.
28935 When we begin this code we have |cur_q=tail| and |cur_l=character(lig_stack)|.
28936
28937 @<Move the cursor past a pseudo-ligature...@>=
28938 main_p:=lig_ptr(lig_stack);
28939 if main_p>null then tail_append(main_p); {append a single character}
28940 temp_ptr:=lig_stack; lig_stack:=link(temp_ptr);
28941 free_node(temp_ptr,small_node_size);
28942 main_i:=char_info(main_f)(cur_l); ligature_present:=true;
28943 if lig_stack=null then
28944 if main_p>null then goto main_loop_lookahead
28945 else cur_r:=bchar
28946 else cur_r:=character(lig_stack);
28947 goto main_lig_loop
28948
28949 @ The result of \.{\\char} can participate in a ligature or kern, so we must
28950 look ahead for it.
28951
28952 @<Look ahead for another character...@>=
28953 get_next; {set only |cur_cmd| and |cur_chr|, for speed}
28954 if cur_cmd=letter then goto main_loop_lookahead+1;
28955 if cur_cmd=other_char then goto main_loop_lookahead+1;
28956 if cur_cmd=char_given then goto main_loop_lookahead+1;
28957 x_token; {now expand and set |cur_cmd|, |cur_chr|, |cur_tok|}
28958 if cur_cmd=letter then goto main_loop_lookahead+1;
28959 if cur_cmd=other_char then goto main_loop_lookahead+1;
28960 if cur_cmd=char_given then goto main_loop_lookahead+1;
28961 if cur_cmd=char_num then
28962 begin scan_char_num; cur_chr:=cur_val; goto main_loop_lookahead+1;
28963 end;
28964 if cur_cmd=no_boundary then bchar:=non_char;
28965 cur_r:=bchar; lig_stack:=null; goto main_lig_loop;
28966 main_loop_lookahead+1: adjust_space_factor;
28967 fast_get_avail(lig_stack); font(lig_stack):=main_f;
28968 cur_r:=qi(cur_chr); character(lig_stack):=cur_r;
28969 if cur_r=false_bchar then cur_r:=non_char {this prevents spurious ligatures}
28970
28971 @ Even though comparatively few characters have a lig/kern program, several
28972 of the instructions here count as part of \TeX's inner loop, since a
28973 @^inner loop@>
28974 potentially long sequential search must be performed. For example, tests with
28975 Computer Modern Roman showed that about 40 per cent of all characters
28976 actually encountered in practice had a lig/kern program, and that about four
28977 lig/kern commands were investigated for every such character.
28978
28979 At the beginning of this code we have |main_i=char_info(main_f)(cur_l)|.
28980
28981 @<If there's a ligature/kern command...@>=
28982 tmp_k1 := get_auto_kern(main_f, cur_l, cur_r);
28983 @<If |tmp_k1| is not null then append that kern@>;
28984 if char_tag(main_i)<>lig_tag then goto main_loop_wrapup;
28985 if cur_r=non_char then goto main_loop_wrapup;
28986 main_k:=lig_kern_start(main_f)(main_i); main_j:=font_info[main_k].qqqq;
28987 if skip_byte(main_j)<=stop_flag then goto main_lig_loop+2;
28988 main_k:=lig_kern_restart(main_f)(main_j);
28989 main_lig_loop+1:main_j:=font_info[main_k].qqqq;
28990 main_lig_loop+2:if next_char(main_j)=cur_r then
28991 if skip_byte(main_j)<=stop_flag then
28992 @<Do ligature or kern command, returning to |main_lig_loop|
28993 or |main_loop_wrapup| or |main_loop_move|@>;
28994 if skip_byte(main_j)=qi(0) then incr(main_k)
28995 else begin if skip_byte(main_j)>=stop_flag then goto main_loop_wrapup;
28996 main_k:=main_k+qo(skip_byte(main_j))+1;
28997 end;
28998 goto main_lig_loop+1
28999
29000 @ @<If |tmp_k1| is not null then append that kern@>=
29001 if tmp_k1 <> null then begin
29002 wrapup(rt_hit); {Note: |wrapup| might insert a null discretionary}
29003 save_tail := tail;
29004 {insert auto-kern before a null discretionary inserted by |wrapup| if appropriate}
29005 if (not is_char_node(tail))
29006 and (type(tail) = disc_node)
29007 and (replace_count(tail) = 0)
29008 and (pre_break(tail) = null)
29009 and (post_break(tail) = null)
29010 and (link(prev_tail) = tail) then
29011 begin
29012 insert_before_tail(tmp_k1);
29013 end
29014 else
29015 tail_append(tmp_k1);
29016 goto main_loop_move;
29017 end
29018
29019 @ When a ligature or kern instruction matches a character, we know from
29020 |read_font_info| that the character exists in the font, even though we
29021 haven't verified its existence in the normal way.
29022
29023 This section could be made into a subroutine, if the code inside
29024 |main_control| needs to be shortened.
29025
29026 \chardef\?='174 % vertical line to indicate character retention
29027
29028 @<Do ligature or kern command...@>=
29029 begin if op_byte(main_j)>=kern_flag then
29030 begin wrapup(rt_hit);
29031 tail_append(new_kern(char_kern(main_f)(main_j))); goto main_loop_move;
29032 end;
29033 if cur_l=non_char then lft_hit:=true
29034 else if lig_stack=null then rt_hit:=true;
29035 check_interrupt; {allow a way out in case there's an infinite ligature loop}
29036 case op_byte(main_j) of
29037 qi(1),qi(5):begin cur_l:=rem_byte(main_j); {\.{=:\?}, \.{=:\?>}}
29038 main_i:=char_info(main_f)(cur_l); ligature_present:=true;
29039 end;
29040 qi(2),qi(6):begin cur_r:=rem_byte(main_j); {\.{\?=:}, \.{\?=:>}}
29041 if lig_stack=null then {right boundary character is being consumed}
29042 begin lig_stack:=new_lig_item(cur_r); bchar:=non_char;
29043 end
29044 else if is_char_node(lig_stack) then {|link(lig_stack)=null|}
29045 begin main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
29046 lig_ptr(lig_stack):=main_p;
29047 end
29048 else character(lig_stack):=cur_r;
29049 end;
29050 qi(3):begin cur_r:=rem_byte(main_j); {\.{\?=:\?}}
29051 main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
29052 link(lig_stack):=main_p;
29053 end;
29054 qi(7),qi(11):begin wrapup(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
29055 cur_q:=tail; cur_l:=rem_byte(main_j);
29056 main_i:=char_info(main_f)(cur_l); ligature_present:=true;
29057 end;
29058 othercases begin cur_l:=rem_byte(main_j); ligature_present:=true; {\.{=:}}
29059 if lig_stack=null then goto main_loop_wrapup
29060 else goto main_loop_move+1;
29061 end
29062 endcases;
29063 if op_byte(main_j)>qi(4) then
29064 if op_byte(main_j)<>qi(7) then goto main_loop_wrapup;
29065 if cur_l<non_char then goto main_lig_loop;
29066 main_k:=bchar_label[main_f]; goto main_lig_loop+1;
29067 end
29068
29069 @ The occurrence of blank spaces is almost part of \TeX's inner loop,
29070 @^inner loop@>
29071 since we usually encounter about one space for every five non-blank characters.
29072 Therefore |main_control| gives second-highest priority to ordinary spaces.
29073
29074 When a glue parameter like \.{\\spaceskip} is set to `\.{0pt}', we will
29075 see to it later that the corresponding glue specification is precisely
29076 |zero_glue|, not merely a pointer to some specification that happens
29077 to be full of zeroes. Therefore it is simple to test whether a glue parameter
29078 is zero or~not.
29079
29080 @<Append a normal inter-word space...@>=
29081 if space_skip=zero_glue then
29082 begin @<Find the glue specification, |main_p|, for
29083 text spaces in the current font@>;
29084 temp_ptr:=new_glue(main_p);
29085 end
29086 else temp_ptr:=new_param_glue(space_skip_code);
29087 if pdf_adjust_interword_glue > 0 then
29088 adjust_interword_glue(tail, temp_ptr);
29089 link(tail):=temp_ptr; tail:=temp_ptr;
29090 goto big_switch
29091
29092 @ Having |font_glue| allocated for each text font saves both time and memory.
29093 If any of the three spacing parameters are subsequently changed by the
29094 use of \.{\\fontdimen}, the |find_font_dimen| procedure deallocates the
29095 |font_glue| specification allocated here.
29096
29097 @<Find the glue specification...@>=
29098 begin main_p:=font_glue[cur_font];
29099 if main_p=null then
29100 begin main_p:=new_spec(zero_glue); main_k:=param_base[cur_font]+space_code;
29101 width(main_p):=font_info[main_k].sc; {that's |space(cur_font)|}
29102 stretch(main_p):=font_info[main_k+1].sc; {and |space_stretch(cur_font)|}
29103 shrink(main_p):=font_info[main_k+2].sc; {and |space_shrink(cur_font)|}
29104 font_glue[cur_font]:=main_p;
29105 end;
29106 end
29107
29108 @ @<Declare act...@>=
29109 procedure app_space; {handle spaces when |space_factor<>1000|}
29110 var@!q:pointer; {glue node}
29111 begin if (space_factor>=2000)and(xspace_skip<>zero_glue) then
29112 q:=new_param_glue(xspace_skip_code)
29113 else begin if space_skip<>zero_glue then main_p:=space_skip
29114 else @<Find the glue specification...@>;
29115 main_p:=new_spec(main_p);
29116 @<Modify the glue specification in |main_p| according to the space factor@>;
29117 q:=new_glue(main_p); glue_ref_count(main_p):=null;
29118 end;
29119 link(tail):=q; tail:=q;
29120 end;
29121
29122 @ @<Modify the glue specification in |main_p| according to the space factor@>=
29123 if space_factor>=2000 then width(main_p):=width(main_p)+extra_space(cur_font);
29124 stretch(main_p):=xn_over_d(stretch(main_p),space_factor,1000);
29125 shrink(main_p):=xn_over_d(shrink(main_p),1000,space_factor)
29126
29127 @ Whew---that covers the main loop. We can now proceed at a leisurely
29128 pace through the other combinations of possibilities.
29129
29130 @d any_mode(#)==vmode+#,hmode+#,mmode+# {for mode-independent commands}
29131
29132 @<Cases of |main_control| that are not part of the inner loop@>=
29133 any_mode(relax),vmode+spacer,mmode+spacer,mmode+no_boundary:do_nothing;
29134 any_mode(ignore_spaces): begin
29135 if cur_chr = 0 then begin
29136 @<Get the next non-blank non-call...@>;
29137 goto reswitch;
29138 end
29139 else begin
29140 t:=scanner_status;
29141 scanner_status:=normal;
29142 get_next;
29143 scanner_status:=t;
29144 if cur_cs < hash_base then
29145 cur_cs := prim_lookup(cur_cs-single_base)
29146 else
29147 cur_cs := prim_lookup(text(cur_cs));
29148 if cur_cs<>undefined_primitive then begin
29149 cur_cmd := prim_eq_type(cur_cs);
29150 cur_chr := prim_equiv(cur_cs);
29151 cur_tok := cs_token_flag+prim_eqtb_base+cur_cs;
29152 goto reswitch;
29153 end;
29154 end;
29155 end;
29156 vmode+stop: if its_all_over then return; {this is the only way out}
29157 @t\4@>@<Forbidden cases detected in |main_control|@>@+@,any_mode(mac_param):
29158 report_illegal_case;
29159 @<Math-only cases in non-math modes, or vice versa@>: insert_dollar_sign;
29160 @t\4@>@<Cases of |main_control| that build boxes and lists@>@;
29161 @t\4@>@<Cases of |main_control| that don't depend on |mode|@>@;
29162 @t\4@>@<Cases of |main_control| that are for extensions to \TeX@>@;
29163
29164 @ Here is a list of cases where the user has probably gotten into or out of math
29165 mode by mistake. \TeX\ will insert a dollar sign and rescan the current token.
29166
29167 @d non_math(#)==vmode+#,hmode+#
29168
29169 @<Math-only cases in non-math modes...@>=
29170 non_math(sup_mark), non_math(sub_mark), non_math(math_char_num),
29171 non_math(math_given), non_math(math_comp), non_math(delim_num),
29172 non_math(left_right), non_math(above), non_math(radical),
29173 non_math(math_style), non_math(math_choice), non_math(vcenter),
29174 non_math(non_script), non_math(mkern), non_math(limit_switch),
29175 non_math(mskip), non_math(math_accent),
29176 mmode+endv, mmode+par_end, mmode+stop, mmode+vskip, mmode+un_vbox,
29177 mmode+valign, mmode+hrule
29178
29179 @ @<Declare action...@>=
29180 procedure insert_dollar_sign;
29181 begin back_input; cur_tok:=math_shift_token+"$";
29182 print_err("Missing $ inserted");
29183 @.Missing \$ inserted@>
29184 help2("I've inserted a begin-math/end-math symbol since I think")@/
29185 ("you left one out. Proceed, with fingers crossed."); ins_error;
29186 end;
29187
29188 @ When erroneous situations arise, \TeX\ usually issues an error message
29189 specific to the particular error. For example, `\.{\\noalign}' should
29190 not appear in any mode, since it is recognized by the |align_peek| routine
29191 in all of its legitimate appearances; a special error message is given
29192 when `\.{\\noalign}' occurs elsewhere. But sometimes the most appropriate
29193 error message is simply that the user is not allowed to do what he or she
29194 has attempted. For example, `\.{\\moveleft}' is allowed only in vertical mode,
29195 and `\.{\\lower}' only in non-vertical modes. Such cases are enumerated
29196 here and in the other sections referred to under `See also \dots.'
29197
29198 @<Forbidden cases...@>=
29199 vmode+vmove,hmode+hmove,mmode+hmove,any_mode(last_item),
29200
29201 @ The `|you_cant|' procedure prints a line saying that the current command
29202 is illegal in the current mode; it identifies these things symbolically.
29203
29204 @<Declare action...@>=
29205 procedure you_cant;
29206 begin print_err("You can't use `");
29207 @.You can't use x in y mode@>
29208 print_cmd_chr(cur_cmd,cur_chr);
29209 print("' in "); print_mode(mode);
29210 end;
29211
29212 @ @<Declare act...@>=
29213 procedure report_illegal_case;
29214 begin you_cant;
29215 help4("Sorry, but I'm not programmed to handle this case;")@/
29216 ("I'll just pretend that you didn't ask for it.")@/
29217 ("If you're in the wrong mode, you might be able to")@/
29218 ("return to the right one by typing `I}' or `I$' or `I\par'.");@/
29219 error;
29220 end;
29221
29222 @ Some operations are allowed only in privileged modes, i.e., in cases
29223 that |mode>0|. The |privileged| function is used to detect violations
29224 of this rule; it issues an error message and returns |false| if the
29225 current |mode| is negative.
29226
29227 @<Declare act...@>=
29228 function privileged:boolean;
29229 begin if mode>0 then privileged:=true
29230 else begin report_illegal_case; privileged:=false;
29231 end;
29232 end;
29233
29234 @ Either \.{\\dump} or \.{\\end} will cause |main_control| to enter the
29235 endgame, since both of them have `|stop|' as their command code.
29236
29237 @<Put each...@>=
29238 primitive("end",stop,0);@/
29239 @!@:end_}{\.{\\end} primitive@>
29240 primitive("dump",stop,1);@/
29241 @!@:dump_}{\.{\\dump} primitive@>
29242
29243 @ @<Cases of |print_cmd_chr|...@>=
29244 stop:if chr_code=1 then print_esc("dump")@+else print_esc("end");
29245
29246 @ We don't want to leave |main_control| immediately when a |stop| command
29247 is sensed, because it may be necessary to invoke an \.{\\output} routine
29248 several times before things really grind to a halt. (The output routine
29249 might even say `\.{\\gdef\\end\{...\}}', to prolong the life of the job.)
29250 Therefore |its_all_over| is |true| only when the current page
29251 and contribution list are empty, and when the last output was not a
29252 ``dead cycle.''
29253
29254 @<Declare act...@>=
29255 function its_all_over:boolean; {do this when \.{\\end} or \.{\\dump} occurs}
29256 label exit;
29257 begin if privileged then
29258 begin if (page_head=page_tail)and(head=tail)and(dead_cycles=0) then
29259 begin its_all_over:=true; return;
29260 end;
29261 back_input; {we will try to end again after ejecting residual material}
29262 tail_append(new_null_box);
29263 width(tail):=hsize;
29264 tail_append(new_glue(fill_glue));
29265 tail_append(new_penalty(-@'10000000000));@/
29266 build_page; {append \.{\\hbox to \\hsize\{\}\\vfill\\penalty-'10000000000}}
29267 end;
29268 its_all_over:=false;
29269 exit:end;
29270
29271 @* \[47] Building boxes and lists.
29272 The most important parts of |main_control| are concerned with \TeX's
29273 chief mission of box-making. We need to control the activities that put
29274 entries on vlists and hlists, as well as the activities that convert
29275 those lists into boxes. All of the necessary machinery has already been
29276 developed; it remains for us to ``push the buttons'' at the right times.
29277
29278 @ As an introduction to these routines, let's consider one of the simplest
29279 cases: What happens when `\.{\\hrule}' occurs in vertical mode, or
29280 `\.{\\vrule}' in horizontal mode or math mode? The code in |main_control|
29281 is short, since the |scan_rule_spec| routine already does most of what is
29282 required; thus, there is no need for a special action procedure.
29283
29284 Note that baselineskip calculations are disabled after a rule in vertical
29285 mode, by setting |prev_depth:=pdf_ignored_dimen|.
29286
29287 @<Cases of |main_control| that build...@>=
29288 vmode+hrule,hmode+vrule,mmode+vrule: begin tail_append(scan_rule_spec);
29289 if abs(mode)=vmode then prev_depth:=pdf_ignored_dimen
29290 else if abs(mode)=hmode then space_factor:=1000;
29291 end;
29292
29293 @ The processing of things like \.{\\hskip} and \.{\\vskip} is slightly
29294 more complicated. But the code in |main_control| is very short, since
29295 it simply calls on the action routine |append_glue|. Similarly, \.{\\kern}
29296 activates |append_kern|.
29297
29298 @<Cases of |main_control| that build...@>=
29299 vmode+vskip,hmode+hskip,mmode+hskip,mmode+mskip: append_glue;
29300 any_mode(kern),mmode+mkern: append_kern;
29301
29302 @ The |hskip| and |vskip| command codes are used for control sequences
29303 like \.{\\hss} and \.{\\vfil} as well as for \.{\\hskip} and \.{\\vskip}.
29304 The difference is in the value of |cur_chr|.
29305
29306 @d fil_code=0 {identifies \.{\\hfil} and \.{\\vfil}}
29307 @d fill_code=1 {identifies \.{\\hfill} and \.{\\vfill}}
29308 @d ss_code=2 {identifies \.{\\hss} and \.{\\vss}}
29309 @d fil_neg_code=3 {identifies \.{\\hfilneg} and \.{\\vfilneg}}
29310 @d skip_code=4 {identifies \.{\\hskip} and \.{\\vskip}}
29311 @d mskip_code=5 {identifies \.{\\mskip}}
29312
29313 @<Put each...@>=
29314 primitive("hskip",hskip,skip_code);@/
29315 @!@:hskip_}{\.{\\hskip} primitive@>
29316 primitive("hfil",hskip,fil_code);
29317 @!@:hfil_}{\.{\\hfil} primitive@>
29318 primitive("hfill",hskip,fill_code);@/
29319 @!@:hfill_}{\.{\\hfill} primitive@>
29320 primitive("hss",hskip,ss_code);
29321 @!@:hss_}{\.{\\hss} primitive@>
29322 primitive("hfilneg",hskip,fil_neg_code);@/
29323 @!@:hfil_neg_}{\.{\\hfilneg} primitive@>
29324 primitive("vskip",vskip,skip_code);@/
29325 @!@:vskip_}{\.{\\vskip} primitive@>
29326 primitive("vfil",vskip,fil_code);
29327 @!@:vfil_}{\.{\\vfil} primitive@>
29328 primitive("vfill",vskip,fill_code);@/
29329 @!@:vfill_}{\.{\\vfill} primitive@>
29330 primitive("vss",vskip,ss_code);
29331 @!@:vss_}{\.{\\vss} primitive@>
29332 primitive("vfilneg",vskip,fil_neg_code);@/
29333 @!@:vfil_neg_}{\.{\\vfilneg} primitive@>
29334 primitive("mskip",mskip,mskip_code);@/
29335 @!@:mskip_}{\.{\\mskip} primitive@>
29336 primitive("kern",kern,explicit);
29337 @!@:kern_}{\.{\\kern} primitive@>
29338 primitive("mkern",mkern,mu_glue);@/
29339 @!@:mkern_}{\.{\\mkern} primitive@>
29340
29341 @ @<Cases of |print_cmd_chr|...@>=
29342 hskip: case chr_code of
29343 skip_code:print_esc("hskip");
29344 fil_code:print_esc("hfil");
29345 fill_code:print_esc("hfill");
29346 ss_code:print_esc("hss");
29347 othercases print_esc("hfilneg")
29348 endcases;
29349 vskip: case chr_code of
29350 skip_code:print_esc("vskip");
29351 fil_code:print_esc("vfil");
29352 fill_code:print_esc("vfill");
29353 ss_code:print_esc("vss");
29354 othercases print_esc("vfilneg")
29355 endcases;
29356 mskip: print_esc("mskip");
29357 kern: print_esc("kern");
29358 mkern: print_esc("mkern");
29359
29360 @ All the work relating to glue creation has been relegated to the
29361 following subroutine. It does not call |build_page|, because it is
29362 used in at least one place where that would be a mistake.
29363
29364 @<Declare action...@>=
29365 procedure append_glue;
29366 var s:small_number; {modifier of skip command}
29367 begin s:=cur_chr;
29368 case s of
29369 fil_code: cur_val:=fil_glue;
29370 fill_code: cur_val:=fill_glue;
29371 ss_code: cur_val:=ss_glue;
29372 fil_neg_code: cur_val:=fil_neg_glue;
29373 skip_code: scan_glue(glue_val);
29374 mskip_code: scan_glue(mu_val);
29375 end; {now |cur_val| points to the glue specification}
29376 tail_append(new_glue(cur_val));
29377 if s>=skip_code then
29378 begin decr(glue_ref_count(cur_val));
29379 if s>skip_code then subtype(tail):=mu_glue;
29380 end;
29381 end;
29382
29383 @ @<Declare act...@>=
29384 procedure append_kern;
29385 var s:quarterword; {|subtype| of the kern node}
29386 begin s:=cur_chr; scan_dimen(s=mu_glue,false,false);
29387 tail_append(new_kern(cur_val)); subtype(tail):=s;
29388 end;
29389
29390 @ Many of the actions related to box-making are triggered by the appearance
29391 of braces in the input. For example, when the user says `\.{\\hbox}
29392 \.{to} \.{100pt\{$\langle\,\hbox{\rm hlist}\,\rangle$\}}' in vertical mode,
29393 the information about the box size (100pt, |exactly|) is put onto |save_stack|
29394 with a level boundary word just above it, and |cur_group:=adjusted_hbox_group|;
29395 \TeX\ enters restricted horizontal mode to process the hlist. The right
29396 brace eventually causes |save_stack| to be restored to its former state,
29397 at which time the information about the box size (100pt, |exactly|) is
29398 available once again; a box is packaged and we leave restricted horizontal
29399 mode, appending the new box to the current list of the enclosing mode
29400 (in this case to the current list of vertical mode), followed by any
29401 vertical adjustments that were removed from the box by |hpack|.
29402
29403 The next few sections of the program are therefore concerned with the
29404 treatment of left and right curly braces.
29405
29406 @ If a left brace occurs in the middle of a page or paragraph, it simply
29407 introduces a new level of grouping, and the matching right brace will not have
29408 such a drastic effect. Such grouping affects neither the mode nor the
29409 current list.
29410
29411 @<Cases of |main_control| that build...@>=
29412 non_math(left_brace): new_save_level(simple_group);
29413 any_mode(begin_group): new_save_level(semi_simple_group);
29414 any_mode(end_group): if cur_group=semi_simple_group then unsave
29415 else off_save;
29416
29417 @ We have to deal with errors in which braces and such things are not
29418 properly nested. Sometimes the user makes an error of commission by
29419 inserting an extra symbol, but sometimes the user makes an error of omission.
29420 \TeX\ can't always tell one from the other, so it makes a guess and tries
29421 to avoid getting into a loop.
29422
29423 The |off_save| routine is called when the current group code is wrong. It tries
29424 to insert something into the user's input that will help clean off
29425 the top level.
29426
29427 @<Declare act...@>=
29428 procedure off_save;
29429 var p:pointer; {inserted token}
29430 begin if cur_group=bottom_level then
29431 @<Drop current token and complain that it was unmatched@>
29432 else begin back_input; p:=get_avail; link(temp_head):=p;
29433 print_err("Missing ");
29434 @<Prepare to insert a token that matches |cur_group|,
29435 and print what it is@>;
29436 print(" inserted"); ins_list(link(temp_head));
29437 help5("I've inserted something that you may have forgotten.")@/
29438 ("(See the <inserted text> above.)")@/
29439 ("With luck, this will get me unwedged. But if you")@/
29440 ("really didn't forget anything, try typing `2' now; then")@/
29441 ("my insertion and my current dilemma will both disappear.");
29442 error;
29443 end;
29444 end;
29445
29446 @ At this point, |link(temp_head)=p|, a pointer to an empty one-word node.
29447
29448 @<Prepare to insert a token that matches |cur_group|...@>=
29449 case cur_group of
29450 semi_simple_group: begin info(p):=cs_token_flag+frozen_end_group;
29451 print_esc("endgroup");
29452 @.Missing \\endgroup inserted@>
29453 end;
29454 math_shift_group: begin info(p):=math_shift_token+"$"; print_char("$");
29455 @.Missing \$ inserted@>
29456 end;
29457 math_left_group: begin info(p):=cs_token_flag+frozen_right; link(p):=get_avail;
29458 p:=link(p); info(p):=other_token+"."; print_esc("right.");
29459 @.Missing \\right\hbox{.} inserted@>
29460 @^null delimiter@>
29461 end;
29462 othercases begin info(p):=right_brace_token+"}"; print_char("}");
29463 @.Missing \} inserted@>
29464 end
29465 endcases
29466
29467 @ @<Drop current token and complain that it was unmatched@>=
29468 begin print_err("Extra "); print_cmd_chr(cur_cmd,cur_chr);
29469 @.Extra x@>
29470 help1("Things are pretty mixed up, but I think the worst is over.");@/
29471 error;
29472 end
29473
29474 @ The routine for a |right_brace| character branches into many subcases,
29475 since a variety of things may happen, depending on |cur_group|. Some
29476 types of groups are not supposed to be ended by a right brace; error
29477 messages are given in hopes of pinpointing the problem. Most branches
29478 of this routine will be filled in later, when we are ready to understand
29479 them; meanwhile, we must prepare ourselves to deal with such errors.
29480
29481 @<Cases of |main_control| that build...@>=
29482 any_mode(right_brace): handle_right_brace;
29483
29484 @ @<Declare the procedure called |handle_right_brace|@>=
29485 procedure handle_right_brace;
29486 var p,@!q:pointer; {for short-term use}
29487 @!d:scaled; {holds |split_max_depth| in |insert_group|}
29488 @!f:integer; {holds |floating_penalty| in |insert_group|}
29489 begin case cur_group of
29490 simple_group: unsave;
29491 bottom_level: begin print_err("Too many }'s");
29492 @.Too many \}'s@>
29493 help2("You've closed more groups than you opened.")@/
29494 ("Such booboos are generally harmless, so keep going."); error;
29495 end;
29496 semi_simple_group,math_shift_group,math_left_group: extra_right_brace;
29497 @t\4@>@<Cases of |handle_right_brace| where a |right_brace| triggers
29498 a delayed action@>@;
29499 othercases confusion("rightbrace")
29500 @:this can't happen rightbrace}{\quad rightbrace@>
29501 endcases;
29502 end;
29503
29504 @ @<Declare act...@>=
29505 procedure extra_right_brace;
29506 begin print_err("Extra }, or forgotten ");
29507 @.Extra \}, or forgotten x@>
29508 case cur_group of
29509 semi_simple_group: print_esc("endgroup");
29510 math_shift_group: print_char("$");
29511 math_left_group: print_esc("right");
29512 end;@/
29513 help5("I've deleted a group-closing symbol because it seems to be")@/
29514 ("spurious, as in `$x}$'. But perhaps the } is legitimate and")@/
29515 ("you forgot something else, as in `\hbox{$x}'. In such cases")@/
29516 ("the way to recover is to insert both the forgotten and the")@/
29517 ("deleted material, e.g., by typing `I$}'."); error;
29518 incr(align_state);
29519 end;
29520
29521 @ Here is where we clear the parameters that are supposed to revert to their
29522 default values after every paragraph and when internal vertical mode is entered.
29523
29524 @<Declare act...@>=
29525 procedure normal_paragraph;
29526 begin if looseness<>0 then eq_word_define(int_base+looseness_code,0);
29527 if hang_indent<>0 then eq_word_define(dimen_base+hang_indent_code,0);
29528 if hang_after<>1 then eq_word_define(int_base+hang_after_code,1);
29529 if par_shape_ptr<>null then eq_define(par_shape_loc,shape_ref,null);
29530 if inter_line_penalties_ptr<>null then
29531 eq_define(inter_line_penalties_loc,shape_ref,null);
29532 end;
29533
29534 @ Now let's turn to the question of how \.{\\hbox} is treated. We actually
29535 need to consider also a slightly larger context, since constructions like
29536 `\.{\\setbox3=}\penalty0\.{\\hbox...}' and
29537 `\.{\\leaders}\penalty0\.{\\hbox...}' and
29538 `\.{\\lower3.8pt\\hbox...}'
29539 are supposed to invoke quite
29540 different actions after the box has been packaged. Conversely,
29541 constructions like `\.{\\setbox3=}' can be followed by a variety of
29542 different kinds of boxes, and we would like to encode such things in an
29543 efficient way.
29544
29545 In other words, there are two problems: to represent the context of a box,
29546 and to represent its type.
29547
29548 The first problem is solved by putting a ``context code'' on the |save_stack|,
29549 just below the two entries that give the dimensions produced by |scan_spec|.
29550 The context code is either a (signed) shift amount, or it is a large
29551 integer |>=box_flag|, where |box_flag=@t$2^{30}$@>|. Codes |box_flag| through
29552 |global_box_flag-1| represent `\.{\\setbox0}' through `\.{\\setbox32767}';
29553 codes |global_box_flag| through |ship_out_flag-1| represent
29554 `\.{\\global\\setbox0}' through `\.{\\global\\setbox32767}';
29555 code |ship_out_flag| represents `\.{\\shipout}'; and codes |leader_flag|
29556 through |leader_flag+2| represent `\.{\\leaders}', `\.{\\cleaders}',
29557 and `\.{\\xleaders}'.
29558
29559 The second problem is solved by giving the command code |make_box| to all
29560 control sequences that produce a box, and by using the following |chr_code|
29561 values to distinguish between them: |box_code|, |copy_code|, |last_box_code|,
29562 |vsplit_code|, |vtop_code|, |vtop_code+vmode|, and |vtop_code+hmode|, where
29563 the latter two are used to denote \.{\\vbox} and \.{\\hbox}, respectively.
29564
29565 @d box_flag==@'10000000000 {context code for `\.{\\setbox0}'}
29566 @d global_box_flag==@'10000100000 {context code for `\.{\\global\\setbox0}'}
29567 @d ship_out_flag==@'10000200000 {context code for `\.{\\shipout}'}
29568 @d leader_flag==@'10000200001 {context code for `\.{\\leaders}'}
29569 @d box_code=0 {|chr_code| for `\.{\\box}'}
29570 @d copy_code=1 {|chr_code| for `\.{\\copy}'}
29571 @d last_box_code=2 {|chr_code| for `\.{\\lastbox}'}
29572 @d vsplit_code=3 {|chr_code| for `\.{\\vsplit}'}
29573 @d vtop_code=4 {|chr_code| for `\.{\\vtop}'}
29574
29575 @<Put each...@>=
29576 primitive("moveleft",hmove,1);
29577 @!@:move_left_}{\.{\\moveleft} primitive@>
29578 primitive("moveright",hmove,0);@/
29579 @!@:move_right_}{\.{\\moveright} primitive@>
29580 primitive("raise",vmove,1);
29581 @!@:raise_}{\.{\\raise} primitive@>
29582 primitive("lower",vmove,0);
29583 @!@:lower_}{\.{\\lower} primitive@>
29584 @#
29585 primitive("box",make_box,box_code);
29586 @!@:box_}{\.{\\box} primitive@>
29587 primitive("copy",make_box,copy_code);
29588 @!@:copy_}{\.{\\copy} primitive@>
29589 primitive("lastbox",make_box,last_box_code);
29590 @!@:last_box_}{\.{\\lastbox} primitive@>
29591 primitive("vsplit",make_box,vsplit_code);
29592 @!@:vsplit_}{\.{\\vsplit} primitive@>
29593 primitive("vtop",make_box,vtop_code);@/
29594 @!@:vtop_}{\.{\\vtop} primitive@>
29595 primitive("vbox",make_box,vtop_code+vmode);
29596 @!@:vbox_}{\.{\\vbox} primitive@>
29597 primitive("hbox",make_box,vtop_code+hmode);@/
29598 @!@:hbox_}{\.{\\hbox} primitive@>
29599 primitive("shipout",leader_ship,a_leaders-1); {|ship_out_flag=leader_flag-1|}
29600 @!@:ship_out_}{\.{\\shipout} primitive@>
29601 primitive("leaders",leader_ship,a_leaders);
29602 @!@:leaders_}{\.{\\leaders} primitive@>
29603 primitive("cleaders",leader_ship,c_leaders);
29604 @!@:c_leaders_}{\.{\\cleaders} primitive@>
29605 primitive("xleaders",leader_ship,x_leaders);
29606 @!@:x_leaders_}{\.{\\xleaders} primitive@>
29607
29608 @ @<Cases of |print_cmd_chr|...@>=
29609 hmove: if chr_code=1 then print_esc("moveleft")@+else print_esc("moveright");
29610 vmove: if chr_code=1 then print_esc("raise")@+else print_esc("lower");
29611 make_box: case chr_code of
29612 box_code: print_esc("box");
29613 copy_code: print_esc("copy");
29614 last_box_code: print_esc("lastbox");
29615 vsplit_code: print_esc("vsplit");
29616 vtop_code: print_esc("vtop");
29617 vtop_code+vmode: print_esc("vbox");
29618 othercases print_esc("hbox")
29619 endcases;
29620 leader_ship: if chr_code=a_leaders then print_esc("leaders")
29621 else if chr_code=c_leaders then print_esc("cleaders")
29622 else if chr_code=x_leaders then print_esc("xleaders")
29623 else print_esc("shipout");
29624
29625 @ Constructions that require a box are started by calling |scan_box| with
29626 a specified context code. The |scan_box| routine verifies
29627 that a |make_box| command comes next and then it calls |begin_box|.
29628
29629 @<Cases of |main_control| that build...@>=
29630 vmode+hmove,hmode+vmove,mmode+vmove: begin t:=cur_chr;
29631 scan_normal_dimen;
29632 if t=0 then scan_box(cur_val)@+else scan_box(-cur_val);
29633 end;
29634 any_mode(leader_ship): scan_box(leader_flag-a_leaders+cur_chr);
29635 any_mode(make_box): begin_box(0);
29636
29637 @ The global variable |cur_box| will point to a newly made box. If the box
29638 is void, we will have |cur_box=null|. Otherwise we will have
29639 |type(cur_box)=hlist_node| or |vlist_node| or |rule_node|; the |rule_node|
29640 case can occur only with leaders.
29641
29642 @<Glob...@>=
29643 @!cur_box:pointer; {box to be placed into its context}
29644
29645 @ The |box_end| procedure does the right thing with |cur_box|, if
29646 |box_context| represents the context as explained above.
29647
29648 @<Declare act...@>=
29649 procedure box_end(@!box_context:integer);
29650 var p:pointer; {|ord_noad| for new box in math mode}
29651 @!a:small_number; {global prefix}
29652 begin if box_context<box_flag then @<Append box |cur_box| to the current list,
29653 shifted by |box_context|@>
29654 else if box_context<ship_out_flag then @<Store \(c)|cur_box| in a box register@>
29655 else if cur_box<>null then
29656 if box_context>ship_out_flag then @<Append a new leader node that
29657 uses |cur_box|@>
29658 else ship_out(cur_box);
29659 end;
29660
29661 @ The global variable |adjust_tail| will be non-null if and only if the
29662 current box might include adjustments that should be appended to the
29663 current vertical list.
29664
29665 @<Append box |cur_box| to the current...@>=
29666 begin if cur_box<>null then
29667 begin shift_amount(cur_box):=box_context;
29668 if abs(mode)=vmode then
29669 begin
29670 if pre_adjust_tail <> null then begin
29671 if pre_adjust_head <> pre_adjust_tail then
29672 append_list(pre_adjust_head)(pre_adjust_tail);
29673 pre_adjust_tail := null;
29674 end;
29675 append_to_vlist(cur_box);
29676 if adjust_tail <> null then begin
29677 if adjust_head <> adjust_tail then
29678 append_list(adjust_head)(adjust_tail);
29679 adjust_tail := null;
29680 end;
29681 if mode>0 then build_page;
29682 end
29683 else begin if abs(mode)=hmode then space_factor:=1000
29684 else begin p:=new_noad;
29685 math_type(nucleus(p)):=sub_box;
29686 info(nucleus(p)):=cur_box; cur_box:=p;
29687 end;
29688 link(tail):=cur_box; tail:=cur_box;
29689 end;
29690 end;
29691 end
29692
29693 @ @<Store \(c)|cur_box| in a box register@>=
29694 begin if box_context<global_box_flag then
29695 begin cur_val:=box_context-box_flag; a:=0;
29696 end
29697 else begin cur_val:=box_context-global_box_flag; a:=4;
29698 end;
29699 if cur_val<256 then define(box_base+cur_val,box_ref,cur_box)
29700 else sa_def_box;
29701 end
29702
29703 @ @<Append a new leader node ...@>=
29704 begin @<Get the next non-blank non-relax...@>;
29705 if ((cur_cmd=hskip)and(abs(mode)<>vmode))or@|
29706 ((cur_cmd=vskip)and(abs(mode)=vmode)) then
29707 begin append_glue; subtype(tail):=box_context-(leader_flag-a_leaders);
29708 leader_ptr(tail):=cur_box;
29709 end
29710 else begin print_err("Leaders not followed by proper glue");
29711 @.Leaders not followed by...@>
29712 help3("You should say `\leaders <box or rule><hskip or vskip>'.")@/
29713 ("I found the <box or rule>, but there's no suitable")@/
29714 ("<hskip or vskip>, so I'm ignoring these leaders."); back_error;
29715 flush_node_list(cur_box);
29716 end;
29717 end
29718
29719 @ Now that we can see what eventually happens to boxes, we can consider
29720 the first steps in their creation. The |begin_box| routine is called when
29721 |box_context| is a context specification, |cur_chr| specifies the type of
29722 box desired, and |cur_cmd=make_box|.
29723
29724 @<Declare act...@>=
29725 procedure begin_box(@!box_context:integer);
29726 label exit, done;
29727 var @!p,@!q:pointer; {run through the current list}
29728 @!r:pointer; {running behind |p|}
29729 @!fm:boolean; {a final \.{\\beginM} \.{\\endM} node pair?}
29730 @!tx:pointer; {effective tail node}
29731 @!m:quarterword; {the length of a replacement list}
29732 @!k:halfword; {0 or |vmode| or |hmode|}
29733 @!n:halfword; {a box number}
29734 begin case cur_chr of
29735 box_code: begin scan_register_num; fetch_box(cur_box);
29736 change_box(null); {the box becomes void, at the same level}
29737 end;
29738 copy_code: begin scan_register_num; fetch_box(q); cur_box:=copy_node_list(q);
29739 end;
29740 last_box_code: @<If the current list ends with a box node, delete it from
29741 the list and make |cur_box| point to it; otherwise set |cur_box:=null|@>;
29742 vsplit_code: @<Split off part of a vertical box, make |cur_box| point to it@>;
29743 othercases @<Initiate the construction of an hbox or vbox, then |return|@>
29744 endcases;@/
29745 box_end(box_context); {in simple cases, we use the box immediately}
29746 exit:end;
29747
29748 @ Note that the condition |not is_char_node(tail)| implies that |head<>tail|,
29749 since |head| is a one-word node.
29750
29751 @d fetch_effective_tail_eTeX(#)== {extract |tx|,
29752 drop \.{\\beginM} \.{\\endM} pair}
29753 q:=head; p:=null;
29754 repeat r:=p; p:=q; fm:=false;
29755 if not is_char_node(q) then
29756 if type(q)=disc_node then
29757 begin for m:=1 to replace_count(q) do p:=link(p);
29758 if p=tx then #;
29759 end
29760 else if (type(q)=math_node)and(subtype(q)=begin_M_code) then fm:=true;
29761 q:=link(p);
29762 until q=tx; {found |r|$\to$|p|$\to$|q=tx|}
29763 q:=link(tx); link(p):=q; link(tx):=null;
29764 if q=null then if fm then confusion("tail1")
29765 @:this can't happen tail1}{\quad tail1@>
29766 else tail:=p
29767 else if fm then {|r|$\to$|p=begin_M|$\to$|q=end_M|}
29768 begin tail:=r; link(r):=null; flush_node_list(p);@+end
29769 @#
29770 @d check_effective_tail(#)==find_effective_tail_eTeX
29771 @d fetch_effective_tail==fetch_effective_tail_eTeX
29772
29773 @<If the current list ends with a box node, delete it...@>=
29774 begin cur_box:=null;
29775 if abs(mode)=mmode then
29776 begin you_cant; help1("Sorry; this \lastbox will be void."); error;
29777 end
29778 else if (mode=vmode)and(head=tail) then
29779 begin you_cant;
29780 help2("Sorry...I usually can't take things from the current page.")@/
29781 ("This \lastbox will therefore be void."); error;
29782 end
29783 else begin check_effective_tail(goto done);
29784 if not is_char_node(tx) then
29785 if (type(tx)=hlist_node)or(type(tx)=vlist_node) then
29786 @<Remove the last box, unless it's part of a discretionary@>;
29787 done:end;
29788 end
29789
29790 @ @<Remove the last box...@>=
29791 begin fetch_effective_tail(goto done);
29792 cur_box:=tx; shift_amount(cur_box):=0;
29793 end
29794
29795 @ Here we deal with things like `\.{\\vsplit 13 to 100pt}'.
29796
29797 @<Split off part of a vertical box, make |cur_box| point to it@>=
29798 begin scan_register_num; n:=cur_val;
29799 if not scan_keyword("to") then
29800 @.to@>
29801 begin print_err("Missing `to' inserted");
29802 @.Missing `to' inserted@>
29803 help2("I'm working on `\vsplit<box number> to <dimen>';")@/
29804 ("will look for the <dimen> next."); error;
29805 end;
29806 scan_normal_dimen;
29807 cur_box:=vsplit(n,cur_val);
29808 end
29809
29810 @ Here is where we enter restricted horizontal mode or internal vertical
29811 mode, in order to make a box.
29812
29813 @<Initiate the construction of an hbox or vbox, then |return|@>=
29814 begin k:=cur_chr-vtop_code; saved(0):=box_context;
29815 if k=hmode then
29816 if (box_context<box_flag)and(abs(mode)=vmode) then
29817 scan_spec(adjusted_hbox_group,true)
29818 else scan_spec(hbox_group,true)
29819 else begin if k=vmode then scan_spec(vbox_group,true)
29820 else begin scan_spec(vtop_group,true); k:=vmode;
29821 end;
29822 normal_paragraph;
29823 end;
29824 push_nest; mode:=-k;
29825 if k=vmode then
29826 begin prev_depth:=pdf_ignored_dimen;
29827 if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
29828 end
29829 else begin space_factor:=1000;
29830 if every_hbox<>null then begin_token_list(every_hbox,every_hbox_text);
29831 end;
29832 return;
29833 end
29834
29835 @ @<Declare act...@>=
29836 procedure scan_box(@!box_context:integer);
29837 {the next input should specify a box or perhaps a rule}
29838 begin @<Get the next non-blank non-relax...@>;
29839 if cur_cmd=make_box then begin_box(box_context)
29840 else if (box_context>=leader_flag)and((cur_cmd=hrule)or(cur_cmd=vrule)) then
29841 begin cur_box:=scan_rule_spec; box_end(box_context);
29842 end
29843 else begin@t@>@;@/
29844 print_err("A <box> was supposed to be here");@/
29845 @.A <box> was supposed to...@>
29846 help3("I was expecting to see \hbox or \vbox or \copy or \box or")@/
29847 ("something like that. So you might find something missing in")@/
29848 ("your output. But keep trying; you can fix this later."); back_error;
29849 end;
29850 end;
29851
29852 @ When the right brace occurs at the end of an \.{\\hbox} or \.{\\vbox} or
29853 \.{\\vtop} construction, the |package| routine comes into action. We might
29854 also have to finish a paragraph that hasn't ended.
29855
29856 @<Cases of |handle...@>=
29857 hbox_group: package(0);
29858 adjusted_hbox_group: begin adjust_tail:=adjust_head;
29859 pre_adjust_tail:=pre_adjust_head; package(0);
29860 end;
29861 vbox_group: begin end_graf; package(0);
29862 end;
29863 vtop_group: begin end_graf; package(vtop_code);
29864 end;
29865
29866 @ @<Declare action...@>=
29867 procedure package(@!c:small_number);
29868 var h:scaled; {height of box}
29869 @!p:pointer; {first node in a box}
29870 @!d:scaled; {max depth}
29871 begin d:=box_max_depth; unsave; save_ptr:=save_ptr-3;
29872 if mode=-hmode then cur_box:=hpack(link(head),saved(2),saved(1))
29873 else begin cur_box:=vpackage(link(head),saved(2),saved(1),d);
29874 if c=vtop_code then @<Readjust the height and depth of |cur_box|,
29875 for \.{\\vtop}@>;
29876 end;
29877 pop_nest; box_end(saved(0));
29878 end;
29879
29880 @ The height of a `\.{\\vtop}' box is inherited from the first item on its list,
29881 if that item is an |hlist_node|, |vlist_node|, or |rule_node|; otherwise
29882 the \.{\\vtop} height is zero.
29883
29884
29885 @<Readjust the height...@>=
29886 begin h:=0; p:=list_ptr(cur_box);
29887 if p<>null then if type(p)<=rule_node then h:=height(p);
29888 depth(cur_box):=depth(cur_box)-h+height(cur_box); height(cur_box):=h;
29889 end
29890
29891 @ Here is a really small patch to add a new primitive called
29892 \.{\\quitvmode}. In vertical modes, it is identical to \.{\\indent},
29893 but in horizontal and math modes it is really a no-op (as opposed to
29894 \.{\\indent}, which executes the |indent_in_hmode| procedure).
29895
29896 A paragraph begins when horizontal-mode material occurs in vertical mode,
29897 or when the paragraph is explicitly started by `\.{\\quitvmode}',
29898 `\.{\\indent}' or `\.{\\noindent}'.
29899
29900 @<Put each...@>=
29901 primitive("indent",start_par,1);
29902 @!@:indent_}{\.{\\indent} primitive@>
29903 primitive("noindent",start_par,0);
29904 @!@:no_indent_}{\.{\\noindent} primitive@>
29905 primitive("quitvmode",start_par,2);
29906 @!@:quit_vmode_}{\.{\\quitvmode} primitive@>
29907
29908 @ @<Cases of |print_cmd_chr|...@>=
29909 start_par: if chr_code=0 then print_esc("noindent")@+ else if chr_code=1 then print_esc("indent")@+ else print_esc("quitvmode");
29910
29911 @ @<Cases of |main_control| that build...@>=
29912 vmode+start_par: new_graf(cur_chr>0);
29913 vmode+letter,vmode+other_char,vmode+char_num,vmode+char_given,
29914 vmode+math_shift,vmode+un_hbox,vmode+vrule,
29915 vmode+accent,vmode+discretionary,vmode+hskip,vmode+valign,
29916 vmode+ex_space,vmode+no_boundary:@t@>@;@/
29917 begin back_input; new_graf(true);
29918 end;
29919
29920 @ @<Declare act...@>=
29921 function norm_min(@!h:integer):small_number;
29922 begin if h<=0 then norm_min:=1@+else if h>=63 then norm_min:=63@+
29923 else norm_min:=h;
29924 end;
29925 @#
29926 procedure new_graf(@!indented:boolean);
29927 begin prev_graf:=0;
29928 if (mode=vmode)or(head<>tail) then
29929 tail_append(new_param_glue(par_skip_code));
29930 push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
29931 prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
29932 *@'200000+cur_lang;
29933 if indented then
29934 begin tail:=new_null_box; link(head):=tail; width(tail):=par_indent;@+
29935 end;
29936 if every_par<>null then begin_token_list(every_par,every_par_text);
29937 if nest_ptr=1 then build_page; {put |par_skip| glue on current page}
29938 end;
29939
29940 @ @<Cases of |main_control| that build...@>=
29941 hmode+start_par,mmode+start_par: if cur_chr<>2 then indent_in_hmode;
29942
29943 @ @<Declare act...@>=
29944 procedure indent_in_hmode;
29945 var p,@!q:pointer;
29946 begin if cur_chr>0 then {\.{\\indent}}
29947 begin p:=new_null_box; width(p):=par_indent;
29948 if abs(mode)=hmode then space_factor:=1000
29949 else begin q:=new_noad; math_type(nucleus(q)):=sub_box;
29950 info(nucleus(q)):=p; p:=q;
29951 end;
29952 tail_append(p);
29953 end;
29954 end;
29955
29956 @ A paragraph ends when a |par_end| command is sensed, or when we are in
29957 horizontal mode when reaching the right brace of vertical-mode routines
29958 like \.{\\vbox}, \.{\\insert}, or \.{\\output}.
29959
29960 @<Cases of |main_control| that build...@>=
29961 vmode+par_end: begin normal_paragraph;
29962 if mode>0 then build_page;
29963 end;
29964 hmode+par_end: begin if align_state<0 then off_save; {this tries to
29965 recover from an alignment that didn't end properly}
29966 end_graf; {this takes us to the enclosing mode, if |mode>0|}
29967 if mode=vmode then build_page;
29968 end;
29969 hmode+stop,hmode+vskip,hmode+hrule,hmode+un_vbox,hmode+halign: head_for_vmode;
29970
29971 @ @<Declare act...@>=
29972 procedure head_for_vmode;
29973 begin if mode<0 then
29974 if cur_cmd<>hrule then off_save
29975 else begin print_err("You can't use `");
29976 print_esc("hrule"); print("' here except with leaders");
29977 @.You can't use \\hrule...@>
29978 help2("To put a horizontal rule in an hbox or an alignment,")@/
29979 ("you should use \leaders or \hrulefill (see The TeXbook).");
29980 error;
29981 end
29982 else begin back_input; cur_tok:=par_token; back_input; token_type:=inserted;
29983 end;
29984 end;
29985
29986 @ @<Declare act...@>=
29987 procedure end_graf;
29988 begin if mode=hmode then
29989 begin if head=tail then pop_nest {null paragraphs are ignored}
29990 else line_break(false);
29991 if LR_save<>null then
29992 begin flush_list(LR_save); LR_save:=null;
29993 end;
29994 normal_paragraph;
29995 error_count:=0;
29996 end;
29997 end;
29998
29999 @ Insertion and adjustment and mark nodes are constructed by the following
30000 pieces of the program.
30001
30002 @<Cases of |main_control| that build...@>=
30003 any_mode(insert),hmode+vadjust,mmode+vadjust: begin_insert_or_adjust;
30004 any_mode(mark): make_mark;
30005
30006 @ @<Forbidden...@>=
30007 vmode+vadjust,
30008
30009 @ @<Declare act...@>=
30010 procedure begin_insert_or_adjust;
30011 begin if cur_cmd=vadjust then cur_val:=255
30012 else begin scan_eight_bit_int;
30013 if cur_val=255 then
30014 begin print_err("You can't "); print_esc("insert"); print_int(255);
30015 @.You can't \\insert255@>
30016 help1("I'm changing to \insert0; box 255 is special.");
30017 error; cur_val:=0;
30018 end;
30019 end;
30020 saved(0) := cur_val;
30021 if (cur_cmd = vadjust) and scan_keyword("pre") then
30022 saved(1) := 1
30023 else
30024 saved(1) := 0;
30025 save_ptr := save_ptr + 2;
30026 new_save_level(insert_group); scan_left_brace; normal_paragraph;
30027 push_nest; mode:=-vmode; prev_depth:=pdf_ignored_dimen;
30028 end;
30029
30030 @ @<Cases of |handle...@>=
30031 insert_group: begin end_graf; q:=split_top_skip; add_glue_ref(q);
30032 d:=split_max_depth; f:=floating_penalty; unsave; save_ptr := save_ptr - 2;
30033 {now |saved(0)| is the insertion number, or 255 for |vadjust|}
30034 p:=vpack(link(head),natural); pop_nest;
30035 if saved(0)<255 then
30036 begin tail_append(get_node(ins_node_size));
30037 type(tail):=ins_node; subtype(tail):=qi(saved(0));
30038 height(tail):=height(p)+depth(p); ins_ptr(tail):=list_ptr(p);
30039 split_top_ptr(tail):=q; depth(tail):=d; float_cost(tail):=f;
30040 end
30041 else begin tail_append(get_node(small_node_size));
30042 type(tail):=adjust_node;@/
30043 adjust_pre(tail) := saved(1); {the |subtype| is used for |adjust_pre|}
30044 adjust_ptr(tail):=list_ptr(p); delete_glue_ref(q);
30045 end;
30046 free_node(p,box_node_size);
30047 if nest_ptr=0 then build_page;
30048 end;
30049 output_group: @<Resume the page builder...@>;
30050
30051 @ @<Declare act...@>=
30052 procedure make_mark;
30053 var p:pointer; {new node}
30054 @!c:halfword; {the mark class}
30055 begin if cur_chr=0 then c:=0
30056 else begin scan_register_num; c:=cur_val;
30057 end;
30058 p:=scan_toks(false,true); p:=get_node(small_node_size);
30059 mark_class(p):=c;
30060 type(p):=mark_node; subtype(p):=0; {the |subtype| is not used}
30061 mark_ptr(p):=def_ref; link(tail):=p; tail:=p;
30062 end;
30063
30064 @ Penalty nodes get into a list via the |break_penalty| command.
30065 @^penalties@>
30066
30067 @<Cases of |main_control| that build...@>=
30068 any_mode(break_penalty): append_penalty;
30069
30070 @ @<Declare action...@>=
30071 procedure append_penalty;
30072 begin scan_int; tail_append(new_penalty(cur_val));
30073 if mode=vmode then build_page;
30074 end;
30075
30076 @ The |remove_item| command removes a penalty, kern, or glue node if it
30077 appears at the tail of the current list, using a brute-force linear scan.
30078 Like \.{\\lastbox}, this command is not allowed in vertical mode (except
30079 internal vertical mode), since the current list in vertical mode is sent
30080 to the page builder. But if we happen to be able to implement it in
30081 vertical mode, we do.
30082
30083 @<Cases of |main_control| that build...@>=
30084 any_mode(remove_item): delete_last;
30085
30086 @ When |delete_last| is called, |cur_chr| is the |type| of node that
30087 will be deleted, if present.
30088
30089 @<Declare action...@>=
30090 procedure delete_last;
30091 label exit;
30092 var @!p,@!q:pointer; {run through the current list}
30093 @!r:pointer; {running behind |p|}
30094 @!fm:boolean; {a final \.{\\beginM} \.{\\endM} node pair?}
30095 @!tx:pointer; {effective tail node}
30096 @!m:quarterword; {the length of a replacement list}
30097 begin if (mode=vmode)and(tail=head) then
30098 @<Apologize for inability to do the operation now,
30099 unless \.{\\unskip} follows non-glue@>
30100 else begin check_effective_tail(return);
30101 if not is_char_node(tx) then if type(tx)=cur_chr then
30102 begin fetch_effective_tail(return);
30103 flush_node_list(tx);
30104 end;
30105 end;
30106 exit:end;
30107
30108 @ @<Apologize for inability to do the operation...@>=
30109 begin if (cur_chr<>glue_node)or(last_glue<>max_halfword) then
30110 begin you_cant;
30111 help2("Sorry...I usually can't take things from the current page.")@/
30112 ("Try `I\vskip-\lastskip' instead.");
30113 if cur_chr=kern_node then help_line[0]:=
30114 ("Try `I\kern-\lastkern' instead.")
30115 else if cur_chr<>glue_node then help_line[0]:=@|
30116 ("Perhaps you can make the output routine do it.");
30117 error;
30118 end;
30119 end
30120
30121 @ @<Put each...@>=
30122 primitive("unpenalty",remove_item,penalty_node);@/
30123 @!@:un_penalty_}{\.{\\unpenalty} primitive@>
30124 primitive("unkern",remove_item,kern_node);@/
30125 @!@:un_kern_}{\.{\\unkern} primitive@>
30126 primitive("unskip",remove_item,glue_node);@/
30127 @!@:un_skip_}{\.{\\unskip} primitive@>
30128 primitive("unhbox",un_hbox,box_code);@/
30129 @!@:un_hbox_}{\.{\\unhbox} primitive@>
30130 primitive("unhcopy",un_hbox,copy_code);@/
30131 @!@:un_hcopy_}{\.{\\unhcopy} primitive@>
30132 primitive("unvbox",un_vbox,box_code);@/
30133 @!@:un_vbox_}{\.{\\unvbox} primitive@>
30134 primitive("unvcopy",un_vbox,copy_code);@/
30135 @!@:un_vcopy_}{\.{\\unvcopy} primitive@>
30136
30137 @ @<Cases of |print_cmd_chr|...@>=
30138 remove_item: if chr_code=glue_node then print_esc("unskip")
30139 else if chr_code=kern_node then print_esc("unkern")
30140 else print_esc("unpenalty");
30141 un_hbox: if chr_code=copy_code then print_esc("unhcopy")
30142 else print_esc("unhbox");
30143 un_vbox: if chr_code=copy_code then print_esc("unvcopy")
30144 @<Cases of |un_vbox| for |print_cmd_chr|@>@/
30145 else print_esc("unvbox");
30146
30147 @ The |un_hbox| and |un_vbox| commands unwrap one of the 256 current boxes.
30148
30149 @<Cases of |main_control| that build...@>=
30150 vmode+un_vbox,hmode+un_hbox,mmode+un_hbox: unpackage;
30151
30152 @ @<Declare act...@>=
30153 procedure unpackage;
30154 label done, exit;
30155 var p:pointer; {the box}
30156 r: pointer; {to remove marginal kern nodes}
30157 @!c:box_code..copy_code; {should we copy?}
30158 begin if cur_chr>copy_code then @<Handle saved items and |goto done|@>;
30159 c:=cur_chr; scan_register_num; fetch_box(p);
30160 if p=null then return;
30161 if (abs(mode)=mmode)or((abs(mode)=vmode)and(type(p)<>vlist_node))or@|
30162 ((abs(mode)=hmode)and(type(p)<>hlist_node)) then
30163 begin print_err("Incompatible list can't be unboxed");
30164 @.Incompatible list...@>
30165 help3("Sorry, Pandora. (You sneaky devil.)")@/
30166 ("I refuse to unbox an \hbox in vertical mode or vice versa.")@/
30167 ("And I can't open any boxes in math mode.");@/
30168 error; return;
30169 end;
30170 if c=copy_code then link(tail):=copy_node_list(list_ptr(p))
30171 else begin link(tail):=list_ptr(p); change_box(null);
30172 free_node(p,box_node_size);
30173 end;
30174 done:
30175 while link(tail) <> null do begin
30176 r := link(tail);
30177 if not is_char_node(r) and (type(r) = margin_kern_node) then begin
30178 link(tail) := link(r);
30179 free_avail(margin_char(r));
30180 free_node(r, margin_kern_node_size);
30181 end;
30182 tail:=link(tail);
30183 end;
30184 exit:end;
30185
30186 @ @<Forbidden...@>=vmode+ital_corr,
30187
30188 @ Italic corrections are converted to kern nodes when the |ital_corr| command
30189 follows a character. In math mode the same effect is achieved by appending
30190 a kern of zero here, since italic corrections are supplied later.
30191
30192 @<Cases of |main_control| that build...@>=
30193 hmode+ital_corr: append_italic_correction;
30194 mmode+ital_corr: tail_append(new_kern(0));
30195
30196 @ @<Declare act...@>=
30197 procedure append_italic_correction;
30198 label exit;
30199 var p:pointer; {|char_node| at the tail of the current list}
30200 @!f:internal_font_number; {the font in the |char_node|}
30201 begin if tail<>head then
30202 begin if is_char_node(tail) then p:=tail
30203 else if type(tail)=ligature_node then p:=lig_char(tail)
30204 else return;
30205 f:=font(p);
30206 tail_append(new_kern(char_italic(f)(char_info(f)(character(p)))));
30207 subtype(tail):=explicit;
30208 end;
30209 exit:end;
30210
30211 @ Discretionary nodes are easy in the common case `\.{\\-}', but in the
30212 general case we must process three braces full of items.
30213
30214 @<Put each...@>=
30215 primitive("-",discretionary,1);
30216 @!@:Single-character primitives -}{\quad\.{\\-}@>
30217 primitive("discretionary",discretionary,0);
30218 @!@:discretionary_}{\.{\\discretionary} primitive@>
30219
30220 @ @<Cases of |print_cmd_chr|...@>=
30221 discretionary: if chr_code=1 then
30222 print_esc("-")@+else print_esc("discretionary");
30223
30224 @ @<Cases of |main_control| that build...@>=
30225 hmode+discretionary,mmode+discretionary: append_discretionary;
30226
30227 @ The space factor does not change when we append a discretionary node,
30228 but it starts out as 1000 in the subsidiary lists.
30229
30230 @<Declare act...@>=
30231 procedure append_discretionary;
30232 var c:integer; {hyphen character}
30233 app_kern, pre_kern, p, c_node: pointer;
30234 begin tail_append(new_disc);
30235 if cur_chr=1 then
30236 begin c:=hyphen_char[cur_font];
30237 if c>=0 then if c<256 then begin
30238 pre_kern := get_auto_kern(cur_font, non_char, c);
30239 app_kern := get_auto_kern(cur_font, c, non_char);
30240 c_node := new_character(cur_font,c);
30241 if (app_kern = null) and (pre_kern = null) then {no auto-kern}
30242 pre_break(tail) := c_node
30243 else begin
30244 if pre_kern = null then
30245 pre_break(tail) := c_node
30246 else begin
30247 pre_break(tail) := pre_kern;
30248 link(pre_kern) := c_node;
30249 end;
30250 if app_kern <> null then
30251 link(c_node) := app_kern;
30252 end;
30253 end;
30254 end
30255 else begin incr(save_ptr); saved(-1):=0; new_save_level(disc_group);
30256 scan_left_brace; push_nest; mode:=-hmode; space_factor:=1000;
30257 end;
30258 end;
30259
30260 @ The three discretionary lists are constructed somewhat as if they were
30261 hboxes. A~subroutine called |build_discretionary| handles the transitions.
30262 (This is sort of fun.)
30263
30264 @<Cases of |handle...@>=
30265 disc_group: build_discretionary;
30266
30267 @ @<Declare act...@>=
30268 procedure build_discretionary;
30269 label done,exit;
30270 var p,@!q:pointer; {for link manipulation}
30271 @!n:integer; {length of discretionary list}
30272 begin unsave;
30273 @<Prune the current list, if necessary, until it contains only
30274 |char_node|, |kern_node|, |hlist_node|, |vlist_node|, |rule_node|,
30275 and |ligature_node| items; set |n| to the length of the list,
30276 and set |q| to the list's tail@>;
30277 p:=link(head); pop_nest;
30278 case saved(-1) of
30279 0:pre_break(tail):=p;
30280 1:post_break(tail):=p;
30281 2:@<Attach list |p| to the current list, and record its length;
30282 then finish up and |return|@>;
30283 end; {there are no other cases}
30284 incr(saved(-1)); new_save_level(disc_group); scan_left_brace;
30285 push_nest; mode:=-hmode; space_factor:=1000;
30286 exit:end;
30287
30288 @ @<Attach list |p| to the current...@>=
30289 begin if (n>0)and(abs(mode)=mmode) then
30290 begin print_err("Illegal math "); print_esc("discretionary");
30291 @.Illegal math \\disc...@>
30292 help2("Sorry: The third part of a discretionary break must be")@/
30293 ("empty, in math formulas. I had to delete your third part.");
30294 flush_node_list(p); n:=0; error;
30295 end
30296 else link(tail):=p;
30297 if n<=max_quarterword then replace_count(tail):=n
30298 else begin print_err("Discretionary list is too long");
30299 @.Discretionary list is too long@>
30300 help2("Wow---I never thought anybody would tweak me here.")@/
30301 ("You can't seriously need such a huge discretionary list?");
30302 error;
30303 end;
30304 if n>0 then tail:=q;
30305 decr(save_ptr); return;
30306 end
30307
30308 @ During this loop, |p=link(q)| and there are |n| items preceding |p|.
30309
30310 @<Prune the current list, if necessary...@>=
30311 q:=head; p:=link(q); n:=0;
30312 while p<>null do
30313 begin if not is_char_node(p) then if type(p)>rule_node then
30314 if type(p)<>kern_node then if type(p)<>ligature_node then
30315 begin print_err("Improper discretionary list");
30316 @.Improper discretionary list@>
30317 help1("Discretionary lists must contain only boxes and kerns.");@/
30318 error;
30319 begin_diagnostic;
30320 print_nl("The following discretionary sublist has been deleted:");
30321 @.The following...deleted@>
30322 show_box(p);
30323 end_diagnostic(true);
30324 flush_node_list(p); link(q):=null; goto done;
30325 end;
30326 q:=p; p:=link(q); incr(n);
30327 end;
30328 done:
30329
30330 @ We need only one more thing to complete the horizontal mode routines, namely
30331 the \.{\\accent} primitive.
30332
30333 @<Cases of |main_control| that build...@>=
30334 hmode+accent: make_accent;
30335
30336 @ The positioning of accents is straightforward but tedious. Given an accent
30337 of width |a|, designed for characters of height |x| and slant |s|;
30338 and given a character of width |w|, height |h|, and slant |t|: We will shift
30339 the accent down by |x-h|, and we will insert kern nodes that have the effect of
30340 centering the accent over the character and shifting the accent to the
30341 right by $\delta={1\over2}(w-a)+h\cdot t-x\cdot s$. If either character is
30342 absent from the font, we will simply use the other, without shifting.
30343
30344 @<Declare act...@>=
30345 procedure make_accent;
30346 var s,@!t: real; {amount of slant}
30347 @!p,@!q,@!r:pointer; {character, box, and kern nodes}
30348 @!f:internal_font_number; {relevant font}
30349 @!a,@!h,@!x,@!w,@!delta:scaled; {heights and widths, as explained above}
30350 @!i:four_quarters; {character information}
30351 begin scan_char_num; f:=cur_font; p:=new_character(f,cur_val);
30352 if p<>null then
30353 begin x:=x_height(f); s:=slant(f)/float_constant(65536);
30354 @^real division@>
30355 a:=char_width(f)(char_info(f)(character(p)));@/
30356 do_assignments;@/
30357 @<Create a character node |q| for the next character,
30358 but set |q:=null| if problems arise@>;
30359 if q<>null then @<Append the accent with appropriate kerns,
30360 then set |p:=q|@>;
30361 link(tail):=p; tail:=p; space_factor:=1000;
30362 end;
30363 end;
30364
30365 @ @<Create a character node |q| for the next...@>=
30366 q:=null; f:=cur_font;
30367 if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given) then
30368 q:=new_character(f,cur_chr)
30369 else if cur_cmd=char_num then
30370 begin scan_char_num; q:=new_character(f,cur_val);
30371 end
30372 else back_input
30373
30374 @ The kern nodes appended here must be distinguished from other kerns, lest
30375 they be wiped away by the hyphenation algorithm or by a previous line break.
30376
30377 The two kerns are computed with (machine-dependent) |real| arithmetic, but
30378 their sum is machine-independent; the net effect is machine-independent,
30379 because the user cannot remove these nodes nor access them via \.{\\lastkern}.
30380
30381 @<Append the accent with appropriate kerns...@>=
30382 begin t:=slant(f)/float_constant(65536);
30383 @^real division@>
30384 i:=char_info(f)(character(q));
30385 w:=char_width(f)(i); h:=char_height(f)(height_depth(i));
30386 if h<>x then {the accent must be shifted up or down}
30387 begin p:=hpack(p,natural); shift_amount(p):=x-h;
30388 end;
30389 delta:=round((w-a)/float_constant(2)+h*t-x*s);
30390 @^real multiplication@>
30391 @^real addition@>
30392 r:=new_kern(delta); subtype(r):=acc_kern; link(tail):=r; link(r):=p;
30393 tail:=new_kern(-a-delta); subtype(tail):=acc_kern; link(p):=tail; p:=q;
30394 end
30395
30396 @ When `\.{\\cr}' or `\.{\\span}' or a tab mark comes through the scanner
30397 into |main_control|, it might be that the user has foolishly inserted
30398 one of them into something that has nothing to do with alignment. But it is
30399 far more likely that a left brace or right brace has been omitted, since
30400 |get_next| takes actions appropriate to alignment only when `\.{\\cr}'
30401 or `\.{\\span}' or tab marks occur with |align_state=0|. The following
30402 program attempts to make an appropriate recovery.
30403
30404 @<Cases of |main_control| that build...@>=
30405 any_mode(car_ret), any_mode(tab_mark): align_error;
30406 any_mode(no_align): no_align_error;
30407 any_mode(omit): omit_error;
30408
30409 @ @<Declare act...@>=
30410 procedure align_error;
30411 begin if abs(align_state)>2 then
30412 @<Express consternation over the fact that no alignment is in progress@>
30413 else begin back_input;
30414 if align_state<0 then
30415 begin print_err("Missing { inserted");
30416 @.Missing \{ inserted@>
30417 incr(align_state); cur_tok:=left_brace_token+"{";
30418 end
30419 else begin print_err("Missing } inserted");
30420 @.Missing \} inserted@>
30421 decr(align_state); cur_tok:=right_brace_token+"}";
30422 end;
30423 help3("I've put in what seems to be necessary to fix")@/
30424 ("the current column of the current alignment.")@/
30425 ("Try to go on, since this might almost work."); ins_error;
30426 end;
30427 end;
30428
30429 @ @<Express consternation...@>=
30430 begin print_err("Misplaced "); print_cmd_chr(cur_cmd,cur_chr);
30431 @.Misplaced \&@>
30432 @.Misplaced \\span@>
30433 @.Misplaced \\cr@>
30434 if cur_tok=tab_token+"&" then
30435 begin help6("I can't figure out why you would want to use a tab mark")@/
30436 ("here. If you just want an ampersand, the remedy is")@/
30437 ("simple: Just type `I\&' now. But if some right brace")@/
30438 ("up above has ended a previous alignment prematurely,")@/
30439 ("you're probably due for more error messages, and you")@/
30440 ("might try typing `S' now just to see what is salvageable.");
30441 end
30442 else begin help5("I can't figure out why you would want to use a tab mark")@/
30443 ("or \cr or \span just now. If something like a right brace")@/
30444 ("up above has ended a previous alignment prematurely,")@/
30445 ("you're probably due for more error messages, and you")@/
30446 ("might try typing `S' now just to see what is salvageable.");
30447 end;
30448 error;
30449 end
30450
30451 @ The help messages here contain a little white lie, since \.{\\noalign}
30452 and \.{\\omit} are allowed also after `\.{\\noalign\{...\}}'.
30453
30454 @<Declare act...@>=
30455 procedure no_align_error;
30456 begin print_err("Misplaced "); print_esc("noalign");
30457 @.Misplaced \\noalign@>
30458 help2("I expect to see \noalign only after the \cr of")@/
30459 ("an alignment. Proceed, and I'll ignore this case."); error;
30460 end;
30461 procedure omit_error;
30462 begin print_err("Misplaced "); print_esc("omit");
30463 @.Misplaced \\omit@>
30464 help2("I expect to see \omit only after tab marks or the \cr of")@/
30465 ("an alignment. Proceed, and I'll ignore this case."); error;
30466 end;
30467
30468 @ We've now covered most of the abuses of \.{\\halign} and \.{\\valign}.
30469 Let's take a look at what happens when they are used correctly.
30470
30471 @<Cases of |main_control| that build...@>=
30472 vmode+halign:init_align;
30473 hmode+valign:@<Cases of |main_control| for |hmode+valign|@>@; init_align;
30474 mmode+halign: if privileged then
30475 if cur_group=math_shift_group then init_align
30476 else off_save;
30477 vmode+endv,hmode+endv: do_endv;
30478
30479 @ An |align_group| code is supposed to remain on the |save_stack|
30480 during an entire alignment, until |fin_align| removes it.
30481
30482 A devious user might force an |endv| command to occur just about anywhere;
30483 we must defeat such hacks.
30484
30485 @<Declare act...@>=
30486 procedure do_endv;
30487 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
30488 while (input_stack[base_ptr].index_field<>v_template) and
30489 (input_stack[base_ptr].loc_field=null) and
30490 (input_stack[base_ptr].state_field=token_list) do decr(base_ptr);
30491 if (input_stack[base_ptr].index_field<>v_template) or
30492 (input_stack[base_ptr].loc_field<>null) or
30493 (input_stack[base_ptr].state_field<>token_list) then
30494 fatal_error("(interwoven alignment preambles are not allowed)");
30495 @.interwoven alignment preambles...@>
30496 if cur_group=align_group then
30497 begin end_graf;
30498 if fin_col then fin_row;
30499 end
30500 else off_save;
30501 end;
30502
30503 @ @<Cases of |handle_right_brace|...@>=
30504 align_group: begin back_input; cur_tok:=cs_token_flag+frozen_cr;
30505 print_err("Missing "); print_esc("cr"); print(" inserted");
30506 @.Missing \\cr inserted@>
30507 help1("I'm guessing that you meant to end an alignment here.");
30508 ins_error;
30509 end;
30510
30511 @ @<Cases of |handle_right_brace|...@>=
30512 no_align_group: begin end_graf; unsave; align_peek;
30513 end;
30514
30515 @ Finally, \.{\\endcsname} is not supposed to get through to |main_control|.
30516
30517 @<Cases of |main_control| that build...@>=
30518 any_mode(end_cs_name): cs_error;
30519
30520 @ @<Declare act...@>=
30521 procedure cs_error;
30522 begin print_err("Extra "); print_esc("endcsname");
30523 @.Extra \\endcsname@>
30524 help1("I'm ignoring this, since I wasn't doing a \csname.");
30525 error;
30526 end;
30527
30528 @* \[48] Building math lists.
30529 The routines that \TeX\ uses to create mlists are similar to those we have
30530 just seen for the generation of hlists and vlists. But it is necessary to
30531 make ``noads'' as well as nodes, so the reader should review the
30532 discussion of math mode data structures before trying to make sense out of
30533 the following program.
30534
30535 Here is a little routine that needs to be done whenever a subformula
30536 is about to be processed. The parameter is a code like |math_group|.
30537
30538 @<Declare act...@>=
30539 procedure push_math(@!c:group_code);
30540 begin push_nest; mode:=-mmode; incompleat_noad:=null; new_save_level(c);
30541 end;
30542
30543 @ We get into math mode from horizontal mode when a `\.\$' (i.e., a
30544 |math_shift| character) is scanned. We must check to see whether this
30545 `\.\$' is immediately followed by another, in case display math mode is
30546 called for.
30547
30548 @<Cases of |main_control| that build...@>=
30549 hmode+math_shift:init_math;
30550
30551 @ @<Declare act...@>=
30552 @t\4@>@<Declare subprocedures for |init_math|@>@;
30553 procedure init_math;
30554 label reswitch,found,not_found,done;
30555 var w:scaled; {new or partial |pre_display_size|}
30556 @!j:pointer; {prototype box for display}
30557 @!x:integer; {new |pre_display_direction|}
30558 @!l:scaled; {new |display_width|}
30559 @!s:scaled; {new |display_indent|}
30560 @!p:pointer; {current node when calculating |pre_display_size|}
30561 @!q:pointer; {glue specification when calculating |pre_display_size|}
30562 @!f:internal_font_number; {font in current |char_node|}
30563 @!n:integer; {scope of paragraph shape specification}
30564 @!v:scaled; {|w| plus possible glue amount}
30565 @!d:scaled; {increment to |v|}
30566 begin get_token; {|get_x_token| would fail on \.{\\ifmmode}\thinspace!}
30567 if (cur_cmd=math_shift)and(mode>0) then @<Go into display math mode@>
30568 else begin back_input; @<Go into ordinary math mode@>;
30569 end;
30570 end;
30571
30572 @ @<Go into ordinary math mode@>=
30573 begin push_math(math_shift_group); eq_word_define(int_base+cur_fam_code,-1);
30574 if every_math<>null then begin_token_list(every_math,every_math_text);
30575 end
30576
30577 @ We get into ordinary math mode from display math mode when `\.{\\eqno}' or
30578 `\.{\\leqno}' appears. In such cases |cur_chr| will be 0 or~1, respectively;
30579 the value of |cur_chr| is placed onto |save_stack| for safe keeping.
30580
30581 @<Cases of |main_control| that build...@>=
30582 mmode+eq_no: if privileged then
30583 if cur_group=math_shift_group then start_eq_no
30584 else off_save;
30585
30586 @ @<Put each...@>=
30587 primitive("eqno",eq_no,0);
30588 @!@:eq_no_}{\.{\\eqno} primitive@>
30589 primitive("leqno",eq_no,1);
30590 @!@:leq_no_}{\.{\\leqno} primitive@>
30591
30592 @ When \TeX\ is in display math mode, |cur_group=math_shift_group|,
30593 so it is not necessary for the |start_eq_no| procedure to test for
30594 this condition.
30595
30596 @<Declare act...@>=
30597 procedure start_eq_no;
30598 begin saved(0):=cur_chr; incr(save_ptr);
30599 @<Go into ordinary math mode@>;
30600 end;
30601
30602 @ @<Cases of |print_cmd_chr|...@>=
30603 eq_no:if chr_code=1 then print_esc("leqno")@+else print_esc("eqno");
30604
30605 @ @<Forbidden...@>=non_math(eq_no),
30606
30607 @ When we enter display math mode, we need to call |line_break| to
30608 process the partial paragraph that has just been interrupted by the
30609 display. Then we can set the proper values of |display_width| and
30610 |display_indent| and |pre_display_size|.
30611
30612 @<Go into display math mode@>=
30613 begin j:=null; w:=-max_dimen;
30614 if head=tail then {`\.{\\noindent\$\$}' or `\.{\$\${ }\$\$}'}
30615 @<Prepare for display after an empty paragraph@>
30616 else begin line_break(true);@/
30617 @<Calculate the natural width, |w|, by which the characters of the
30618 final line extend to the right of the reference point,
30619 plus two ems; or set |w:=max_dimen| if the non-blank information
30620 on that line is affected by stretching or shrinking@>;
30621 end;
30622 {now we are in vertical mode, working on the list that will contain the display}
30623 @<Calculate the length, |l|, and the shift amount, |s|, of the display lines@>;
30624 push_math(math_shift_group); mode:=mmode;
30625 eq_word_define(int_base+cur_fam_code,-1);@/
30626 eq_word_define(dimen_base+pre_display_size_code,w);
30627 LR_box:=j;
30628 if eTeX_ex then eq_word_define(int_base+pre_display_direction_code,x);
30629 eq_word_define(dimen_base+display_width_code,l);
30630 eq_word_define(dimen_base+display_indent_code,s);
30631 if every_display<>null then begin_token_list(every_display,every_display_text);
30632 if nest_ptr=1 then build_page;
30633 end
30634
30635 @ @<Calculate the natural width, |w|, by which...@>=
30636 @<Prepare for display after a non-empty paragraph@>;
30637 while p<>null do
30638 begin @<Let |d| be the natural width of node |p|;
30639 if the node is ``visible,'' |goto found|;
30640 if the node is glue that stretches or shrinks, set |v:=max_dimen|@>;
30641 if v<max_dimen then v:=v+d;
30642 goto not_found;
30643 found: if v<max_dimen then
30644 begin v:=v+d; w:=v;
30645 end
30646 else begin w:=max_dimen; goto done;
30647 end;
30648 not_found: p:=link(p);
30649 end;
30650 done:
30651 @<Finish the natural width computation@>
30652
30653 @ @<Let |d| be the natural width of node |p|...@>=
30654 reswitch: if is_char_node(p) then
30655 begin f:=font(p); d:=char_width(f)(char_info(f)(character(p)));
30656 goto found;
30657 end;
30658 case type(p) of
30659 hlist_node,vlist_node,rule_node: begin d:=width(p); goto found;
30660 end;
30661 ligature_node:@<Make node |p| look like a |char_node|...@>;
30662 margin_kern_node: d:=width(p);
30663 kern_node: d:=width(p);
30664 @t\4@>@<Cases of `Let |d| be the natural width' that need special treatment@>@;
30665 glue_node:@<Let |d| be the natural width of this glue; if stretching
30666 or shrinking, set |v:=max_dimen|; |goto found| in the case of leaders@>;
30667 whatsit_node: @<Let |d| be the width of the whatsit |p|@>;
30668 othercases d:=0
30669 endcases
30670
30671 @ We need to be careful that |w|, |v|, and |d| do not depend on any |glue_set|
30672 values, since such values are subject to system-dependent rounding.
30673 System-dependent numbers are not allowed to infiltrate parameters like
30674 |pre_display_size|, since \TeX82 is supposed to make the same decisions on all
30675 machines.
30676
30677 @<Let |d| be the natural width of this glue...@>=
30678 begin q:=glue_ptr(p); d:=width(q);
30679 if glue_sign(just_box)=stretching then
30680 begin if (glue_order(just_box)=stretch_order(q))and@|
30681 (stretch(q)<>0) then
30682 v:=max_dimen;
30683 end
30684 else if glue_sign(just_box)=shrinking then
30685 begin if (glue_order(just_box)=shrink_order(q))and@|
30686 (shrink(q)<>0) then
30687 v:=max_dimen;
30688 end;
30689 if subtype(p)>=a_leaders then goto found;
30690 end
30691
30692 @ A displayed equation is considered to be three lines long, so we
30693 calculate the length and offset of line number |prev_graf+2|.
30694
30695 @<Calculate the length, |l|, ...@>=
30696 if par_shape_ptr=null then
30697 if (hang_indent<>0)and@|
30698 (((hang_after>=0)and(prev_graf+2>hang_after))or@|
30699 (prev_graf+1<-hang_after)) then
30700 begin l:=hsize-abs(hang_indent);
30701 if hang_indent>0 then s:=hang_indent@+else s:=0;
30702 end
30703 else begin l:=hsize; s:=0;
30704 end
30705 else begin n:=info(par_shape_ptr);
30706 if prev_graf+2>=n then p:=par_shape_ptr+2*n
30707 else p:=par_shape_ptr+2*(prev_graf+2);
30708 s:=mem[p-1].sc; l:=mem[p].sc;
30709 end
30710
30711 @ Subformulas of math formulas cause a new level of math mode to be entered,
30712 on the semantic nest as well as the save stack. These subformulas arise in
30713 several ways: (1)~A left brace by itself indicates the beginning of a
30714 subformula that will be put into a box, thereby freezing its glue and
30715 preventing line breaks. (2)~A subscript or superscript is treated as a
30716 subformula if it is not a single character; the same applies to
30717 the nucleus of things like \.{\\underline}. (3)~The \.{\\left} primitive
30718 initiates a subformula that will be terminated by a matching \.{\\right}.
30719 The group codes placed on |save_stack| in these three cases are
30720 |math_group|, |math_group|, and |math_left_group|, respectively.
30721
30722 Here is the code that handles case (1); the other cases are not quite as
30723 trivial, so we shall consider them later.
30724
30725 @<Cases of |main_control| that build...@>=
30726 mmode+left_brace: begin tail_append(new_noad);
30727 back_input; scan_math(nucleus(tail));
30728 end;
30729
30730 @ Recall that the |nucleus|, |subscr|, and |supscr| fields in a noad are
30731 broken down into subfields called |math_type| and either |info| or
30732 |(fam,character)|. The job of |scan_math| is to figure out what to place
30733 in one of these principal fields; it looks at the subformula that
30734 comes next in the input, and places an encoding of that subformula
30735 into a given word of |mem|.
30736
30737 @d fam_in_range==((cur_fam>=0)and(cur_fam<16))
30738
30739 @<Declare act...@>=
30740 procedure scan_math(@!p:pointer);
30741 label restart,reswitch,exit;
30742 var c:integer; {math character code}
30743 begin restart:@<Get the next non-blank non-relax...@>;
30744 reswitch:case cur_cmd of
30745 letter,other_char,char_given: begin c:=ho(math_code(cur_chr));
30746 if c=@'100000 then
30747 begin @<Treat |cur_chr| as an active character@>;
30748 goto restart;
30749 end;
30750 end;
30751 char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
30752 goto reswitch;
30753 end;
30754 math_char_num: begin scan_fifteen_bit_int; c:=cur_val;
30755 end;
30756 math_given: c:=cur_chr;
30757 delim_num: begin scan_twenty_seven_bit_int; c:=cur_val div @'10000;
30758 end;
30759 othercases @<Scan a subformula enclosed in braces and |return|@>
30760 endcases;@/
30761 math_type(p):=math_char; character(p):=qi(c mod 256);
30762 if (c>=var_code)and fam_in_range then fam(p):=cur_fam
30763 else fam(p):=(c div 256) mod 16;
30764 exit:end;
30765
30766 @ An active character that is an |outer_call| is allowed here.
30767
30768 @<Treat |cur_chr|...@>=
30769 begin cur_cs:=cur_chr+active_base;
30770 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
30771 x_token; back_input;
30772 end
30773
30774 @ The pointer |p| is placed on |save_stack| while a complex subformula
30775 is being scanned.
30776
30777 @<Scan a subformula...@>=
30778 begin back_input; scan_left_brace;@/
30779 saved(0):=p; incr(save_ptr); push_math(math_group); return;
30780 end
30781
30782 @ The simplest math formula is, of course, `\.{\${ }\$}', when no noads are
30783 generated. The next simplest cases involve a single character, e.g.,
30784 `\.{\$x\$}'. Even though such cases may not seem to be very interesting,
30785 the reader can perhaps understand how happy the author was when `\.{\$x\$}'
30786 was first properly typeset by \TeX. The code in this section was used.
30787 @^Knuth, Donald Ervin@>
30788
30789 @<Cases of |main_control| that build...@>=
30790 mmode+letter,mmode+other_char,mmode+char_given:
30791 set_math_char(ho(math_code(cur_chr)));
30792 mmode+char_num: begin scan_char_num; cur_chr:=cur_val;
30793 set_math_char(ho(math_code(cur_chr)));
30794 end;
30795 mmode+math_char_num: begin scan_fifteen_bit_int; set_math_char(cur_val);
30796 end;
30797 mmode+math_given: set_math_char(cur_chr);
30798 mmode+delim_num: begin scan_twenty_seven_bit_int;
30799 set_math_char(cur_val div @'10000);
30800 end;
30801
30802 @ The |set_math_char| procedure creates a new noad appropriate to a given
30803 math code, and appends it to the current mlist. However, if the math code
30804 is sufficiently large, the |cur_chr| is treated as an active character and
30805 nothing is appended.
30806
30807 @<Declare act...@>=
30808 procedure set_math_char(@!c:integer);
30809 var p:pointer; {the new noad}
30810 begin if c>=@'100000 then
30811 @<Treat |cur_chr|...@>
30812 else begin p:=new_noad; math_type(nucleus(p)):=math_char;
30813 character(nucleus(p)):=qi(c mod 256);
30814 fam(nucleus(p)):=(c div 256) mod 16;
30815 if c>=var_code then
30816 begin if fam_in_range then fam(nucleus(p)):=cur_fam;
30817 type(p):=ord_noad;
30818 end
30819 else type(p):=ord_noad+(c div @'10000);
30820 link(tail):=p; tail:=p;
30821 end;
30822 end;
30823
30824 @ Primitive math operators like \.{\\mathop} and \.{\\underline} are given
30825 the command code |math_comp|, supplemented by the noad type that they
30826 generate.
30827
30828 @<Put each...@>=
30829 primitive("mathord",math_comp,ord_noad);
30830 @!@:math_ord_}{\.{\\mathord} primitive@>
30831 primitive("mathop",math_comp,op_noad);
30832 @!@:math_op_}{\.{\\mathop} primitive@>
30833 primitive("mathbin",math_comp,bin_noad);
30834 @!@:math_bin_}{\.{\\mathbin} primitive@>
30835 primitive("mathrel",math_comp,rel_noad);
30836 @!@:math_rel_}{\.{\\mathrel} primitive@>
30837 primitive("mathopen",math_comp,open_noad);
30838 @!@:math_open_}{\.{\\mathopen} primitive@>
30839 primitive("mathclose",math_comp,close_noad);
30840 @!@:math_close_}{\.{\\mathclose} primitive@>
30841 primitive("mathpunct",math_comp,punct_noad);
30842 @!@:math_punct_}{\.{\\mathpunct} primitive@>
30843 primitive("mathinner",math_comp,inner_noad);
30844 @!@:math_inner_}{\.{\\mathinner} primitive@>
30845 primitive("underline",math_comp,under_noad);
30846 @!@:underline_}{\.{\\underline} primitive@>
30847 primitive("overline",math_comp,over_noad);@/
30848 @!@:overline_}{\.{\\overline} primitive@>
30849 primitive("displaylimits",limit_switch,normal);
30850 @!@:display_limits_}{\.{\\displaylimits} primitive@>
30851 primitive("limits",limit_switch,limits);
30852 @!@:limits_}{\.{\\limits} primitive@>
30853 primitive("nolimits",limit_switch,no_limits);
30854 @!@:no_limits_}{\.{\\nolimits} primitive@>
30855
30856 @ @<Cases of |print_cmd_chr|...@>=
30857 math_comp: case chr_code of
30858 ord_noad: print_esc("mathord");
30859 op_noad: print_esc("mathop");
30860 bin_noad: print_esc("mathbin");
30861 rel_noad: print_esc("mathrel");
30862 open_noad: print_esc("mathopen");
30863 close_noad: print_esc("mathclose");
30864 punct_noad: print_esc("mathpunct");
30865 inner_noad: print_esc("mathinner");
30866 under_noad: print_esc("underline");
30867 othercases print_esc("overline")
30868 endcases;
30869 limit_switch: if chr_code=limits then print_esc("limits")
30870 else if chr_code=no_limits then print_esc("nolimits")
30871 else print_esc("displaylimits");
30872
30873 @ @<Cases of |main_control| that build...@>=
30874 mmode+math_comp: begin tail_append(new_noad);
30875 type(tail):=cur_chr; scan_math(nucleus(tail));
30876 end;
30877 mmode+limit_switch: math_limit_switch;
30878
30879 @ @<Declare act...@>=
30880 procedure math_limit_switch;
30881 label exit;
30882 begin if head<>tail then if type(tail)=op_noad then
30883 begin subtype(tail):=cur_chr; return;
30884 end;
30885 print_err("Limit controls must follow a math operator");
30886 @.Limit controls must follow...@>
30887 help1("I'm ignoring this misplaced \limits or \nolimits command."); error;
30888 exit:end;
30889
30890 @ Delimiter fields of noads are filled in by the |scan_delimiter| routine.
30891 The first parameter of this procedure is the |mem| address where the
30892 delimiter is to be placed; the second tells if this delimiter follows
30893 \.{\\radical} or not.
30894
30895 @<Declare act...@>=
30896 procedure scan_delimiter(@!p:pointer;@!r:boolean);
30897 begin if r then scan_twenty_seven_bit_int
30898 else begin @<Get the next non-blank non-relax...@>;
30899 case cur_cmd of
30900 letter,other_char: cur_val:=del_code(cur_chr);
30901 delim_num: scan_twenty_seven_bit_int;
30902 othercases cur_val:=-1
30903 endcases;
30904 end;
30905 if cur_val<0 then @<Report that an invalid delimiter code is being changed
30906 to null; set~|cur_val:=0|@>;
30907 small_fam(p):=(cur_val div @'4000000) mod 16;
30908 small_char(p):=qi((cur_val div @'10000) mod 256);
30909 large_fam(p):=(cur_val div 256) mod 16;
30910 large_char(p):=qi(cur_val mod 256);
30911 end;
30912
30913 @ @<Report that an invalid delimiter...@>=
30914 begin print_err("Missing delimiter (. inserted)");
30915 @.Missing delimiter...@>
30916 help6("I was expecting to see something like `(' or `\{' or")@/
30917 ("`\}' here. If you typed, e.g., `{' instead of `\{', you")@/
30918 ("should probably delete the `{' by typing `1' now, so that")@/
30919 ("braces don't get unbalanced. Otherwise just proceed.")@/
30920 ("Acceptable delimiters are characters whose \delcode is")@/
30921 ("nonnegative, or you can use `\delimiter <delimiter code>'.");
30922 back_error; cur_val:=0;
30923 end
30924
30925 @ @<Cases of |main_control| that build...@>=
30926 mmode+radical:math_radical;
30927
30928 @ @<Declare act...@>=
30929 procedure math_radical;
30930 begin tail_append(get_node(radical_noad_size));
30931 type(tail):=radical_noad; subtype(tail):=normal;
30932 mem[nucleus(tail)].hh:=empty_field;
30933 mem[subscr(tail)].hh:=empty_field;
30934 mem[supscr(tail)].hh:=empty_field;
30935 scan_delimiter(left_delimiter(tail),true); scan_math(nucleus(tail));
30936 end;
30937
30938 @ @<Cases of |main_control| that build...@>=
30939 mmode+accent,mmode+math_accent:math_ac;
30940
30941 @ @<Declare act...@>=
30942 procedure math_ac;
30943 begin if cur_cmd=accent then
30944 @<Complain that the user should have said \.{\\mathaccent}@>;
30945 tail_append(get_node(accent_noad_size));
30946 type(tail):=accent_noad; subtype(tail):=normal;
30947 mem[nucleus(tail)].hh:=empty_field;
30948 mem[subscr(tail)].hh:=empty_field;
30949 mem[supscr(tail)].hh:=empty_field;
30950 math_type(accent_chr(tail)):=math_char;
30951 scan_fifteen_bit_int;
30952 character(accent_chr(tail)):=qi(cur_val mod 256);
30953 if (cur_val>=var_code)and fam_in_range then fam(accent_chr(tail)):=cur_fam
30954 else fam(accent_chr(tail)):=(cur_val div 256) mod 16;
30955 scan_math(nucleus(tail));
30956 end;
30957
30958 @ @<Complain that the user should have said \.{\\mathaccent}@>=
30959 begin print_err("Please use "); print_esc("mathaccent");
30960 print(" for accents in math mode");
30961 @.Please use \\mathaccent...@>
30962 help2("I'm changing \accent to \mathaccent here; wish me luck.")@/
30963 ("(Accents are not the same in formulas as they are in text.)");
30964 error;
30965 end
30966
30967 @ @<Cases of |main_control| that build...@>=
30968 mmode+vcenter: begin scan_spec(vcenter_group,false); normal_paragraph;
30969 push_nest; mode:=-vmode; prev_depth:=pdf_ignored_dimen;
30970 if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
30971 end;
30972
30973 @ @<Cases of |handle...@>=
30974 vcenter_group: begin end_graf; unsave; save_ptr:=save_ptr-2;
30975 p:=vpack(link(head),saved(1),saved(0)); pop_nest;
30976 tail_append(new_noad); type(tail):=vcenter_noad;
30977 math_type(nucleus(tail)):=sub_box; info(nucleus(tail)):=p;
30978 end;
30979
30980 @ The routine that inserts a |style_node| holds no surprises.
30981
30982 @<Put each...@>=
30983 primitive("displaystyle",math_style,display_style);
30984 @!@:display_style_}{\.{\\displaystyle} primitive@>
30985 primitive("textstyle",math_style,text_style);
30986 @!@:text_style_}{\.{\\textstyle} primitive@>
30987 primitive("scriptstyle",math_style,script_style);
30988 @!@:script_style_}{\.{\\scriptstyle} primitive@>
30989 primitive("scriptscriptstyle",math_style,script_script_style);
30990 @!@:script_script_style_}{\.{\\scriptscriptstyle} primitive@>
30991
30992 @ @<Cases of |print_cmd_chr|...@>=
30993 math_style: print_style(chr_code);
30994
30995 @ @<Cases of |main_control| that build...@>=
30996 mmode+math_style: tail_append(new_style(cur_chr));
30997 mmode+non_script: begin tail_append(new_glue(zero_glue));
30998 subtype(tail):=cond_math_glue;
30999 end;
31000 mmode+math_choice: append_choices;
31001
31002 @ The routine that scans the four mlists of a \.{\\mathchoice} is very
31003 much like the routine that builds discretionary nodes.
31004
31005 @<Declare act...@>=
31006 procedure append_choices;
31007 begin tail_append(new_choice); incr(save_ptr); saved(-1):=0;
31008 push_math(math_choice_group); scan_left_brace;
31009 end;
31010
31011 @ @<Cases of |handle_right_brace|...@>=
31012 math_choice_group: build_choices;
31013
31014 @ @<Declare act...@>=
31015 @t\4@>@<Declare the function called |fin_mlist|@>@t@>@;@/
31016 procedure build_choices;
31017 label exit;
31018 var p:pointer; {the current mlist}
31019 begin unsave; p:=fin_mlist(null);
31020 case saved(-1) of
31021 0:display_mlist(tail):=p;
31022 1:text_mlist(tail):=p;
31023 2:script_mlist(tail):=p;
31024 3:begin script_script_mlist(tail):=p; decr(save_ptr); return;
31025 end;
31026 end; {there are no other cases}
31027 incr(saved(-1)); push_math(math_choice_group); scan_left_brace;
31028 exit:end;
31029
31030 @ Subscripts and superscripts are attached to the previous nucleus by the
31031 @^superscripts@>@^subscripts@>
31032 action procedure called |sub_sup|. We use the facts that |sub_mark=sup_mark+1|
31033 and |subscr(p)=supscr(p)+1|.
31034
31035 @<Cases of |main_control| that build...@>=
31036 mmode+sub_mark,mmode+sup_mark: sub_sup;
31037
31038 @ @<Declare act...@>=
31039 procedure sub_sup;
31040 var t:small_number; {type of previous sub/superscript}
31041 @!p:pointer; {field to be filled by |scan_math|}
31042 begin t:=empty; p:=null;
31043 if tail<>head then if scripts_allowed(tail) then
31044 begin p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
31045 t:=math_type(p);
31046 end;
31047 if (p=null)or(t<>empty) then @<Insert a dummy noad to be sub/superscripted@>;
31048 scan_math(p);
31049 end;
31050
31051 @ @<Insert a dummy...@>=
31052 begin tail_append(new_noad);
31053 p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
31054 if t<>empty then
31055 begin if cur_cmd=sup_mark then
31056 begin print_err("Double superscript");
31057 @.Double superscript@>
31058 help1("I treat `x^1^2' essentially like `x^1{}^2'.");
31059 end
31060 else begin print_err("Double subscript");
31061 @.Double subscript@>
31062 help1("I treat `x_1_2' essentially like `x_1{}_2'.");
31063 end;
31064 error;
31065 end;
31066 end
31067
31068 @ An operation like `\.{\\over}' causes the current mlist to go into a
31069 state of suspended animation: |incompleat_noad| points to a |fraction_noad|
31070 that contains the mlist-so-far as its numerator, while the denominator
31071 is yet to come. Finally when the mlist is finished, the denominator will
31072 go into the incompleat fraction noad, and that noad will become the
31073 whole formula, unless it is surrounded by `\.{\\left}' and `\.{\\right}'
31074 delimiters.
31075
31076 @d above_code=0 { `\.{\\above}' }
31077 @d over_code=1 { `\.{\\over}' }
31078 @d atop_code=2 { `\.{\\atop}' }
31079 @d delimited_code=3 { `\.{\\abovewithdelims}', etc.}
31080
31081 @<Put each...@>=
31082 primitive("above",above,above_code);@/
31083 @!@:above_}{\.{\\above} primitive@>
31084 primitive("over",above,over_code);@/
31085 @!@:over_}{\.{\\over} primitive@>
31086 primitive("atop",above,atop_code);@/
31087 @!@:atop_}{\.{\\atop} primitive@>
31088 primitive("abovewithdelims",above,delimited_code+above_code);@/
31089 @!@:above_with_delims_}{\.{\\abovewithdelims} primitive@>
31090 primitive("overwithdelims",above,delimited_code+over_code);@/
31091 @!@:over_with_delims_}{\.{\\overwithdelims} primitive@>
31092 primitive("atopwithdelims",above,delimited_code+atop_code);
31093 @!@:atop_with_delims_}{\.{\\atopwithdelims} primitive@>
31094
31095 @ @<Cases of |print_cmd_chr|...@>=
31096 above: case chr_code of
31097 over_code:print_esc("over");
31098 atop_code:print_esc("atop");
31099 delimited_code+above_code:print_esc("abovewithdelims");
31100 delimited_code+over_code:print_esc("overwithdelims");
31101 delimited_code+atop_code:print_esc("atopwithdelims");
31102 othercases print_esc("above")
31103 endcases;
31104
31105 @ @<Cases of |main_control| that build...@>=
31106 mmode+above: math_fraction;
31107
31108 @ @<Declare act...@>=
31109 procedure math_fraction;
31110 var c:small_number; {the type of generalized fraction we are scanning}
31111 begin c:=cur_chr;
31112 if incompleat_noad<>null then
31113 @<Ignore the fraction operation and complain about this ambiguous case@>
31114 else begin incompleat_noad:=get_node(fraction_noad_size);
31115 type(incompleat_noad):=fraction_noad;
31116 subtype(incompleat_noad):=normal;
31117 math_type(numerator(incompleat_noad)):=sub_mlist;
31118 info(numerator(incompleat_noad)):=link(head);
31119 mem[denominator(incompleat_noad)].hh:=empty_field;
31120 mem[left_delimiter(incompleat_noad)].qqqq:=null_delimiter;
31121 mem[right_delimiter(incompleat_noad)].qqqq:=null_delimiter;@/
31122 link(head):=null; tail:=head;
31123 @<Use code |c| to distinguish between generalized fractions@>;
31124 end;
31125 end;
31126
31127 @ @<Use code |c|...@>=
31128 if c>=delimited_code then
31129 begin scan_delimiter(left_delimiter(incompleat_noad),false);
31130 scan_delimiter(right_delimiter(incompleat_noad),false);
31131 end;
31132 case c mod delimited_code of
31133 above_code: begin scan_normal_dimen;
31134 thickness(incompleat_noad):=cur_val;
31135 end;
31136 over_code: thickness(incompleat_noad):=default_code;
31137 atop_code: thickness(incompleat_noad):=0;
31138 end {there are no other cases}
31139
31140 @ @<Ignore the fraction...@>=
31141 begin if c>=delimited_code then
31142 begin scan_delimiter(garbage,false); scan_delimiter(garbage,false);
31143 end;
31144 if c mod delimited_code=above_code then scan_normal_dimen;
31145 print_err("Ambiguous; you need another { and }");
31146 @.Ambiguous...@>
31147 help3("I'm ignoring this fraction specification, since I don't")@/
31148 ("know whether a construction like `x \over y \over z'")@/
31149 ("means `{x \over y} \over z' or `x \over {y \over z}'.");
31150 error;
31151 end
31152
31153 @ At the end of a math formula or subformula, the |fin_mlist| routine is
31154 called upon to return a pointer to the newly completed mlist, and to
31155 pop the nest back to the enclosing semantic level. The parameter to
31156 |fin_mlist|, if not null, points to a |right_noad| that ends the
31157 current mlist; this |right_noad| has not yet been appended.
31158
31159 @<Declare the function called |fin_mlist|@>=
31160 function fin_mlist(@!p:pointer):pointer;
31161 var q:pointer; {the mlist to return}
31162 begin if incompleat_noad<>null then @<Compleat the incompleat noad@>
31163 else begin link(tail):=p; q:=link(head);
31164 end;
31165 pop_nest; fin_mlist:=q;
31166 end;
31167
31168 @ @<Compleat...@>=
31169 begin math_type(denominator(incompleat_noad)):=sub_mlist;
31170 info(denominator(incompleat_noad)):=link(head);
31171 if p=null then q:=incompleat_noad
31172 else begin q:=info(numerator(incompleat_noad));
31173 if (type(q)<>left_noad)or(delim_ptr=null) then confusion("right");
31174 @:this can't happen right}{\quad right@>
31175 info(numerator(incompleat_noad)):=link(delim_ptr);
31176 link(delim_ptr):=incompleat_noad; link(incompleat_noad):=p;
31177 end;
31178 end
31179
31180 @ Now at last we're ready to see what happens when a right brace occurs
31181 in a math formula. Two special cases are simplified here: Braces are effectively
31182 removed when they surround a single Ord without sub/superscripts, or when they
31183 surround an accent that is the nucleus of an Ord atom.
31184
31185 @<Cases of |handle...@>=
31186 math_group: begin unsave; decr(save_ptr);@/
31187 math_type(saved(0)):=sub_mlist; p:=fin_mlist(null); info(saved(0)):=p;
31188 if p<>null then if link(p)=null then
31189 if type(p)=ord_noad then
31190 begin if math_type(subscr(p))=empty then
31191 if math_type(supscr(p))=empty then
31192 begin mem[saved(0)].hh:=mem[nucleus(p)].hh;
31193 free_node(p,noad_size);
31194 end;
31195 end
31196 else if type(p)=accent_noad then if saved(0)=nucleus(tail) then
31197 if type(tail)=ord_noad then @<Replace the tail of the list by |p|@>;
31198 end;
31199
31200 @ @<Replace the tail...@>=
31201 begin q:=head; while link(q)<>tail do q:=link(q);
31202 link(q):=p; free_node(tail,noad_size); tail:=p;
31203 end
31204
31205 @ We have dealt with all constructions of math mode except `\.{\\left}' and
31206 `\.{\\right}', so the picture is completed by the following sections of
31207 the program.
31208
31209 @<Put each...@>=
31210 primitive("left",left_right,left_noad);
31211 @!@:left_}{\.{\\left} primitive@>
31212 primitive("right",left_right,right_noad);
31213 @!@:right_}{\.{\\right} primitive@>
31214 text(frozen_right):="right"; eqtb[frozen_right]:=eqtb[cur_val];
31215
31216 @ @<Cases of |print_cmd_chr|...@>=
31217 left_right: if chr_code=left_noad then print_esc("left")
31218 @/@<Cases of |left_right| for |print_cmd_chr|@>@/
31219 else print_esc("right");
31220
31221 @ @<Cases of |main_control| that build...@>=
31222 mmode+left_right: math_left_right;
31223
31224 @ @<Declare act...@>=
31225 procedure math_left_right;
31226 var t:small_number; {|left_noad| or |right_noad|}
31227 @!p:pointer; {new noad}
31228 @!q:pointer; {resulting mlist}
31229 begin t:=cur_chr;
31230 if (t<>left_noad)and(cur_group<>math_left_group) then
31231 @<Try to recover from mismatched \.{\\right}@>
31232 else begin p:=new_noad; type(p):=t;
31233 scan_delimiter(delimiter(p),false);
31234 if t=middle_noad then
31235 begin type(p):=right_noad; subtype(p):=middle_noad;
31236 end;
31237 if t=left_noad then q:=p
31238 else begin q:=fin_mlist(p); unsave; {end of |math_left_group|}
31239 end;
31240 if t<>right_noad then
31241 begin push_math(math_left_group); link(head):=q; tail:=p;
31242 delim_ptr:=p;
31243 end
31244 else begin
31245 tail_append(new_noad); type(tail):=inner_noad;
31246 math_type(nucleus(tail)):=sub_mlist;
31247 info(nucleus(tail)):=q;
31248 end;
31249 end;
31250 end;
31251
31252 @ @<Try to recover from mismatch...@>=
31253 begin if cur_group=math_shift_group then
31254 begin scan_delimiter(garbage,false);
31255 print_err("Extra ");
31256 if t=middle_noad then
31257 begin print_esc("middle");
31258 @.Extra \\middle.@>
31259 help1("I'm ignoring a \middle that had no matching \left.");
31260 end
31261 else begin print_esc("right");
31262 @.Extra \\right.@>
31263 help1("I'm ignoring a \right that had no matching \left.");
31264 end;
31265 error;
31266 end
31267 else off_save;
31268 end
31269
31270 @ Here is the only way out of math mode.
31271
31272 @<Cases of |main_control| that build...@>=
31273 mmode+math_shift: if cur_group=math_shift_group then after_math
31274 else off_save;
31275
31276 @ @<Declare act...@>=
31277 @t\4@>@<Declare subprocedures for |after_math|@>@;
31278 procedure after_math;
31279 var l:boolean; {`\.{\\leqno}' instead of `\.{\\eqno}'}
31280 @!danger:boolean; {not enough symbol fonts are present}
31281 @!m:integer; {|mmode| or |-mmode|}
31282 @!p:pointer; {the formula}
31283 @!a:pointer; {box containing equation number}
31284 @<Local variables for finishing a displayed formula@>@;
31285 begin danger:=false;
31286 @<Retrieve the prototype box@>;
31287 @<Check that the necessary fonts for math symbols are present;
31288 if not, flush the current math lists and set |danger:=true|@>;
31289 m:=mode; l:=false; p:=fin_mlist(null); {this pops the nest}
31290 if mode=-m then {end of equation number}
31291 begin @<Check that another \.\$ follows@>;
31292 cur_mlist:=p; cur_style:=text_style; mlist_penalties:=false;
31293 mlist_to_hlist; a:=hpack(link(temp_head),natural);
31294 set_box_lr(a)(dlist);
31295 unsave; decr(save_ptr); {now |cur_group=math_shift_group|}
31296 if saved(0)=1 then l:=true;
31297 danger:=false;
31298 @<Retrieve the prototype box@>;
31299 @<Check that the necessary fonts for math symbols are present;
31300 if not, flush the current math lists and set |danger:=true|@>;
31301 m:=mode; p:=fin_mlist(null);
31302 end
31303 else a:=null;
31304 if m<0 then @<Finish math in text@>
31305 else begin if a=null then @<Check that another \.\$ follows@>;
31306 @<Finish displayed math@>;
31307 end;
31308 end;
31309
31310 @ @<Check that the necessary fonts...@>=
31311 if (font_params[fam_fnt(2+text_size)]<total_mathsy_params)or@|
31312 (font_params[fam_fnt(2+script_size)]<total_mathsy_params)or@|
31313 (font_params[fam_fnt(2+script_script_size)]<total_mathsy_params) then
31314 begin print_err("Math formula deleted: Insufficient symbol fonts");@/
31315 @.Math formula deleted...@>
31316 help3("Sorry, but I can't typeset math unless \textfont 2")@/
31317 ("and \scriptfont 2 and \scriptscriptfont 2 have all")@/
31318 ("the \fontdimen values needed in math symbol fonts.");
31319 error; flush_math; danger:=true;
31320 end
31321 else if (font_params[fam_fnt(3+text_size)]<total_mathex_params)or@|
31322 (font_params[fam_fnt(3+script_size)]<total_mathex_params)or@|
31323 (font_params[fam_fnt(3+script_script_size)]<total_mathex_params) then
31324 begin print_err("Math formula deleted: Insufficient extension fonts");@/
31325 help3("Sorry, but I can't typeset math unless \textfont 3")@/
31326 ("and \scriptfont 3 and \scriptscriptfont 3 have all")@/
31327 ("the \fontdimen values needed in math extension fonts.");
31328 error; flush_math; danger:=true;
31329 end
31330
31331 @ The |unsave| is done after everything else here; hence an appearance of
31332 `\.{\\mathsurround}' inside of `\.{\$...\$}' affects the spacing at these
31333 particular \.\$'s. This is consistent with the conventions of
31334 `\.{\$\$...\$\$}', since `\.{\\abovedisplayskip}' inside a display affects the
31335 space above that display.
31336
31337 @<Finish math in text@>=
31338 begin tail_append(new_math(math_surround,before));
31339 cur_mlist:=p; cur_style:=text_style; mlist_penalties:=(mode>0); mlist_to_hlist;
31340 link(tail):=link(temp_head);
31341 while link(tail)<>null do tail:=link(tail);
31342 tail_append(new_math(math_surround,after));
31343 space_factor:=1000; unsave;
31344 end
31345
31346 @ \TeX\ gets to the following part of the program when the first `\.\$' ending
31347 a display has been scanned.
31348
31349 @<Check that another \.\$ follows@>=
31350 begin get_x_token;
31351 if cur_cmd<>math_shift then
31352 begin print_err("Display math should end with $$");
31353 @.Display math...with \$\$@>
31354 help2("The `$' that I just saw supposedly matches a previous `$$'.")@/
31355 ("So I shall assume that you typed `$$' both times.");
31356 back_error;
31357 end;
31358 end
31359
31360 @ We have saved the worst for last: The fussiest part of math mode processing
31361 occurs when a displayed formula is being centered and placed with an optional
31362 equation number.
31363
31364 @<Local variables for finishing...@>=
31365 @!b:pointer; {box containing the equation}
31366 @!w:scaled; {width of the equation}
31367 @!z:scaled; {width of the line}
31368 @!e:scaled; {width of equation number}
31369 @!q:scaled; {width of equation number plus space to separate from equation}
31370 @!d:scaled; {displacement of equation in the line}
31371 @!s:scaled; {move the line right this much}
31372 @!g1,@!g2:small_number; {glue parameter codes for before and after}
31373 @!r:pointer; {kern node used to position the display}
31374 @!t:pointer; {tail of adjustment list}
31375 @!pre_t:pointer; {tail of pre-adjustment list}
31376
31377 @ At this time |p| points to the mlist for the formula; |a| is either
31378 |null| or it points to a box containing the equation number; and we are in
31379 vertical mode (or internal vertical mode).
31380
31381 @<Finish displayed math@>=
31382 cur_mlist:=p; cur_style:=display_style; mlist_penalties:=false;
31383 mlist_to_hlist; p:=link(temp_head);@/
31384 adjust_tail:=adjust_head; pre_adjust_tail:=pre_adjust_head;
31385 b:=hpack(p,natural); p:=list_ptr(b);
31386 t:=adjust_tail; adjust_tail:=null;@/
31387 pre_t:=pre_adjust_tail; pre_adjust_tail:=null;@/
31388 w:=width(b); z:=display_width; s:=display_indent;
31389 if pre_display_direction<0 then s:=-s-z;
31390 if (a=null)or danger then
31391 begin e:=0; q:=0;
31392 end
31393 else begin e:=width(a); q:=e+math_quad(text_size);
31394 end;
31395 if w+q>z then
31396 @<Squeeze the equation as much as possible; if there is an equation
31397 number that should go on a separate line by itself,
31398 set~|e:=0|@>;
31399 @<Determine the displacement, |d|, of the left edge of the equation, with
31400 respect to the line size |z|, assuming that |l=false|@>;
31401 @<Append the glue or equation number preceding the display@>;
31402 @<Append the display and perhaps also the equation number@>;
31403 @<Append the glue or equation number following the display@>;
31404 @<Flush the prototype box@>;
31405 resume_after_display
31406
31407 @ @<Declare act...@>=
31408 procedure resume_after_display;
31409 begin if cur_group<>math_shift_group then confusion("display");
31410 @:this can't happen display}{\quad display@>
31411 unsave; prev_graf:=prev_graf+3;
31412 push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
31413 prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
31414 *@'200000+cur_lang;
31415 @<Scan an optional space@>;
31416 if nest_ptr=1 then build_page;
31417 end;
31418
31419 @ The user can force the equation number to go on a separate line
31420 by causing its width to be zero.
31421
31422 @<Squeeze the equation as much as possible...@>=
31423 begin if (e<>0)and((w-total_shrink[normal]+q<=z)or@|
31424 (total_shrink[fil]<>0)or(total_shrink[fill]<>0)or
31425 (total_shrink[filll]<>0)) then
31426 begin free_node(b,box_node_size);
31427 b:=hpack(p,z-q,exactly);
31428 end
31429 else begin e:=0;
31430 if w>z then
31431 begin free_node(b,box_node_size);
31432 b:=hpack(p,z,exactly);
31433 end;
31434 end;
31435 w:=width(b);
31436 end
31437
31438 @ We try first to center the display without regard to the existence of
31439 the equation number. If that would make it too close (where ``too close''
31440 means that the space between display and equation number is less than the
31441 width of the equation number), we either center it in the remaining space
31442 or move it as far from the equation number as possible. The latter alternative
31443 is taken only if the display begins with glue, since we assume that the
31444 user put glue there to control the spacing precisely.
31445
31446 @<Determine the displacement, |d|, of the left edge of the equation...@>=
31447 set_box_lr(b)(dlist);
31448 d:=half(z-w);
31449 if (e>0)and(d<2*e) then {too close}
31450 begin d:=half(z-w-e);
31451 if p<>null then if not is_char_node(p) then if type(p)=glue_node then d:=0;
31452 end
31453
31454 @ If the equation number is set on a line by itself, either before or
31455 after the formula, we append an infinite penalty so that no page break will
31456 separate the display from its number; and we use the same size and
31457 displacement for all three potential lines of the display, even though
31458 `\.{\\parshape}' may specify them differently.
31459
31460 @<Append the glue or equation number preceding the display@>=
31461 tail_append(new_penalty(pre_display_penalty));@/
31462 if (d+s<=pre_display_size)or l then {not enough clearance}
31463 begin g1:=above_display_skip_code; g2:=below_display_skip_code;
31464 end
31465 else begin g1:=above_display_short_skip_code;
31466 g2:=below_display_short_skip_code;
31467 end;
31468 if l and(e=0) then {it follows that |type(a)=hlist_node|}
31469 begin app_display(j,a,0);
31470 tail_append(new_penalty(inf_penalty));
31471 end
31472 else tail_append(new_param_glue(g1))
31473
31474 @ @<Append the display and perhaps also the equation number@>=
31475 if e<>0 then
31476 begin r:=new_kern(z-w-e-d);
31477 if l then
31478 begin link(a):=r; link(r):=b; b:=a; d:=0;
31479 end
31480 else begin link(b):=r; link(r):=a;
31481 end;
31482 b:=hpack(b,natural);
31483 end;
31484 app_display(j,b,d)
31485
31486 @ @<Append the glue or equation number following the display@>=
31487 if (a<>null)and(e=0)and not l then
31488 begin tail_append(new_penalty(inf_penalty));
31489 app_display(j,a,z-width(a));
31490 g2:=0;
31491 end;
31492 if t<>adjust_head then {migrating material comes after equation number}
31493 begin link(tail):=link(adjust_head); tail:=t;
31494 end;
31495 if pre_t<>pre_adjust_head then
31496 begin link(tail):=link(pre_adjust_head); tail:=pre_t;
31497 end;
31498 tail_append(new_penalty(post_display_penalty));
31499 if g2>0 then tail_append(new_param_glue(g2))
31500
31501 @ When \.{\\halign} appears in a display, the alignment routines operate
31502 essentially as they do in vertical mode. Then the following program is
31503 activated, with |p| and |q| pointing to the beginning and end of the
31504 resulting list, and with |aux_save| holding the |prev_depth| value.
31505
31506 @<Finish an alignment in a display@>=
31507 begin do_assignments;
31508 if cur_cmd<>math_shift then @<Pontificate about improper alignment in display@>
31509 else @<Check that another \.\$ follows@>;
31510 flush_node_list(LR_box);
31511 pop_nest;
31512 tail_append(new_penalty(pre_display_penalty));
31513 tail_append(new_param_glue(above_display_skip_code));
31514 link(tail):=p;
31515 if p<>null then tail:=q;
31516 tail_append(new_penalty(post_display_penalty));
31517 tail_append(new_param_glue(below_display_skip_code));
31518 prev_depth:=aux_save.sc; resume_after_display;
31519 end
31520
31521 @ @<Pontificate...@>=
31522 begin print_err("Missing $$ inserted");
31523 @.Missing {\$\$} inserted@>
31524 help2("Displays can use special alignments (like \eqalignno)")@/
31525 ("only if nothing but the alignment itself is between $$'s.");
31526 back_error;
31527 end
31528
31529 @* \[49] Mode-independent processing.
31530 The long |main_control| procedure has now been fully specified, except for
31531 certain activities that are independent of the current mode. These activities
31532 do not change the current vlist or hlist or mlist; if they change anything,
31533 it is the value of a parameter or the meaning of a control sequence.
31534
31535 Assignments to values in |eqtb| can be global or local. Furthermore, a
31536 control sequence can be defined to be `\.{\\long}', `\.{\\protected}',
31537 or `\.{\\outer}', and it might or might not be expanded. The prefixes
31538 `\.{\\global}', `\.{\\long}', `\.{\\protected}',
31539 and `\.{\\outer}' can occur in any order. Therefore we assign binary numeric
31540 codes, making it possible to accumulate the union of all specified prefixes
31541 by adding the corresponding codes. (\PASCAL's |set| operations could also
31542 have been used.)
31543
31544 @<Put each...@>=
31545 primitive("long",prefix,1);
31546 @!@:long_}{\.{\\long} primitive@>
31547 primitive("outer",prefix,2);
31548 @!@:outer_}{\.{\\outer} primitive@>
31549 primitive("global",prefix,4);
31550 @!@:global_}{\.{\\global} primitive@>
31551 primitive("def",def,0);
31552 @!@:def_}{\.{\\def} primitive@>
31553 primitive("gdef",def,1);
31554 @!@:gdef_}{\.{\\gdef} primitive@>
31555 primitive("edef",def,2);
31556 @!@:edef_}{\.{\\edef} primitive@>
31557 primitive("xdef",def,3);
31558 @!@:xdef_}{\.{\\xdef} primitive@>
31559
31560 @ @<Cases of |print_cmd_chr|...@>=
31561 prefix: if chr_code=1 then print_esc("long")
31562 else if chr_code=2 then print_esc("outer")
31563 @/@<Cases of |prefix| for |print_cmd_chr|@>@/
31564 else print_esc("global");
31565 def: if chr_code=0 then print_esc("def")
31566 else if chr_code=1 then print_esc("gdef")
31567 else if chr_code=2 then print_esc("edef")
31568 else print_esc("xdef");
31569
31570 @ Every prefix, and every command code that might or might not be prefixed,
31571 calls the action procedure |prefixed_command|. This routine accumulates
31572 a sequence of prefixes until coming to a non-prefix, then it carries out
31573 the command.
31574
31575 @<Cases of |main_control| that don't...@>=
31576 any_mode(toks_register),
31577 any_mode(assign_toks),
31578 any_mode(assign_int),
31579 any_mode(assign_dimen),
31580 any_mode(assign_glue),
31581 any_mode(assign_mu_glue),
31582 any_mode(assign_font_dimen),
31583 any_mode(assign_font_int),
31584 any_mode(set_aux),
31585 any_mode(set_prev_graf),
31586 any_mode(set_page_dimen),
31587 any_mode(set_page_int),
31588 any_mode(set_box_dimen),
31589 any_mode(set_shape),
31590 any_mode(def_code),
31591 any_mode(def_family),
31592 any_mode(set_font),
31593 any_mode(def_font),
31594 any_mode(letterspace_font),
31595 any_mode(pdf_copy_font),
31596 any_mode(register),
31597 any_mode(advance),
31598 any_mode(multiply),
31599 any_mode(divide),
31600 any_mode(prefix),
31601 any_mode(let),
31602 any_mode(shorthand_def),
31603 any_mode(read_to_cs),
31604 any_mode(def),
31605 any_mode(set_box),
31606 any_mode(hyph_data),
31607 any_mode(set_interaction):prefixed_command;
31608
31609 @ If the user says, e.g., `\.{\\global\\global}', the redundancy is
31610 silently accepted.
31611
31612 @<Declare act...@>=
31613 @t\4@>@<Declare subprocedures for |prefixed_command|@>@t@>@;@/
31614 procedure prefixed_command;
31615 label done,exit;
31616 var a:small_number; {accumulated prefix codes so far}
31617 @!f:internal_font_number; {identifies a font}
31618 @!j:halfword; {index into a \.{\\parshape} specification}
31619 @!k:font_index; {index into |font_info|}
31620 @!p,@!q:pointer; {for temporary short-term use}
31621 @!n:integer; {ditto}
31622 @!e:boolean; {should a definition be expanded? or was \.{\\let} not done?}
31623 begin a:=0;
31624 while cur_cmd=prefix do
31625 begin if not odd(a div cur_chr) then a:=a+cur_chr;
31626 @<Get the next non-blank non-relax...@>;
31627 if cur_cmd<=max_non_prefixed_command then
31628 @<Discard erroneous prefixes and |return|@>;
31629 if tracing_commands>2 then if eTeX_ex then show_cur_cmd_chr;
31630 end;
31631 @<Discard the prefixes \.{\\long} and \.{\\outer} if they are irrelevant@>;
31632 @<Adjust \(f)for the setting of \.{\\globaldefs}@>;
31633 case cur_cmd of
31634 @t\4@>@<Assignments@>@;
31635 othercases confusion("prefix")
31636 @:this can't happen prefix}{\quad prefix@>
31637 endcases;
31638 done: @<Insert a token saved by \.{\\afterassignment}, if any@>;
31639 exit:end;
31640
31641 @ @<Discard erroneous...@>=
31642 begin print_err("You can't use a prefix with `");
31643 @.You can't use a prefix with x@>
31644 print_cmd_chr(cur_cmd,cur_chr); print_char("'");
31645 help1("I'll pretend you didn't say \long or \outer or \global.");
31646 if eTeX_ex then help_line[0]:=@|
31647 "I'll pretend you didn't say \long or \outer or \global or \protected.";
31648 back_error; return;
31649 end
31650
31651 @ @<Discard the prefixes...@>=
31652 if a>=8 then
31653 begin j:=protected_token; a:=a-8;
31654 end
31655 else j:=0;
31656 if (cur_cmd<>def)and((a mod 4<>0)or(j<>0)) then
31657 begin print_err("You can't use `"); print_esc("long"); print("' or `");
31658 print_esc("outer");
31659 help1("I'll pretend you didn't say \long or \outer here.");
31660 if eTeX_ex then
31661 begin help_line[0]:=@|
31662 "I'll pretend you didn't say \long or \outer or \protected here.";
31663 print("' or `"); print_esc("protected");
31664 end;
31665 print("' with `");
31666 @.You can't use \\long...@>
31667 print_cmd_chr(cur_cmd,cur_chr); print_char("'");
31668 error;
31669 end
31670
31671 @ The previous routine does not have to adjust |a| so that |a mod 4=0|,
31672 since the following routines test for the \.{\\global} prefix as follows.
31673
31674 @d global==(a>=4)
31675 @d define(#)==if global then geq_define(#)@+else eq_define(#)
31676 @d word_define(#)==if global then geq_word_define(#)@+else eq_word_define(#)
31677
31678 @<Adjust \(f)for the setting of \.{\\globaldefs}@>=
31679 if global_defs<>0 then
31680 if global_defs<0 then
31681 begin if global then a:=a-4;
31682 end
31683 else begin if not global then a:=a+4;
31684 end
31685
31686 @ When a control sequence is to be defined, by \.{\\def} or \.{\\let} or
31687 something similar, the |get_r_token| routine will substitute a special
31688 control sequence for a token that is not redefinable.
31689
31690 @<Declare subprocedures for |prefixed_command|@>=
31691 procedure get_r_token;
31692 label restart;
31693 begin restart: repeat get_token;
31694 until cur_tok<>space_token;
31695 if (cur_cs=0)or(cur_cs>frozen_control_sequence) then
31696 begin print_err("Missing control sequence inserted");
31697 @.Missing control...@>
31698 help5("Please don't say `\def cs{...}', say `\def\cs{...}'.")@/
31699 ("I've inserted an inaccessible control sequence so that your")@/
31700 ("definition will be completed without mixing me up too badly.")@/
31701 ("You can recover graciously from this error, if you're")@/
31702 ("careful; see exercise 27.2 in The TeXbook.");
31703 @:TeXbook}{\sl The \TeX book@>
31704 if cur_cs=0 then back_input;
31705 cur_tok:=cs_token_flag+frozen_protection; ins_error; goto restart;
31706 end;
31707 end;
31708
31709 @ @<Initialize table entries...@>=
31710 text(frozen_protection):="inaccessible";
31711 @.inaccessible@>
31712
31713 @ Here's an example of the way many of the following routines operate.
31714 (Unfortunately, they aren't all as simple as this.)
31715
31716 @<Assignments@>=
31717 set_font: define(cur_font_loc,data,cur_chr);
31718
31719 @ When a |def| command has been scanned,
31720 |cur_chr| is odd if the definition is supposed to be global, and
31721 |cur_chr>=2| if the definition is supposed to be expanded.
31722
31723 @<Assignments@>=
31724 def: begin if odd(cur_chr)and not global and(global_defs>=0) then a:=a+4;
31725 e:=(cur_chr>=2); get_r_token; p:=cur_cs;
31726 q:=scan_toks(true,e);
31727 if j<>0 then
31728 begin q:=get_avail; info(q):=j; link(q):=link(def_ref);
31729 link(def_ref):=q;
31730 end;
31731 define(p,call+(a mod 4),def_ref);
31732 end;
31733
31734 @ Both \.{\\let} and \.{\\futurelet} share the command code |let|.
31735
31736 @<Put each...@>=
31737 primitive("let",let,normal);@/
31738 @!@:let_}{\.{\\let} primitive@>
31739 primitive("futurelet",let,normal+1);@/
31740 @!@:future_let_}{\.{\\futurelet} primitive@>
31741
31742 @ @<Cases of |print_cmd_chr|...@>=
31743 let: if chr_code<>normal then print_esc("futurelet")@+else print_esc("let");
31744
31745 @ @<Assignments@>=
31746 let: begin n:=cur_chr;
31747 get_r_token; p:=cur_cs;
31748 if n=normal then
31749 begin repeat get_token;
31750 until cur_cmd<>spacer;
31751 if cur_tok=other_token+"=" then
31752 begin get_token;
31753 if cur_cmd=spacer then get_token;
31754 end;
31755 end
31756 else begin get_token; q:=cur_tok; get_token; back_input;
31757 cur_tok:=q; back_input; {look ahead, then back up}
31758 end; {note that |back_input| doesn't affect |cur_cmd|, |cur_chr|}
31759 if cur_cmd>=call then add_token_ref(cur_chr)
31760 else if (cur_cmd=register)or(cur_cmd=toks_register) then
31761 if (cur_chr<mem_bot)or(cur_chr>lo_mem_stat_max) then
31762 add_sa_ref(cur_chr);
31763 define(p,cur_cmd,cur_chr);
31764 end;
31765
31766 @ A \.{\\chardef} creates a control sequence whose |cmd| is |char_given|;
31767 a \.{\\mathchardef} creates a control sequence whose |cmd| is |math_given|;
31768 and the corresponding |chr| is the character code or math code. A \.{\\countdef}
31769 or \.{\\dimendef} or \.{\\skipdef} or \.{\\muskipdef} creates a control
31770 sequence whose |cmd| is |assign_int| or \dots\ or |assign_mu_glue|, and the
31771 corresponding |chr| is the |eqtb| location of the internal register in question.
31772
31773 @d char_def_code=0 {|shorthand_def| for \.{\\chardef}}
31774 @d math_char_def_code=1 {|shorthand_def| for \.{\\mathchardef}}
31775 @d count_def_code=2 {|shorthand_def| for \.{\\countdef}}
31776 @d dimen_def_code=3 {|shorthand_def| for \.{\\dimendef}}
31777 @d skip_def_code=4 {|shorthand_def| for \.{\\skipdef}}
31778 @d mu_skip_def_code=5 {|shorthand_def| for \.{\\muskipdef}}
31779 @d toks_def_code=6 {|shorthand_def| for \.{\\toksdef}}
31780
31781 @<Put each...@>=
31782 primitive("chardef",shorthand_def,char_def_code);@/
31783 @!@:char_def_}{\.{\\chardef} primitive@>
31784 primitive("mathchardef",shorthand_def,math_char_def_code);@/
31785 @!@:math_char_def_}{\.{\\mathchardef} primitive@>
31786 primitive("countdef",shorthand_def,count_def_code);@/
31787 @!@:count_def_}{\.{\\countdef} primitive@>
31788 primitive("dimendef",shorthand_def,dimen_def_code);@/
31789 @!@:dimen_def_}{\.{\\dimendef} primitive@>
31790 primitive("skipdef",shorthand_def,skip_def_code);@/
31791 @!@:skip_def_}{\.{\\skipdef} primitive@>
31792 primitive("muskipdef",shorthand_def,mu_skip_def_code);@/
31793 @!@:mu_skip_def_}{\.{\\muskipdef} primitive@>
31794 primitive("toksdef",shorthand_def,toks_def_code);@/
31795 @!@:toks_def_}{\.{\\toksdef} primitive@>
31796
31797 @ @<Cases of |print_cmd_chr|...@>=
31798 shorthand_def: case chr_code of
31799 char_def_code: print_esc("chardef");
31800 math_char_def_code: print_esc("mathchardef");
31801 count_def_code: print_esc("countdef");
31802 dimen_def_code: print_esc("dimendef");
31803 skip_def_code: print_esc("skipdef");
31804 mu_skip_def_code: print_esc("muskipdef");
31805 othercases print_esc("toksdef")
31806 endcases;
31807 char_given: begin print_esc("char"); print_hex(chr_code);
31808 end;
31809 math_given: begin print_esc("mathchar"); print_hex(chr_code);
31810 end;
31811
31812 @ We temporarily define |p| to be |relax|, so that an occurrence of |p|
31813 while scanning the definition will simply stop the scanning instead of
31814 producing an ``undefined control sequence'' error or expanding the
31815 previous meaning. This allows, for instance, `\.{\\chardef\\foo=123\\foo}'.
31816
31817 @<Assignments@>=
31818 shorthand_def: begin n:=cur_chr; get_r_token; p:=cur_cs; define(p,relax,256);
31819 scan_optional_equals;
31820 case n of
31821 char_def_code: begin scan_char_num; define(p,char_given,cur_val);
31822 end;
31823 math_char_def_code: begin scan_fifteen_bit_int; define(p,math_given,cur_val);
31824 end;
31825 othercases begin scan_register_num;
31826 if cur_val>255 then
31827 begin j:=n-count_def_code; {|int_val..box_val|}
31828 if j>mu_val then j:=tok_val; {|int_val..mu_val| or |tok_val|}
31829 find_sa_element(j,cur_val,true); add_sa_ref(cur_ptr);
31830 if j=tok_val then j:=toks_register@+else j:=register;
31831 define(p,j,cur_ptr);
31832 end
31833 else
31834 case n of
31835 count_def_code: define(p,assign_int,count_base+cur_val);
31836 dimen_def_code: define(p,assign_dimen,scaled_base+cur_val);
31837 skip_def_code: define(p,assign_glue,skip_base+cur_val);
31838 mu_skip_def_code: define(p,assign_mu_glue,mu_skip_base+cur_val);
31839 toks_def_code: define(p,assign_toks,toks_base+cur_val);
31840 end; {there are no other cases}
31841 end
31842 endcases;
31843 end;
31844
31845 @ @<Assignments@>=
31846 read_to_cs: begin j:=cur_chr; scan_int; n:=cur_val;
31847 if not scan_keyword("to") then
31848 @.to@>
31849 begin print_err("Missing `to' inserted");
31850 @.Missing `to'...@>
31851 help2("You should have said `\read<number> to \cs'.")@/
31852 ("I'm going to look for the \cs now."); error;
31853 end;
31854 get_r_token;
31855 p:=cur_cs; read_toks(n,p,j); define(p,call,cur_val);
31856 end;
31857
31858 @ The token-list parameters, \.{\\output} and \.{\\everypar}, etc., receive
31859 their values in the following way. (For safety's sake, we place an
31860 enclosing pair of braces around an \.{\\output} list.)
31861
31862 @<Assignments@>=
31863 toks_register,assign_toks: begin q:=cur_cs;
31864 e:=false; {just in case, will be set |true| for sparse array elements}
31865 if cur_cmd=toks_register then
31866 if cur_chr=mem_bot then
31867 begin scan_register_num;
31868 if cur_val>255 then
31869 begin find_sa_element(tok_val,cur_val,true);
31870 cur_chr:=cur_ptr; e:=true;
31871 end
31872 else cur_chr:=toks_base+cur_val;
31873 end
31874 else e:=true;
31875 p:=cur_chr; {|p=every_par_loc| or |output_routine_loc| or \dots}
31876 scan_optional_equals;
31877 @<Get the next non-blank non-relax non-call token@>;
31878 if cur_cmd<>left_brace then @<If the right-hand side is a token parameter
31879 or token register, finish the assignment and |goto done|@>;
31880 back_input; cur_cs:=q; q:=scan_toks(false,false);
31881 if link(def_ref)=null then {empty list: revert to the default}
31882 begin sa_define(p,null)(p,undefined_cs,null); free_avail(def_ref);
31883 end
31884 else begin if (p=output_routine_loc)and not e then {enclose in curlies}
31885 begin link(q):=get_avail; q:=link(q);
31886 info(q):=right_brace_token+"}";
31887 q:=get_avail; info(q):=left_brace_token+"{";
31888 link(q):=link(def_ref); link(def_ref):=q;
31889 end;
31890 sa_define(p,def_ref)(p,call,def_ref);
31891 end;
31892 end;
31893
31894 @ @<If the right-hand side is a token parameter...@>=
31895 if (cur_cmd=toks_register)or(cur_cmd=assign_toks) then
31896 begin if cur_cmd=toks_register then
31897 if cur_chr=mem_bot then
31898 begin scan_register_num;
31899 if cur_val<256 then q:=equiv(toks_base+cur_val)
31900 else begin find_sa_element(tok_val,cur_val,false);
31901 if cur_ptr=null then q:=null
31902 else q:=sa_ptr(cur_ptr);
31903 end;
31904 end
31905 else q:=sa_ptr(cur_chr)
31906 else q:=equiv(cur_chr);
31907 if q=null then sa_define(p,null)(p,undefined_cs,null)
31908 else begin add_token_ref(q); sa_define(p,q)(p,call,q);
31909 end;
31910 goto done;
31911 end
31912
31913 @ Similar routines are used to assign values to the numeric parameters.
31914
31915 @<Assignments@>=
31916 assign_int: begin p:=cur_chr; scan_optional_equals; scan_int;
31917 word_define(p,cur_val);
31918 end;
31919 assign_dimen: begin p:=cur_chr; scan_optional_equals;
31920 scan_normal_dimen; word_define(p,cur_val);
31921 end;
31922 assign_glue,assign_mu_glue: begin p:=cur_chr; n:=cur_cmd; scan_optional_equals;
31923 if n=assign_mu_glue then scan_glue(mu_val)@+else scan_glue(glue_val);
31924 trap_zero_glue;
31925 define(p,glue_ref,cur_val);
31926 end;
31927
31928 @ When a glue register or parameter becomes zero, it will always point to
31929 |zero_glue| because of the following procedure. (Exception: The tabskip
31930 glue isn't trapped while preambles are being scanned.)
31931
31932 @<Declare subprocedures for |prefixed_command|@>=
31933 procedure trap_zero_glue;
31934 begin if (width(cur_val)=0)and(stretch(cur_val)=0)and(shrink(cur_val)=0) then
31935 begin add_glue_ref(zero_glue);
31936 delete_glue_ref(cur_val); cur_val:=zero_glue;
31937 end;
31938 end;
31939
31940 @ The various character code tables are changed by the |def_code| commands,
31941 and the font families are declared by |def_family|.
31942
31943 @<Put each...@>=
31944 primitive("catcode",def_code,cat_code_base);
31945 @!@:cat_code_}{\.{\\catcode} primitive@>
31946 primitive("mathcode",def_code,math_code_base);
31947 @!@:math_code_}{\.{\\mathcode} primitive@>
31948 primitive("lccode",def_code,lc_code_base);
31949 @!@:lc_code_}{\.{\\lccode} primitive@>
31950 primitive("uccode",def_code,uc_code_base);
31951 @!@:uc_code_}{\.{\\uccode} primitive@>
31952 primitive("sfcode",def_code,sf_code_base);
31953 @!@:sf_code_}{\.{\\sfcode} primitive@>
31954 primitive("delcode",def_code,del_code_base);
31955 @!@:del_code_}{\.{\\delcode} primitive@>
31956 primitive("textfont",def_family,math_font_base);
31957 @!@:text_font_}{\.{\\textfont} primitive@>
31958 primitive("scriptfont",def_family,math_font_base+script_size);
31959 @!@:script_font_}{\.{\\scriptfont} primitive@>
31960 primitive("scriptscriptfont",def_family,math_font_base+script_script_size);
31961 @!@:script_script_font_}{\.{\\scriptscriptfont} primitive@>
31962
31963 @ @<Cases of |print_cmd_chr|...@>=
31964 def_code: if chr_code=cat_code_base then print_esc("catcode")
31965 else if chr_code=math_code_base then print_esc("mathcode")
31966 else if chr_code=lc_code_base then print_esc("lccode")
31967 else if chr_code=uc_code_base then print_esc("uccode")
31968 else if chr_code=sf_code_base then print_esc("sfcode")
31969 else print_esc("delcode");
31970 def_family: print_size(chr_code-math_font_base);
31971
31972 @ The different types of code values have different legal ranges; the
31973 following program is careful to check each case properly.
31974
31975 @<Assignments@>=
31976 def_code: begin @<Let |n| be the largest legal code value, based on |cur_chr|@>;
31977 p:=cur_chr; scan_char_num; p:=p+cur_val; scan_optional_equals;
31978 scan_int;
31979 if ((cur_val<0)and(p<del_code_base))or(cur_val>n) then
31980 begin print_err("Invalid code ("); print_int(cur_val);
31981 @.Invalid code@>
31982 if p<del_code_base then print("), should be in the range 0..")
31983 else print("), should be at most ");
31984 print_int(n);
31985 help1("I'm going to use 0 instead of that illegal code value.");@/
31986 error; cur_val:=0;
31987 end;
31988 if p<math_code_base then define(p,data,cur_val)
31989 else if p<del_code_base then define(p,data,hi(cur_val))
31990 else word_define(p,cur_val);
31991 end;
31992
31993 @ @<Let |n| be the largest...@>=
31994 if cur_chr=cat_code_base then n:=max_char_code
31995 else if cur_chr=math_code_base then n:=@'100000
31996 else if cur_chr=sf_code_base then n:=@'77777
31997 else if cur_chr=del_code_base then n:=@'77777777
31998 else n:=255
31999
32000 @ @<Assignments@>=
32001 def_family: begin p:=cur_chr; scan_four_bit_int; p:=p+cur_val;
32002 scan_optional_equals; scan_font_ident; define(p,data,cur_val);
32003 end;
32004
32005 @ Next we consider changes to \TeX's numeric registers.
32006
32007 @<Assignments@>=
32008 register,advance,multiply,divide: do_register_command(a);
32009
32010 @ We use the fact that |register<advance<multiply<divide|.
32011
32012 @<Declare subprocedures for |prefixed_command|@>=
32013 procedure do_register_command(@!a:small_number);
32014 label found,exit;
32015 var l,@!q,@!r,@!s:pointer; {for list manipulation}
32016 @!p:int_val..mu_val; {type of register involved}
32017 @!e:boolean; {does |l| refer to a sparse array element?}
32018 @!w:integer; {integer or dimen value of |l|}
32019 begin q:=cur_cmd;
32020 e:=false; {just in case, will be set |true| for sparse array elements}
32021 @<Compute the register location |l| and its type |p|; but |return| if invalid@>;
32022 if q=register then scan_optional_equals
32023 else if scan_keyword("by") then do_nothing; {optional `\.{by}'}
32024 @.by@>
32025 arith_error:=false;
32026 if q<multiply then @<Compute result of |register| or
32027 |advance|, put it in |cur_val|@>
32028 else @<Compute result of |multiply| or |divide|, put it in |cur_val|@>;
32029 if arith_error then
32030 begin print_err("Arithmetic overflow");
32031 @.Arithmetic overflow@>
32032 help2("I can't carry out that multiplication or division,")@/
32033 ("since the result is out of range.");
32034 if p>=glue_val then delete_glue_ref(cur_val);
32035 error; return;
32036 end;
32037 if p<glue_val then sa_word_define(l,cur_val)
32038 else begin trap_zero_glue; sa_define(l,cur_val)(l,glue_ref,cur_val);
32039 end;
32040 exit: end;
32041
32042 @ Here we use the fact that the consecutive codes |int_val..mu_val| and
32043 |assign_int..assign_mu_glue| correspond to each other nicely.
32044
32045 @<Compute the register location |l| and its type |p|...@>=
32046 begin if q<>register then
32047 begin get_x_token;
32048 if (cur_cmd>=assign_int)and(cur_cmd<=assign_mu_glue) then
32049 begin l:=cur_chr; p:=cur_cmd-assign_int; goto found;
32050 end;
32051 if cur_cmd<>register then
32052 begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
32053 @.You can't use x after ...@>
32054 print("' after "); print_cmd_chr(q,0);
32055 help1("I'm forgetting what you said and not changing anything.");
32056 error; return;
32057 end;
32058 end;
32059 if (cur_chr<mem_bot)or(cur_chr>lo_mem_stat_max) then
32060 begin l:=cur_chr; p:=sa_type(l); e:=true;
32061 end
32062 else begin p:=cur_chr-mem_bot; scan_register_num;
32063 if cur_val>255 then
32064 begin find_sa_element(p,cur_val,true); l:=cur_ptr; e:=true;
32065 end
32066 else
32067 case p of
32068 int_val: l:=cur_val+count_base;
32069 dimen_val: l:=cur_val+scaled_base;
32070 glue_val: l:=cur_val+skip_base;
32071 mu_val: l:=cur_val+mu_skip_base;
32072 end; {there are no other cases}
32073 end;
32074 end;
32075 found: if p<glue_val then@+if e then w:=sa_int(l)@+else w:=eqtb[l].int
32076 else if e then s:=sa_ptr(l)@+else s:=equiv(l)
32077
32078 @ @<Compute result of |register| or |advance|...@>=
32079 if p<glue_val then
32080 begin if p=int_val then scan_int@+else scan_normal_dimen;
32081 if q=advance then cur_val:=cur_val+w;
32082 end
32083 else begin scan_glue(p);
32084 if q=advance then @<Compute the sum of two glue specs@>;
32085 end
32086
32087 @ @<Compute the sum of two glue specs@>=
32088 begin q:=new_spec(cur_val); r:=s;
32089 delete_glue_ref(cur_val);
32090 width(q):=width(q)+width(r);
32091 if stretch(q)=0 then stretch_order(q):=normal;
32092 if stretch_order(q)=stretch_order(r) then stretch(q):=stretch(q)+stretch(r)
32093 else if (stretch_order(q)<stretch_order(r))and(stretch(r)<>0) then
32094 begin stretch(q):=stretch(r); stretch_order(q):=stretch_order(r);
32095 end;
32096 if shrink(q)=0 then shrink_order(q):=normal;
32097 if shrink_order(q)=shrink_order(r) then shrink(q):=shrink(q)+shrink(r)
32098 else if (shrink_order(q)<shrink_order(r))and(shrink(r)<>0) then
32099 begin shrink(q):=shrink(r); shrink_order(q):=shrink_order(r);
32100 end;
32101 cur_val:=q;
32102 end
32103
32104 @ @<Compute result of |multiply| or |divide|...@>=
32105 begin scan_int;
32106 if p<glue_val then
32107 if q=multiply then
32108 if p=int_val then cur_val:=mult_integers(w,cur_val)
32109 else cur_val:=nx_plus_y(w,cur_val,0)
32110 else cur_val:=x_over_n(w,cur_val)
32111 else begin r:=new_spec(s);
32112 if q=multiply then
32113 begin width(r):=nx_plus_y(width(s),cur_val,0);
32114 stretch(r):=nx_plus_y(stretch(s),cur_val,0);
32115 shrink(r):=nx_plus_y(shrink(s),cur_val,0);
32116 end
32117 else begin width(r):=x_over_n(width(s),cur_val);
32118 stretch(r):=x_over_n(stretch(s),cur_val);
32119 shrink(r):=x_over_n(shrink(s),cur_val);
32120 end;
32121 cur_val:=r;
32122 end;
32123 end
32124
32125 @ The processing of boxes is somewhat different, because we may need
32126 to scan and create an entire box before we actually change the value of the old
32127 one.
32128
32129 @<Assignments@>=
32130 set_box: begin scan_register_num;
32131 if global then n:=global_box_flag+cur_val@+else n:=box_flag+cur_val;
32132 scan_optional_equals;
32133 if set_box_allowed then scan_box(n)
32134 else begin print_err("Improper "); print_esc("setbox");
32135 @.Improper \\setbox@>
32136 help2("Sorry, \setbox is not allowed after \halign in a display,")@/
32137 ("or between \accent and an accented character."); error;
32138 end;
32139 end;
32140
32141 @ The |space_factor| or |prev_depth| settings are changed when a |set_aux|
32142 command is sensed. Similarly, |prev_graf| is changed in the presence of
32143 |set_prev_graf|, and |dead_cycles| or |insert_penalties| in the presence of
32144 |set_page_int|. These definitions are always global.
32145
32146 When some dimension of a box register is changed, the change isn't exactly
32147 global; but \TeX\ does not look at the \.{\\global} switch.
32148
32149 @<Assignments@>=
32150 set_aux:alter_aux;
32151 set_prev_graf:alter_prev_graf;
32152 set_page_dimen:alter_page_so_far;
32153 set_page_int:alter_integer;
32154 set_box_dimen:alter_box_dimen;
32155
32156 @ @<Declare subprocedures for |prefixed_command|@>=
32157 procedure alter_aux;
32158 var c:halfword; {|hmode| or |vmode|}
32159 begin if cur_chr<>abs(mode) then report_illegal_case
32160 else begin c:=cur_chr; scan_optional_equals;
32161 if c=vmode then
32162 begin scan_normal_dimen; prev_depth:=cur_val;
32163 end
32164 else begin scan_int;
32165 if (cur_val<=0)or(cur_val>32767) then
32166 begin print_err("Bad space factor");
32167 @.Bad space factor@>
32168 help1("I allow only values in the range 1..32767 here.");
32169 int_error(cur_val);
32170 end
32171 else space_factor:=cur_val;
32172 end;
32173 end;
32174 end;
32175
32176 @ @<Declare subprocedures for |prefixed_command|@>=
32177 procedure alter_prev_graf;
32178 var p:0..nest_size; {index into |nest|}
32179 begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
32180 while abs(nest[p].mode_field)<>vmode do decr(p);
32181 scan_optional_equals; scan_int;
32182 if cur_val<0 then
32183 begin print_err("Bad "); print_esc("prevgraf");
32184 @.Bad \\prevgraf@>
32185 help1("I allow only nonnegative values here.");
32186 int_error(cur_val);
32187 end
32188 else begin nest[p].pg_field:=cur_val; cur_list:=nest[nest_ptr];
32189 end;
32190 end;
32191
32192 @ @<Declare subprocedures for |prefixed_command|@>=
32193 procedure alter_page_so_far;
32194 var c:0..7; {index into |page_so_far|}
32195 begin c:=cur_chr; scan_optional_equals; scan_normal_dimen;
32196 page_so_far[c]:=cur_val;
32197 end;
32198
32199 @ @<Declare subprocedures for |prefixed_command|@>=
32200 procedure alter_integer;
32201 var c:small_number;
32202 {0 for \.{\\deadcycles}, 1 for \.{\\insertpenalties}, etc.}
32203 begin c:=cur_chr; scan_optional_equals; scan_int;
32204 if c=0 then dead_cycles:=cur_val
32205 @/@<Cases for |alter_integer|@>@/
32206 else insert_penalties:=cur_val;
32207 end;
32208
32209 @ @<Declare subprocedures for |prefixed_command|@>=
32210 procedure alter_box_dimen;
32211 var c:small_number; {|width_offset| or |height_offset| or |depth_offset|}
32212 @!b:pointer; {box register}
32213 begin c:=cur_chr; scan_register_num; fetch_box(b); scan_optional_equals;
32214 scan_normal_dimen;
32215 if b<>null then mem[b+c].sc:=cur_val;
32216 end;
32217
32218 @ Paragraph shapes are set up in the obvious way.
32219
32220 @<Assignments@>=
32221 set_shape: begin q:=cur_chr; scan_optional_equals; scan_int; n:=cur_val;
32222 if n<=0 then p:=null
32223 else if q>par_shape_loc then
32224 begin n:=(cur_val div 2)+1; p:=get_node(2*n+1); info(p):=n;
32225 n:=cur_val; mem[p+1].int:=n; {number of penalties}
32226 for j:=p+2 to p+n+1 do
32227 begin scan_int; mem[j].int:=cur_val; {penalty values}
32228 end;
32229 if not odd(n) then mem[p+n+2].int:=0; {unused}
32230 end
32231 else begin p:=get_node(2*n+1); info(p):=n;
32232 for j:=1 to n do
32233 begin scan_normal_dimen;
32234 mem[p+2*j-1].sc:=cur_val; {indentation}
32235 scan_normal_dimen;
32236 mem[p+2*j].sc:=cur_val; {width}
32237 end;
32238 end;
32239 define(q,shape_ref,p);
32240 end;
32241
32242 @ Here's something that isn't quite so obvious. It guarantees that
32243 |info(par_shape_ptr)| can hold any positive~|n| for which |get_node(2*n+1)|
32244 doesn't overflow the memory capacity.
32245
32246 @<Check the ``constant''...@>=
32247 if 2*max_halfword<mem_top-mem_min then bad:=41;
32248
32249 @ New hyphenation data is loaded by the |hyph_data| command.
32250
32251 @<Put each...@>=
32252 primitive("hyphenation",hyph_data,0);
32253 @!@:hyphenation_}{\.{\\hyphenation} primitive@>
32254 primitive("patterns",hyph_data,1);
32255 @!@:patterns_}{\.{\\patterns} primitive@>
32256
32257 @ @<Cases of |print_cmd_chr|...@>=
32258 hyph_data: if chr_code=1 then print_esc("patterns")
32259 else print_esc("hyphenation");
32260
32261 @ @<Assignments@>=
32262 hyph_data: if cur_chr=1 then
32263 begin @!init new_patterns; goto done;@;@+tini@/
32264 print_err("Patterns can be loaded only by INITEX");
32265 @.Patterns can be...@>
32266 help0; error;
32267 repeat get_token; until cur_cmd=right_brace; {flush the patterns}
32268 return;
32269 end
32270 else begin new_hyph_exceptions; goto done;
32271 end;
32272
32273 @ All of \TeX's parameters are kept in |eqtb| except the font information,
32274 the interaction mode, and the hyphenation tables; these are strictly global.
32275
32276 @<Assignments@>=
32277 assign_font_dimen: begin find_font_dimen(true); k:=cur_val;
32278 scan_optional_equals; scan_normal_dimen; font_info[k].sc:=cur_val;
32279 end;
32280 assign_font_int: begin n:=cur_chr; scan_font_ident; f:=cur_val;
32281 if n = no_lig_code then set_no_ligatures(f)
32282 else if n < lp_code_base then begin
32283 scan_optional_equals; scan_int;
32284 if n=0 then hyphen_char[f]:=cur_val@+else skew_char[f]:=cur_val;
32285 end
32286 else begin
32287 scan_char_num; p := cur_val;
32288 scan_optional_equals; scan_int;
32289 case n of
32290 lp_code_base: set_lp_code(f, p, cur_val);
32291 rp_code_base: set_rp_code(f, p, cur_val);
32292 ef_code_base: set_ef_code(f, p, cur_val);
32293 tag_code: set_tag_code(f, p, cur_val);
32294 kn_bs_code_base: set_kn_bs_code(f, p, cur_val);
32295 st_bs_code_base: set_st_bs_code(f, p, cur_val);
32296 sh_bs_code_base: set_sh_bs_code(f, p, cur_val);
32297 kn_bc_code_base: set_kn_bc_code(f, p, cur_val);
32298 kn_ac_code_base: set_kn_ac_code(f, p, cur_val);
32299 end;
32300 end;
32301 end;
32302
32303 @ @<Put each...@>=
32304 primitive("hyphenchar",assign_font_int,0);
32305 @!@:hyphen_char_}{\.{\\hyphenchar} primitive@>
32306 primitive("skewchar",assign_font_int,1);
32307 @!@:skew_char_}{\.{\\skewchar} primitive@>
32308 primitive("lpcode",assign_font_int,lp_code_base);
32309 @!@:lp_code_}{\.{\\lpcode} primitive@>
32310 primitive("rpcode",assign_font_int,rp_code_base);
32311 @!@:rp_code_}{\.{\\rpcode} primitive@>
32312 primitive("efcode",assign_font_int,ef_code_base);
32313 @!@:ef_code_}{\.{\\efcode} primitive@>
32314 primitive("tagcode",assign_font_int,tag_code);
32315 @!@:tag_code_}{\.{\\tagcode} primitive@>
32316 primitive("knbscode",assign_font_int,kn_bs_code_base);
32317 @!@:kn_bs_code_}{\.{\\knbscode} primitive@>
32318 primitive("stbscode",assign_font_int,st_bs_code_base);
32319 @!@:st_bs_code_}{\.{\\stbscode} primitive@>
32320 primitive("shbscode",assign_font_int,sh_bs_code_base);
32321 @!@:sh_bs_code_}{\.{\\shbscode} primitive@>
32322 primitive("knbccode",assign_font_int,kn_bc_code_base);
32323 @!@:kn_bc_code_}{\.{\\knbccode} primitive@>
32324 primitive("knaccode",assign_font_int,kn_ac_code_base);
32325 @!@:kn_ac_code_}{\.{\\knaccode} primitive@>
32326 primitive("pdfnoligatures",assign_font_int,no_lig_code);
32327 @!@:no_lig_code_}{\.{\\pdfnoligatures} primitive@>
32328
32329 @ @<Cases of |print_cmd_chr|...@>=
32330 assign_font_int: case chr_code of
32331 0: print_esc("hyphenchar");
32332 1: print_esc("skewchar");
32333 lp_code_base: print_esc("lpcode");
32334 rp_code_base: print_esc("rpcode");
32335 ef_code_base: print_esc("efcode");
32336 tag_code: print_esc("tagcode");
32337 kn_bs_code_base: print_esc("knbscode");
32338 st_bs_code_base: print_esc("stbscode");
32339 sh_bs_code_base: print_esc("shbscode");
32340 kn_bc_code_base: print_esc("knbccode");
32341 kn_ac_code_base: print_esc("knaccode");
32342 no_lig_code: print_esc("pdfnoligatures");
32343 endcases;
32344
32345 @ Here is where the information for a new font gets loaded.
32346
32347 @<Assignments@>=
32348 def_font: new_font(a);
32349 letterspace_font: new_letterspaced_font(a);
32350 pdf_copy_font: make_font_copy(a);
32351
32352 @ @<Declare subprocedures for |prefixed_command|@>=
32353 procedure new_font(@!a:small_number);
32354 label common_ending;
32355 var u:pointer; {user's font identifier}
32356 @!s:scaled; {stated ``at'' size, or negative of scaled magnification}
32357 @!f:internal_font_number; {runs through existing fonts}
32358 @!t:str_number; {name for the frozen font identifier}
32359 @!old_setting:0..max_selector; {holds |selector| setting}
32360 @!flushable_string:str_number; {string not yet referenced}
32361 begin if job_name=0 then open_log_file;
32362 {avoid confusing \.{texput} with the font name}
32363 @.texput@>
32364 get_r_token; u:=cur_cs;
32365 if u>=hash_base then t:=text(u)
32366 else if u>=single_base then
32367 if u=null_cs then t:="FONT"@+else t:=u-single_base
32368 else begin old_setting:=selector; selector:=new_string;
32369 print("FONT"); print(u-active_base); selector:=old_setting;
32370 @.FONTx@>
32371 str_room(1); t:=make_string;
32372 end;
32373 define(u,set_font,null_font); scan_optional_equals; scan_file_name;
32374 @<Scan the font size specification@>;
32375 @<If this font has already been loaded, set |f| to the internal
32376 font number and |goto common_ending|@>;
32377 f:=read_font_info(u,cur_name,cur_area,s);
32378 common_ending: define(u,set_font,f); eqtb[font_id_base+f]:=eqtb[u]; font_id_text(f):=t;
32379 end;
32380
32381 @ @<Scan the font size specification@>=
32382 name_in_progress:=true; {this keeps |cur_name| from being changed}
32383 if scan_keyword("at") then @<Put the \(p)(positive) `at' size into |s|@>
32384 @.at@>
32385 else if scan_keyword("scaled") then
32386 @.scaled@>
32387 begin scan_int; s:=-cur_val;
32388 if (cur_val<=0)or(cur_val>32768) then
32389 begin print_err("Illegal magnification has been changed to 1000");@/
32390 @.Illegal magnification...@>
32391 help1("The magnification ratio must be between 1 and 32768.");
32392 int_error(cur_val); s:=-1000;
32393 end;
32394 end
32395 else s:=-1000;
32396 name_in_progress:=false
32397
32398 @ @<Put the \(p)(positive) `at' size into |s|@>=
32399 begin scan_normal_dimen; s:=cur_val;
32400 if (s<=0)or(s>=@'1000000000) then
32401 begin print_err("Improper `at' size (");
32402 print_scaled(s); print("pt), replaced by 10pt");
32403 @.Improper `at' size...@>
32404 help2("I can only handle fonts at positive sizes that are")@/
32405 ("less than 2048pt, so I've changed what you said to 10pt.");
32406 error; s:=10*unity;
32407 end;
32408 end
32409
32410 @ When the user gives a new identifier to a font that was previously loaded,
32411 the new name becomes the font identifier of record. Font names `\.{xyz}' and
32412 `\.{XYZ}' are considered to be different.
32413
32414 @<If this font has already been loaded...@>=
32415 flushable_string:=str_ptr-1;
32416 for f:=font_base+1 to font_ptr do
32417 if str_eq_str(font_name[f],cur_name)and str_eq_str(font_area[f],cur_area) then
32418 begin if cur_name=flushable_string then
32419 begin flush_string; cur_name:=font_name[f];
32420 end;
32421 if s>0 then
32422 begin if s=font_size[f] then goto common_ending;
32423 end
32424 else if font_size[f]=xn_over_d(font_dsize[f],-s,1000) then
32425 goto common_ending;
32426 end
32427
32428 @ @<Cases of |print_cmd_chr|...@>=
32429 set_font:begin print("select font "); slow_print(font_name[chr_code]);
32430 if font_size[chr_code]<>font_dsize[chr_code] then
32431 begin print(" at "); print_scaled(font_size[chr_code]);
32432 print("pt");
32433 end;
32434 end;
32435
32436 @ @<Put each...@>=
32437 primitive("batchmode",set_interaction,batch_mode);
32438 @!@:batch_mode_}{\.{\\batchmode} primitive@>
32439 primitive("nonstopmode",set_interaction,nonstop_mode);
32440 @!@:nonstop_mode_}{\.{\\nonstopmode} primitive@>
32441 primitive("scrollmode",set_interaction,scroll_mode);
32442 @!@:scroll_mode_}{\.{\\scrollmode} primitive@>
32443 primitive("errorstopmode",set_interaction,error_stop_mode);
32444 @!@:error_stop_mode_}{\.{\\errorstopmode} primitive@>
32445
32446 @ @<Cases of |print_cmd_chr|...@>=
32447 set_interaction: case chr_code of
32448 batch_mode: print_esc("batchmode");
32449 nonstop_mode: print_esc("nonstopmode");
32450 scroll_mode: print_esc("scrollmode");
32451 othercases print_esc("errorstopmode")
32452 endcases;
32453
32454 @ @<Assignments@>=
32455 set_interaction: new_interaction;
32456
32457 @ @<Declare subprocedures for |prefixed_command|@>=
32458 procedure new_interaction;
32459 begin print_ln;
32460 interaction:=cur_chr;
32461 @<Initialize the print |selector| based on |interaction|@>;
32462 if log_opened then selector:=selector+2;
32463 end;
32464
32465 @ The \.{\\afterassignment} command puts a token into the global
32466 variable |after_token|. This global variable is examined just after
32467 every assignment has been performed.
32468
32469 @<Glob...@>=
32470 @!after_token:halfword; {zero, or a saved token}
32471
32472 @ @<Set init...@>=
32473 after_token:=0;
32474
32475 @ @<Cases of |main_control| that don't...@>=
32476 any_mode(after_assignment):begin get_token; after_token:=cur_tok;
32477 end;
32478
32479 @ @<Insert a token saved by \.{\\afterassignment}, if any@>=
32480 if after_token<>0 then
32481 begin cur_tok:=after_token; back_input; after_token:=0;
32482 end
32483
32484 @ Here is a procedure that might be called `Get the next non-blank non-relax
32485 non-call non-assignment token'.
32486
32487 @<Declare act...@>=
32488 procedure do_assignments;
32489 label exit;
32490 begin loop begin @<Get the next non-blank non-relax...@>;
32491 if cur_cmd<=max_non_prefixed_command then return;
32492 set_box_allowed:=false; prefixed_command; set_box_allowed:=true;
32493 end;
32494 exit:end;
32495
32496 @ @<Cases of |main_control| that don't...@>=
32497 any_mode(after_group):begin get_token; save_for_after(cur_tok);
32498 end;
32499
32500 @ Files for \.{\\read} are opened and closed by the |in_stream| command.
32501
32502 @<Put each...@>=
32503 primitive("openin",in_stream,1);
32504 @!@:open_in_}{\.{\\openin} primitive@>
32505 primitive("closein",in_stream,0);
32506 @!@:close_in_}{\.{\\closein} primitive@>
32507
32508 @ @<Cases of |print_cmd_chr|...@>=
32509 in_stream: if chr_code=0 then print_esc("closein")
32510 else print_esc("openin");
32511
32512 @ @<Cases of |main_control| that don't...@>=
32513 any_mode(in_stream): open_or_close_in;
32514
32515 @ @<Declare act...@>=
32516 procedure open_or_close_in;
32517 var c:0..1; {1 for \.{\\openin}, 0 for \.{\\closein}}
32518 @!n:0..15; {stream number}
32519 begin c:=cur_chr; scan_four_bit_int; n:=cur_val;
32520 if read_open[n]<>closed then
32521 begin a_close(read_file[n]); read_open[n]:=closed;
32522 end;
32523 if c<>0 then
32524 begin scan_optional_equals; scan_file_name;
32525 if cur_ext="" then cur_ext:=".tex";
32526 pack_cur_name;
32527 if a_open_in(read_file[n]) then read_open[n]:=just_open;
32528 end;
32529 end;
32530
32531 @ The user can issue messages to the terminal, regardless of the
32532 current mode.
32533
32534 @<Cases of |main_control| that don't...@>=
32535 any_mode(message):issue_message;
32536
32537 @ @<Put each...@>=
32538 primitive("message",message,0);
32539 @!@:message_}{\.{\\message} primitive@>
32540 primitive("errmessage",message,1);
32541 @!@:err_message_}{\.{\\errmessage} primitive@>
32542
32543 @ @<Cases of |print_cmd_chr|...@>=
32544 message: if chr_code=0 then print_esc("message")
32545 else print_esc("errmessage");
32546
32547 @ @<Declare act...@>=
32548 procedure issue_message;
32549 var old_setting:0..max_selector; {holds |selector| setting}
32550 @!c:0..1; {identifies \.{\\message} and \.{\\errmessage}}
32551 @!s:str_number; {the message}
32552 begin c:=cur_chr; link(garbage):=scan_toks(false,true);
32553 old_setting:=selector; selector:=new_string;
32554 token_show(def_ref); selector:=old_setting;
32555 flush_list(def_ref);
32556 str_room(1); s:=make_string;
32557 if c=0 then @<Print string |s| on the terminal@>
32558 else @<Print string |s| as an error message@>;
32559 flush_string;
32560 end;
32561
32562 @ @<Print string |s| on the terminal@>=
32563 begin if term_offset+length(s)>max_print_line-2 then print_ln
32564 else if (term_offset>0)or(file_offset>0) then print_char(" ");
32565 slow_print(s); update_terminal;
32566 end
32567
32568 @ If \.{\\errmessage} occurs often in |scroll_mode|, without user-defined
32569 \.{\\errhelp}, we don't want to give a long help message each time. So we
32570 give a verbose explanation only once.
32571
32572 @<Glob...@>=
32573 @!long_help_seen:boolean; {has the long \.{\\errmessage} help been used?}
32574
32575 @ @<Set init...@>=long_help_seen:=false;
32576
32577 @ @<Print string |s| as an error message@>=
32578 begin print_err(""); slow_print(s);
32579 if err_help<>null then use_err_help:=true
32580 else if long_help_seen then help1("(That was another \errmessage.)")
32581 else begin if interaction<error_stop_mode then long_help_seen:=true;
32582 help4("This error message was generated by an \errmessage")@/
32583 ("command, so I can't give any explicit help.")@/
32584 ("Pretend that you're Hercule Poirot: Examine all clues,")@/
32585 @^Poirot, Hercule@>
32586 ("and deduce the truth by order and method.");
32587 end;
32588 error; use_err_help:=false;
32589 end
32590
32591 @ The |error| routine calls on |give_err_help| if help is requested from
32592 the |err_help| parameter.
32593
32594 @p procedure give_err_help;
32595 begin token_show(err_help);
32596 end;
32597
32598 @ The \.{\\uppercase} and \.{\\lowercase} commands are implemented by
32599 building a token list and then changing the cases of the letters in it.
32600
32601 @<Cases of |main_control| that don't...@>=
32602 any_mode(case_shift):shift_case;
32603
32604 @ @<Put each...@>=
32605 primitive("lowercase",case_shift,lc_code_base);
32606 @!@:lowercase_}{\.{\\lowercase} primitive@>
32607 primitive("uppercase",case_shift,uc_code_base);
32608 @!@:uppercase_}{\.{\\uppercase} primitive@>
32609
32610 @ @<Cases of |print_cmd_chr|...@>=
32611 case_shift:if chr_code=lc_code_base then print_esc("lowercase")
32612 else print_esc("uppercase");
32613
32614 @ @<Declare act...@>=
32615 procedure shift_case;
32616 var b:pointer; {|lc_code_base| or |uc_code_base|}
32617 @!p:pointer; {runs through the token list}
32618 @!t:halfword; {token}
32619 @!c:eight_bits; {character code}
32620 begin b:=cur_chr; p:=scan_toks(false,false); p:=link(def_ref);
32621 while p<>null do
32622 begin @<Change the case of the token in |p|, if a change is appropriate@>;
32623 p:=link(p);
32624 end;
32625 back_list(link(def_ref)); free_avail(def_ref); {omit reference count}
32626 end;
32627
32628 @ When the case of a |chr_code| changes, we don't change the |cmd|.
32629 We also change active characters, using the fact that
32630 |cs_token_flag+active_base| is a multiple of~256.
32631 @^data structure assumptions@>
32632
32633 @<Change the case of the token in |p|, if a change is appropriate@>=
32634 t:=info(p);
32635 if t<cs_token_flag+single_base then
32636 begin c:=t mod 256;
32637 if equiv(b+c)<>0 then info(p):=t-c+equiv(b+c);
32638 end
32639
32640 @ We come finally to the last pieces missing from |main_control|, namely the
32641 `\.{\\show}' commands that are useful when debugging.
32642
32643 @<Cases of |main_control| that don't...@>=
32644 any_mode(xray): show_whatever;
32645
32646 @ @d show_code=0 { \.{\\show} }
32647 @d show_box_code=1 { \.{\\showbox} }
32648 @d show_the_code=2 { \.{\\showthe} }
32649 @d show_lists_code=3 { \.{\\showlists} }
32650
32651 @<Put each...@>=
32652 primitive("show",xray,show_code);
32653 @!@:show_}{\.{\\show} primitive@>
32654 primitive("showbox",xray,show_box_code);
32655 @!@:show_box_}{\.{\\showbox} primitive@>
32656 primitive("showthe",xray,show_the_code);
32657 @!@:show_the_}{\.{\\showthe} primitive@>
32658 primitive("showlists",xray,show_lists_code);
32659 @!@:show_lists_code_}{\.{\\showlists} primitive@>
32660
32661 @ @<Cases of |print_cmd_chr|...@>=
32662 xray: case chr_code of
32663 show_box_code:print_esc("showbox");
32664 show_the_code:print_esc("showthe");
32665 show_lists_code:print_esc("showlists");
32666 @<Cases of |xray| for |print_cmd_chr|@>@;@/
32667 othercases print_esc("show")
32668 endcases;
32669
32670 @ @<Declare act...@>=
32671 procedure show_whatever;
32672 label common_ending;
32673 var p:pointer; {tail of a token list to show}
32674 @!t:small_number; {type of conditional being shown}
32675 @!m:normal..or_code; {upper bound on |fi_or_else| codes}
32676 @!l:integer; {line where that conditional began}
32677 @!n:integer; {level of \.{\\if...\\fi} nesting}
32678 begin case cur_chr of
32679 show_lists_code: begin begin_diagnostic; show_activities;
32680 end;
32681 show_box_code: @<Show the current contents of a box@>;
32682 show_code: @<Show the current meaning of a token, then |goto common_ending|@>;
32683 @<Cases for |show_whatever|@>@;@/
32684 othercases @<Show the current value of some parameter or register,
32685 then |goto common_ending|@>
32686 endcases;@/
32687 @<Complete a potentially long \.{\\show} command@>;
32688 common_ending: if interaction<error_stop_mode then
32689 begin help0; decr(error_count);
32690 end
32691 else if tracing_online>0 then
32692 begin@t@>@;@/
32693 help3("This isn't an error message; I'm just \showing something.")@/
32694 ("Type `I\show...' to show more (e.g., \show\cs,")@/
32695 ("\showthe\count10, \showbox255, \showlists).");
32696 end
32697 else begin@t@>@;@/
32698 help5("This isn't an error message; I'm just \showing something.")@/
32699 ("Type `I\show...' to show more (e.g., \show\cs,")@/
32700 ("\showthe\count10, \showbox255, \showlists).")@/
32701 ("And type `I\tracingonline=1\show...' to show boxes and")@/
32702 ("lists on your terminal as well as in the transcript file.");
32703 end;
32704 error;
32705 end;
32706
32707 @ @<Show the current meaning of a token...@>=
32708 begin get_token;
32709 if interaction=error_stop_mode then wake_up_terminal;
32710 print_nl("> ");
32711 if cur_cs<>0 then
32712 begin sprint_cs(cur_cs); print_char("=");
32713 end;
32714 print_meaning; goto common_ending;
32715 end
32716
32717 @ @<Cases of |print_cmd_chr|...@>=
32718 undefined_cs: print("undefined");
32719 call,long_call,outer_call,long_outer_call: begin n:=cmd-call;
32720 if info(link(chr_code))=protected_token then n:=n+4;
32721 if odd(n div 4) then print_esc("protected");
32722 if odd(n) then print_esc("long");
32723 if odd(n div 2) then print_esc("outer");
32724 if n>0 then print_char(" ");
32725 print("macro");
32726 end;
32727 end_template: print_esc("outer endtemplate");
32728
32729 @ @<Show the current contents of a box@>=
32730 begin scan_register_num; fetch_box(p); begin_diagnostic;
32731 print_nl("> \box"); print_int(cur_val); print_char("=");
32732 if p=null then print("void")@+else show_box(p);
32733 end
32734
32735 @ @<Show the current value of some parameter...@>=
32736 begin p:=the_toks;
32737 if interaction=error_stop_mode then wake_up_terminal;
32738 print_nl("> "); token_show(temp_head);
32739 flush_list(link(temp_head)); goto common_ending;
32740 end
32741
32742 @ @<Complete a potentially long \.{\\show} command@>=
32743 end_diagnostic(true); print_err("OK");
32744 @.OK@>
32745 if selector=term_and_log then if tracing_online<=0 then
32746 begin selector:=term_only; print(" (see the transcript file)");
32747 selector:=term_and_log;
32748 end
32749
32750 @* \[50] Dumping and undumping the tables.
32751 After \.{INITEX} has seen a collection of fonts and macros, it
32752 can write all the necessary information on an auxiliary file so
32753 that production versions of \TeX\ are able to initialize their
32754 memory at high speed. The present section of the program takes
32755 care of such output and input. We shall consider simultaneously
32756 the processes of storing and restoring,
32757 so that the inverse relation between them is clear.
32758 @.INITEX@>
32759
32760 The global variable |format_ident| is a string that is printed right
32761 after the |banner| line when \TeX\ is ready to start. For \.{INITEX} this
32762 string says simply `\.{ (INITEX)}'; for other versions of \TeX\ it says,
32763 for example, `\.{ (preloaded format=plain 1982.11.19)}', showing the year,
32764 month, and day that the format file was created. We have |format_ident=0|
32765 before \TeX's tables are loaded.
32766
32767 @<Glob...@>=
32768 @!format_ident:str_number;
32769
32770 @ @<Set init...@>=
32771 format_ident:=0;
32772
32773 @ @<Initialize table entries...@>=
32774 format_ident:=" (INITEX)";
32775
32776 @ @<Declare act...@>=
32777 @!init procedure store_fmt_file;
32778 label found1,found2,done1,done2;
32779 var j,@!k,@!l:integer; {all-purpose indices}
32780 @!p,@!q: pointer; {all-purpose pointers}
32781 @!x: integer; {something to dump}
32782 @!w: four_quarters; {four ASCII codes}
32783 begin @<If dumping is not allowed, abort@>;
32784 @<Create the |format_ident|, open the format file,
32785 and inform the user that dumping has begun@>;
32786 @<Dump constants for consistency check@>;
32787 @<Dump the string pool@>;
32788 @<Dump the dynamic memory@>;
32789 @<Dump the table of equivalents@>;
32790 @<Dump the font information@>;
32791 @<Dump the hyphenation tables@>;
32792 @<Dump pdftex data@>;
32793 @<Dump a couple more things and the closing check word@>;
32794 @<Close the format file@>;
32795 end;
32796 tini
32797
32798 @ Corresponding to the procedure that dumps a format file, we have a function
32799 that reads one in. The function returns |false| if the dumped format is
32800 incompatible with the present \TeX\ table sizes, etc.
32801
32802 @d bad_fmt=6666 {go here if the format file is unacceptable}
32803 @d too_small(#)==begin wake_up_terminal;
32804 wterm_ln('---! Must increase the ',#);
32805 @.Must increase the x@>
32806 goto bad_fmt;
32807 end
32808
32809 @p @t\4@>@<Declare the function called |open_fmt_file|@>@;
32810 function load_fmt_file:boolean;
32811 label bad_fmt,exit;
32812 var j,@!k:integer; {all-purpose indices}
32813 @!p,@!q: pointer; {all-purpose pointers}
32814 @!x: integer; {something undumped}
32815 @!w: four_quarters; {four ASCII codes}
32816 begin @<Undump constants for consistency check@>;
32817 @<Undump the string pool@>;
32818 @<Undump the dynamic memory@>;
32819 @<Undump the table of equivalents@>;
32820 @<Undump the font information@>;
32821 @<Undump the hyphenation tables@>;
32822 @<Undump pdftex data@>;
32823 @<Undump a couple more things and the closing check word@>;
32824 prev_depth := pdf_ignored_dimen;
32825 load_fmt_file:=true; return; {it worked!}
32826 bad_fmt: wake_up_terminal;
32827 wterm_ln('(Fatal format file error; I''m stymied)');
32828 @.Fatal format file error@>
32829 load_fmt_file:=false;
32830 exit:end;
32831
32832 @ The user is not allowed to dump a format file unless |save_ptr=0|.
32833 This condition implies that |cur_level=level_one|, hence
32834 the |xeq_level| array is constant and it need not be dumped.
32835
32836 @<If dumping is not allowed, abort@>=
32837 if save_ptr<>0 then
32838 begin print_err("You can't dump inside a group");
32839 @.You can't dump...@>
32840 help1("`{...\dump}' is a no-no."); succumb;
32841 end
32842
32843 @ Format files consist of |memory_word| items, and we use the following
32844 macros to dump words of different types:
32845
32846 @d dump_wd(#)==begin fmt_file^:=#; put(fmt_file);@+end
32847 @d dump_int(#)==begin fmt_file^.int:=#; put(fmt_file);@+end
32848 @d dump_hh(#)==begin fmt_file^.hh:=#; put(fmt_file);@+end
32849 @d dump_qqqq(#)==begin fmt_file^.qqqq:=#; put(fmt_file);@+end
32850
32851 @<Glob...@>=
32852 @!fmt_file:word_file; {for input or output of format information}
32853
32854 @ The inverse macros are slightly more complicated, since we need to check
32855 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
32856 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
32857 System error messages should be suppressed when undumping.
32858 @^system dependencies@>
32859
32860 @d undump_wd(#)==begin get(fmt_file); #:=fmt_file^;@+end
32861 @d undump_int(#)==begin get(fmt_file); #:=fmt_file^.int;@+end
32862 @d undump_hh(#)==begin get(fmt_file); #:=fmt_file^.hh;@+end
32863 @d undump_qqqq(#)==begin get(fmt_file); #:=fmt_file^.qqqq;@+end
32864 @d undump_end_end(#)==#:=x;@+end
32865 @d undump_end(#)==(x>#) then goto bad_fmt@+else undump_end_end
32866 @d undump(#)==begin undump_int(x); if (x<#) or undump_end
32867 @d undump_size_end_end(#)==too_small(#)@+else undump_end_end
32868 @d undump_size_end(#)==if x># then undump_size_end_end
32869 @d undump_size(#)==begin undump_int(x);
32870 if x<# then goto bad_fmt; undump_size_end
32871
32872 @ The next few sections of the program should make it clear how we use the
32873 dump/undump macros.
32874
32875 @<Dump constants for consistency check@>=
32876 dump_int(@$);@/
32877 @<Dump the \eTeX\ state@>@/
32878 dump_int(mem_bot);@/
32879 dump_int(mem_top);@/
32880 dump_int(eqtb_size);@/
32881 dump_int(hash_prime);@/
32882 dump_int(hyph_size)
32883
32884 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
32885 strings to the string pool; therefore \.{INITEX} and \TeX\ will have
32886 the same strings. (And it is, of course, a good thing that they do.)
32887 @.WEB@>
32888 @^string pool@>
32889
32890 @<Undump constants for consistency check@>=
32891 x:=fmt_file^.int;
32892 if x<>@$ then goto bad_fmt; {check that strings are the same}
32893 @/@<Undump the \eTeX\ state@>@/
32894 undump_int(x);
32895 if x<>mem_bot then goto bad_fmt;
32896 undump_int(x);
32897 if x<>mem_top then goto bad_fmt;
32898 undump_int(x);
32899 if x<>eqtb_size then goto bad_fmt;
32900 undump_int(x);
32901 if x<>hash_prime then goto bad_fmt;
32902 undump_int(x);
32903 if x<>hyph_size then goto bad_fmt
32904
32905 @ @d dump_four_ASCII==
32906 w.b0:=qi(so(str_pool[k])); w.b1:=qi(so(str_pool[k+1]));
32907 w.b2:=qi(so(str_pool[k+2])); w.b3:=qi(so(str_pool[k+3]));
32908 dump_qqqq(w)
32909
32910 @<Dump the string pool@>=
32911 dump_int(pool_ptr);
32912 dump_int(str_ptr);
32913 for k:=0 to str_ptr do dump_int(str_start[k]);
32914 k:=0;
32915 while k+4<pool_ptr do
32916 begin dump_four_ASCII; k:=k+4;
32917 end;
32918 k:=pool_ptr-4; dump_four_ASCII;
32919 print_ln; print_int(str_ptr); print(" strings of total length ");
32920 print_int(pool_ptr)
32921
32922 @ @d undump_four_ASCII==
32923 undump_qqqq(w);
32924 str_pool[k]:=si(qo(w.b0)); str_pool[k+1]:=si(qo(w.b1));
32925 str_pool[k+2]:=si(qo(w.b2)); str_pool[k+3]:=si(qo(w.b3))
32926
32927 @<Undump the string pool@>=
32928 undump_size(0)(pool_size)('string pool size')(pool_ptr);
32929 undump_size(0)(max_strings)('max strings')(str_ptr);
32930 for k:=0 to str_ptr do undump(0)(pool_ptr)(str_start[k]);
32931 k:=0;
32932 while k+4<pool_ptr do
32933 begin undump_four_ASCII; k:=k+4;
32934 end;
32935 k:=pool_ptr-4; undump_four_ASCII;
32936 init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr
32937
32938 @ By sorting the list of available spaces in the variable-size portion of
32939 |mem|, we are usually able to get by without having to dump very much
32940 of the dynamic memory.
32941
32942 We recompute |var_used| and |dyn_used|, so that \.{INITEX} dumps valid
32943 information even when it has not been gathering statistics.
32944
32945 @<Dump the dynamic memory@>=
32946 sort_avail; var_used:=0;
32947 dump_int(lo_mem_max); dump_int(rover);
32948 if eTeX_ex then for k:=int_val to tok_val do dump_int(sa_root[k]);
32949 p:=mem_bot; q:=rover; x:=0;
32950 repeat for k:=p to q+1 do dump_wd(mem[k]);
32951 x:=x+q+2-p; var_used:=var_used+q-p;
32952 p:=q+node_size(q); q:=rlink(q);
32953 until q=rover;
32954 var_used:=var_used+lo_mem_max-p; dyn_used:=mem_end+1-hi_mem_min;@/
32955 for k:=p to lo_mem_max do dump_wd(mem[k]);
32956 x:=x+lo_mem_max+1-p;
32957 dump_int(hi_mem_min); dump_int(avail);
32958 for k:=hi_mem_min to mem_end do dump_wd(mem[k]);
32959 x:=x+mem_end+1-hi_mem_min;
32960 p:=avail;
32961 while p<>null do
32962 begin decr(dyn_used); p:=link(p);
32963 end;
32964 dump_int(var_used); dump_int(dyn_used);
32965 print_ln; print_int(x);
32966 print(" memory locations dumped; current usage is ");
32967 print_int(var_used); print_char("&"); print_int(dyn_used)
32968
32969 @ @<Undump the dynamic memory@>=
32970 undump(lo_mem_stat_max+1000)(hi_mem_stat_min-1)(lo_mem_max);
32971 undump(lo_mem_stat_max+1)(lo_mem_max)(rover);
32972 if eTeX_ex then for k:=int_val to tok_val do
32973 undump(null)(lo_mem_max)(sa_root[k]);
32974 p:=mem_bot; q:=rover;
32975 repeat for k:=p to q+1 do undump_wd(mem[k]);
32976 p:=q+node_size(q);
32977 if (p>lo_mem_max)or((q>=rlink(q))and(rlink(q)<>rover)) then goto bad_fmt;
32978 q:=rlink(q);
32979 until q=rover;
32980 for k:=p to lo_mem_max do undump_wd(mem[k]);
32981 if mem_min<mem_bot-2 then {make more low memory available}
32982 begin p:=llink(rover); q:=mem_min+1;
32983 link(mem_min):=null; info(mem_min):=null; {we don't use the bottom word}
32984 rlink(p):=q; llink(rover):=q;@/
32985 rlink(q):=rover; llink(q):=p; link(q):=empty_flag;
32986 node_size(q):=mem_bot-q;
32987 end;
32988 undump(lo_mem_max+1)(hi_mem_stat_min)(hi_mem_min);
32989 undump(null)(mem_top)(avail); mem_end:=mem_top;
32990 for k:=hi_mem_min to mem_end do undump_wd(mem[k]);
32991 undump_int(var_used); undump_int(dyn_used)
32992
32993 @ @<Dump the table of equivalents@>=
32994 @<Dump regions 1 to 4 of |eqtb|@>;
32995 @<Dump regions 5 and 6 of |eqtb|@>;
32996 dump_int(par_loc); dump_int(write_loc);@/
32997 @<Dump the hash table@>
32998
32999 @ @<Undump the table of equivalents@>=
33000 @<Undump regions 1 to 6 of |eqtb|@>;
33001 undump(hash_base)(frozen_control_sequence)(par_loc);
33002 par_token:=cs_token_flag+par_loc;@/
33003 undump(hash_base)(frozen_control_sequence)(write_loc);@/
33004 @<Undump the hash table@>
33005
33006 @ The table of equivalents usually contains repeated information, so we dump it
33007 in compressed form: The sequence of $n+2$ values $(n,x_1,\ldots,x_n,m)$ in the
33008 format file represents $n+m$ consecutive entries of |eqtb|, with |m| extra
33009 copies of $x_n$, namely $(x_1,\ldots,x_n,x_n,\ldots,x_n)$.
33010
33011 @<Dump regions 1 to 4 of |eqtb|@>=
33012 k:=active_base;
33013 repeat j:=k;
33014 while j<int_base-1 do
33015 begin if (equiv(j)=equiv(j+1))and(eq_type(j)=eq_type(j+1))and@|
33016 (eq_level(j)=eq_level(j+1)) then goto found1;
33017 incr(j);
33018 end;
33019 l:=int_base; goto done1; {|j=int_base-1|}
33020 found1: incr(j); l:=j;
33021 while j<int_base-1 do
33022 begin if (equiv(j)<>equiv(j+1))or(eq_type(j)<>eq_type(j+1))or@|
33023 (eq_level(j)<>eq_level(j+1)) then goto done1;
33024 incr(j);
33025 end;
33026 done1:dump_int(l-k);
33027 while k<l do
33028 begin dump_wd(eqtb[k]); incr(k);
33029 end;
33030 k:=j+1; dump_int(k-l);
33031 until k=int_base
33032
33033 @ @<Dump regions 5 and 6 of |eqtb|@>=
33034 repeat j:=k;
33035 while j<eqtb_size do
33036 begin if eqtb[j].int=eqtb[j+1].int then goto found2;
33037 incr(j);
33038 end;
33039 l:=eqtb_size+1; goto done2; {|j=eqtb_size|}
33040 found2: incr(j); l:=j;
33041 while j<eqtb_size do
33042 begin if eqtb[j].int<>eqtb[j+1].int then goto done2;
33043 incr(j);
33044 end;
33045 done2:dump_int(l-k);
33046 while k<l do
33047 begin dump_wd(eqtb[k]); incr(k);
33048 end;
33049 k:=j+1; dump_int(k-l);
33050 until k>eqtb_size
33051
33052 @ @<Undump regions 1 to 6 of |eqtb|@>=
33053 k:=active_base;
33054 repeat undump_int(x);
33055 if (x<1)or(k+x>eqtb_size+1) then goto bad_fmt;
33056 for j:=k to k+x-1 do undump_wd(eqtb[j]);
33057 k:=k+x;
33058 undump_int(x);
33059 if (x<0)or(k+x>eqtb_size+1) then goto bad_fmt;
33060 for j:=k to k+x-1 do eqtb[j]:=eqtb[k-1];
33061 k:=k+x;
33062 until k>eqtb_size
33063
33064 @ A different scheme is used to compress the hash table, since its lower
33065 region is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output
33066 two words, |p| and |hash[p]|. The hash table is, of course, densely packed
33067 for |p>=hash_used|, so the remaining entries are output in a~block.
33068
33069 @<Dump the hash table@>=
33070 for p:=0 to prim_size do dump_hh(prim[p]);
33071 dump_int(hash_used); cs_count:=frozen_control_sequence-1-hash_used;
33072 for p:=hash_base to hash_used do if text(p)<>0 then
33073 begin dump_int(p); dump_hh(hash[p]); incr(cs_count);
33074 end;
33075 for p:=hash_used+1 to undefined_control_sequence-1 do dump_hh(hash[p]);
33076 dump_int(cs_count);@/
33077 print_ln; print_int(cs_count); print(" multiletter control sequences")
33078
33079 @ @<Undump the hash table@>=
33080 for p:=0 to prim_size do undump_hh(prim[p]);
33081 undump(hash_base)(frozen_control_sequence)(hash_used); p:=hash_base-1;
33082 repeat undump(p+1)(hash_used)(p); undump_hh(hash[p]);
33083 until p=hash_used;
33084 for p:=hash_used+1 to undefined_control_sequence-1 do undump_hh(hash[p]);
33085 undump_int(cs_count)
33086
33087 @ @<Dump the font information@>=
33088 dump_int(fmem_ptr);
33089 for k:=0 to fmem_ptr-1 do dump_wd(font_info[k]);
33090 dump_int(font_ptr);
33091 for k:=null_font to font_ptr do
33092 @<Dump the array info for internal font number |k|@>;
33093 print_ln; print_int(fmem_ptr-7); print(" words of font info for ");
33094 print_int(font_ptr-font_base); print(" preloaded font");
33095 if font_ptr<>font_base+1 then print_char("s")
33096
33097 @ @<Undump the font information@>=
33098 undump_size(7)(font_mem_size)('font mem size')(fmem_ptr);
33099 for k:=0 to fmem_ptr-1 do undump_wd(font_info[k]);
33100 undump_size(font_base)(font_max)('font max')(font_ptr);
33101 for k:=null_font to font_ptr do
33102 @<Undump the array info for internal font number |k|@>
33103
33104 @ @<Dump the array info for internal font number |k|@>=
33105 begin dump_qqqq(font_check[k]);
33106 dump_int(font_size[k]);
33107 dump_int(font_dsize[k]);
33108 dump_int(font_params[k]);@/
33109 dump_int(hyphen_char[k]);
33110 dump_int(skew_char[k]);@/
33111 dump_int(font_name[k]);
33112 dump_int(font_area[k]);@/
33113 dump_int(font_bc[k]);
33114 dump_int(font_ec[k]);@/
33115 dump_int(char_base[k]);
33116 dump_int(width_base[k]);
33117 dump_int(height_base[k]);@/
33118 dump_int(depth_base[k]);
33119 dump_int(italic_base[k]);
33120 dump_int(lig_kern_base[k]);@/
33121 dump_int(kern_base[k]);
33122 dump_int(exten_base[k]);
33123 dump_int(param_base[k]);@/
33124 dump_int(font_glue[k]);@/
33125 dump_int(bchar_label[k]);
33126 dump_int(font_bchar[k]);
33127 dump_int(font_false_bchar[k]);@/
33128 print_nl("\font"); print_esc(font_id_text(k)); print_char("=");
33129 print_file_name(font_name[k],font_area[k],"");
33130 if font_size[k]<>font_dsize[k] then
33131 begin print(" at "); print_scaled(font_size[k]); print("pt");
33132 end;
33133 end
33134
33135 @ @<Undump the array info for internal font number |k|@>=
33136 begin undump_qqqq(font_check[k]);@/
33137 undump_int(font_size[k]);
33138 undump_int(font_dsize[k]);
33139 undump(min_halfword)(max_halfword)(font_params[k]);@/
33140 undump_int(hyphen_char[k]);
33141 undump_int(skew_char[k]);@/
33142 undump(0)(str_ptr)(font_name[k]);
33143 undump(0)(str_ptr)(font_area[k]);@/
33144 undump(0)(255)(font_bc[k]);
33145 undump(0)(255)(font_ec[k]);@/
33146 undump_int(char_base[k]);
33147 undump_int(width_base[k]);
33148 undump_int(height_base[k]);@/
33149 undump_int(depth_base[k]);
33150 undump_int(italic_base[k]);
33151 undump_int(lig_kern_base[k]);@/
33152 undump_int(kern_base[k]);
33153 undump_int(exten_base[k]);
33154 undump_int(param_base[k]);@/
33155 undump(min_halfword)(lo_mem_max)(font_glue[k]);@/
33156 undump(0)(fmem_ptr-1)(bchar_label[k]);
33157 undump(min_quarterword)(non_char)(font_bchar[k]);
33158 undump(min_quarterword)(non_char)(font_false_bchar[k]);
33159 end
33160
33161 @ @<Dump the hyphenation tables@>=
33162 dump_int(hyph_count);
33163 for k:=0 to hyph_size do if hyph_word[k]<>0 then
33164 begin dump_int(k); dump_int(hyph_word[k]); dump_int(hyph_list[k]);
33165 end;
33166 print_ln; print_int(hyph_count); print(" hyphenation exception");
33167 if hyph_count<>1 then print_char("s");
33168 if trie_not_ready then init_trie;
33169 dump_int(trie_max);
33170 dump_int(hyph_start);
33171 for k:=0 to trie_max do dump_hh(trie[k]);
33172 dump_int(trie_op_ptr);
33173 for k:=1 to trie_op_ptr do
33174 begin dump_int(hyf_distance[k]);
33175 dump_int(hyf_num[k]);
33176 dump_int(hyf_next[k]);
33177 end;
33178 print_nl("Hyphenation trie of length "); print_int(trie_max);
33179 @.Hyphenation trie...@>
33180 print(" has "); print_int(trie_op_ptr); print(" op");
33181 if trie_op_ptr<>1 then print_char("s");
33182 print(" out of "); print_int(trie_op_size);
33183 for k:=255 downto 0 do if trie_used[k]>min_quarterword then
33184 begin print_nl(" "); print_int(qo(trie_used[k]));
33185 print(" for language "); print_int(k);
33186 dump_int(k); dump_int(qo(trie_used[k]));
33187 end
33188
33189 @ Only ``nonempty'' parts of |op_start| need to be restored.
33190
33191 @<Undump the hyphenation tables@>=
33192 undump(0)(hyph_size)(hyph_count);
33193 for k:=1 to hyph_count do
33194 begin undump(0)(hyph_size)(j);
33195 undump(0)(str_ptr)(hyph_word[j]);
33196 undump(min_halfword)(max_halfword)(hyph_list[j]);
33197 end;
33198 undump_size(0)(trie_size)('trie size')(j); @+init trie_max:=j;@+tini
33199 undump(0)(j)(hyph_start);
33200 for k:=0 to j do undump_hh(trie[k]);
33201 undump_size(0)(trie_op_size)('trie op size')(j); @+init trie_op_ptr:=j;@+tini
33202 for k:=1 to j do
33203 begin undump(0)(63)(hyf_distance[k]); {a |small_number|}
33204 undump(0)(63)(hyf_num[k]);
33205 undump(min_quarterword)(max_quarterword)(hyf_next[k]);
33206 end;
33207 init for k:=0 to 255 do trie_used[k]:=min_quarterword;@+tini@;@/
33208 k:=256;
33209 while j>0 do
33210 begin undump(0)(k-1)(k); undump(1)(j)(x);@+init trie_used[k]:=qi(x);@+tini@;@/
33211 j:=j-x; op_start[k]:=qo(j);
33212 end;
33213 @!init trie_not_ready:=false @+tini
33214
33215 @ Store some of the pdftex data structures in the format. The idea here is
33216 to ensure that any data structures referenced from pdftex-specific whatsit
33217 nodes are retained. For the sake of simplicity and speed, all the filled parts
33218 of |pdf_mem| and |obj_tab| are retained, in the present implementation. We also
33219 retain three of the linked lists that start from |head_tab|, so that it is
33220 possible to, say, load an image in the \.{INITEX} run and then reference it in a
33221 \.{VIRTEX} run that uses the dumped format.
33222
33223 @<Dump pdftex data@>=
33224 begin
33225 dumpimagemeta; {the image information array }
33226 dump_int(pdf_mem_size);
33227 dump_int(pdf_mem_ptr);
33228 for k:=1 to pdf_mem_ptr-1 do begin
33229 dump_int(pdf_mem[k]);
33230 end;
33231 print_ln; print_int(pdf_mem_ptr-1); print(" words of pdfTeX memory");
33232 dump_int(obj_tab_size);
33233 dump_int(obj_ptr);
33234 dump_int(sys_obj_ptr);
33235 for k:=1 to sys_obj_ptr do begin
33236 dump_int(obj_tab[k].int0);
33237 dump_int(obj_tab[k].int1);
33238 dump_int(obj_tab[k].int3);
33239 dump_int(obj_tab[k].int4);
33240 end;
33241 print_ln; print_int(sys_obj_ptr); print(" indirect objects");
33242 dump_int(pdf_obj_count);
33243 dump_int(pdf_xform_count);
33244 dump_int(pdf_ximage_count);
33245 dump_int(head_tab[obj_type_obj]);
33246 dump_int(head_tab[obj_type_xform]);
33247 dump_int(head_tab[obj_type_ximage]);
33248 dump_int(pdf_last_obj);
33249 dump_int(pdf_last_xform);
33250 dump_int(pdf_last_ximage);
33251 dumptounicode;
33252 end
33253
33254 @ And restoring the pdftex data structures from the format. The
33255 two function arguments to |undumpimagemeta| have been restored
33256 already in an earlier module.
33257
33258 @<Undump pdftex data@>=
33259 begin
33260 undumpimagemeta(pdf_major_version,pdf_minor_version,pdf_inclusion_errorlevel); {the image information array }
33261 undump_int(pdf_mem_size);
33262 pdf_mem := xrealloc_array(pdf_mem, integer, pdf_mem_size);
33263 undump_int(pdf_mem_ptr);
33264 for k:=1 to pdf_mem_ptr-1 do begin
33265 undump_int(pdf_mem[k]);
33266 end;
33267 undump_int(obj_tab_size);
33268 undump_int(obj_ptr);
33269 undump_int(sys_obj_ptr);
33270 for k:=1 to sys_obj_ptr do begin
33271 undump_int(obj_tab[k].int0);
33272 undump_int(obj_tab[k].int1);
33273 obj_tab[k].int2 := -1;
33274 undump_int(obj_tab[k].int3);
33275 undump_int(obj_tab[k].int4);
33276 end;
33277 undump_int(pdf_obj_count);
33278 undump_int(pdf_xform_count);
33279 undump_int(pdf_ximage_count);
33280 undump_int(head_tab[obj_type_obj]);
33281 undump_int(head_tab[obj_type_xform]);
33282 undump_int(head_tab[obj_type_ximage]);
33283 undump_int(pdf_last_obj);
33284 undump_int(pdf_last_xform);
33285 undump_int(pdf_last_ximage);
33286 undumptounicode;
33287 end
33288
33289 @ We have already printed a lot of statistics, so we set |tracing_stats:=0|
33290 to prevent them from appearing again.
33291
33292 @<Dump a couple more things and the closing check word@>=
33293 dump_int(interaction); dump_int(format_ident); dump_int(69069);
33294 tracing_stats:=0
33295
33296 @ @<Undump a couple more things and the closing check word@>=
33297 undump(batch_mode)(error_stop_mode)(interaction);
33298 undump(0)(str_ptr)(format_ident);
33299 undump_int(x);
33300 if (x<>69069)or eof(fmt_file) then goto bad_fmt
33301
33302 @ @<Create the |format_ident|...@>=
33303 selector:=new_string;
33304 print(" (preloaded format="); print(job_name); print_char(" ");
33305 print_int(year); print_char(".");
33306 print_int(month); print_char("."); print_int(day); print_char(")");
33307 if interaction=batch_mode then selector:=log_only
33308 else selector:=term_and_log;
33309 str_room(1);
33310 format_ident:=make_string;
33311 pack_job_name(format_extension);
33312 while not w_open_out(fmt_file) do
33313 prompt_file_name("format file name",format_extension);
33314 print_nl("Beginning to dump on file ");
33315 @.Beginning to dump...@>
33316 slow_print(w_make_name_string(fmt_file)); flush_string;
33317 print_nl(""); slow_print(format_ident)
33318
33319 @ @<Close the format file@>=
33320 w_close(fmt_file)
33321
33322 @* \[51] The main program.
33323 This is it: the part of \TeX\ that executes all those procedures we have
33324 written.
33325
33326 Well---almost. Let's leave space for a few more routines that we may
33327 have forgotten.
33328
33329 @p @<Last-minute procedures@>
33330
33331 @ We have noted that there are two versions of \TeX82. One, called \.{INITEX},
33332 @.INITEX@>
33333 has to be run first; it initializes everything from scratch, without
33334 reading a format file, and it has the capability of dumping a format file.
33335 The other one is called `\.{VIRTEX}'; it is a ``virgin'' program that needs
33336 @.VIRTEX@>
33337 to input a format file in order to get started. \.{VIRTEX} typically has
33338 more memory capacity than \.{INITEX}, because it does not need the space
33339 consumed by the auxiliary hyphenation tables and the numerous calls on
33340 |primitive|, etc.
33341
33342 The \.{VIRTEX} program cannot read a format file instantaneously, of course;
33343 the best implementations therefore allow for production versions of \TeX\ that
33344 not only avoid the loading routine for \PASCAL\ object code, they also have
33345 a format file pre-loaded. This is impossible to do if we stick to standard
33346 \PASCAL; but there is a simple way to fool many systems into avoiding the
33347 initialization, as follows:\quad(1)~We declare a global integer variable
33348 called |ready_already|. The probability is negligible that this
33349 variable holds any particular value like 314159 when \.{VIRTEX} is first
33350 loaded.\quad(2)~After we have read in a format file and initialized
33351 everything, we set |ready_already:=314159|.\quad(3)~Soon \.{VIRTEX}
33352 will print `\.*', waiting for more input; and at this point we
33353 interrupt the program and save its core image in some form that the
33354 operating system can reload speedily.\quad(4)~When that core image is
33355 activated, the program starts again at the beginning; but now
33356 |ready_already=314159| and all the other global variables have
33357 their initial values too. The former chastity has vanished!
33358
33359 In other words, if we allow ourselves to test the condition
33360 |ready_already=314159|, before |ready_already| has been
33361 assigned a value, we can avoid the lengthy initialization. Dirty tricks
33362 rarely pay off so handsomely.
33363 @^dirty \PASCAL@>
33364 @^system dependencies@>
33365
33366 On systems that allow such preloading, the standard program called \.{TeX}
33367 should be the one that has \.{plain} format preloaded, since that agrees
33368 with {\sl The \TeX book}. Other versions, e.g., \.{AmSTeX}, should also
33369 @:TeXbook}{\sl The \TeX book@>
33370 @.AmSTeX@>
33371 @.plain@>
33372 be provided for commonly used formats.
33373
33374 @<Glob...@>=
33375 @!ready_already:integer; {a sacrifice of purity for economy}
33376
33377 @ Now this is really it: \TeX\ starts and ends here.
33378
33379 The initial test involving |ready_already| should be deleted if the
33380 \PASCAL\ runtime system is smart enough to detect such a ``mistake.''
33381 @^system dependencies@>
33382
33383 @p begin @!{|start_here|}
33384 history:=fatal_error_stop; {in case we quit during initialization}
33385 t_open_out; {open the terminal for output}
33386 if ready_already=314159 then goto start_of_TEX;
33387 @<Check the ``constant'' values...@>@;
33388 if bad>0 then
33389 begin wterm_ln('Ouch---my internal constants have been clobbered!',
33390 '---case ',bad:1);
33391 @.Ouch...clobbered@>
33392 goto final_end;
33393 end;
33394 initialize; {set global variables to their starting values}
33395 @!init if not get_strings_started then goto final_end;
33396 init_prim; {call |primitive| for each primitive}
33397 init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr; fix_date_and_time;
33398 tini@/
33399 ready_already:=314159;
33400 start_of_TEX: @<Initialize the output routines@>;
33401 @<Get the first line of input and prepare to start@>;
33402 history:=spotless; {ready to go!}
33403 main_control; {come to life}
33404 final_cleanup; {prepare for death}
33405 end_of_TEX: close_files_and_terminate;
33406 final_end: ready_already:=0;
33407 end.
33408
33409 @ Here we do whatever is needed to complete \TeX's job gracefully on the
33410 local operating system. The code here might come into play after a fatal
33411 error; it must therefore consist entirely of ``safe'' operations that
33412 cannot produce error messages. For example, it would be a mistake to call
33413 |str_room| or |make_string| at this time, because a call on |overflow|
33414 might lead to an infinite loop.
33415 @^system dependencies@>
33416 (Actually there's one way to get error messages, via |prepare_mag|;
33417 but that can't cause infinite recursion.)
33418 @^recursion@>
33419
33420 If |final_cleanup| is bypassed, this program doesn't bother to close
33421 the input files that may still be open.
33422
33423 @<Last-minute...@>=
33424 procedure close_files_and_terminate;
33425 label done, done1;
33426 var a, b, c, i, j, k, l: integer; {all-purpose index}
33427 is_root: boolean; {|pdf_last_pages| is root of Pages tree?}
33428 is_names: boolean; {flag for name tree output: is it Names or Kids?}
33429 root, outlines, threads, names_tree, dests: integer;
33430 xref_offset_width, names_head, names_tail: integer;
33431 begin @<Finish the extensions@>; new_line_char:=-1;
33432 @!stat if tracing_stats>0 then @<Output statistics about this job@>;@;@+tats@/
33433 wake_up_terminal;
33434 if not fixed_pdfoutput_set then
33435 fix_pdfoutput;
33436 if fixed_pdfoutput > 0 then begin
33437 if history = fatal_error_stop then begin
33438 remove_pdffile;
33439 print_err(" ==> Fatal error occurred, no output PDF file produced!")
33440 end
33441 else begin
33442 @<Finish the PDF file@>;
33443 if log_opened then
33444 begin wlog_cr;
33445 wlog_ln('PDF statistics:');
33446 wlog_ln(' ',obj_ptr:1,' PDF objects out of ',obj_tab_size:1,
33447 ' (max. ',sup_obj_tab_size:1,')');
33448 if pdf_os_cntr > 0 then begin
33449 wlog(' ',((pdf_os_cntr - 1) * pdf_os_max_objs + pdf_os_objidx + 1):1,
33450 ' compressed objects within ',pdf_os_cntr:1,' object stream');
33451 if pdf_os_cntr > 1 then
33452 wlog('s');
33453 wlog_cr;
33454 end;
33455 wlog_ln(' ',pdf_dest_names_ptr:1,' named destinations out of ',dest_names_size:1,
33456 ' (max. ',sup_dest_names_size:1,')');
33457 wlog_ln(' ',pdf_mem_ptr:1,' words of extra memory for PDF output out of ',pdf_mem_size:1,
33458 ' (max. ',sup_pdf_mem_size:1,')');
33459 end;
33460 end;
33461 end
33462 else begin
33463 @<Finish the \.{DVI} file@>;
33464 end;
33465 if log_opened then
33466 begin wlog_cr; a_close(log_file); selector:=selector-2;
33467 if selector=term_only then
33468 begin print_nl("Transcript written on ");
33469 @.Transcript written...@>
33470 slow_print(log_name); print_char(".");
33471 end;
33472 end;
33473 end;
33474
33475 @ The present section goes directly to the log file instead of using
33476 |print| commands, because there's no need for these strings to take
33477 up |str_pool| memory when a non-{\bf stat} version of \TeX\ is being used.
33478
33479 @<Output statistics...@>=
33480 if log_opened then
33481 begin wlog_ln(' ');
33482 wlog_ln('Here is how much of TeX''s memory',' you used:');
33483 @.Here is how much...@>
33484 wlog(' ',str_ptr-init_str_ptr:1,' string');
33485 if str_ptr<>init_str_ptr+1 then wlog('s');
33486 wlog_ln(' out of ', max_strings-init_str_ptr:1);@/
33487 wlog_ln(' ',pool_ptr-init_pool_ptr:1,' string characters out of ',
33488 pool_size-init_pool_ptr:1);@/
33489 wlog_ln(' ',lo_mem_max-mem_min+mem_end-hi_mem_min+2:1,@|
33490 ' words of memory out of ',mem_end+1-mem_min:1);@/
33491 wlog_ln(' ',cs_count:1,' multiletter control sequences out of ',
33492 hash_size:1);@/
33493 wlog(' ',fmem_ptr:1,' words of font info for ',
33494 font_ptr-font_base:1,' font');
33495 if font_ptr<>font_base+1 then wlog('s');
33496 wlog_ln(', out of ',font_mem_size:1,' for ',font_max-font_base:1);@/
33497 wlog(' ',hyph_count:1,' hyphenation exception');
33498 if hyph_count<>1 then wlog('s');
33499 wlog_ln(' out of ',hyph_size:1);@/
33500 wlog_ln(' ',max_in_stack:1,'i,',max_nest_stack:1,'n,',@|
33501 max_param_stack:1,'p,',@|
33502 max_buf_stack+1:1,'b,',@|
33503 max_save_stack+6:1,'s stack positions out of ',@|
33504 stack_size:1,'i,',
33505 nest_size:1,'n,',
33506 param_size:1,'p,',
33507 buf_size:1,'b,',
33508 save_size:1,'s');
33509 end
33510
33511 @ We get to the |final_cleanup| routine when \.{\\end} or \.{\\dump} has
33512 been scanned and |its_all_over|\kern-2pt.
33513
33514 @<Last-minute...@>=
33515 procedure final_cleanup;
33516 label exit;
33517 var c:small_number; {0 for \.{\\end}, 1 for \.{\\dump}}
33518 begin c:=cur_chr; if c<>1 then new_line_char:=-1;
33519 if job_name=0 then open_log_file;
33520 while input_ptr>0 do
33521 if state=token_list then end_token_list@+else end_file_reading;
33522 while open_parens>0 do
33523 begin print(" )"); decr(open_parens);
33524 end;
33525 if cur_level>level_one then
33526 begin print_nl("("); print_esc("end occurred ");
33527 print("inside a group at level ");
33528 @:end_}{\.{(\\end occurred...)}@>
33529 print_int(cur_level-level_one); print_char(")");
33530 if eTeX_ex then show_save_groups;
33531 end;
33532 while cond_ptr<>null do
33533 begin print_nl("("); print_esc("end occurred ");
33534 print("when "); print_cmd_chr(if_test,cur_if);
33535 if if_line<>0 then
33536 begin print(" on line "); print_int(if_line);
33537 end;
33538 print(" was incomplete)");
33539 if_line:=if_line_field(cond_ptr);
33540 cur_if:=subtype(cond_ptr); temp_ptr:=cond_ptr;
33541 cond_ptr:=link(cond_ptr); free_node(temp_ptr,if_node_size);
33542 end;
33543 if history<>spotless then
33544 if ((history=warning_issued)or(interaction<error_stop_mode)) then
33545 if selector=term_and_log then
33546 begin selector:=term_only;
33547 print_nl("(see the transcript file for additional information)");
33548 @.see the transcript file...@>
33549 selector:=term_and_log;
33550 end;
33551 if c=1 then
33552 begin @!init for c:=top_mark_code to split_bot_mark_code do
33553 if cur_mark[c]<>null then delete_token_ref(cur_mark[c]);
33554 if sa_mark<>null then
33555 if do_marks(destroy_marks,0,sa_mark) then sa_mark:=null;
33556 for c:=last_box_code to vsplit_code do flush_node_list(disc_ptr[c]);
33557 if last_glue<>max_halfword then delete_glue_ref(last_glue);
33558 store_fmt_file; return;@+tini@/
33559 print_nl("(\dump is performed only by INITEX)"); return;
33560 @:dump_}{\.{\\dump...only by INITEX}@>
33561 end;
33562 exit:end;
33563
33564 @ @<Last-minute...@>=
33565 @!init procedure init_prim; {initialize all the primitives}
33566 begin no_new_control_sequence:=false;
33567 first:=0;
33568 @<Put each...@>;
33569 no_new_control_sequence:=true;
33570 end;
33571 tini
33572
33573 @ When we begin the following code, \TeX's tables may still contain garbage;
33574 the strings might not even be present. Thus we must proceed cautiously to get
33575 bootstrapped in.
33576
33577 But when we finish this part of the program, \TeX\ is ready to call on the
33578 |main_control| routine to do its work.
33579
33580 @<Get the first line...@>=
33581 begin @<Initialize the input routines@>;
33582 @<Enable \eTeX, if requested@>@;@/
33583 if (format_ident=0)or(buffer[loc]="&") then
33584 begin if format_ident<>0 then initialize; {erase preloaded format}
33585 if not open_fmt_file then goto final_end;
33586 if not load_fmt_file then
33587 begin w_close(fmt_file); goto final_end;
33588 end;
33589 w_close(fmt_file);
33590 while (loc<limit)and(buffer[loc]=" ") do incr(loc);
33591 end;
33592 if (pdf_output_option <> 0) then pdf_output := pdf_output_value;
33593 if (pdf_draftmode_option <> 0) then pdf_draftmode := pdf_draftmode_value;
33594 pdf_init_map_file('pdftex.map');
33595 if eTeX_ex then wterm_ln('entering extended mode');
33596 if end_line_char_inactive then decr(limit)
33597 else buffer[limit]:=end_line_char;
33598 fix_date_and_time;@/
33599 random_seed :=(microseconds*1000)+(epochseconds mod 1000000);@/
33600 init_randoms(random_seed);@/
33601 @<Compute the magic offset@>;
33602 @<Initialize the print |selector|...@>;
33603 if (loc<limit)and(cat_code(buffer[loc])<>escape) then start_input;
33604 {\.{\\input} assumed}
33605 end
33606
33607 @* \[52] Debugging.
33608 Once \TeX\ is working, you should be able to diagnose most errors with
33609 the \.{\\show} commands and other diagnostic features. But for the initial
33610 stages of debugging, and for the revelation of really deep mysteries, you
33611 can compile \TeX\ with a few more aids, including the \PASCAL\ runtime
33612 checks and its debugger. An additional routine called |debug_help|
33613 will also come into play when you type `\.D' after an error message;
33614 |debug_help| also occurs just before a fatal error causes \TeX\ to succumb.
33615 @^debugging@>
33616 @^system dependencies@>
33617
33618 The interface to |debug_help| is primitive, but it is good enough when used
33619 with a \PASCAL\ debugger that allows you to set breakpoints and to read
33620 variables and change their values. After getting the prompt `\.{debug \#}', you
33621 type either a negative number (this exits |debug_help|), or zero (this
33622 goes to a location where you can set a breakpoint, thereby entering into
33623 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
33624 an argument |n|. The meaning of |m| and |n| will be clear from the
33625 program below. (If |m=13|, there is an additional argument, |l|.)
33626 @.debug \#@>
33627
33628 @d breakpoint=888 {place where a breakpoint is desirable}
33629
33630 @<Last-minute...@>=
33631 @!debug procedure debug_help; {routine to display various things}
33632 label breakpoint,exit;
33633 var k,@!l,@!m,@!n:integer;
33634 begin clear_terminal;
33635 loop begin wake_up_terminal;
33636 print_nl("debug # (-1 to exit):"); update_terminal;
33637 @.debug \#@>
33638 read(term_in,m);
33639 if m<0 then return
33640 else if m=0 then
33641 begin goto breakpoint;@/ {go to every declared label at least once}
33642 breakpoint: m:=0; @{'BREAKPOINT'@}@/
33643 end
33644 else begin read(term_in,n);
33645 case m of
33646 @t\4@>@<Numbered cases for |debug_help|@>@;
33647 othercases print("?")
33648 endcases;
33649 end;
33650 end;
33651 exit:end;
33652 gubed
33653
33654 @ @<Numbered cases...@>=
33655 1: print_word(mem[n]); {display |mem[n]| in all forms}
33656 2: print_int(info(n));
33657 3: print_int(link(n));
33658 4: print_word(eqtb[n]);
33659 5: print_word(font_info[n]);
33660 6: print_word(save_stack[n]);
33661 7: show_box(n);
33662 {show a box, abbreviated by |show_box_depth| and |show_box_breadth|}
33663 8: begin breadth_max:=10000; depth_threshold:=pool_size-pool_ptr-10;
33664 show_node_list(n); {show a box in its entirety}
33665 end;
33666 9: show_token_list(n,null,1000);
33667 10: slow_print(n);
33668 11: check_mem(n>0); {check wellformedness; print new busy locations if |n>0|}
33669 12: search_mem(n); {look for pointers to |n|}
33670 13: begin read(term_in,l); print_cmd_chr(n,l);
33671 end;
33672 14: for k:=0 to n do print(buffer[k]);
33673 15: begin font_in_short_display:=null_font; short_display(n);
33674 end;
33675 16: panicking:=not panicking;
33676
33677 @* \[53] Extensions.
33678 The program above includes a bunch of ``hooks'' that allow further
33679 capabilities to be added without upsetting \TeX's basic structure.
33680 Most of these hooks are concerned with ``whatsit'' nodes, which are
33681 intended to be used for special purposes; whenever a new extension to
33682 \TeX\ involves a new kind of whatsit node, a corresponding change needs
33683 to be made to the routines below that deal with such nodes,
33684 but it will usually be unnecessary to make many changes to the
33685 other parts of this program.
33686
33687 In order to demonstrate how extensions can be made, we shall treat
33688 `\.{\\write}', `\.{\\openout}', `\.{\\closeout}', `\.{\\immediate}',
33689 `\.{\\special}', and `\.{\\setlanguage}' as if they were extensions.
33690 These commands are actually primitives of \TeX, and they should
33691 appear in all implementations of the system; but let's try to imagine
33692 that they aren't. Then the program below illustrates how a person
33693 could add them.
33694
33695 Sometimes, of course, an extension will require changes to \TeX\ itself;
33696 no system of hooks could be complete enough for all conceivable extensions.
33697 The features associated with `\.{\\write}' are almost all confined to the
33698 following paragraphs, but there are small parts of the |print_ln| and
33699 |print_char| procedures that were introduced specifically to \.{\\write}
33700 characters. Furthermore one of the token lists recognized by the scanner
33701 is a |write_text|; and there are a few other miscellaneous places where we
33702 have already provided for some aspect of \.{\\write}. The goal of a \TeX\
33703 extender should be to minimize alterations to the standard parts of the
33704 program, and to avoid them completely if possible. He or she should also
33705 be quite sure that there's no easy way to accomplish the desired goals
33706 with the standard features that \TeX\ already has. ``Think thrice before
33707 extending,'' because that may save a lot of work, and it will also keep
33708 incompatible extensions of \TeX\ from proliferating.
33709 @^system dependencies@>
33710 @^extensions to \TeX@>
33711
33712 @ First let's consider the format of whatsit nodes that are used to represent
33713 the data associated with \.{\\write} and its relatives. Recall that a whatsit
33714 has |type=whatsit_node|, and the |subtype| is supposed to distinguish
33715 different kinds of whatsits. Each node occupies two or more words; the
33716 exact number is immaterial, as long as it is readily determined from the
33717 |subtype| or other data.
33718
33719 We shall introduce five |subtype| values here, corresponding to the
33720 control sequences \.{\\openout}, \.{\\write}, \.{\\closeout}, \.{\\special}, and
33721 \.{\\setlanguage}. The second word of I/O whatsits has a |write_stream| field
33722 that identifies the write-stream number (0 to 15, or 16 for out-of-range and
33723 positive, or 17 for out-of-range and negative).
33724 In the case of \.{\\write} and \.{\\special}, there is also a field that
33725 points to the reference count of a token list that should be sent. In the
33726 case of \.{\\openout}, we need three words and three auxiliary subfields
33727 to hold the string numbers for name, area, and extension.
33728
33729 @d write_node_size=2 {number of words in a write/whatsit node}
33730 @d open_node_size=3 {number of words in an open/whatsit node}
33731 @d open_node=0 {|subtype| in whatsits that represent files to \.{\\openout}}
33732 @d write_node=1 {|subtype| in whatsits that represent things to \.{\\write}}
33733 @d close_node=2 {|subtype| in whatsits that represent streams to \.{\\closeout}}
33734 @d special_node=3 {|subtype| in whatsits that represent \.{\\special} things}
33735 @d latespecial_node==4 {|subtype| in whatsits that represent \.{\\special} things expanded during output}
33736 @d language_node=5 {|subtype| in whatsits that change the current language}
33737 @d what_lang(#)==link(#+1) {language number, in the range |0..255|}
33738 @d what_lhm(#)==type(#+1) {minimum left fragment, in the range |1..63|}
33739 @d what_rhm(#)==subtype(#+1) {minimum right fragment, in the range |1..63|}
33740 @d write_tokens(#) == link(#+1) {reference count of token list to write}
33741 @d write_stream(#) == info(#+1) {stream number (0 to 17)}
33742 @d open_name(#) == link(#+1) {string number of file name to open}
33743 @d open_area(#) == info(#+2) {string number of file area for |open_name|}
33744 @d open_ext(#) == link(#+2) {string number of file extension for |open_name|}
33745
33746 @ The sixteen possible \.{\\write} streams are represented by the |write_file|
33747 array. The |j|th file is open if and only if |write_open[j]=true|. The last
33748 two streams are special; |write_open[16]| represents a stream number
33749 greater than 15, while |write_open[17]| represents a negative stream number,
33750 and both of these variables are always |false|.
33751
33752 @<Glob...@>=
33753 @!write_file:array[0..15] of alpha_file;
33754 @!write_open:array[0..17] of boolean;
33755
33756 @ @<Set init...@>=
33757 for k:=0 to 17 do write_open[k]:=false;
33758
33759 @ Extensions might introduce new command codes; but it's best to use
33760 |extension| with a modifier, whenever possible, so that |main_control|
33761 stays the same.
33762
33763 @d immediate_code=5 {command modifier for \.{\\immediate}}
33764 @d set_language_code=6 {command modifier for \.{\\setlanguage}}
33765 @d pdftex_first_extension_code = 7
33766 @d pdf_literal_node == pdftex_first_extension_code + 0
33767 @d pdf_lateliteral_node == pdftex_first_extension_code + 1
33768 @d pdf_obj_code == pdftex_first_extension_code + 2
33769 @d pdf_refobj_node == pdftex_first_extension_code + 3
33770 @d pdf_xform_code == pdftex_first_extension_code + 4
33771 @d pdf_refxform_node == pdftex_first_extension_code + 5
33772 @d pdf_ximage_code == pdftex_first_extension_code + 6
33773 @d pdf_refximage_node == pdftex_first_extension_code + 7
33774 @d pdf_annot_node == pdftex_first_extension_code + 8
33775 @d pdf_start_link_node == pdftex_first_extension_code + 9
33776 @d pdf_end_link_node == pdftex_first_extension_code + 10
33777 @d pdf_outline_code == pdftex_first_extension_code + 11
33778 @d pdf_dest_node == pdftex_first_extension_code + 12
33779 @d pdf_thread_node == pdftex_first_extension_code + 13
33780 @d pdf_start_thread_node == pdftex_first_extension_code + 14
33781 @d pdf_end_thread_node == pdftex_first_extension_code + 15
33782 @d pdf_save_pos_node == pdftex_first_extension_code + 16
33783 @d pdf_info_code == pdftex_first_extension_code + 17
33784 @d pdf_catalog_code == pdftex_first_extension_code + 18
33785 @d pdf_names_code == pdftex_first_extension_code + 19
33786 @d pdf_font_attr_code == pdftex_first_extension_code + 20
33787 @d pdf_include_chars_code == pdftex_first_extension_code + 21
33788 @d pdf_map_file_code == pdftex_first_extension_code + 22
33789 @d pdf_map_line_code == pdftex_first_extension_code + 23
33790 @d pdf_trailer_code == pdftex_first_extension_code + 24
33791 @d pdf_trailer_id_code == pdftex_first_extension_code + 25
33792 @d reset_timer_code == pdftex_first_extension_code + 26
33793 @d pdf_font_expand_code == pdftex_first_extension_code + 27
33794 @d set_random_seed_code == pdftex_first_extension_code + 28
33795 @d pdf_snap_ref_point_node == pdftex_first_extension_code + 29
33796 @d pdf_snapy_node == pdftex_first_extension_code + 30
33797 @d pdf_snapy_comp_node == pdftex_first_extension_code + 31
33798 @d pdf_glyph_to_unicode_code == pdftex_first_extension_code + 32
33799 @d pdf_colorstack_node == pdftex_first_extension_code + 33
33800 @d pdf_setmatrix_node == pdftex_first_extension_code + 34
33801 @d pdf_save_node == pdftex_first_extension_code + 35
33802 @d pdf_restore_node == pdftex_first_extension_code + 36
33803 @d pdf_nobuiltin_tounicode_code== pdftex_first_extension_code + 37
33804 @d pdf_interword_space_on_node == pdftex_first_extension_code + 38
33805 @d pdf_interword_space_off_node== pdftex_first_extension_code + 39
33806 @d pdf_fake_space_node == pdftex_first_extension_code + 40
33807 @d pdf_running_link_off_node == pdftex_first_extension_code + 41
33808 @d pdf_running_link_on_node == pdftex_first_extension_code + 42
33809 @d pdf_space_font_code == pdftex_first_extension_code + 43
33810 @d pdftex_last_extension_code == pdftex_first_extension_code + 43
33811
33812 @<Put each...@>=
33813 primitive("openout",extension,open_node);@/
33814 @!@:open_out_}{\.{\\openout} primitive@>
33815 primitive("write",extension,write_node); write_loc:=cur_val;@/
33816 @!@:write_}{\.{\\write} primitive@>
33817 primitive("closeout",extension,close_node);@/
33818 @!@:close_out_}{\.{\\closeout} primitive@>
33819 primitive("special",extension,special_node);@/
33820 @!@:special_}{\.{\\special} primitive@>
33821 primitive("immediate",extension,immediate_code);@/
33822 @!@:immediate_}{\.{\\immediate} primitive@>
33823 primitive("setlanguage",extension,set_language_code);@/
33824 @!@:set_language_}{\.{\\setlanguage} primitive@>
33825 primitive("pdfliteral",extension,pdf_literal_node);@/
33826 @!@:pdf_literal_}{\.{\\pdfliteral} primitive@>
33827 primitive("pdfcolorstack",extension,pdf_colorstack_node);@/
33828 @!@:pdf_colorstack_}{\.{\\pdfcolorstack} primitive@>
33829 primitive("pdfsetmatrix",extension,pdf_setmatrix_node);@/
33830 @!@:pdf_setmatrix_}{\.{\\pdfsetmatrix} primitive@>
33831 primitive("pdfsave",extension,pdf_save_node);@/
33832 @!@:pdf_save_}{\.{\\pdfsave} primitive@>
33833 primitive("pdfrestore",extension,pdf_restore_node);@/
33834 @!@:pdf_restore_}{\.{\\pdfrestore} primitive@>
33835 primitive("pdfobj",extension,pdf_obj_code);@/
33836 @!@:pdf_obj_}{\.{\\pdfobj} primitive@>
33837 primitive("pdfrefobj",extension,pdf_refobj_node);@/
33838 @!@:pdf_refobj_}{\.{\\pdfrefobj} primitive@>
33839 primitive("pdfxform",extension,pdf_xform_code);@/
33840 @!@:pdf_xform_}{\.{\\pdfxform} primitive@>
33841 primitive("pdfrefxform",extension,pdf_refxform_node);@/
33842 @!@:pdf_refxform_}{\.{\\pdfrefxform} primitive@>
33843 primitive("pdfximage",extension,pdf_ximage_code);@/
33844 @!@:pdf_ximage_}{\.{\\pdfximage} primitive@>
33845 primitive("pdfrefximage",extension,pdf_refximage_node);@/
33846 @!@:pdf_refximage_}{\.{\\pdfrefximage} primitive@>
33847 primitive("pdfannot",extension,pdf_annot_node);@/
33848 @!@:pdf_annot_}{\.{\\pdfannot} primitive@>
33849 primitive("pdfstartlink",extension,pdf_start_link_node);@/
33850 @!@:pdf_start_link_}{\.{\\pdfstartlink} primitive@>
33851 primitive("pdfendlink",extension,pdf_end_link_node);@/
33852 @!@:pdf_end_link_}{\.{\\pdfendlink} primitive@>
33853 primitive("pdfoutline",extension,pdf_outline_code);@/
33854 @!@:pdf_outline_}{\.{\\pdfoutline} primitive@>
33855 primitive("pdfdest",extension,pdf_dest_node);@/
33856 @!@:pdf_dest_}{\.{\\pdfdest} primitive@>
33857 primitive("pdfthread",extension,pdf_thread_node);@/
33858 @!@:pdf_thread_}{\.{\\pdfthread} primitive@>
33859 primitive("pdfstartthread",extension,pdf_start_thread_node);@/
33860 @!@:pdf_start_thread_}{\.{\\pdfstartthread} primitive@>
33861 primitive("pdfendthread",extension,pdf_end_thread_node);@/
33862 @!@:pdf_end_thread_}{\.{\\pdfendthread} primitive@>
33863 primitive("pdfsavepos",extension,pdf_save_pos_node);@/
33864 @!@:pdf_save_pos_}{\.{\\pdfsavepos} primitive@>
33865 primitive("pdfsnaprefpoint",extension,pdf_snap_ref_point_node);@/
33866 @!@:pdf_snap_ref_point_}{\.{\\pdfsnaprefpoint} primitive@>
33867 primitive("pdfsnapy",extension,pdf_snapy_node);@/
33868 @!@:pdf_snapy_}{\.{\\pdfsnapy} primitive@>
33869 primitive("pdfsnapycomp",extension,pdf_snapy_comp_node);@/
33870 @!@:pdf_snapy_comp_}{\.{\\pdfsnapycomp} primitive@>
33871 primitive("pdfinfo",extension,pdf_info_code);@/
33872 @!@:pdf_info_}{\.{\\pdfinfo} primitive@>
33873 primitive("pdfcatalog",extension,pdf_catalog_code);@/
33874 @!@:pdf_catalog_}{\.{\\pdfcatalog} primitive@>
33875 primitive("pdfnames",extension,pdf_names_code);@/
33876 @!@:pdf_names_}{\.{\\pdfnames} primitive@>
33877 primitive("pdfincludechars",extension,pdf_include_chars_code);@/
33878 @!@:pdf_include_chars_}{\.{\\pdfincludechars} primitive@>
33879 primitive("pdffontattr",extension,pdf_font_attr_code);@/
33880 @!@:pdf_font_attr_}{\.{\\pdffontattr} primitive@>
33881 primitive("pdfmapfile",extension,pdf_map_file_code);@/
33882 @!@:pdf_map_file_}{\.{\\pdfmapfile} primitive@>
33883 primitive("pdfmapline",extension,pdf_map_line_code);@/
33884 @!@:pdf_map_line_}{\.{\\pdfmapline} primitive@>
33885 primitive("pdftrailer",extension,pdf_trailer_code);@/
33886 @!@:pdf_trailer_}{\.{\\pdftrailer} primitive@>
33887 primitive("pdftrailerid",extension,pdf_trailer_id_code);@/
33888 @!@:pdf_trailer_id_}{\.{\\pdftrailerid} primitive@>
33889 primitive("pdfresettimer",extension,reset_timer_code);@/
33890 @!@:reset_timer_}{\.{\\pdfresettimer} primitive@>
33891 primitive("pdfsetrandomseed",extension,set_random_seed_code);@/
33892 @!@:set_random_seed_code}{\.{\\pdfsetrandomseed} primitive@>
33893 primitive("pdffontexpand",extension,pdf_font_expand_code);@/
33894 @!@:pdf_font_expand_}{\.{\\pdffontexpand} primitive@>
33895 primitive("pdfglyphtounicode",extension,pdf_glyph_to_unicode_code);@/
33896 @!@:pdf_glyph_to_unicode_}{\.{\\pdfglyphtounicode} primitive@>
33897 primitive("pdfnobuiltintounicode",extension,pdf_nobuiltin_tounicode_code);@/
33898 @!@:pdf_nobuiltin_tounicode_}{\.{\\pdfnobuiltintounicode} primitive@>
33899 primitive("pdfinterwordspaceon",extension,pdf_interword_space_on_node);@/
33900 @!@:pdf_interword_space_on_}{\.{\\pdfinterwordspaceon} primitive@>
33901 primitive("pdfinterwordspaceoff",extension,pdf_interword_space_off_node);@/
33902 @!@:pdf_interword_space_off_}{\.{\\pdfinterwordspaceoff} primitive@>
33903 primitive("pdffakespace",extension,pdf_fake_space_node);@/
33904 @!@:pdf_fake_space_}{\.{\\pdffakespace} primitive@>
33905 primitive("pdfrunninglinkoff",extension,pdf_running_link_off_node);@/
33906 @!@:pdf_running_link_off_}{\.{\\pdfrunninglinkoff} primitive@>
33907 primitive("pdfrunninglinkon",extension,pdf_running_link_on_node);@/
33908 @!@:pdf_running_link_on_}{\.{\\pdfrunninglinkon} primitive@>
33909 primitive("pdfspacefont",extension,pdf_space_font_code);@/
33910 @!@:pdf_space_font_}{\.{\\pdfspacefont} primitive@>
33911
33912 @ The variable |write_loc| just introduced is used to provide an
33913 appropriate error message in case of ``runaway'' write texts.
33914
33915 @<Glob...@>=
33916 @!write_loc:pointer; {|eqtb| address of \.{\\write}}
33917
33918 @ @<Cases of |print_cmd_chr|...@>=
33919 extension: case chr_code of
33920 open_node:print_esc("openout");
33921 write_node:print_esc("write");
33922 close_node:print_esc("closeout");
33923 special_node:print_esc("special");
33924 immediate_code:print_esc("immediate");
33925 set_language_code:print_esc("setlanguage");
33926 pdf_annot_node: print_esc("pdfannot");
33927 pdf_catalog_code: print_esc("pdfcatalog");
33928 pdf_dest_node: print_esc("pdfdest");
33929 pdf_end_link_node: print_esc("pdfendlink");
33930 pdf_end_thread_node: print_esc("pdfendthread");
33931 pdf_font_attr_code: print_esc("pdffontattr");
33932 pdf_font_expand_code: print_esc("pdffontexpand");
33933 pdf_include_chars_code: print_esc("pdfincludechars");
33934 pdf_info_code: print_esc("pdfinfo");
33935 pdf_literal_node: print_esc("pdfliteral");
33936 pdf_colorstack_node: print_esc("pdfcolorstack");
33937 pdf_setmatrix_node: print_esc("pdfsetmatrix");
33938 pdf_save_node: print_esc("pdfsave");
33939 pdf_restore_node: print_esc("pdfrestore");
33940 pdf_map_file_code: print_esc("pdfmapfile");
33941 pdf_map_line_code: print_esc("pdfmapline");
33942 pdf_names_code: print_esc("pdfnames");
33943 pdf_obj_code: print_esc("pdfobj");
33944 pdf_outline_code: print_esc("pdfoutline");
33945 pdf_refobj_node: print_esc("pdfrefobj");
33946 pdf_refxform_node: print_esc("pdfrefxform");
33947 pdf_refximage_node: print_esc("pdfrefximage");
33948 pdf_save_pos_node: print_esc("pdfsavepos");
33949 pdf_snap_ref_point_node: print_esc("pdfsnaprefpoint");
33950 pdf_snapy_comp_node: print_esc("pdfsnapycomp");
33951 pdf_snapy_node: print_esc("pdfsnapy");
33952 pdf_start_link_node: print_esc("pdfstartlink");
33953 pdf_start_thread_node: print_esc("pdfstartthread");
33954 pdf_thread_node: print_esc("pdfthread");
33955 pdf_trailer_code: print_esc("pdftrailer");
33956 pdf_trailer_id_code: print_esc("pdftrailerid");
33957 pdf_xform_code: print_esc("pdfxform");
33958 pdf_ximage_code: print_esc("pdfximage");
33959 reset_timer_code: print_esc("pdfresettimer");
33960 set_random_seed_code: print_esc("pdfsetrandomseed");
33961 pdf_nobuiltin_tounicode_code: print_esc("pdfnobuiltintounicode");
33962 pdf_glyph_to_unicode_code: print_esc("pdfglyphtounicode");
33963 pdf_interword_space_on_node: print_esc("pdfinterwordspaceon");
33964 pdf_interword_space_off_node: print_esc("pdfinterwordspaceoff");
33965 pdf_fake_space_node: print_esc("pdffakespace");
33966 pdf_running_link_off_node: print_esc("pdfrunninglinkoff");
33967 pdf_running_link_on_node: print_esc("pdfrunninglinkon");
33968 pdf_space_font_code: print_esc("pdfspacefont");
33969 othercases print("[unknown extension!]")
33970 endcases;
33971
33972 @ When an |extension| command occurs in |main_control|, in any mode,
33973 the |do_extension| routine is called.
33974
33975 @<Cases of |main_control| that are for extensions...@>=
33976 any_mode(extension):do_extension;
33977
33978 @ @<Declare act...@>=
33979 @t\4@>@<Declare procedures needed in |do_extension|@>@;
33980 procedure do_extension;
33981 var i,@!j,@!k:integer; {all-purpose integers}
33982 @!p,@!q,@!r:pointer; {all-purpose pointers}
33983 begin case cur_chr of
33984 open_node:@<Implement \.{\\openout}@>;
33985 write_node:@<Implement \.{\\write}@>;
33986 close_node:@<Implement \.{\\closeout}@>;
33987 special_node:@<Implement \.{\\special}@>;
33988 immediate_code:@<Implement \.{\\immediate}@>;
33989 set_language_code:@<Implement \.{\\setlanguage}@>;
33990 pdf_annot_node: @<Implement \.{\\pdfannot}@>;
33991 pdf_catalog_code: @<Implement \.{\\pdfcatalog}@>;
33992 pdf_dest_node: @<Implement \.{\\pdfdest}@>;
33993 pdf_end_link_node: @<Implement \.{\\pdfendlink}@>;
33994 pdf_end_thread_node: @<Implement \.{\\pdfendthread}@>;
33995 pdf_font_attr_code: @<Implement \.{\\pdffontattr}@>;
33996 pdf_font_expand_code: @<Implement \.{\\pdffontexpand}@>;
33997 pdf_include_chars_code: @<Implement \.{\\pdfincludechars}@>;
33998 pdf_info_code: @<Implement \.{\\pdfinfo}@>;
33999 pdf_literal_node: @<Implement \.{\\pdfliteral}@>;
34000 pdf_colorstack_node: @<Implement \.{\\pdfcolorstack}@>;
34001 pdf_setmatrix_node: @<Implement \.{\\pdfsetmatrix}@>;
34002 pdf_save_node: @<Implement \.{\\pdfsave}@>;
34003 pdf_restore_node: @<Implement \.{\\pdfrestore}@>;
34004 pdf_map_file_code: @<Implement \.{\\pdfmapfile}@>;
34005 pdf_map_line_code: @<Implement \.{\\pdfmapline}@>;
34006 pdf_names_code: @<Implement \.{\\pdfnames}@>;
34007 pdf_obj_code: @<Implement \.{\\pdfobj}@>;
34008 pdf_outline_code: @<Implement \.{\\pdfoutline}@>;
34009 pdf_refobj_node: @<Implement \.{\\pdfrefobj}@>;
34010 pdf_refxform_node: @<Implement \.{\\pdfrefxform}@>;
34011 pdf_refximage_node: @<Implement \.{\\pdfrefximage}@>;
34012 pdf_save_pos_node: @<Implement \.{\\pdfsavepos}@>;
34013 pdf_snap_ref_point_node: @<Implement \.{\\pdfsnaprefpoint}@>;
34014 pdf_snapy_comp_node: @<Implement \.{\\pdfsnapycomp}@>;
34015 pdf_snapy_node: @<Implement \.{\\pdfsnapy}@>;
34016 pdf_start_link_node: @<Implement \.{\\pdfstartlink}@>;
34017 pdf_start_thread_node: @<Implement \.{\\pdfstartthread}@>;
34018 pdf_thread_node: @<Implement \.{\\pdfthread}@>;
34019 pdf_trailer_code: @<Implement \.{\\pdftrailer}@>;
34020 pdf_trailer_id_code: @<Implement \.{\\pdftrailerid}@>;
34021 pdf_xform_code: @<Implement \.{\\pdfxform}@>;
34022 pdf_ximage_code: @<Implement \.{\\pdfximage}@>;
34023 reset_timer_code: @<Implement \.{\\pdfresettimer}@>;
34024 set_random_seed_code: @<Implement \.{\\pdfsetrandomseed}@>;
34025 pdf_glyph_to_unicode_code: @<Implement \.{\\pdfglyphtounicode}@>;
34026 pdf_nobuiltin_tounicode_code: @<Implement \.{\\pdfnobuiltintounicode}@>;
34027 pdf_interword_space_on_node: @<Implement \.{\\pdfinterwordspaceon}@>;
34028 pdf_interword_space_off_node: @<Implement \.{\\pdfinterwordspaceoff}@>;
34029 pdf_fake_space_node: @<Implement \.{\\pdffakespace}@>;
34030 pdf_running_link_off_node: @<Implement \.{\\pdfrunninglinkoff}@>;
34031 pdf_running_link_on_node: @<Implement \.{\\pdfrunninglinkon}@>;
34032 pdf_space_font_code: @<Implement \.{\\pdfspacefont}@>;
34033 othercases confusion("ext1")
34034 @:this can't happen ext1}{\quad ext1@>
34035 endcases;
34036 end;
34037
34038 @ Here is a subroutine that creates a whatsit node having a given |subtype|
34039 and a given number of words. It initializes only the first word of the whatsit,
34040 and appends it to the current list.
34041
34042 @<Declare procedures needed in |do_extension|@>=
34043 procedure new_whatsit(@!s:small_number;@!w:small_number);
34044 var p:pointer; {the new node}
34045 begin p:=get_node(w); type(p):=whatsit_node; subtype(p):=s;
34046 link(tail):=p; tail:=p;
34047 end;
34048
34049 @ The next subroutine uses |cur_chr| to decide what sort of whatsit is
34050 involved, and also inserts a |write_stream| number.
34051
34052 @<Declare procedures needed in |do_ext...@>=
34053 procedure new_write_whatsit(@!w:small_number);
34054 begin new_whatsit(cur_chr,w);
34055 if w<>write_node_size then scan_four_bit_int
34056 else begin scan_int;
34057 if cur_val<0 then cur_val:=17
34058 else if cur_val>15 then cur_val:=16;
34059 end;
34060 write_stream(tail):=cur_val;
34061 end;
34062
34063 @ @<Implement \.{\\openout}@>=
34064 begin new_write_whatsit(open_node_size);
34065 scan_optional_equals; scan_file_name;@/
34066 open_name(tail):=cur_name; open_area(tail):=cur_area; open_ext(tail):=cur_ext;
34067 end
34068
34069 @ When `\.{\\write 12\{...\}}' appears, we scan the token list `\.{\{...\}}'
34070 without expanding its macros; the macros will be expanded later when this
34071 token list is rescanned.
34072
34073 @<Implement \.{\\write}@>=
34074 begin k:=cur_cs; new_write_whatsit(write_node_size);@/
34075 cur_cs:=k; p:=scan_toks(false,false); write_tokens(tail):=def_ref;
34076 end
34077
34078 @ @<Implement \.{\\closeout}@>=
34079 begin new_write_whatsit(write_node_size); write_tokens(tail):=null;
34080 end
34081
34082 @ When `\.{\\special\{...\}}' appears, we expand the macros in the token
34083 list as in \.{\\xdef} and \.{\\mark}. When marked with \.{shipout}, we keep
34084 tokens unexpanded for now.
34085
34086 Unfortunately, the |write_stream(tail):=null| done here is not a valid
34087 assignment in Web2C, because |null| (a.k.a.\ |min_halfword|) is a large
34088 negative number ($-268435455 = -@"FFFFFFF$, set in \.{tex.ch}); too
34089 large to fit in the {\bf short} structure element that's being assigned.
34090 The warning from gcc~8.5.0 was:
34091
34092 \.{pdftex0.c: In function 'doextension':}
34093 \.{pdftex0.c:37849:40: warning: overflow in conversion from 'long int' to 'short int'}
34094 \.{changes value from '-268435455' to '1' [-Woverflow]}\hfil\break
34095 \.{ mem [curlist .tailfield + 1 ].hh.b0 = -268435455L ;}
34096
34097 The correct thing to do is not immediately evident. However, for Web2C,
34098 it does not matter, because these lines are changed for enc\TeX, in
34099 \.{enctex2.ch}, and now zero is assigned, instead of |null|.
34100
34101 @<Implement \.{\\special}@>=
34102 begin if scan_keyword("shipout") then
34103 begin new_whatsit(latespecial_node,write_node_size); write_stream(tail):=null;
34104 p:=scan_toks(false,false); write_tokens(tail):=def_ref;
34105 end else
34106 begin new_whatsit(special_node,write_node_size); write_stream(tail):=null;
34107 p:=scan_toks(false,true); write_tokens(tail):=def_ref;
34108 end; end
34109
34110 @ @<Implement \.{\\pdffontexpand}@>=
34111 read_expand_font
34112
34113 @ The following macros are needed for further manipulation with whatsit nodes
34114 for \pdfTeX{} extensions (copying, destroying, etc.).
34115
34116 @d add_action_ref(#) == incr(pdf_action_refcount(#)) {increase count of
34117 references to this action}
34118
34119 @d delete_action_ref(#) == {decrease count of references to this
34120 action; free it if there is no reference to this action}
34121 begin
34122 if pdf_action_refcount(#) = null then begin
34123 if pdf_action_type(#) = pdf_action_user then
34124 delete_token_ref(pdf_action_user_tokens(#))
34125 else begin
34126 if pdf_action_file(#) <> null then
34127 delete_token_ref(pdf_action_file(#));
34128 if pdf_action_type(#) = pdf_action_page then
34129 delete_token_ref(pdf_action_page_tokens(#))
34130 else if (pdf_action_named_id(#) and 1) = 1 then
34131 delete_token_ref(pdf_action_id(#));
34132 if (pdf_action_named_id(#) and 2) = 2 then
34133 delete_token_ref(pdf_action_struct_id(#));
34134 end;
34135 free_node(#, pdf_action_size);
34136 end
34137 else
34138 decr(pdf_action_refcount(#));
34139 end
34140
34141 @ We have to check whether \.{\\pdfoutput} is set for using \pdfTeX{}
34142 extensions.
34143 @<Declare procedures needed in |do_ext...@>=
34144 procedure check_pdfoutput(s: str_number; is_error : boolean);
34145 begin
34146 if pdf_output <= 0 then
34147 begin
34148 if is_error then
34149 pdf_error(s, "not allowed in DVI mode (\pdfoutput <= 0)")
34150 else
34151 pdf_warning(s, "not allowed in DVI mode (\pdfoutput <= 0); ignoring it", true, true);
34152 end
34153 end;
34154
34155 procedure scan_pdf_ext_toks;
34156 begin
34157 call_func(scan_toks(false, true)); {like \.{\\special}}
34158 end;
34159
34160 procedure scan_pdf_ext_late_toks;
34161 begin
34162 call_func(scan_toks(false, false)); {like \.{\\special}, but doesn't expand}
34163 end;
34164
34165 procedure compare_strings; {to implement \.{\\pdfstrcmp}}
34166 label done;
34167 var s1, s2: str_number;
34168 i1, i2, j1, j2: pool_pointer;
34169 save_cur_cs: pointer;
34170 begin
34171 save_cur_cs:=cur_cs; call_func(scan_toks(false, true));
34172 s1 := tokens_to_string(def_ref);
34173 delete_token_ref(def_ref);
34174 cur_cs:=save_cur_cs; call_func(scan_toks(false, true));
34175 s2 := tokens_to_string(def_ref);
34176 delete_token_ref(def_ref);
34177 i1 := str_start[s1];
34178 j1 := str_start[s1 + 1];
34179 i2 := str_start[s2];
34180 j2 := str_start[s2 + 1];
34181 while (i1 < j1) and (i2 < j2) do begin
34182 if str_pool[i1] < str_pool[i2] then begin
34183 cur_val := -1;
34184 goto done;
34185 end;
34186 if str_pool[i1] > str_pool[i2] then begin
34187 cur_val := 1;
34188 goto done;
34189 end;
34190 incr(i1);
34191 incr(i2);
34192 end;
34193 if (i1 = j1) and (i2 = j2) then
34194 cur_val := 0
34195 else if i1 < j1 then
34196 cur_val := 1
34197 else
34198 cur_val := -1;
34199 done:
34200 flush_str(s2);
34201 flush_str(s1);
34202 cur_val_level := int_val;
34203 end;
34204
34205 @ @<Implement \.{\\pdfliteral}@>=
34206 begin
34207 check_pdfoutput("\pdfliteral", true);
34208 if scan_keyword("shipout") then k:=pdf_lateliteral_node
34209 else k:=pdf_literal_node;
34210 new_whatsit(k, write_node_size);
34211 if scan_keyword("direct") then
34212 pdf_literal_mode(tail) := direct_always
34213 else if scan_keyword("page") then
34214 pdf_literal_mode(tail) := direct_page
34215 else
34216 pdf_literal_mode(tail) := set_origin;
34217 if k=pdf_literal_node then
34218 scan_pdf_ext_toks else scan_pdf_ext_late_toks;
34219 pdf_literal_data(tail) := def_ref;
34220 end
34221
34222 @ @<Implement \.{\\pdfcolorstack}@>=
34223 begin
34224 check_pdfoutput("\pdfcolorstack", true);
34225 {Scan and check the stack number and store in |cur_val|}
34226 scan_int;
34227 if cur_val >= colorstackused then begin
34228 print_err("Unknown color stack number ");
34229 print_int(cur_val);
34230 @.Unknown color stack@>
34231 help3("Allocate and initialize a color stack with \\pdfcolorstackinit.")@/
34232 ("I'll use default color stack 0 here.")@/
34233 ("Proceed, with fingers crossed.");
34234 error;
34235 cur_val := 0;
34236 end;
34237 if cur_val < 0 then begin
34238 print_err("Invalid negative color stack number");
34239 @.Invalid negative color stack number@>
34240 help2("I'll use default color stack 0 here.")@/
34241 ("Proceed, with fingers crossed.");
34242 error;
34243 cur_val := 0;
34244 end;
34245 {Scan the command and store in i, j holds the node size}
34246 if scan_keyword("set") then begin
34247 i := colorstack_set;
34248 j := pdf_colorstack_setter_node_size;
34249 end
34250 else if scan_keyword("push") then begin
34251 i := colorstack_push;
34252 j := pdf_colorstack_setter_node_size;
34253 end
34254 else if scan_keyword("pop") then begin
34255 i := colorstack_pop;
34256 j := pdf_colorstack_getter_node_size;
34257 end
34258 else if scan_keyword("current") then begin
34259 i := colorstack_current;
34260 j := pdf_colorstack_getter_node_size;
34261 end
34262 else begin
34263 i := -1; {error}
34264 end;
34265 if i >= 0 then begin
34266 new_whatsit(pdf_colorstack_node, j);
34267 pdf_colorstack_stack(tail) := cur_val;
34268 pdf_colorstack_cmd(tail) := i;
34269 if i <= colorstack_data then begin
34270 scan_pdf_ext_toks;
34271 pdf_colorstack_data(tail) := def_ref;
34272 end;
34273 end
34274 else begin
34275 print_err("Color stack action is missing");
34276 @.Color stack action is missing@>
34277 help3("The expected actions for \pdfcolorstack:")@/
34278 (" set, push, pop, current")@/
34279 ("I'll ignore the color stack command.");
34280 error;
34281 end
34282 end
34283
34284 @ @<Implement \.{\\pdfsetmatrix}@>=
34285 begin
34286 check_pdfoutput("\pdfsetmatrix", true);
34287 new_whatsit(pdf_setmatrix_node, pdf_setmatrix_node_size);
34288 scan_pdf_ext_toks;
34289 pdf_setmatrix_data(tail) := def_ref;
34290 end
34291
34292 @ @<Implement \.{\\pdfsave}@>=
34293 begin
34294 check_pdfoutput("\pdfsave", true);
34295 new_whatsit(pdf_save_node, pdf_save_node_size);
34296 end
34297
34298 @ @<Implement \.{\\pdfrestore}@>=
34299 begin
34300 check_pdfoutput("\pdfrestore", true);
34301 new_whatsit(pdf_restore_node, pdf_restore_node_size);
34302 end
34303
34304 @ The \.{\\pdfobj} primitive is used to create a ``raw'' object in the PDF
34305 output file. The object contents will be hold in memory and will be written
34306 out only when the object is referenced by \.{\\pdfrefobj}. When \.{\\pdfobj}
34307 is used with \.{\\immediate}, the object contents will be written out
34308 immediately. Objects referenced in the current page are appended into
34309 |pdf_obj_list|.
34310
34311 @<Glob...@>=
34312 @!pdf_last_obj: integer;
34313
34314 @ @<Implement \.{\\pdfobj}@>=
34315 begin
34316 check_pdfoutput("\pdfobj", true);
34317 if scan_keyword("reserveobjnum") then begin
34318 @<Scan an optional space@>;
34319 incr(pdf_obj_count);
34320 pdf_create_obj(obj_type_obj, pdf_obj_count);
34321 pdf_last_obj := obj_ptr;
34322 end
34323 else begin
34324 k := -1;
34325 if scan_keyword("useobjnum") then begin
34326 scan_int;
34327 k := cur_val;
34328 if (k <= 0) or (k > obj_ptr) or (obj_data_ptr(k) <> 0) then begin
34329 pdf_warning("\pdfobj", "invalid object number being ignored", true, true);
34330 pdf_retval := -1; {signal the problem}
34331 k := -1; {will be generated again}
34332 end;
34333 end;
34334 if k < 0 then begin
34335 incr(pdf_obj_count);
34336 pdf_create_obj(obj_type_obj, pdf_obj_count);
34337 k := obj_ptr;
34338 end;
34339 obj_data_ptr(k) := pdf_get_mem(pdfmem_obj_size);
34340 if scan_keyword("stream") then begin
34341 obj_obj_is_stream(k) := 1;
34342 if scan_keyword("attr") then begin
34343 scan_pdf_ext_toks;
34344 obj_obj_stream_attr(k) := def_ref;
34345 end
34346 else
34347 obj_obj_stream_attr(k) := null;
34348 end
34349 else
34350 obj_obj_is_stream(k) := 0;
34351 if scan_keyword("file") then
34352 obj_obj_is_file(k) := 1
34353 else
34354 obj_obj_is_file(k) := 0;
34355 scan_pdf_ext_toks;
34356 obj_obj_data(k) := def_ref;
34357 pdf_last_obj := k;
34358 end;
34359 end
34360
34361 @ We need to check whether the referenced object exists.
34362
34363 @<Declare procedures that need to be declared forward for \pdfTeX@>=
34364 function prev_rightmost(s, e: pointer): pointer;
34365 {finds the node preceding the rightmost node |e|; |s| is some node
34366 before |e|}
34367 var p: pointer;
34368 begin
34369 prev_rightmost := null;
34370 p := s;
34371 if p = null then
34372 return;
34373 while link(p) <> e do begin
34374 p := link(p);
34375 if p = null then
34376 return;
34377 end;
34378 prev_rightmost := p;
34379 end;
34380
34381 procedure pdf_check_obj(t, n: integer);
34382 var k: integer;
34383 begin
34384 k := head_tab[t];
34385 while (k <> 0) and (k <> n) do
34386 k := obj_link(k);
34387 if k = 0 then
34388 pdf_error("ext1", "cannot find referenced object");
34389 end;
34390
34391 @ @<Implement \.{\\pdfrefobj}@>=
34392 begin
34393 check_pdfoutput("\pdfrefobj", true);
34394 scan_int;
34395 pdf_check_obj(obj_type_obj, cur_val);
34396 new_whatsit(pdf_refobj_node, pdf_refobj_node_size);
34397 pdf_obj_objnum(tail) := cur_val;
34398 end
34399
34400 @ \.{\\pdfxform} and \.{\\pdfrefxform} are similar to \.{\\pdfobj} and
34401 \.{\\pdfrefobj}.
34402
34403 @<Glob...@>=
34404 @!pdf_last_xform: integer;
34405
34406 @ @<Implement \.{\\pdfxform}@>=
34407 begin
34408 check_pdfoutput("\pdfxform", true);
34409 incr(pdf_xform_count);
34410 pdf_create_obj(obj_type_xform, pdf_xform_count);
34411 k := obj_ptr;
34412 obj_data_ptr(k) := pdf_get_mem(pdfmem_xform_size);
34413 if scan_keyword("attr") then begin
34414 scan_pdf_ext_toks;
34415 obj_xform_attr(k) := def_ref;
34416 end
34417 else
34418 obj_xform_attr(k) := null;
34419 if scan_keyword("resources") then begin
34420 scan_pdf_ext_toks;
34421 obj_xform_resources(k) := def_ref;
34422 end
34423 else
34424 obj_xform_resources(k) := null;
34425 scan_register_num;
34426 fetch_box(p);
34427 if p = null then
34428 pdf_error("ext1", "\pdfxform cannot be used with a void box");
34429 obj_xform_width(k) := width(p);
34430 obj_xform_height(k) := height(p);
34431 obj_xform_depth(k) := depth(p);
34432 obj_xform_box(k) := p; {save pointer to the box}
34433 change_box(null);
34434 pdf_last_xform := k;
34435 end
34436
34437 @ @<Implement \.{\\pdfrefxform}@>=
34438 begin
34439 check_pdfoutput("\pdfrefxform", true);
34440 scan_int;
34441 pdf_check_obj(obj_type_xform, cur_val);
34442 new_whatsit(pdf_refxform_node, pdf_refxform_node_size);
34443 pdf_xform_objnum(tail) := cur_val;
34444 pdf_width(tail) := obj_xform_width(cur_val);
34445 pdf_height(tail) := obj_xform_height(cur_val);
34446 pdf_depth(tail) := obj_xform_depth(cur_val);
34447 end
34448
34449 @ \.{\\pdfximage} and \.{\\pdfrefximage} are similar to \.{\\pdfxform} and
34450 \.{\\pdfrefxform}. As we have to scan |<rule spec>| quite often, it is better
34451 have a |rule_node| that holds the most recently scanned |<rule spec>|.
34452
34453 @<Glob...@>=
34454 @!pdf_last_ximage: integer;
34455 @!pdf_last_ximage_pages: integer;
34456 @!pdf_last_ximage_colordepth: integer;
34457 @!alt_rule: pointer;
34458 @!warn_pdfpagebox: boolean;
34459
34460 @ @<Set init...@>=
34461 alt_rule := null;
34462 warn_pdfpagebox := true;
34463
34464 @ @<Declare procedures needed in |do_ext...@>=
34465 procedure scale_image(n: integer);
34466 var x, y, xr, yr: integer; {size and resolution of image}
34467 w, h: scaled; {indeed size corresponds to image resolution}
34468 default_res: integer;
34469 image: integer;
34470 begin
34471 image := obj_ximage_data(n);
34472 if (image_rotate(image) = 90) or (image_rotate(image) = 270) then begin
34473 y := image_width(image);
34474 x := image_height(image);
34475 yr := image_x_res(image);
34476 xr := image_y_res(image);
34477 end else begin
34478 x := image_width(image);
34479 y := image_height(image);
34480 xr := image_x_res(image);
34481 yr := image_y_res(image);
34482 end;
34483
34484 if (xr > 65535) or (yr > 65535) then begin
34485 xr := 0;
34486 yr := 0;
34487 pdf_warning("ext1", "too large image resolution ignored", true, true);
34488 end;
34489 if (x <= 0) or (y <= 0) or (xr < 0) or (yr < 0) then
34490 pdf_error("ext1", "invalid image dimensions");
34491 if (xr = 0) and (yr = 0) then begin
34492 {If both resolutions are zero, that suggests that the resolution data
34493 is missing, so we should never issue a warning.}
34494 end
34495 else if (x / one_inch >= xr) or (y / one_inch >= yr) then begin
34496 {It's better to warn and ignore too-small resolutions given in
34497 the image file, usually 1dpi x 1dpi, to avoid arithmetic overflow.}
34498 xr := 0;
34499 yr := 0;
34500 pdf_warning("ext1", "too small image resolution ignored", true, true);
34501 end;
34502 if is_pdf_image(image) then begin
34503 w := x;
34504 h := y;
34505 end
34506 else begin
34507 default_res := fix_int(pdf_image_resolution, 0, 65535);
34508 if (default_res > 0) and ((xr = 0) or (yr = 0)) then begin
34509 xr := default_res;
34510 yr := default_res;
34511 end;
34512 if is_running(obj_ximage_width(n)) and
34513 is_running(obj_ximage_height(n)) then
34514 begin
34515 if (xr > 0) and (yr > 0) then begin
34516 w := ext_xn_over_d(one_hundred_inch, x, 100*xr);
34517 h := ext_xn_over_d(one_hundred_inch, y, 100*yr);
34518 end
34519 else begin
34520 w := ext_xn_over_d(one_hundred_inch, x, 7200);
34521 h := ext_xn_over_d(one_hundred_inch, y, 7200);
34522 end;
34523 end;
34524 end;
34525 if is_running(obj_ximage_width(n)) and is_running(obj_ximage_height(n)) and
34526 is_running(obj_ximage_depth(n)) then begin
34527 obj_ximage_width(n) := w;
34528 obj_ximage_height(n) := h;
34529 obj_ximage_depth(n) := 0;
34530 end
34531 else if is_running(obj_ximage_width(n)) then begin
34532 {image depth or height is explicitly specified}
34533 if is_running(obj_ximage_height(n)) then begin
34534 {image depth is explicitly specified}
34535 obj_ximage_width(n) := ext_xn_over_d(h, x, y);
34536 obj_ximage_height(n) := h - obj_ximage_depth(n);
34537 end
34538 else if is_running(obj_ximage_depth(n)) then begin
34539 {image height is explicitly specified}
34540 obj_ximage_width(n) := ext_xn_over_d(obj_ximage_height(n), x, y);
34541 obj_ximage_depth(n) := 0;
34542 end
34543 else begin
34544 {both image depth and height are explicitly specified}
34545 obj_ximage_width(n) := ext_xn_over_d(obj_ximage_height(n) +
34546 obj_ximage_depth(n), x, y);
34547 end;
34548 end
34549 else begin
34550 {image width is explicitly specified}
34551 if is_running(obj_ximage_height(n)) and
34552 is_running(obj_ximage_depth(n)) then begin
34553 {both image depth and height are not specified}
34554 obj_ximage_height(n) := ext_xn_over_d(obj_ximage_width(n), y, x);
34555 obj_ximage_depth(n) := 0;
34556 end
34557 {image depth is explicitly specified}
34558 else if is_running(obj_ximage_height(n)) then begin
34559 obj_ximage_height(n) :=
34560 ext_xn_over_d(obj_ximage_width(n), y, x) - obj_ximage_depth(n);
34561 end
34562 {image height is explicitly specified}
34563 else if is_running(obj_ximage_depth(n)) then begin
34564 obj_ximage_depth(n) := 0;
34565 end
34566 {both image depth and height are explicitly specified}
34567 else
34568 do_nothing;
34569 end;
34570 end;
34571
34572 function scan_pdf_box_spec: integer; {scans PDF pagebox specification}
34573 begin
34574 scan_pdf_box_spec := 0;
34575 if scan_keyword("mediabox") then
34576 scan_pdf_box_spec := pdf_box_spec_media
34577 else if scan_keyword("cropbox") then
34578 scan_pdf_box_spec := pdf_box_spec_crop
34579 else if scan_keyword("bleedbox") then
34580 scan_pdf_box_spec := pdf_box_spec_bleed
34581 else if scan_keyword("trimbox") then
34582 scan_pdf_box_spec := pdf_box_spec_trim
34583 else if scan_keyword("artbox") then
34584 scan_pdf_box_spec := pdf_box_spec_art
34585 end;
34586
34587 procedure scan_alt_rule; {scans rule spec to |alt_rule|}
34588 label reswitch;
34589 begin
34590 if alt_rule = null then
34591 alt_rule := new_rule;
34592 width(alt_rule) := null_flag;
34593 height(alt_rule) := null_flag;
34594 depth(alt_rule) := null_flag;
34595 reswitch:
34596 if scan_keyword("width") then begin
34597 scan_normal_dimen;
34598 width(alt_rule) := cur_val;
34599 goto reswitch;
34600 end;
34601 if scan_keyword("height") then begin
34602 scan_normal_dimen;
34603 height(alt_rule) := cur_val;
34604 goto reswitch;
34605 end;
34606 if scan_keyword("depth") then begin
34607 scan_normal_dimen;
34608 depth(alt_rule) := cur_val;
34609 goto reswitch;
34610 end;
34611 end;
34612
34613 procedure scan_image;
34614 label reswitch;
34615 var k: integer;
34616 named: str_number;
34617 s: str_number;
34618 page, pagebox, colorspace: integer;
34619 begin
34620 incr(pdf_ximage_count);
34621 pdf_create_obj(obj_type_ximage, pdf_ximage_count);
34622 k := obj_ptr;
34623 obj_data_ptr(k) := pdf_get_mem(pdfmem_ximage_size);
34624 scan_alt_rule; {scans |<rule spec>| to |alt_rule|}
34625 obj_ximage_width(k) := width(alt_rule);
34626 obj_ximage_height(k) := height(alt_rule);
34627 obj_ximage_depth(k) := depth(alt_rule);
34628 if scan_keyword("attr") then begin
34629 scan_pdf_ext_toks;
34630 obj_ximage_attr(k) := def_ref;
34631 end
34632 else
34633 obj_ximage_attr(k) := null;
34634 named := 0;
34635 if scan_keyword("named") then begin
34636 scan_pdf_ext_toks;
34637 named := tokens_to_string(def_ref);
34638 delete_token_ref(def_ref);
34639 end
34640 else if scan_keyword("page") then begin
34641 scan_int;
34642 page := cur_val;
34643 end
34644 else
34645 page := 1;
34646 if scan_keyword("colorspace") then begin
34647 scan_int;
34648 colorspace := cur_val;
34649 end
34650 else
34651 colorspace := 0;
34652 pagebox := scan_pdf_box_spec;
34653 if pagebox = 0 then
34654 pagebox := pdf_pagebox;
34655 scan_pdf_ext_toks;
34656 s := tokens_to_string(def_ref);
34657 delete_token_ref(def_ref);
34658 if pdf_option_always_use_pdfpagebox <> 0 then begin
34659 pdf_warning("PDF inclusion", "Primitive \pdfoptionalwaysusepdfpagebox is obsolete; use \pdfpagebox instead.", true, true);
34660 pdf_force_pagebox := pdf_option_always_use_pdfpagebox;
34661 pdf_option_always_use_pdfpagebox := 0; {warn once}
34662 warn_pdfpagebox := false;
34663 end;
34664 if pdf_option_pdf_inclusion_errorlevel <> 0 then begin
34665 pdf_warning("PDF inclusion", "Primitive \pdfoptionpdfinclusionerrorlevel is obsolete; use \pdfinclusionerrorlevel instead.", true, true);
34666 pdf_inclusion_errorlevel := pdf_option_pdf_inclusion_errorlevel;
34667 pdf_option_pdf_inclusion_errorlevel := 0; {warn once}
34668 end;
34669 if pdf_force_pagebox > 0 then begin
34670 if warn_pdfpagebox then begin
34671 pdf_warning("PDF inclusion", "Primitive \pdfforcepagebox is obsolete; use \pdfpagebox instead.", true, true);
34672 warn_pdfpagebox := false;
34673 end;
34674 pagebox := pdf_force_pagebox;
34675 end;
34676 if pagebox = 0 then {no pagebox specification given}
34677 pagebox := pdf_box_spec_crop;
34678 obj_ximage_data(k) := read_image(s, page, named, colorspace, pagebox,
34679 pdf_major_version, pdf_minor_version,
34680 pdf_inclusion_errorlevel);
34681 if named <> 0 then flush_str(named);
34682 flush_str(s);
34683 scale_image(k);
34684 pdf_last_ximage := k;
34685 pdf_last_ximage_pages := image_pages(obj_ximage_data(k));
34686 pdf_last_ximage_colordepth := image_colordepth(obj_ximage_data(k));
34687 end;
34688
34689 @ @<Implement \.{\\pdfximage}@>=
34690 begin
34691 check_pdfoutput("\pdfximage", true);
34692 check_pdfversion;
34693 scan_image;
34694 end
34695
34696 @ @<Implement \.{\\pdfrefximage}@>=
34697 begin
34698 check_pdfoutput("\pdfrefximage", true);
34699 scan_int;
34700 pdf_check_obj(obj_type_ximage, cur_val);
34701 new_whatsit(pdf_refximage_node, pdf_refximage_node_size);
34702 pdf_ximage_objnum(tail) := cur_val;
34703 pdf_width(tail) := obj_ximage_width(cur_val);
34704 pdf_height(tail) := obj_ximage_height(cur_val);
34705 pdf_depth(tail) := obj_ximage_depth(cur_val);
34706 end
34707
34708 @ The following function finds object with identifier |i| and type |t|.
34709 |i < 0| indicates that |-i| should be treated as a string number. If no
34710 such object exists then it will be created. This function is used mainly to
34711 find destination for link annotations and outlines; however it is also used
34712 in |pdf_ship_out| (to check whether a Page object already exists) so we need
34713 to declare it together with subroutines needed in |pdf_hlist_out| and
34714 |pdf_vlist_out|.
34715
34716 @<Declare procedures that need to be declared forward for \pdfTeX@>=
34717 function find_obj(t, i: integer; byname: boolean): integer;
34718 begin
34719 find_obj := avl_find_obj(t, i, byname);
34720 end;
34721
34722 procedure flush_str(s: str_number); {flush a string if possible}
34723 begin
34724 if flushable(s) then
34725 flush_string;
34726 end;
34727
34728 function get_obj(t, i: integer; byname: boolean): integer;
34729 var r: integer;
34730 s: str_number;
34731 begin
34732 if byname > 0 then begin
34733 s := tokens_to_string(i);
34734 r := find_obj(t, s, true);
34735 end
34736 else begin
34737 s := 0;
34738 r := find_obj(t, i, false);
34739 end;
34740 if r = 0 then begin
34741 if byname > 0 then begin
34742 pdf_create_obj(t, -s);
34743 s := 0;
34744 end
34745 else
34746 pdf_create_obj(t, i);
34747 r := obj_ptr;
34748 if (t = obj_type_dest) or (t = obj_type_struct_dest) then
34749 obj_dest_ptr(r) := null;
34750 end;
34751 if s <> 0 then
34752 flush_str(s);
34753 get_obj := r;
34754 end;
34755
34756 function get_microinterval:integer;
34757 var s,@!m:integer; {seconds and microseconds}
34758 begin
34759 seconds_and_micros(s,m);
34760 if (s-epochseconds)>32767 then
34761 get_microinterval := max_integer
34762 else if (microseconds>m) then
34763 get_microinterval := ((s-1-epochseconds)*65536)+ (((m+1000000-microseconds)/100)*65536)/10000
34764 else
34765 get_microinterval := ((s-epochseconds)*65536) + (((m-microseconds)/100)*65536)/10000;
34766 end;
34767
34768
34769 @ @<Declare procedures needed in |do_ext...@>=
34770 function scan_action: pointer; {read an action specification}
34771 var p: integer;
34772 begin
34773 p := get_node(pdf_action_size);
34774 scan_action := p;
34775 pdf_action_file(p) := null;
34776 pdf_action_refcount(p) := null;
34777 if scan_keyword("user") then
34778 pdf_action_type(p) := pdf_action_user
34779 else if scan_keyword("goto") then
34780 pdf_action_type(p) := pdf_action_goto
34781 else if scan_keyword("thread") then
34782 pdf_action_type(p) := pdf_action_thread
34783 else
34784 pdf_error("ext1", "action type missing");
34785 if pdf_action_type(p) = pdf_action_user then begin
34786 scan_pdf_ext_toks;
34787 pdf_action_user_tokens(p) := def_ref;
34788 return;
34789 end;
34790 pdf_action_named_id(p) := 0;
34791 if scan_keyword("file") then begin
34792 scan_pdf_ext_toks;
34793 pdf_action_file(p) := def_ref;
34794 end;
34795 if scan_keyword("struct") then begin
34796 if pdf_action_type(p) <> pdf_action_goto then
34797 pdf_error("ext1", "only GoTo action can be used with `struct'");
34798 if pdf_action_file(p) <> null then begin
34799 scan_pdf_ext_toks;
34800 pdf_action_named_id(p) := pdf_action_named_id(p) + 2;
34801 pdf_action_struct_id(p) := def_ref;
34802 end
34803 else if scan_keyword("name") then begin
34804 scan_pdf_ext_toks;
34805 pdf_action_named_id(p) := pdf_action_named_id(p) + 2;
34806 pdf_action_struct_id(p) := def_ref;
34807 end
34808 else if scan_keyword("num") then begin
34809 scan_int;
34810 if cur_val <= 0 then
34811 pdf_error("ext1", "num identifier must be positive");
34812 pdf_action_struct_id(p) := cur_val;
34813 end
34814 else
34815 pdf_error("ext1", "identifier type missing");
34816 end
34817 else
34818 pdf_action_struct_id(p) := null;
34819 if scan_keyword("page") then begin
34820 if pdf_action_type(p) <> pdf_action_goto then
34821 pdf_error("ext1", "only GoTo action can be used with `page'");
34822 pdf_action_type(p) := pdf_action_page;
34823 scan_int;
34824 if cur_val <= 0 then
34825 pdf_error("ext1", "page number must be positive");
34826 pdf_action_id(p) := cur_val;
34827 scan_pdf_ext_toks;
34828 pdf_action_page_tokens(p) := def_ref;
34829 end
34830 else if scan_keyword("name") then begin
34831 scan_pdf_ext_toks;
34832 pdf_action_named_id(p) := pdf_action_named_id(p) + 1;
34833 pdf_action_id(p) := def_ref;
34834 end
34835 else if scan_keyword("num") then begin
34836 if (pdf_action_type(p) = pdf_action_goto) and
34837 (pdf_action_file(p) <> null) then
34838 pdf_error("ext1",
34839 "`goto' option cannot be used with both `file' and `num'");
34840 scan_int;
34841 if cur_val <= 0 then
34842 pdf_error("ext1", "num identifier must be positive");
34843 pdf_action_id(p) := cur_val;
34844 end
34845 else
34846 pdf_error("ext1", "identifier type missing");
34847 if scan_keyword("newwindow") then begin
34848 pdf_action_new_window(p) := 1;
34849 @<Scan an optional space@>; end
34850 else if scan_keyword("nonewwindow") then begin
34851 pdf_action_new_window(p) := 2;
34852 @<Scan an optional space@>; end
34853 else
34854 pdf_action_new_window(p) := 0;
34855 if (pdf_action_new_window(p) > 0) and
34856 (((pdf_action_type(p) <> pdf_action_goto) and
34857 (pdf_action_type(p) <> pdf_action_page)) or
34858 (pdf_action_file(p) = null)) then
34859 pdf_error("ext1",
34860 "`newwindow'/`nonewwindow' must be used with `goto' and `file' option");
34861 end;
34862
34863 procedure new_annot_whatsit(w, s: small_number); {create a new whatsit node for
34864 annotation}
34865 begin
34866 new_whatsit(w, s);
34867 scan_alt_rule; {scans |<rule spec>| to |alt_rule|}
34868 pdf_width(tail) := width(alt_rule);
34869 pdf_height(tail) := height(alt_rule);
34870 pdf_depth(tail) := depth(alt_rule);
34871 if (w = pdf_start_link_node) then begin
34872 if scan_keyword("attr") then begin
34873 scan_pdf_ext_toks;
34874 pdf_link_attr(tail) := def_ref;
34875 end
34876 else
34877 pdf_link_attr(tail) := null;
34878 end;
34879 if (w = pdf_thread_node) or (w = pdf_start_thread_node) then begin
34880 if scan_keyword("attr") then begin
34881 scan_pdf_ext_toks;
34882 pdf_thread_attr(tail) := def_ref;
34883 end
34884 else
34885 pdf_thread_attr(tail) := null;
34886 end;
34887 end;
34888
34889 @ @<Glob...@>=
34890 @!pdf_last_annot: integer;
34891
34892 @ @<Implement \.{\\pdfannot}@>=
34893 begin
34894 check_pdfoutput("\pdfannot", true);
34895 if scan_keyword("reserveobjnum") then begin
34896 pdf_last_annot := pdf_new_objnum;
34897 @<Scan an optional space@>; end
34898 else begin
34899 if scan_keyword("useobjnum") then begin
34900 scan_int;
34901 k := cur_val;
34902 if (k <= 0) or (k > obj_ptr) or (obj_annot_ptr(k) <> 0) then
34903 pdf_error("ext1", "invalid object number");
34904 end
34905 else
34906 k := pdf_new_objnum;
34907 new_annot_whatsit(pdf_annot_node, pdf_annot_node_size);
34908 pdf_annot_objnum(tail) := k;
34909 scan_pdf_ext_toks;
34910 pdf_annot_data(tail) := def_ref;
34911 pdf_last_annot := k;
34912 end
34913 end
34914
34915 @ \.{\\pdflastlink} needs an extra global variable.
34916 @<Glob...@>=
34917 @!pdf_last_link: integer;
34918
34919 @ @<Implement \.{\\pdfstartlink}@>=
34920 begin
34921 check_pdfoutput("\pdfstartlink", true);
34922 if abs(mode) = vmode then
34923 pdf_error("ext1", "\pdfstartlink cannot be used in vertical mode");
34924 k := pdf_new_objnum;
34925 new_annot_whatsit(pdf_start_link_node, pdf_annot_node_size);
34926 pdf_link_action(tail) := scan_action;
34927 pdf_link_objnum(tail) := k;
34928 pdf_last_link := k;
34929 {N.B.: although it is possible to set |obj_annot_ptr(k) := tail| here, it
34930 is not safe if nodes are later copied/destroyed/moved; a better place
34931 to do this is inside |do_link|, when the whatsit node is written out}
34932 end
34933
34934 @ @<Implement \.{\\pdfendlink}@>=
34935 begin
34936 check_pdfoutput("\pdfendlink", true);
34937 if abs(mode) = vmode then
34938 pdf_error("ext1", "\pdfendlink cannot be used in vertical mode");
34939 new_whatsit(pdf_end_link_node, small_node_size);
34940 end
34941
34942 @ @<Declare procedures needed in |do_ext...@>=
34943 function outline_list_count(p: pointer): integer; {return number of outline
34944 entries in the same level with |p|}
34945 var k: integer;
34946 begin
34947 k := 1;
34948 while obj_outline_prev(p) <> 0 do begin
34949 incr(k);
34950 p := obj_outline_prev(p);
34951 end;
34952 outline_list_count := k;
34953 end;
34954
34955 @ @<Implement \.{\\pdfoutline}@>=
34956 begin
34957 check_pdfoutput("\pdfoutline", true);
34958 if scan_keyword("attr") then begin
34959 scan_pdf_ext_toks;
34960 r := def_ref;
34961 end
34962 else
34963 r := 0;
34964 p := scan_action;
34965 if scan_keyword("count") then begin
34966 scan_int;
34967 i := cur_val;
34968 end
34969 else
34970 i := 0;
34971 scan_pdf_ext_toks;
34972 q := def_ref;
34973 pdf_new_obj(obj_type_others, 0, 1);
34974 j := obj_ptr;
34975 write_action(p);
34976 pdf_end_obj;
34977 delete_action_ref(p);
34978 pdf_create_obj(obj_type_outline, 0);
34979 k := obj_ptr;
34980 obj_outline_ptr(k) := pdf_get_mem(pdfmem_outline_size);
34981 obj_outline_action_objnum(k) := j;
34982 obj_outline_count(k) := i;
34983 pdf_new_obj(obj_type_others, 0, 1);
34984 pdf_print_str_ln(tokens_to_string(q));
34985 flush_str(last_tokens_string);
34986 delete_token_ref(q);
34987 pdf_end_obj;
34988 obj_outline_title(k) := obj_ptr;
34989 obj_outline_prev(k) := 0;
34990 obj_outline_next(k) := 0;
34991 obj_outline_first(k) := 0;
34992 obj_outline_last(k) := 0;
34993 obj_outline_parent(k) := pdf_parent_outline;
34994 obj_outline_attr(k) := r;
34995 if pdf_first_outline = 0 then
34996 pdf_first_outline := k;
34997 if pdf_last_outline = 0 then begin
34998 if pdf_parent_outline <> 0 then
34999 obj_outline_first(pdf_parent_outline) := k;
35000 end
35001 else begin
35002 obj_outline_next(pdf_last_outline) := k;
35003 obj_outline_prev(k) := pdf_last_outline;
35004 end;
35005 pdf_last_outline := k;
35006 if obj_outline_count(k) <> 0 then begin
35007 pdf_parent_outline := k;
35008 pdf_last_outline := 0;
35009 end
35010 else if (pdf_parent_outline <> 0) and
35011 (outline_list_count(k) = abs(obj_outline_count(pdf_parent_outline))) then
35012 begin
35013 j := pdf_last_outline;
35014 repeat
35015 obj_outline_last(pdf_parent_outline) := j;
35016 j := pdf_parent_outline;
35017 pdf_parent_outline := obj_outline_parent(pdf_parent_outline);
35018 until (pdf_parent_outline = 0) or
35019 (outline_list_count(j) < abs(obj_outline_count(pdf_parent_outline)));
35020 if pdf_parent_outline = 0 then
35021 pdf_last_outline := pdf_first_outline
35022 else
35023 pdf_last_outline := obj_outline_first(pdf_parent_outline);
35024 while obj_outline_next(pdf_last_outline) <> 0 do
35025 pdf_last_outline := obj_outline_next(pdf_last_outline);
35026 end;
35027 end
35028
35029 @ When a destination is created we need to check whether another destination
35030 with the same identifier already exists and give a warning if needed.
35031
35032 @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
35033 procedure warn_dest_dup(id: integer; byname: small_number; s1, s2: str_number);
35034 begin
35035 if pdf_suppress_warning_dup_dest > 0 then
35036 return;
35037 pdf_warning(s1, "destination with the same identifier (", true, false);
35038 if byname > 0 then begin
35039 print("name");
35040 print_mark(id);
35041 end
35042 else begin
35043 print("num");
35044 print_int(id);
35045 end;
35046 print(") ");
35047 print(s2);
35048 print_ln;
35049 show_context;
35050 end;
35051
35052 @ Notice that |scan_keyword| doesn't care if two words have same prefix; so
35053 we should be careful when scan keywords with same prefix. The main rule: if
35054 there are two or more keywords with the same prefix, then always test in
35055 order from the longest one to the shortest one.
35056
35057 @<Implement \.{\\pdfdest}@>=
35058 begin
35059 check_pdfoutput("\pdfdest", true);
35060 q := tail;
35061 new_whatsit(pdf_dest_node, pdf_dest_node_size);
35062 if scan_keyword("struct") then begin
35063 scan_int;
35064 if cur_val <= 0 then
35065 pdf_error("ext1", "struct identifier must be positive");
35066 pdf_dest_objnum(tail) := cur_val;
35067 j := obj_type_struct_dest;
35068 end else begin
35069 pdf_dest_objnum(tail) := null;
35070 j := obj_type_dest;
35071 end;
35072 if scan_keyword("num") then begin
35073 scan_int;
35074 if cur_val <= 0 then
35075 pdf_error("ext1", "num identifier must be positive");
35076 if cur_val > max_halfword then
35077 pdf_error("ext1", "number too big");
35078 pdf_dest_id(tail) := cur_val;
35079 pdf_dest_named_id(tail) := 0;
35080 end
35081 else if scan_keyword("name") then begin
35082 scan_pdf_ext_toks;
35083 pdf_dest_id(tail) := def_ref;
35084 pdf_dest_named_id(tail) := 1;
35085 end
35086 else
35087 pdf_error("ext1", "identifier type missing");
35088 if scan_keyword("xyz") then begin
35089 pdf_dest_type(tail) := pdf_dest_xyz;
35090 if scan_keyword("zoom") then begin
35091 scan_int;
35092 if cur_val > max_halfword then
35093 pdf_error("ext1", "number too big");
35094 pdf_dest_xyz_zoom(tail) := cur_val;
35095 end
35096 else
35097 pdf_dest_xyz_zoom(tail) := null;
35098 end
35099 else if scan_keyword("fitbh") then
35100 pdf_dest_type(tail) := pdf_dest_fitbh
35101 else if scan_keyword("fitbv") then
35102 pdf_dest_type(tail) := pdf_dest_fitbv
35103 else if scan_keyword("fitb") then
35104 pdf_dest_type(tail) := pdf_dest_fitb
35105 else if scan_keyword("fith") then
35106 pdf_dest_type(tail) := pdf_dest_fith
35107 else if scan_keyword("fitv") then
35108 pdf_dest_type(tail) := pdf_dest_fitv
35109 else if scan_keyword("fitr") then
35110 pdf_dest_type(tail) := pdf_dest_fitr
35111 else if scan_keyword("fit") then
35112 pdf_dest_type(tail) := pdf_dest_fit
35113 else
35114 pdf_error("ext1", "destination type missing");
35115 @<Scan an optional space@>;
35116 if pdf_dest_type(tail) = pdf_dest_fitr then begin
35117 scan_alt_rule; {scans |<rule spec>| to |alt_rule|}
35118 pdf_width(tail) := width(alt_rule);
35119 pdf_height(tail) := height(alt_rule);
35120 pdf_depth(tail) := depth(alt_rule);
35121 end;
35122 if pdf_dest_named_id(tail) <> 0 then begin
35123 i := tokens_to_string(pdf_dest_id(tail));
35124 k := find_obj(j, i, true);
35125 flush_str(i);
35126 end
35127 else
35128 k := find_obj(j, pdf_dest_id(tail), false);
35129 if (k <> 0) and (obj_dest_ptr(k) <> null) then begin
35130 warn_dest_dup(pdf_dest_id(tail), pdf_dest_named_id(tail),
35131 "ext4", "has been already used, duplicate ignored");
35132 flush_node_list(tail);
35133 tail := q;
35134 link(q) := null;
35135 end;
35136 end
35137
35138 @ @<Declare procedures needed in |do_ext...@>=
35139 procedure scan_thread_id;
35140 begin
35141 if scan_keyword("num") then begin
35142 scan_int;
35143 if cur_val <= 0 then
35144 pdf_error("ext1", "num identifier must be positive");
35145 if cur_val > max_halfword then
35146 pdf_error("ext1", "number too big");
35147 pdf_thread_id(tail) := cur_val;
35148 pdf_thread_named_id(tail) := 0;
35149 end
35150 else if scan_keyword("name") then begin
35151 scan_pdf_ext_toks;
35152 pdf_thread_id(tail) := def_ref;
35153 pdf_thread_named_id(tail) := 1;
35154 end
35155 else
35156 pdf_error("ext1", "identifier type missing");
35157 end;
35158
35159 @ @<Implement \.{\\pdfthread}@>=
35160 begin
35161 check_pdfoutput("\pdfthread", true);
35162 new_annot_whatsit(pdf_thread_node, pdf_thread_node_size);
35163 scan_thread_id;
35164 end
35165
35166 @ @<Implement \.{\\pdfstartthread}@>=
35167 begin
35168 check_pdfoutput("\pdfstartthread", true);
35169 new_annot_whatsit(pdf_start_thread_node, pdf_thread_node_size);
35170 scan_thread_id;
35171 end
35172
35173 @ @<Implement \.{\\pdfendthread}@>=
35174 begin
35175 check_pdfoutput("\pdfendthread", true);
35176 new_whatsit(pdf_end_thread_node, small_node_size);
35177 end
35178
35179 @ @<Glob...@>=
35180 @!pdf_last_x_pos: integer;
35181 @!pdf_last_y_pos: integer;
35182 @!pdf_snapx_refpos: integer;
35183 @!pdf_snapy_refpos: integer;
35184 @!count_do_snapy: integer;
35185
35186 @ @<Set init...@>=
35187 count_do_snapy := 0;
35188
35189 @ @<Implement \.{\\pdfsnaprefpoint}@>=
35190 begin
35191 check_pdfoutput("\pdfsnaprefpoint", true);
35192 new_whatsit(pdf_snap_ref_point_node, small_node_size);
35193 end
35194
35195 @ @<Declare procedures needed in |do_ext...@>=
35196 function new_snap_node(s: small_number): pointer;
35197 var p: pointer;
35198 begin
35199 scan_glue(glue_val);
35200 if width(cur_val) < 0 then
35201 pdf_error("ext1", "negative snap glue");
35202 p := get_node(snap_node_size);
35203 type(p) := whatsit_node;
35204 subtype(p) := s;
35205 link(p) := null;
35206 snap_glue_ptr(p) := cur_val;
35207 final_skip(p) := 0;
35208 new_snap_node := p;
35209 end;
35210
35211 @ @<Implement \.{\\pdfsnapy}@>=
35212 begin
35213 check_pdfoutput("\pdfsnapy", true);
35214 tail_append(new_snap_node(pdf_snapy_node));
35215 end
35216
35217 @ @<Implement \.{\\pdfsnapycomp}@>=
35218 begin
35219 check_pdfoutput("\pdfsnapycomp", true);
35220 new_whatsit(pdf_snapy_comp_node, small_node_size);
35221 scan_int;
35222 snapy_comp_ratio(tail) := fix_int(cur_val, 0, 1000);
35223 end
35224
35225 @ @<Implement \.{\\pdfsavepos}@>=
35226 begin
35227 new_whatsit(pdf_save_pos_node, small_node_size);
35228 end
35229
35230 @ To implement primitives as \.{\\pdfinfo}, \.{\\pdfcatalog} or
35231 \.{\\pdfnames} we need to concatenate tokens lists.
35232
35233 @<Declare procedures needed in |do_ext...@>=
35234 function concat_tokens(q, r: pointer): pointer; {concat |q| and |r| and
35235 returns the result tokens list}
35236 var p: pointer;
35237 begin
35238 if q = null then begin
35239 concat_tokens := r;
35240 return;
35241 end;
35242 p := q;
35243 while link(p) <> null do
35244 p := link(p);
35245 link(p) := link(r);
35246 free_avail(r);
35247 concat_tokens := q;
35248 end;
35249
35250 @ @<Implement \.{\\pdfinfo}@>=
35251 begin
35252 check_pdfoutput("\pdfinfo", false);
35253 scan_pdf_ext_toks;
35254 if pdf_output > 0 then
35255 pdf_info_toks := concat_tokens(pdf_info_toks, def_ref);
35256 end
35257
35258 @ @<Implement \.{\\pdfcatalog}@>=
35259 begin
35260 check_pdfoutput("\pdfcatalog", false);
35261 scan_pdf_ext_toks;
35262 if pdf_output > 0 then
35263 pdf_catalog_toks := concat_tokens(pdf_catalog_toks, def_ref);
35264 if scan_keyword("openaction") then begin
35265 if pdf_catalog_openaction <> 0 then
35266 pdf_error("ext1", "duplicate of openaction")
35267 else begin
35268 p := scan_action;
35269 pdf_new_obj(obj_type_others, 0, 1);
35270 if pdf_output > 0 then
35271 pdf_catalog_openaction := obj_ptr;
35272 write_action(p);
35273 pdf_end_obj;
35274 delete_action_ref(p);
35275 end;
35276 end
35277 end
35278
35279 @ @<Implement \.{\\pdfnames}@>=
35280 begin
35281 check_pdfoutput("\pdfnames", true);
35282 scan_pdf_ext_toks;
35283 pdf_names_toks := concat_tokens(pdf_names_toks, def_ref);
35284 end
35285
35286 @ @<Implement \.{\\pdftrailer}@>=
35287 begin
35288 check_pdfoutput("\pdftrailer", false);
35289 scan_pdf_ext_toks;
35290 if pdf_output > 0 then
35291 pdf_trailer_toks := concat_tokens(pdf_trailer_toks, def_ref);
35292 end
35293
35294 @ @<Implement \.{\\pdftrailerid}@>=
35295 begin
35296 check_pdfoutput("\pdftrailerid", false);
35297 scan_pdf_ext_toks;
35298 if pdf_output > 0 then
35299 pdf_trailer_id_toks := concat_tokens(pdf_trailer_id_toks, def_ref);
35300 end
35301
35302 @ @<Glob...@>=
35303 @!pdf_retval: integer; {global multi-purpose return value}
35304
35305 @ @<Set initial values of key variables@>=
35306 seconds_and_micros(epochseconds,microseconds);
35307 init_start_time;
35308
35309 @ Negative random seed values are silently converted to positive ones.
35310
35311 @<Implement \.{\\pdfsetrandomseed}@>=
35312 begin
35313 scan_int;
35314 if cur_val<0 then negate(cur_val);
35315 random_seed := cur_val;
35316 init_randoms(random_seed);
35317 end
35318
35319 @ @<Implement \.{\\pdfresettimer}@>=
35320 begin
35321 seconds_and_micros(epochseconds,microseconds);
35322 end
35323
35324
35325 @ The following subroutines are about PDF-specific font issues.
35326
35327 @<Declare procedures needed in |do_ext...@>=
35328 procedure pdf_include_chars;
35329 var s: str_number;
35330 k: pool_pointer; {running indices}
35331 f: internal_font_number;
35332 begin
35333 scan_font_ident;
35334 f := cur_val;
35335 if f = null_font then
35336 pdf_error("font", "invalid font identifier");
35337 pdf_check_vf_cur_val;
35338 if not font_used[f] then
35339 pdf_init_font(f);
35340 scan_pdf_ext_toks;
35341 s := tokens_to_string(def_ref);
35342 delete_token_ref(def_ref);
35343 k := str_start[s];
35344 while k < str_start[s + 1] do begin
35345 pdf_mark_char(f, str_pool[k]);
35346 incr(k);
35347 end;
35348 flush_str(s);
35349 end;
35350
35351 procedure glyph_to_unicode;
35352 var s1, s2: str_number;
35353 begin
35354 scan_pdf_ext_toks;
35355 s1 := tokens_to_string(def_ref);
35356 delete_token_ref(def_ref);
35357 scan_pdf_ext_toks;
35358 s2 := tokens_to_string(def_ref);
35359 delete_token_ref(def_ref);
35360 def_tounicode(s1, s2);
35361 flush_str(s2);
35362 flush_str(s1);
35363 end;
35364
35365 @ @<Implement \.{\\pdfincludechars}@>=
35366 begin
35367 check_pdfoutput("\pdfincludechars", true);
35368 pdf_include_chars;
35369 end
35370
35371 @ @<Implement \.{\\pdffontattr}@>=
35372 begin
35373 check_pdfoutput("\pdffontattr", true);
35374 scan_font_ident;
35375 k := cur_val;
35376 if k = null_font then
35377 pdf_error("font", "invalid font identifier");
35378 scan_pdf_ext_toks;
35379 pdf_font_attr[k] := tokens_to_string(def_ref);
35380 end
35381
35382 @ @<Implement \.{\\pdfmapfile}@>=
35383 begin
35384 check_pdfoutput("\pdfmapfile", true);
35385 scan_pdf_ext_toks;
35386 pdfmapfile(def_ref);
35387 delete_token_ref(def_ref);
35388 end
35389
35390 @ @<Implement \.{\\pdfmapline}@>=
35391 begin
35392 check_pdfoutput("\pdfmapline", true);
35393 scan_pdf_ext_toks;
35394 pdfmapline(def_ref);
35395 delete_token_ref(def_ref);
35396 end
35397
35398 @ @<Implement \.{\\pdfglyphtounicode}@>=
35399 begin
35400 glyph_to_unicode;
35401 end
35402
35403 @ @<Implement \.{\\pdfnobuiltintounicode}@>=
35404 begin
35405 check_pdfoutput("\pdfnobuiltintounicode", true);
35406 scan_font_ident;
35407 k := cur_val;
35408 if k = null_font then
35409 pdf_error("font", "invalid font identifier");
35410 pdf_font_nobuiltin_tounicode[k] := true;
35411 end
35412
35413 @ @<Implement \.{\\pdfinterwordspaceon}@>=
35414 begin
35415 check_pdfoutput("\pdfinterwordspaceon", true);
35416 new_whatsit(pdf_interword_space_on_node, small_node_size);
35417 end
35418
35419 @ @<Implement \.{\\pdfinterwordspaceoff}@>=
35420 begin
35421 check_pdfoutput("\pdfinterwordspaceoff", true);
35422 new_whatsit(pdf_interword_space_off_node, small_node_size);
35423 end
35424
35425 @ @<Implement \.{\\pdffakespace}@>=
35426 begin
35427 check_pdfoutput("\pdffakespace", true);
35428 new_whatsit(pdf_fake_space_node, small_node_size);
35429 end
35430
35431 @ @<Implement \.{\\pdfrunninglinkoff}@>=
35432 begin
35433 check_pdfoutput("\pdfrunninglinkoff", true);
35434 new_whatsit(pdf_running_link_off_node, small_node_size);
35435 end
35436
35437 @ @<Implement \.{\\pdfrunninglinkon}@>=
35438 begin
35439 check_pdfoutput("\pdfrunninglinkon", true);
35440 new_whatsit(pdf_running_link_on_node, small_node_size);
35441 end
35442
35443 @ @<Implement \.{\\pdfspacefont}@>=
35444 begin
35445 check_pdfoutput("\pdfspacefont", true);
35446 scan_pdf_ext_toks;
35447 pdf_space_font_name := tokens_to_string(def_ref);
35448 delete_token_ref(def_ref);
35449 end
35450
35451 @ The following function are needed for outputting article thread.
35452
35453 @<Declare procedures needed in |do_ext...@>=
35454 procedure thread_title(thread: integer);
35455 begin
35456 pdf_print("/Title (");
35457 if obj_info(thread) < 0 then
35458 pdf_print(-obj_info(thread))
35459 else
35460 pdf_print_int(obj_info(thread));
35461 pdf_print_ln(")");
35462 end;
35463
35464 procedure pdf_fix_thread(thread: integer);
35465 var a: pointer;
35466 begin
35467 pdf_warning("thread", "destination ", true, false);
35468 if obj_info(thread) < 0 then begin
35469 print("name{");
35470 print(-obj_info(thread));
35471 print("}");
35472 end
35473 else begin
35474 print("num");
35475 print_int(obj_info(thread));
35476 end;
35477 print(" has been referenced but does not exist, replaced by a fixed one");
35478 print_ln; print_ln;
35479 pdf_new_dict(obj_type_others, 0, 0);
35480 a := obj_ptr;
35481 pdf_indirect_ln("T", thread);
35482 pdf_indirect_ln("V", a);
35483 pdf_indirect_ln("N", a);
35484 pdf_indirect_ln("P", head_tab[obj_type_page]);
35485 pdf_print("/R [0 0 ");
35486 pdf_print_bp(pdf_page_width); pdf_out(" ");
35487 pdf_print_bp(pdf_page_height);
35488 pdf_print_ln("]");
35489 pdf_end_dict;
35490 pdf_begin_dict(thread, 1);
35491 pdf_print_ln("/I << ");
35492 thread_title(thread);
35493 pdf_print_ln(">>");
35494 pdf_indirect_ln("F", a);
35495 pdf_end_dict;
35496 end;
35497
35498 procedure out_thread(thread: integer);
35499 var a, b: pointer;
35500 last_attr: integer;
35501 begin
35502 if obj_thread_first(thread) = 0 then begin
35503 pdf_fix_thread(thread);
35504 return;
35505 end;
35506 pdf_begin_dict(thread, 1);
35507 a := obj_thread_first(thread);
35508 b := a;
35509 last_attr := 0;
35510 repeat
35511 if obj_bead_attr(a) <> 0 then
35512 last_attr := obj_bead_attr(a);
35513 a := obj_bead_next(a);
35514 until a = b;
35515 if last_attr <> 0 then
35516 pdf_print_ln(last_attr)
35517 else begin
35518 pdf_print_ln("/I << ");
35519 thread_title(thread);
35520 pdf_print_ln(">>");
35521 end;
35522 pdf_indirect_ln("F", a);
35523 pdf_end_dict;
35524 repeat
35525 pdf_begin_dict(a, 1);
35526 if a = b then
35527 pdf_indirect_ln("T", thread);
35528 pdf_indirect_ln("V", obj_bead_prev(a));
35529 pdf_indirect_ln("N", obj_bead_next(a));
35530 pdf_indirect_ln("P", obj_bead_page(a));
35531 pdf_indirect_ln("R", obj_bead_rect(a));
35532 pdf_end_dict;
35533 a := obj_bead_next(a);
35534 until a = b;
35535 end;
35536
35537 @ @<Display <rule spec> for whatsit node created by \pdfTeX@>=
35538 print("(");
35539 print_rule_dimen(pdf_height(p));
35540 print_char("+");
35541 print_rule_dimen(pdf_depth(p));
35542 print(")x");
35543 print_rule_dimen(pdf_width(p))
35544
35545 @ Each new type of node that appears in our data structure must be capable
35546 of being displayed, copied, destroyed, and so on. The routines that we
35547 need for write-oriented whatsits are somewhat like those for mark nodes;
35548 other extensions might, of course, involve more subtlety here.
35549
35550 @<Basic printing...@>=
35551 procedure print_write_whatsit(@!s:str_number;@!p:pointer);
35552 begin print_esc(s);
35553 if write_stream(p)<16 then print_int(write_stream(p))
35554 else if write_stream(p)=16 then print_char("*")
35555 @.*\relax@>
35556 else print_char("-");
35557 end;
35558
35559 @ @<Display the whatsit...@>=
35560 case subtype(p) of
35561 open_node:begin print_write_whatsit("openout",p);
35562 print_char("="); print_file_name(open_name(p),open_area(p),open_ext(p));
35563 end;
35564 write_node:begin print_write_whatsit("write",p);
35565 print_mark(write_tokens(p));
35566 end;
35567 close_node:print_write_whatsit("closeout",p);
35568 special_node:begin print_esc("special");
35569 print_mark(write_tokens(p));
35570 end;
35571 latespecial_node:begin print_esc("special"); print(" shipout");
35572 print_mark(write_tokens(p));
35573 end;
35574 language_node:begin print_esc("setlanguage");
35575 print_int(what_lang(p)); print(" (hyphenmin ");
35576 print_int(what_lhm(p)); print_char(",");
35577 print_int(what_rhm(p)); print_char(")");
35578 end;
35579 pdf_literal_node,pdf_lateliteral_node: begin
35580 print_esc("pdfliteral");
35581 if subtype(p)=pdf_lateliteral_node then print(" shipout");
35582 case pdf_literal_mode(p) of
35583 set_origin:
35584 do_nothing;
35585 direct_page:
35586 print(" page");
35587 direct_always:
35588 print(" direct");
35589 othercases confusion("literal2")
35590 endcases;
35591 print_mark(pdf_literal_data(p));
35592 end;
35593 pdf_colorstack_node: begin
35594 print_esc("pdfcolorstack ");
35595 print_int(pdf_colorstack_stack(p));
35596 case pdf_colorstack_cmd(p) of
35597 colorstack_set:
35598 print(" set ");
35599 colorstack_push:
35600 print(" push ");
35601 colorstack_pop:
35602 print(" pop");
35603 colorstack_current:
35604 print(" current");
35605 othercases confusion("pdfcolorstack")
35606 endcases;
35607 if pdf_colorstack_cmd(p) <= colorstack_data then
35608 print_mark(pdf_colorstack_data(p));
35609 end;
35610 pdf_setmatrix_node: begin
35611 print_esc("pdfsetmatrix");
35612 print_mark(pdf_setmatrix_data(p));
35613 end;
35614 pdf_save_node: begin
35615 print_esc("pdfsave");
35616 end;
35617 pdf_restore_node: begin
35618 print_esc("pdfrestore");
35619 end;
35620 pdf_refobj_node: begin
35621 print_esc("pdfrefobj");
35622 if obj_obj_is_stream(pdf_obj_objnum(p)) > 0 then begin
35623 if obj_obj_stream_attr(pdf_obj_objnum(p)) <> null then begin
35624 print(" attr");
35625 print_mark(obj_obj_stream_attr(pdf_obj_objnum(p)));
35626 end;
35627 print(" stream");
35628 end;
35629 if obj_obj_is_file(pdf_obj_objnum(p)) > 0 then
35630 print(" file");
35631 print_mark(obj_obj_data(pdf_obj_objnum(p)));
35632 end;
35633 pdf_refxform_node: begin
35634 print_esc("pdfrefxform");
35635 print("(");
35636 print_scaled(obj_xform_height(pdf_xform_objnum(p)));
35637 print_char("+");
35638 print_scaled(obj_xform_depth(pdf_xform_objnum(p)));
35639 print(")x");
35640 print_scaled(obj_xform_width(pdf_xform_objnum(p)));
35641 end;
35642 pdf_refximage_node: begin
35643 print_esc("pdfrefximage");
35644 print("(");
35645 print_scaled(obj_ximage_height(pdf_ximage_objnum(p)));
35646 print_char("+");
35647 print_scaled(obj_ximage_depth(pdf_ximage_objnum(p)));
35648 print(")x");
35649 print_scaled(obj_ximage_width(pdf_ximage_objnum(p)));
35650 end;
35651 pdf_annot_node: begin
35652 print_esc("pdfannot");
35653 @<Display <rule spec> for whatsit node created by \pdfTeX@>;
35654 print_mark(pdf_annot_data(p));
35655 end;
35656 pdf_start_link_node: begin
35657 print_esc("pdfstartlink");
35658 @<Display <rule spec> for whatsit node created by \pdfTeX@>;
35659 if pdf_link_attr(p) <> null then begin
35660 print(" attr");
35661 print_mark(pdf_link_attr(p));
35662 end;
35663 print(" action");
35664 if pdf_action_type(pdf_link_action(p)) = pdf_action_user then begin
35665 print(" user");
35666 print_mark(pdf_action_user_tokens(pdf_link_action(p)));
35667 end
35668 else begin
35669 if pdf_action_file(pdf_link_action(p)) <> null then begin
35670 print(" file");
35671 print_mark(pdf_action_file(pdf_link_action(p)));
35672 end;
35673 case pdf_action_type(pdf_link_action(p)) of
35674 pdf_action_goto: begin
35675 if (pdf_action_named_id(pdf_link_action(p)) mod 2) = 1 then begin
35676 print(" goto name");
35677 print_mark(pdf_action_id(pdf_link_action(p)));
35678 end
35679 else begin
35680 print(" goto num");
35681 print_int(pdf_action_id(pdf_link_action(p)))
35682 end;
35683 end;
35684 pdf_action_page: begin
35685 print(" page");
35686 print_int(pdf_action_id(pdf_link_action(p)));
35687 print_mark(pdf_action_page_tokens(pdf_link_action(p)));
35688 end;
35689 pdf_action_thread: begin
35690 if (pdf_action_named_id(pdf_link_action(p)) mod 2) = 1 then begin
35691 print(" thread name");
35692 print_mark(pdf_action_id(pdf_link_action(p)));
35693 end
35694 else begin
35695 print(" thread num");
35696 print_int(pdf_action_id(pdf_link_action(p)));
35697 end;
35698 end;
35699 othercases pdf_error("displaying", "unknown action type");
35700 endcases;
35701 end
35702 end;
35703 pdf_end_link_node: print_esc("pdfendlink");
35704 pdf_dest_node: begin
35705 print_esc("pdfdest");
35706 if pdf_dest_objnum(p) <> null then begin
35707 print(" struct");
35708 print_int(pdf_dest_objnum(p));
35709 end;
35710 if pdf_dest_named_id(p) > 0 then begin
35711 print(" name");
35712 print_mark(pdf_dest_id(p));
35713 end
35714 else begin
35715 print(" num");
35716 print_int(pdf_dest_id(p));
35717 end;
35718 print(" ");
35719 case pdf_dest_type(p) of
35720 pdf_dest_xyz: begin
35721 print("xyz");
35722 if pdf_dest_xyz_zoom(p) <> null then begin
35723 print(" zoom");
35724 print_int(pdf_dest_xyz_zoom(p));
35725 end;
35726 end;
35727 pdf_dest_fitbh: print("fitbh");
35728 pdf_dest_fitbv: print("fitbv");
35729 pdf_dest_fitb: print("fitb");
35730 pdf_dest_fith: print("fith");
35731 pdf_dest_fitv: print("fitv");
35732 pdf_dest_fitr: begin
35733 print("fitr");
35734 @<Display <rule spec> for whatsit node created by \pdfTeX@>;
35735 end;
35736 pdf_dest_fit: print("fit");
35737 othercases print("unknown!");
35738 endcases;
35739 end;
35740 pdf_thread_node,
35741 pdf_start_thread_node: begin
35742 if subtype(p) = pdf_thread_node then
35743 print_esc("pdfthread")
35744 else
35745 print_esc("pdfstartthread");
35746 print("("); print_rule_dimen(pdf_height(p)); print_char("+");
35747 print_rule_dimen(pdf_depth(p)); print(")x");
35748 print_rule_dimen(pdf_width(p));
35749 if pdf_thread_attr(p) <> null then begin
35750 print(" attr");
35751 print_mark(pdf_thread_attr(p));
35752 end;
35753 if pdf_thread_named_id(p) > 0 then begin
35754 print(" name");
35755 print_mark(pdf_thread_id(p));
35756 end
35757 else begin
35758 print(" num");
35759 print_int(pdf_thread_id(p));
35760 end;
35761 end;
35762 pdf_end_thread_node: print_esc("pdfendthread");
35763 pdf_save_pos_node: print_esc("pdfsavepos");
35764 pdf_snap_ref_point_node: print_esc("pdfsnaprefpoint");
35765 pdf_snapy_node: begin
35766 print_esc("pdfsnapy");
35767 print_char(" ");
35768 print_spec(snap_glue_ptr(p), 0);
35769 print_char(" ");
35770 print_spec(final_skip(p), 0);
35771 end;
35772 pdf_snapy_comp_node: begin
35773 print_esc("pdfsnapycomp");
35774 print_char(" ");
35775 print_int(snapy_comp_ratio(p));
35776 end;
35777 pdf_interword_space_on_node: print_esc("pdfinterwordspaceon");
35778 pdf_interword_space_off_node: print_esc("pdfinterwordspaceoff");
35779 pdf_fake_space_node: print_esc("pdffakespace");
35780 pdf_running_link_off_node: print_esc("pdfrunninglinkoff");
35781 pdf_running_link_on_node: print_esc("pdfrunninglinkon");
35782 othercases print("whatsit?")
35783 endcases
35784
35785 @ @<Make a partial copy of the whatsit...@>=
35786 case subtype(p) of
35787 open_node: begin r:=get_node(open_node_size); words:=open_node_size;
35788 end;
35789 write_node,special_node,latespecial_node: begin r:=get_node(write_node_size);
35790 add_token_ref(write_tokens(p)); words:=write_node_size;
35791 end;
35792 close_node,language_node: begin r:=get_node(small_node_size);
35793 words:=small_node_size;
35794 end;
35795 pdf_literal_node,pdf_lateliteral_node: begin
35796 r := get_node(write_node_size);
35797 add_token_ref(pdf_literal_data(p));
35798 words := write_node_size;
35799 end;
35800 pdf_colorstack_node: begin
35801 if pdf_colorstack_cmd(p) <= colorstack_data then begin
35802 r := get_node(pdf_colorstack_setter_node_size);
35803 add_token_ref(pdf_colorstack_data(p));
35804 words := pdf_colorstack_setter_node_size;
35805 end
35806 else begin
35807 r := get_node(pdf_colorstack_getter_node_size);
35808 words := pdf_colorstack_getter_node_size;
35809 end;
35810 end;
35811 pdf_setmatrix_node: begin
35812 r := get_node(pdf_setmatrix_node_size);
35813 add_token_ref(pdf_setmatrix_data(p));
35814 words := pdf_setmatrix_node_size;
35815 end;
35816 pdf_save_node: begin
35817 r := get_node(pdf_save_node_size);
35818 words := pdf_save_node_size;
35819 end;
35820 pdf_restore_node: begin
35821 r := get_node(pdf_restore_node_size);
35822 words := pdf_restore_node_size;
35823 end;
35824 pdf_refobj_node: begin
35825 r := get_node(pdf_refobj_node_size);
35826 words := pdf_refobj_node_size;
35827 end;
35828 pdf_refxform_node: begin
35829 r := get_node(pdf_refxform_node_size);
35830 words := pdf_refxform_node_size;
35831 end;
35832 pdf_refximage_node: begin
35833 r := get_node(pdf_refximage_node_size);
35834 words := pdf_refximage_node_size;
35835 end;
35836 pdf_annot_node: begin
35837 r := get_node(pdf_annot_node_size);
35838 add_token_ref(pdf_annot_data(p));
35839 words := pdf_annot_node_size;
35840 end;
35841 pdf_start_link_node: begin
35842 r := get_node(pdf_annot_node_size);
35843 pdf_height(r) := pdf_height(p);
35844 pdf_depth(r) := pdf_depth(p);
35845 pdf_width(r) := pdf_width(p);
35846 pdf_link_attr(r) := pdf_link_attr(p);
35847 if pdf_link_attr(r) <> null then
35848 add_token_ref(pdf_link_attr(r));
35849 pdf_link_action(r) := pdf_link_action(p);
35850 add_action_ref(pdf_link_action(r));
35851 pdf_link_objnum(r) := pdf_link_objnum(p);
35852 end;
35853 pdf_end_link_node:
35854 r := get_node(small_node_size);
35855 pdf_dest_node: begin
35856 r := get_node(pdf_dest_node_size);
35857 if pdf_dest_named_id(p) > 0 then
35858 add_token_ref(pdf_dest_id(p));
35859 words := pdf_dest_node_size;
35860 end;
35861 pdf_thread_node,
35862 pdf_start_thread_node: begin
35863 r := get_node(pdf_thread_node_size);
35864 if pdf_thread_named_id(p) > 0 then
35865 add_token_ref(pdf_thread_id(p));
35866 if pdf_thread_attr(p) <> null then
35867 add_token_ref(pdf_thread_attr(p));
35868 words := pdf_thread_node_size;
35869 end;
35870 pdf_end_thread_node:
35871 r := get_node(small_node_size);
35872 pdf_save_pos_node:
35873 r := get_node(small_node_size);
35874 pdf_snap_ref_point_node:
35875 r := get_node(small_node_size);
35876 pdf_snapy_node: begin
35877 add_glue_ref(snap_glue_ptr(p));
35878 r := get_node(snap_node_size);
35879 words := snap_node_size;
35880 end;
35881 pdf_snapy_comp_node:
35882 r := get_node(small_node_size);
35883 pdf_interword_space_on_node:
35884 r := get_node(small_node_size);
35885 pdf_interword_space_off_node:
35886 r := get_node(small_node_size);
35887 pdf_fake_space_node:
35888 r := get_node(small_node_size);
35889 pdf_running_link_off_node:
35890 r := get_node(small_node_size);
35891 pdf_running_link_on_node:
35892 r := get_node(small_node_size);
35893 othercases confusion("ext2")
35894 @:this can't happen ext2}{\quad ext2@>
35895 endcases
35896
35897 @ @<Wipe out the whatsit...@>=
35898 begin case subtype(p) of
35899 open_node: free_node(p,open_node_size);
35900 write_node,special_node,latespecial_node: begin delete_token_ref(write_tokens(p));
35901 free_node(p,write_node_size); goto done;
35902 end;
35903 close_node,language_node: free_node(p,small_node_size);
35904 pdf_literal_node,pdf_lateliteral_node: begin
35905 delete_token_ref(pdf_literal_data(p));
35906 free_node(p, write_node_size);
35907 end;
35908 pdf_colorstack_node: begin
35909 if pdf_colorstack_cmd(p) <= colorstack_data then begin
35910 delete_token_ref(pdf_colorstack_data(p));
35911 free_node(p, pdf_colorstack_setter_node_size);
35912 end
35913 else
35914 free_node(p, pdf_colorstack_getter_node_size);
35915 end;
35916 pdf_setmatrix_node: begin
35917 delete_token_ref(pdf_setmatrix_data(p));
35918 free_node(p, pdf_setmatrix_node_size);
35919 end;
35920 pdf_save_node: begin
35921 free_node(p, pdf_save_node_size);
35922 end;
35923 pdf_restore_node: begin
35924 free_node(p, pdf_restore_node_size);
35925 end;
35926 pdf_refobj_node:
35927 free_node(p, pdf_refobj_node_size);
35928 pdf_refxform_node:
35929 free_node(p, pdf_refxform_node_size);
35930 pdf_refximage_node:
35931 free_node(p, pdf_refximage_node_size);
35932 pdf_annot_node: begin
35933 delete_token_ref(pdf_annot_data(p));
35934 free_node(p, pdf_annot_node_size);
35935 end;
35936 pdf_start_link_node: begin
35937 if pdf_link_attr(p) <> null then
35938 delete_token_ref(pdf_link_attr(p));
35939 delete_action_ref(pdf_link_action(p));
35940 free_node(p, pdf_annot_node_size);
35941 end;
35942 pdf_end_link_node:
35943 free_node(p, small_node_size);
35944 pdf_dest_node: begin
35945 if pdf_dest_named_id(p) > 0 then
35946 delete_token_ref(pdf_dest_id(p));
35947 free_node(p, pdf_dest_node_size);
35948 end;
35949 pdf_thread_node,
35950 pdf_start_thread_node: begin
35951 if pdf_thread_named_id(p) > 0 then
35952 delete_token_ref(pdf_thread_id(p));
35953 if pdf_thread_attr(p) <> null then
35954 delete_token_ref(pdf_thread_attr(p));
35955 free_node(p, pdf_thread_node_size);
35956 end;
35957 pdf_end_thread_node:
35958 free_node(p, small_node_size);
35959 pdf_save_pos_node:
35960 free_node(p, small_node_size);
35961 pdf_snap_ref_point_node:
35962 free_node(p, small_node_size);
35963 pdf_snapy_node: begin
35964 delete_glue_ref(snap_glue_ptr(p));
35965 free_node(p, snap_node_size);
35966 end;
35967 pdf_snapy_comp_node:
35968 free_node(p, small_node_size);
35969 pdf_interword_space_on_node:
35970 free_node(p, small_node_size);
35971 pdf_interword_space_off_node:
35972 free_node(p, small_node_size);
35973 pdf_fake_space_node:
35974 free_node(p, small_node_size);
35975 pdf_running_link_off_node:
35976 free_node(p, small_node_size);
35977 pdf_running_link_on_node:
35978 free_node(p, small_node_size);
35979 othercases confusion("ext3")
35980 @:this can't happen ext3}{\quad ext3@>
35981 endcases;@/
35982 goto done;
35983 end
35984
35985 @ @<Incorporate a whatsit node into a vbox@>=
35986 if (subtype(p) = pdf_refxform_node) or (subtype(p) = pdf_refximage_node) then
35987 begin x:=x+d+pdf_height(p); d:=pdf_depth(p);
35988 s:=0;
35989 if pdf_width(p)+s>w then w:=pdf_width(p)+s;
35990 end
35991
35992 @ @<Incorporate a whatsit node into an hbox@>=
35993 if (subtype(p) = pdf_refxform_node) or (subtype(p) = pdf_refximage_node) then
35994 begin x:=x+pdf_width(p);
35995 s:=0;
35996 if pdf_height(p)-s>h then h:=pdf_height(p)-s;
35997 if pdf_depth(p)+s>d then d:=pdf_depth(p)+s;
35998 end
35999
36000 @ @<Let |d| be the width of the whatsit |p|@>=
36001 if (subtype(p) = pdf_refxform_node) or (subtype(p) = pdf_refximage_node) then
36002 d := pdf_width(p)
36003 else
36004 d := 0
36005
36006 @ @d adv_past(#)==@+if subtype(#)=language_node then
36007 begin cur_lang:=what_lang(#); l_hyf:=what_lhm(#); r_hyf:=what_rhm(#);@+end
36008
36009 @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>=@+
36010 begin
36011 adv_past(cur_p);
36012 if (subtype(cur_p) = pdf_refxform_node) or (subtype(cur_p) = pdf_refximage_node) then
36013 act_width:=act_width+pdf_width(cur_p);
36014 end
36015
36016 @ @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>=@+
36017 if subtype(s)=language_node then
36018 begin cur_lang:=what_lang(s); l_hyf:=what_lhm(s); r_hyf:=what_rhm(s);
36019 set_hyph_index;
36020 end
36021
36022 @ @<Prepare to move whatsit |p| to the current page, then |goto contribute|@>=
36023 begin
36024 if (subtype(p) = pdf_refxform_node) or (subtype(p) = pdf_refximage_node) then
36025 begin page_total:=page_total+page_depth+pdf_height(p);
36026 page_depth:=pdf_depth(p);
36027 end;
36028 goto contribute;
36029 end
36030
36031 @ @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>=
36032 begin
36033 if (subtype(p) = pdf_refxform_node) or (subtype(p) = pdf_refximage_node) then
36034 begin cur_height:=cur_height+prev_dp+pdf_height(p); prev_dp:=pdf_depth(p);
36035 end;
36036 goto not_found;
36037 end
36038
36039 @ @<Output the whatsit node |p| in a vlist@>=
36040 out_what(p)
36041
36042 @ @<Output the whatsit node |p| in an hlist@>=
36043 out_what(p)
36044
36045 @ After all this preliminary shuffling, we come finally to the routines
36046 that actually send out the requested data. Let's do \.{\\special} first
36047 (it's easier).
36048
36049 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
36050 procedure special_out(@!p:pointer);
36051 var old_setting:0..max_selector; {holds print |selector|}
36052 @!k:pool_pointer; {index into |str_pool|}
36053 @!h:halfword;
36054 @!q,@!r:pointer; {temporary variables for list manipulation}
36055 @!old_mode:integer; {saved |mode|}
36056 begin synch_h; synch_v;@/
36057 old_setting:=selector; selector:=new_string;
36058 selector:=old_setting;
36059 if subtype(p)=latespecial_node then
36060 begin @<Expand macros in the token list
36061 and make |link(def_ref)| point to the result@>;
36062 h:=def_ref;
36063 end
36064 else h:=write_tokens(p);
36065 selector:=new_string;
36066 show_token_list(link(h),null,pool_size-pool_ptr);
36067 selector:=old_setting;
36068 str_room(1);
36069 if cur_length<256 then
36070 begin dvi_out(xxx1); dvi_out(cur_length);
36071 end
36072 else begin dvi_out(xxx4); dvi_four(cur_length);
36073 end;
36074 for k:=str_start[str_ptr] to pool_ptr-1 do dvi_out(so(str_pool[k]));
36075 pool_ptr:=str_start[str_ptr]; {erase the string}
36076 if subtype(p)=latespecial_node then
36077 flush_list(def_ref);
36078 end;
36079
36080 @ To write a token list, we must run it through \TeX's scanner, expanding
36081 macros and \.{\\the} and \.{\\number}, etc. This might cause runaways,
36082 if a delimited macro parameter isn't matched, and runaways would be
36083 extremely confusing since we are calling on \TeX's scanner in the middle
36084 of a \.{\\shipout} command. Therefore we will put a dummy control sequence as
36085 a ``stopper,'' right after the token list. This control sequence is
36086 artificially defined to be \.{\\outer}.
36087 @:end_write_}{\.{\\endwrite}@>
36088
36089 @<Initialize table...@>=
36090 text(end_write):="endwrite"; eq_level(end_write):=level_one;
36091 eq_type(end_write):=outer_call; equiv(end_write):=null;
36092
36093 @ @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
36094 procedure write_out(@!p:pointer);
36095 var old_setting:0..max_selector; {holds print |selector|}
36096 @!old_mode:integer; {saved |mode|}
36097 @!j:small_number; {write stream number}
36098 @!q,@!r:pointer; {temporary variables for list manipulation}
36099 begin @<Expand macros in the token list
36100 and make |link(def_ref)| point to the result@>;
36101 old_setting:=selector; j:=write_stream(p);
36102 if write_open[j] then selector:=j
36103 else begin {write to the terminal if file isn't open}
36104 if (j=17)and(selector=term_and_log) then selector:=log_only;
36105 print_nl("");
36106 end;
36107 token_show(def_ref); print_ln;
36108 flush_list(def_ref); selector:=old_setting;
36109 end;
36110
36111 @ The final line of this routine is slightly subtle; at least, the author
36112 didn't think about it until getting burnt! There is a used-up token list
36113 @^Knuth, Donald Ervin@>
36114 on the stack, namely the one that contained |end_write_token|. (We
36115 insert this artificial `\.{\\endwrite}' to prevent runaways, as explained
36116 above.) If it were not removed, and if there were numerous writes on a
36117 single page, the stack would overflow.
36118
36119 @d end_write_token==cs_token_flag+end_write
36120
36121 @<Expand macros in the token list and...@>=
36122 q:=get_avail; info(q):=right_brace_token+"}";@/
36123 r:=get_avail; link(q):=r; info(r):=end_write_token; ins_list(q);@/
36124 begin_token_list(write_tokens(p),write_text);@/
36125 q:=get_avail; info(q):=left_brace_token+"{"; ins_list(q);
36126 {now we're ready to scan
36127 `\.\{$\langle\,$token list$\,\rangle$\.{\} \\endwrite}'}
36128 old_mode:=mode; mode:=0;
36129 {disable \.{\\prevdepth}, \.{\\spacefactor}, \.{\\lastskip}, \.{\\prevgraf}}
36130 cur_cs:=write_loc; q:=scan_toks(false,true); {expand macros, etc.}
36131 get_token;@+if cur_tok<>end_write_token then
36132 @<Recover from an unbalanced write command@>;
36133 mode:=old_mode;
36134 end_token_list {conserve stack space}
36135
36136 @ @<Recover from an unbalanced write command@>=
36137 begin print_err("Unbalanced write command");
36138 @.Unbalanced write...@>
36139 help2("On this page there's a \write with fewer real {'s than }'s.")@/
36140 ("I can't handle that very well; good luck."); error;
36141 repeat get_token;
36142 until cur_tok=end_write_token;
36143 end
36144
36145 @ The |out_what| procedure takes care of outputting whatsit nodes for
36146 |vlist_out| and |hlist_out|\kern-.3pt.
36147
36148 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
36149 procedure out_what(@!p:pointer);
36150 var j:small_number; {write stream number}
36151 begin case subtype(p) of
36152 open_node,write_node,close_node:@<Do some work that has been queued up
36153 for \.{\\write}@>;
36154 special_node,latespecial_node:special_out(p);
36155 language_node:do_nothing;
36156 pdf_save_pos_node:
36157 @<Save current position in DVI mode@>;
36158 others: begin
36159 if (pdftex_first_extension_code <= subtype(p)) and (subtype(p) <= pdftex_last_extension_code) then
36160 pdf_error("ext4", "pdf node ended up in DVI mode")
36161 else
36162 confusion("ext4")
36163 @:this can't happen ext4}{\quad ext4@>
36164 end;
36165 endcases;
36166 end;
36167
36168 @ @<Save current position in DVI mode@>=
36169 begin
36170 {4736286 = 1in, the funny DVI origin offset}
36171 pdf_last_x_pos := cur_h + 4736286;
36172 pdf_last_y_pos := cur_page_height - cur_v - 4736286;
36173 end
36174
36175 @ We don't implement \.{\\write} inside of leaders. (The reason is that
36176 the number of times a leader box appears might be different in different
36177 implementations, due to machine-dependent rounding in the glue calculations.)
36178 @^leaders@>
36179
36180 @<Do some work that has been queued up...@>=
36181 if not doing_leaders then
36182 begin j:=write_stream(p);
36183 if subtype(p)=write_node then write_out(p)
36184 else begin if write_open[j] then a_close(write_file[j]);
36185 if subtype(p)=close_node then write_open[j]:=false
36186 else if j<16 then
36187 begin cur_name:=open_name(p); cur_area:=open_area(p);
36188 cur_ext:=open_ext(p);
36189 if cur_ext="" then cur_ext:=".tex";
36190 pack_cur_name;
36191 while not a_open_out(write_file[j]) do
36192 prompt_file_name("output file name",".tex");
36193 write_open[j]:=true;
36194 end;
36195 end;
36196 end
36197
36198 @ The presence of `\.{\\immediate}' causes the |do_extension| procedure
36199 to descend to one level of recursion. Nothing happens unless \.{\\immediate}
36200 is followed by `\.{\\openout}', `\.{\\write}', or `\.{\\closeout}'.
36201 @^recursion@>
36202
36203 @<Implement \.{\\immediate}@>=
36204 begin get_x_token;
36205 if cur_cmd=extension then begin
36206 if cur_chr<=close_node then
36207 begin p:=tail; do_extension; {append a whatsit node}
36208 out_what(tail); {do the action immediately}
36209 flush_node_list(tail); tail:=p; link(p):=null;
36210 end
36211 else case cur_chr of
36212 pdf_obj_code: begin
36213 do_extension; {scan object and set |pdf_last_obj|}
36214 if obj_data_ptr(pdf_last_obj) = 0 then {this object has not been initialized yet}
36215 pdf_error("ext1", "`\pdfobj reserveobjnum' cannot be used with \immediate");
36216 pdf_write_obj(pdf_last_obj);
36217 end;
36218 pdf_xform_code: begin
36219 do_extension; {scan form and set |pdf_last_xform|}
36220 pdf_cur_form := pdf_last_xform;
36221 pdf_ship_out(obj_xform_box(pdf_last_xform), false);
36222 end;
36223 pdf_ximage_code: begin
36224 do_extension; {scan image and set |pdf_last_ximage|}
36225 pdf_write_image(pdf_last_ximage);
36226 end;
36227 othercases back_input
36228 endcases;
36229 end
36230 else
36231 back_input;
36232 end
36233
36234 @ The \.{\\language} extension is somewhat different.
36235 We need a subroutine that comes into play when a character of
36236 a non-|clang| language is being appended to the current paragraph.
36237
36238 @<Declare action...@>=
36239 procedure fix_language;
36240 var @!l:ASCII_code; {the new current language}
36241 begin if language<=0 then l:=0
36242 else if language>255 then l:=0
36243 else l:=language;
36244 if l<>clang then
36245 begin new_whatsit(language_node,small_node_size);
36246 what_lang(tail):=l; clang:=l;@/
36247 what_lhm(tail):=norm_min(left_hyphen_min);
36248 what_rhm(tail):=norm_min(right_hyphen_min);
36249 end;
36250 end;
36251
36252 @ @<Implement \.{\\setlanguage}@>=
36253 if abs(mode)<>hmode then report_illegal_case
36254 else begin new_whatsit(language_node,small_node_size);
36255 scan_int;
36256 if cur_val<=0 then clang:=0
36257 else if cur_val>255 then clang:=0
36258 else clang:=cur_val;
36259 what_lang(tail):=clang;
36260 what_lhm(tail):=norm_min(left_hyphen_min);
36261 what_rhm(tail):=norm_min(right_hyphen_min);
36262 end
36263
36264 @ @<Finish the extensions@>=
36265 for k:=0 to 15 do if write_open[k] then a_close(write_file[k])
36266
36267 @ Shipping out PDF marks.
36268
36269 @<Types...@>=
36270 dest_name_entry = record
36271 objname: str_number; {destination name}
36272 objnum: integer; {destination object number}
36273 end;
36274
36275 @ @<Glob...@>=
36276 @!cur_page_width: scaled; {width of page being shipped}
36277 @!cur_page_height: scaled; {height of page being shipped}
36278 @!cur_h_offset: scaled; {horizontal offset of page being shipped}
36279 @!cur_v_offset: scaled; {vertical offset of page being shipped}
36280 @!pdf_obj_list: pointer; {list of objects in the current page}
36281 @!pdf_xform_list: pointer; {list of forms in the current page}
36282 @!pdf_ximage_list: pointer; {list of images in the current page}
36283 @!last_thread: pointer; {pointer to the last thread}
36284 @!pdf_thread_ht, pdf_thread_dp, pdf_thread_wd: scaled; {dimensions of the last
36285 thread}
36286 @!pdf_last_thread_id: halfword; {identifier of the last thread}
36287 @!pdf_last_thread_named_id: boolean; {is identifier of the last thread named}
36288 @!pdf_thread_level: integer; {depth of nesting of box containing the last thread}
36289 @!pdf_annot_list: pointer; {list of annotations in the current page}
36290 @!pdf_link_list: pointer; {list of link annotations in the current page}
36291 @!pdf_dest_list: pointer; {list of destinations in the current page}
36292 @!pdf_bead_list: pointer; {list of thread beads in the current page}
36293 @!pdf_obj_count: integer; {counter of objects}
36294 @!pdf_xform_count: integer; {counter of forms}
36295 @!pdf_ximage_count: integer; {counter of images}
36296 @!pdf_cur_form: integer; {the form being output}
36297 @!pdf_first_outline, pdf_last_outline, pdf_parent_outline: integer;
36298 @!pdf_xform_width,
36299 @!pdf_xform_height,
36300 @!pdf_xform_depth: scaled; {dimension of the current form}
36301 @!pdf_info_toks: pointer; {additional keys of Info dictionary}
36302 @!pdf_catalog_toks: pointer; {additional keys of Catalog dictionary}
36303 @!pdf_catalog_openaction: integer;
36304 @!pdf_names_toks: pointer; {additional keys of Names dictionary}
36305 @!pdf_dest_names_ptr: integer; {first unused position in |dest_names|}
36306 @!dest_names_size: integer; {maximum number of names in name tree of PDF output file}
36307 @!dest_names: ^dest_name_entry;
36308 @!pk_dpi: integer; {PK pixel density value from \.{texmf.cnf}}
36309 @!image_orig_x, image_orig_y: integer; {origin of cropped PDF images}
36310 @!pdf_trailer_toks: pointer; {additional keys of Trailer dictionary}
36311 @!pdf_trailer_id_toks: pointer; {custom Trailer ID}
36312 @!gen_faked_interword_space: boolean; {flag to turn on/off faked interword spaces}
36313 @!gen_running_link: boolean; {flag to turn on/off running link}
36314 @!pdf_space_font_name: str_number; {name of font used for inter-word space in PDF output}
36315
36316 @ @<Set init...@>=
36317 pdf_first_outline:= 0;
36318 pdf_last_outline:= 0;
36319 pdf_parent_outline:= 0;
36320 pdf_obj_count := 0;
36321 pdf_xform_count := 0;
36322 pdf_ximage_count := 0;
36323 pdf_dest_names_ptr := 0;
36324 pdf_info_toks := null;
36325 pdf_catalog_toks := null;
36326 pdf_names_toks := null;
36327 pdf_catalog_openaction := 0;
36328 pdf_trailer_toks := null;
36329 pdf_trailer_id_toks := null;
36330 gen_faked_interword_space := false;
36331 gen_running_link := true;
36332 pdf_space_font_name := "pdftexspace";
36333
36334
36335 @ The following procedures are needed for outputting whatsit nodes for
36336 \pdfTeX{}.
36337
36338 @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
36339 procedure write_action(p: pointer); {write an action specification}
36340 var s: str_number;
36341 d: integer;
36342 begin
36343 if pdf_action_type(p) = pdf_action_user then begin
36344 pdf_print_toks_ln(pdf_action_user_tokens(p));
36345 return;
36346 end;
36347 pdf_print("<< ");
36348 if pdf_action_file(p) <> null then begin
36349 pdf_print("/F ");
36350 s := tokens_to_string(pdf_action_file(p));
36351 if (str_pool[str_start[s]] = 40) and
36352 (str_pool[str_start[s] + length(s) - 1] = 41) then
36353 pdf_print(s)
36354 else begin
36355 pdf_print_str(s);
36356 end;
36357 flush_str(s);
36358 pdf_print(" ");
36359 if pdf_action_new_window(p) > 0 then begin
36360 pdf_print("/NewWindow ");
36361 if pdf_action_new_window(p) = 1 then
36362 pdf_print("true ")
36363 else
36364 pdf_print("false ");
36365 end;
36366 end;
36367 case pdf_action_type(p) of
36368 pdf_action_page: begin
36369 if pdf_action_file(p) = null then begin
36370 pdf_print("/S /GoTo /D [");
36371 pdf_print_int(get_obj(obj_type_page, pdf_action_id(p), false));
36372 pdf_print(" 0 R");
36373 end
36374 else begin
36375 pdf_print("/S /GoToR /D [");
36376 pdf_print_int(pdf_action_id(p) - 1);
36377 end;
36378 pdf_out(" ");
36379 pdf_print(tokens_to_string(pdf_action_page_tokens(p)));
36380 flush_str(last_tokens_string);
36381 pdf_out("]");
36382 end;
36383 pdf_action_goto: begin
36384 if pdf_action_file(p) = null then begin
36385 pdf_print("/S /GoTo ");
36386 d := get_obj(obj_type_dest, pdf_action_id(p),
36387 pdf_action_named_id(p) mod 2);
36388 end
36389 else
36390 pdf_print("/S /GoToR ");
36391 if (pdf_action_named_id(p) mod 2) = 1 then begin
36392 pdf_str_entry("D", tokens_to_string(pdf_action_id(p)));
36393 flush_str(last_tokens_string);
36394 end
36395 else if pdf_action_file(p) = null then
36396 pdf_indirect("D", d)
36397 else
36398 pdf_error("ext4", "`goto' option cannot be used with both `file' and `num'");
36399 end;
36400 pdf_action_thread: begin
36401 pdf_print("/S /Thread ");
36402 if pdf_action_file(p) = null then
36403 d := get_obj(obj_type_thread, pdf_action_id(p),
36404 pdf_action_named_id(p) mod 2);
36405 if (pdf_action_named_id(p) mod 2) = 1 then begin
36406 pdf_str_entry("D", tokens_to_string(pdf_action_id(p)));
36407 flush_str(last_tokens_string);
36408 end
36409 else if pdf_action_file(p) = null then
36410 pdf_indirect("D", d)
36411 else
36412 pdf_int_entry("D", pdf_action_id(p));
36413 end;
36414 endcases;
36415 if pdf_action_struct_id(p) <> null then begin
36416 pdf_out(" ");
36417 if pdf_action_file(p) = null then
36418 pdf_indirect("SD", get_obj(obj_type_struct_dest,
36419 pdf_action_struct_id(p),
36420 (pdf_action_named_id(p) div 2) mod 2))
36421 else begin
36422 pdf_print("/SD ");
36423 pdf_print(tokens_to_string(pdf_action_struct_id(p)));
36424 flush_str(last_tokens_string);
36425 end;
36426 end;
36427 pdf_print_ln(" >>");
36428 end;
36429
36430 procedure set_rect_dimens(p, parent_box: pointer; x, y, w, h, d, margin: scaled);
36431 begin
36432 pdf_left(p) := cur_h;
36433 if is_running(w) then
36434 pdf_right(p) := x + width(parent_box)
36435 else
36436 pdf_right(p) := cur_h + w;
36437 if is_running(h) then
36438 pdf_top(p) := y - height(parent_box)
36439 else
36440 pdf_top(p) := cur_v - h;
36441 if is_running(d) then
36442 pdf_bottom(p) := y + depth(parent_box)
36443 else
36444 pdf_bottom(p) := cur_v + d;
36445 if is_shipping_page and matrixused then begin
36446 matrixtransformrect(pdf_left(p), cur_page_height - pdf_bottom(p),
36447 pdf_right(p), cur_page_height - pdf_top(p));
36448 pdf_left(p) := getllx;
36449 pdf_bottom(p) := cur_page_height - getlly;
36450 pdf_right(p) := geturx;
36451 pdf_top(p) := cur_page_height - getury;
36452 end;
36453 pdf_left(p) := pdf_left(p) - margin;
36454 pdf_top(p) := pdf_top(p) - margin;
36455 pdf_right(p) := pdf_right(p) + margin;
36456 pdf_bottom(p) := pdf_bottom(p) + margin;
36457 end;
36458
36459 procedure do_annot(p, parent_box: pointer; x, y: scaled);
36460 begin
36461 if not is_shipping_page then
36462 pdf_error("ext4", "annotations cannot be inside an XForm");
36463 if doing_leaders then
36464 return;
36465 if is_obj_scheduled(pdf_annot_objnum(p)) then
36466 pdf_annot_objnum(p) := pdf_new_objnum;
36467 set_rect_dimens(p, parent_box, x, y,
36468 pdf_width(p), pdf_height(p), pdf_depth(p), 0);
36469 obj_annot_ptr(pdf_annot_objnum(p)) := p;
36470 pdf_append_list(pdf_annot_objnum(p))(pdf_annot_list);
36471 set_obj_scheduled(pdf_annot_objnum(p));
36472 end;
36473
36474 @ To implement nested link annotations, we need a stack to hold copy of
36475 |pdf_start_link_node|'s that are being written out, together with their box
36476 nesting level.
36477
36478 @d pdf_link_stack_top == pdf_link_stack[pdf_link_stack_ptr]
36479
36480 @<Constants...@>=
36481 @!pdf_max_link_level = 10; {maximum depth of link nesting}
36482
36483 @ @<Types...@>=
36484 @!pdf_link_stack_record = record
36485 nesting_level: integer;
36486 link_node: pointer; {holds a copy of the corresponding |pdf_start_link_node|}
36487 ref_link_node: pointer; {points to original |pdf_start_link_node|, or a
36488 copy of |link_node| created by |append_link| in
36489 case of multi-line link}
36490 end;
36491
36492 @ @<Glob...@>=
36493 @!pdf_link_stack: array[1..pdf_max_link_level] of pdf_link_stack_record;
36494 @!pdf_link_stack_ptr: small_number;
36495
36496 @ @<Set init...@>=
36497 pdf_link_stack_ptr := 0;
36498
36499 @ @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
36500 procedure push_link_level(p: pointer);
36501 begin
36502 if pdf_link_stack_ptr >= pdf_max_link_level then
36503 overflow("pdf link stack size", pdf_max_link_level);
36504 pdfassert((type(p) = whatsit_node) and (subtype(p) = pdf_start_link_node));
36505 incr(pdf_link_stack_ptr);
36506 pdf_link_stack_top.nesting_level := cur_s;
36507 pdf_link_stack_top.link_node := copy_node_list(p);
36508 pdf_link_stack_top.ref_link_node := p;
36509 end;
36510
36511 procedure pop_link_level;
36512 begin
36513 pdfassert(pdf_link_stack_ptr > 0);
36514 flush_node_list(pdf_link_stack_top.link_node);
36515 decr(pdf_link_stack_ptr);
36516 end;
36517
36518 procedure do_link(p, parent_box: pointer; x, y: scaled);
36519 begin
36520 if not is_shipping_page then
36521 pdf_error("ext4", "link annotations cannot be inside an XForm");
36522 pdfassert(type(parent_box) = hlist_node);
36523 if is_obj_scheduled(pdf_link_objnum(p)) then
36524 pdf_link_objnum(p) := pdf_new_objnum;
36525 push_link_level(p);
36526 set_rect_dimens(p, parent_box, x, y,
36527 pdf_width(p), pdf_height(p), pdf_depth(p),
36528 pdf_link_margin);
36529 obj_annot_ptr(pdf_link_objnum(p)) := p; {the reference for the pdf annot object
36530 must be set here}
36531 pdf_append_list(pdf_link_objnum(p))(pdf_link_list);
36532 set_obj_scheduled(pdf_link_objnum(p));
36533 end;
36534
36535 procedure end_link;
36536 var p: pointer;
36537 begin
36538 if pdf_link_stack_ptr < 1 then
36539 pdf_error("ext4", "pdf_link_stack empty, \pdfendlink used without \pdfstartlink?");
36540 if pdf_link_stack_top.nesting_level <> cur_s then
36541 pdf_warning(0, "\pdfendlink ended up in different nesting level than \pdfstartlink", true, true);
36542
36543 {N.B.: test for running link must be done on |link_node| and not |ref_link_node|,
36544 as |ref_link_node| can be set by |do_link| or |append_link| already}
36545
36546 if is_running(pdf_width(pdf_link_stack_top.link_node)) then begin
36547 p := pdf_link_stack_top.ref_link_node;
36548 if is_shipping_page and matrixused then begin
36549 matrixrecalculate(cur_h + pdf_link_margin);
36550 pdf_left(p) := getllx - pdf_link_margin;
36551 pdf_top(p) := cur_page_height - getury - pdf_link_margin;
36552 pdf_right(p) := geturx + pdf_link_margin;
36553 pdf_bottom(p) := cur_page_height - getlly + pdf_link_margin;
36554 end
36555 else
36556 pdf_right(p) := cur_h + pdf_link_margin;
36557 end;
36558 pop_link_level;
36559 end;
36560
36561 @ For ``running'' annotations we must append a new node when the end of
36562 annotation is in other box than its start. The new created node is identical to
36563 corresponding whatsit node representing the start of annotation, but its
36564 |info| field is |max_halfword|. We set |info| field just before destroying the
36565 node, in order to use |flush_node_list| to do the job.
36566
36567 @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
36568 procedure append_link(parent_box: pointer; x, y: scaled; i: small_number); {append a new
36569 pdf annot to |pdf_link_list|}
36570 var p: pointer;
36571 begin
36572 pdfassert(type(parent_box) = hlist_node);
36573 p := copy_node_list(pdf_link_stack[i].link_node);
36574 pdf_link_stack[i].ref_link_node := p;
36575 info(p) := max_halfword; {mark that this node is not a whatsit node}
36576 link(p) := null; {this node is not linked in any list}
36577 set_rect_dimens(p, parent_box, x, y,
36578 pdf_width(p), pdf_height(p), pdf_depth(p),
36579 pdf_link_margin);
36580 pdf_create_obj(obj_type_others, 0);
36581 obj_annot_ptr(obj_ptr) := p;
36582 pdf_append_list(obj_ptr)(pdf_link_list);
36583 end;
36584
36585 @ Threads are handled in similar way as link annotations.
36586
36587 @<Declare procedures needed in |pdf_hlist_out|, |pdf_vlist_out|@>=
36588 procedure append_bead(p: pointer);
36589 var a, b, c, t: integer;
36590 begin
36591 if not is_shipping_page then
36592 pdf_error("ext4", "threads cannot be inside an XForm");
36593 t := get_obj(obj_type_thread, pdf_thread_id(p), pdf_thread_named_id(p));
36594 b := pdf_new_objnum;
36595 obj_bead_ptr(b) := pdf_get_mem(pdfmem_bead_size);
36596 obj_bead_page(b) := pdf_last_page;
36597 obj_bead_data(b) := p;
36598 if pdf_thread_attr(p) <> null then
36599 obj_bead_attr(b) := tokens_to_string(pdf_thread_attr(p))
36600 else
36601 obj_bead_attr(b) := 0;
36602 if obj_thread_first(t) = 0 then begin
36603 obj_thread_first(t) := b;
36604 obj_bead_next(b) := b;
36605 obj_bead_prev(b) := b;
36606 end
36607 else begin
36608 a := obj_thread_first(t);
36609 c := obj_bead_prev(a);
36610 obj_bead_prev(b) := c;
36611 obj_bead_next(b) := a;
36612 obj_bead_prev(a) := b;
36613 obj_bead_next(c) := b;
36614 end;
36615 pdf_append_list(b)(pdf_bead_list);
36616 end;
36617
36618 procedure do_thread(p, parent_box: pointer; x, y: scaled);
36619 begin
36620 if doing_leaders then
36621 return;
36622 if subtype(p) = pdf_start_thread_node then begin
36623 pdf_thread_wd := pdf_width(p);
36624 pdf_thread_ht := pdf_height(p);
36625 pdf_thread_dp := pdf_depth(p);
36626 pdf_last_thread_id := pdf_thread_id(p);
36627 pdf_last_thread_named_id := (pdf_thread_named_id(p) > 0);
36628 if pdf_last_thread_named_id then
36629 add_token_ref(pdf_thread_id(p));
36630 pdf_thread_level := cur_s;
36631 end;
36632 set_rect_dimens(p, parent_box, x, y,
36633 pdf_width(p), pdf_height(p), pdf_depth(p),
36634 pdf_thread_margin);
36635 append_bead(p);
36636 last_thread := p;
36637 end;
36638
36639 procedure append_thread(parent_box: pointer; x, y: scaled);
36640 var p: pointer;
36641 begin
36642 p := get_node(pdf_thread_node_size);
36643 info(p) := max_halfword; {this is not a whatsit node}
36644 link(p) := null; {this node will be destroyed separately}
36645 pdf_width(p) := pdf_thread_wd;
36646 pdf_height(p) := pdf_thread_ht;
36647 pdf_depth(p) := pdf_thread_dp;
36648 pdf_thread_attr(p) := null;
36649 pdf_thread_id(p) := pdf_last_thread_id;
36650 if pdf_last_thread_named_id then begin
36651 add_token_ref(pdf_thread_id(p));
36652 pdf_thread_named_id(p) := 1;
36653 end
36654 else
36655 pdf_thread_named_id(p) := 0;
36656 set_rect_dimens(p, parent_box, x, y,
36657 pdf_width(p), pdf_height(p), pdf_depth(p),
36658 pdf_thread_margin);
36659 append_bead(p);
36660 last_thread := p;
36661 end;
36662
36663 procedure end_thread;
36664 begin
36665 if pdf_thread_level <> cur_s then
36666 pdf_error("ext4", "\pdfendthread ended up in different nesting level than \pdfstartthread");
36667 if is_running(pdf_thread_dp) and (last_thread <> null) then
36668 pdf_bottom(last_thread) := cur_v + pdf_thread_margin;
36669 if pdf_last_thread_named_id then
36670 delete_token_ref(pdf_last_thread_id);
36671 last_thread := null;
36672 end;
36673
36674 function open_subentries(p: pointer): integer;
36675 var k, c: integer;
36676 l, r: integer;
36677 begin
36678 k := 0;
36679 if obj_outline_first(p) <> 0 then begin
36680 l := obj_outline_first(p);
36681 repeat
36682 incr(k);
36683 c := open_subentries(l);
36684 if obj_outline_count(l) > 0 then
36685 k := k + c;
36686 obj_outline_parent(l) := p;
36687 r := obj_outline_next(l);
36688 if r = 0 then
36689 obj_outline_last(p) := l;
36690 l := r;
36691 until l = 0;
36692 end;
36693 if obj_outline_count(p) > 0 then
36694 obj_outline_count(p) := k
36695 else
36696 obj_outline_count(p) := -k;
36697 open_subentries := k;
36698 end;
36699
36700 procedure do_dest(p, parent_box: pointer; x, y: scaled);
36701 var k: integer;
36702 begin
36703 if not is_shipping_page then
36704 pdf_error("ext4", "destinations cannot be inside an XForm");
36705 if doing_leaders then
36706 return;
36707 if pdf_dest_objnum(p) = null then
36708 k := get_obj(obj_type_dest, pdf_dest_id(p), pdf_dest_named_id(p))
36709 else
36710 k := get_obj(obj_type_struct_dest, pdf_dest_id(p), pdf_dest_named_id(p));
36711 if obj_dest_ptr(k) <> null then begin
36712 warn_dest_dup(pdf_dest_id(p), pdf_dest_named_id(p),
36713 "ext4", "has been already used, duplicate ignored");
36714 return;
36715 end;
36716 obj_dest_ptr(k) := p;
36717 pdf_append_list(k)(pdf_dest_list);
36718 case pdf_dest_type(p) of
36719 pdf_dest_xyz:
36720 if matrixused then
36721 set_rect_dimens(p, parent_box, x, y,
36722 pdf_width(p), pdf_height(p), pdf_depth(p),
36723 pdf_dest_margin)
36724 else begin
36725 pdf_left(p) := cur_h;
36726 pdf_top(p) := cur_v;
36727 end;
36728 pdf_dest_fith,
36729 pdf_dest_fitbh:
36730 if matrixused then
36731 set_rect_dimens(p, parent_box, x, y,
36732 pdf_width(p), pdf_height(p), pdf_depth(p),
36733 pdf_dest_margin)
36734 else
36735 pdf_top(p) := cur_v;
36736 pdf_dest_fitv,
36737 pdf_dest_fitbv:
36738 if matrixused then
36739 set_rect_dimens(p, parent_box, x, y,
36740 pdf_width(p), pdf_height(p), pdf_depth(p),
36741 pdf_dest_margin)
36742 else
36743 pdf_left(p) := cur_h;
36744 pdf_dest_fit,
36745 pdf_dest_fitb:
36746 do_nothing;
36747 pdf_dest_fitr:
36748 set_rect_dimens(p, parent_box, x, y,
36749 pdf_width(p), pdf_height(p), pdf_depth(p),
36750 pdf_dest_margin);
36751 endcases;
36752 end;
36753
36754 procedure out_form(p: pointer);
36755 begin
36756 pdf_end_text;
36757 pdf_print_ln("q");
36758 if pdf_lookup_list(pdf_xform_list, pdf_xform_objnum(p)) = null then
36759 pdf_append_list(pdf_xform_objnum(p))(pdf_xform_list);
36760 cur_v := cur_v + obj_xform_depth(pdf_xform_objnum(p));
36761 pdf_print("1 0 0 1 ");
36762 pdf_print_bp(pdf_x(cur_h)); pdf_out(" ");
36763 pdf_print_bp(pdf_y(cur_v));
36764 pdf_print_ln(" cm");
36765 pdf_print("/Fm");
36766 pdf_print_int(obj_info(pdf_xform_objnum(p)));
36767 pdf_print_resname_prefix;
36768 pdf_print_ln(" Do");
36769 pdf_print_ln("Q");
36770 end;
36771
36772 procedure out_image(p: pointer);
36773 var image, groupref: integer;
36774 img_w, img_h: integer;
36775 begin
36776 image := obj_ximage_data(pdf_ximage_objnum(p));
36777 if (image_rotate(image) = 90) or (image_rotate(image) = 270) then begin
36778 img_h := image_width(image);
36779 img_w := image_height(image);
36780 end else begin
36781 img_w := image_width(image);
36782 img_h := image_height(image);
36783 end;
36784
36785 pdf_end_text;
36786 pdf_print_ln("q");
36787 if pdf_lookup_list(pdf_ximage_list, pdf_ximage_objnum(p)) = null then
36788 pdf_append_list(pdf_ximage_objnum(p))(pdf_ximage_list);
36789 if not is_pdf_image(image) then begin
36790 if is_png_image(image) then begin
36791 groupref := get_image_group_ref(image);
36792 if (groupref > 0) and (pdf_page_group_val = 0) then
36793 pdf_page_group_val := groupref;
36794 end;
36795 pdf_print_real(ext_xn_over_d(pdf_width(p),
36796 ten_pow[6], one_hundred_bp), 4);
36797 pdf_print(" 0 0 ");
36798 pdf_print_real(ext_xn_over_d(pdf_height(p) + pdf_depth(p),
36799 ten_pow[6], one_hundred_bp), 4);
36800 pdf_out(" ");
36801 pdf_print_bp(pdf_x(cur_h)); pdf_out(" ");
36802 pdf_print_bp(pdf_y(cur_v));
36803 end
36804 else begin
36805 {for pdf images we generate the page group object number here}
36806 groupref := get_image_group_ref(image); {0: no group, -1: to be generated; >0: already written}
36807 if (groupref <> 0) and (pdf_page_group_val = 0) then begin
36808 if groupref = -1 then begin
36809 pdf_page_group_val := pdf_new_objnum;
36810 set_image_group_ref(image, pdf_page_group_val);
36811 end
36812 else { groupref > 0 }
36813 pdf_page_group_val := groupref;
36814 end;
36815 pdf_print_real(ext_xn_over_d(pdf_width(p),
36816 ten_pow[6], img_w), 6);
36817 pdf_print(" 0 0 ");
36818 pdf_print_real(ext_xn_over_d(pdf_height(p) + pdf_depth(p),
36819 ten_pow[6], img_h), 6);
36820 pdf_out(" ");
36821 pdf_print_bp(pdf_x(cur_h) -
36822 ext_xn_over_d(pdf_width(p), epdf_orig_x(image),
36823 img_w));
36824 pdf_out(" ");
36825 pdf_print_bp(pdf_y(cur_v) -
36826 ext_xn_over_d(pdf_height(p) + pdf_depth(p), epdf_orig_y(image),
36827 img_h));
36828 end;
36829 pdf_print_ln(" cm");
36830 pdf_print("/Im");
36831 pdf_print_int(obj_info(pdf_ximage_objnum(p)));
36832 pdf_print_resname_prefix;
36833 pdf_print_ln(" Do");
36834 pdf_print_ln("Q");
36835 end;
36836
36837 function gap_amount(p: pointer; cur_pos: scaled): scaled; {find the gap between
36838 the position of the current snap node |p| and the nearest point on the grid}
36839 var snap_unit, stretch_amount, shrink_amount: scaled;
36840 last_pos, next_pos, g, g2: scaled;
36841 begin
36842 snap_unit := width(snap_glue_ptr(p));
36843 if stretch_order(snap_glue_ptr(p)) > normal then
36844 stretch_amount := max_dimen
36845 else
36846 stretch_amount := stretch(snap_glue_ptr(p));
36847 if shrink_order(snap_glue_ptr(p)) > normal then
36848 shrink_amount := max_dimen
36849 else
36850 shrink_amount := shrink(snap_glue_ptr(p));
36851 if subtype(p) = pdf_snapy_node then
36852 last_pos := pdf_snapy_refpos +
36853 snap_unit * ((cur_pos - pdf_snapy_refpos) div snap_unit)
36854 else
36855 pdf_error("snapping", "invalid parameter value for gap_amount");
36856 next_pos := last_pos + snap_unit;
36857 @{
36858 print_nl("snap ref pos = "); print_scaled(pdf_snapy_refpos);
36859 print_nl("snap glue = "); print_spec(snap_glue_ptr(p), 0);
36860 print_nl("gap amount = "); print_scaled(snap_unit);
36861 print_nl("stretch amount = "); print_scaled(stretch_amount);
36862 print_nl("shrink amount = "); print_scaled(shrink_amount);
36863 print_nl("last point = "); print_scaled(last_pos);
36864 print_nl("cur point = "); print_scaled(cur_pos);
36865 print_nl("next point = "); print_scaled(next_pos);
36866 @}
36867 g := max_dimen;
36868 g2 := max_dimen;
36869 gap_amount := 0;
36870 if cur_pos - last_pos < shrink_amount then
36871 g := cur_pos - last_pos;
36872 if (next_pos - cur_pos < stretch_amount) then
36873 g2 := next_pos - cur_pos;
36874 if (g = max_dimen) and (g2 = max_dimen) then
36875 return; {unable to snap}
36876 if g2 <= g then
36877 gap_amount := g2 {skip forward}
36878 else
36879 gap_amount := -g; {skip backward}
36880 end;
36881
36882 function get_vpos(p, q, b: pointer): pointer; {find the vertical position of
36883 node |q| in the output PDF page; this functions is called when the current node
36884 is |p| and current position is |cur_v| (global variable); |b| is the parent
36885 box;}
36886 var tmp_v: scaled;
36887 g_order: glue_ord; {applicable order of infinity for glue}
36888 g_sign: normal..shrinking; {selects type of glue}
36889 glue_temp: real; {glue value before rounding}
36890 cur_glue: real; {glue seen so far}
36891 cur_g: scaled; {rounded equivalent of |cur_glue| times the glue ratio}
36892 this_box: pointer; {pointer to containing box}
36893 begin
36894 tmp_v := cur_v;
36895 this_box := b;
36896 cur_g := 0;
36897 cur_glue := float_constant(0);
36898 g_order := glue_order(this_box);
36899 g_sign := glue_sign(this_box);
36900 while (p <> q) and (p <> null) do begin
36901 if is_char_node(p) then
36902 confusion("get_vpos")
36903 else begin
36904 case type(p) of
36905 hlist_node,
36906 vlist_node,
36907 rule_node:
36908 tmp_v := tmp_v + height(p) + depth(p);
36909 whatsit_node:
36910 if (subtype(p) = pdf_refxform_node) or
36911 (subtype(p) = pdf_refximage_node) then
36912 tmp_v := tmp_v + pdf_height(p) + pdf_depth(p);
36913 glue_node: begin
36914 @<Move down without outputting leaders@>;
36915 tmp_v := tmp_v + rule_ht;
36916 end;
36917 kern_node:
36918 tmp_v := tmp_v + width(p);
36919 othercases do_nothing;
36920 endcases;
36921 end;
36922 p := link(p);
36923 end;
36924 get_vpos := tmp_v;
36925 end;
36926
36927 procedure do_snapy_comp(p, b: pointer); {do snapping compensation in vertical
36928 direction; search for the next snap node and do the compensation if found}
36929 var q: pointer;
36930 tmp_v, g, g2: scaled;
36931 begin
36932 if not (not is_char_node(p) and
36933 (type(p) = whatsit_node) and
36934 (subtype(p) = pdf_snapy_comp_node))
36935 then
36936 pdf_error("snapping", "invalid parameter value for do_snapy_comp");
36937 q := p;
36938 while (q <> null) do begin
36939 if not is_char_node(q) and
36940 (type(q) = whatsit_node) and
36941 (subtype(q) = pdf_snapy_node)
36942 then begin
36943 tmp_v := get_vpos(p, q, b); {get the position of |q|}
36944 g := gap_amount(q, tmp_v); {get the gap to the grid}
36945 g2 := round_xn_over_d(g, snapy_comp_ratio(p), 1000); {adjustment for |p|}
36946 @{
36947 print_nl("do_snapy_comp: tmp_v = "); print_scaled(tmp_v);
36948 print_nl("do_snapy_comp: cur_v = "); print_scaled(cur_v);
36949 print_nl("do_snapy_comp: g = "); print_scaled(g);
36950 print_nl("do_snapy_comp: g2 = "); print_scaled(g2);
36951 @}
36952 cur_v := cur_v + g2;
36953 final_skip(q) := g - g2; {adjustment for |q|}
36954 if final_skip(q) = 0 then
36955 final_skip(q) := 1; {use |1sp| as the magic value to record
36956 that |final_skip| has been set here}
36957 return;
36958 end;
36959 q := link(q);
36960 end;
36961 end;
36962
36963 procedure do_snapy(p: pointer);
36964 begin
36965 incr(count_do_snapy);
36966 @{
36967 print_nl("do_snapy: count = "); print_int(count_do_snapy);
36968 print_nl("do_snapy: cur_v = "); print_scaled(cur_v);
36969 print_nl("do_snapy: final skip = "); print_scaled(final_skip(p));
36970 @}
36971 if final_skip(p) <> 0 then
36972 cur_v := cur_v + final_skip(p)
36973 else
36974 cur_v := cur_v + gap_amount(p, cur_v);
36975 @{
36976 print_nl("do_snapy: cur_v after snap = "); print_scaled(cur_v);
36977 @}
36978 end;
36979
36980 @ @<Move down without outputting leaders@>=
36981 begin g:=glue_ptr(p); rule_ht:=width(g)-cur_g;
36982 if g_sign<>normal then
36983 begin if g_sign=stretching then
36984 begin if stretch_order(g)=g_order then
36985 begin cur_glue:=cur_glue+stretch(g);
36986 vet_glue(float(glue_set(this_box))*cur_glue);
36987 @^real multiplication@>
36988 cur_g:=round(glue_temp);
36989 end;
36990 end
36991 else if shrink_order(g)=g_order then
36992 begin cur_glue:=cur_glue-shrink(g);
36993 vet_glue(float(glue_set(this_box))*cur_glue);
36994 cur_g:=round(glue_temp);
36995 end;
36996 end;
36997 rule_ht:=rule_ht+cur_g;
36998 end
36999
37000 @ @<Output the whatsit node |p| in |pdf_vlist_out|@>=
37001 case subtype(p) of
37002 pdf_literal_node,pdf_lateliteral_node:
37003 pdf_out_literal(p);
37004 pdf_colorstack_node:
37005 pdf_out_colorstack(p);
37006 pdf_setmatrix_node:
37007 pdf_out_setmatrix(p);
37008 pdf_save_node:
37009 pdf_out_save(p);
37010 pdf_restore_node:
37011 pdf_out_restore(p);
37012 pdf_refobj_node:
37013 pdf_append_list(pdf_obj_objnum(p))(pdf_obj_list);
37014 pdf_refxform_node:
37015 @<Output a Form node in a vlist@>;
37016 pdf_refximage_node:
37017 @<Output a Image node in a vlist@>;
37018 pdf_annot_node:
37019 do_annot(p, this_box, left_edge, top_edge + height(this_box));
37020 pdf_start_link_node:
37021 pdf_error("ext4", "\pdfstartlink ended up in vlist");
37022 pdf_end_link_node:
37023 pdf_error("ext4", "\pdfendlink ended up in vlist");
37024 pdf_dest_node:
37025 do_dest(p, this_box, left_edge, top_edge + height(this_box));
37026 pdf_thread_node,
37027 pdf_start_thread_node:
37028 do_thread(p, this_box, left_edge, top_edge + height(this_box));
37029 pdf_end_thread_node:
37030 end_thread;
37031 pdf_save_pos_node:
37032 @<Save current position to |pdf_last_x_pos|, |pdf_last_y_pos|@>;
37033 special_node,latespecial_node:
37034 pdf_special(p);
37035 pdf_snap_ref_point_node:
37036 @<Save current position to |pdf_snapx_refpos|, |pdf_snapy_refpos|@>;
37037 pdf_snapy_comp_node:
37038 do_snapy_comp(p, this_box);
37039 pdf_snapy_node:
37040 do_snapy(p);
37041 pdf_interword_space_on_node:
37042 gen_faked_interword_space := true;
37043 pdf_interword_space_off_node:
37044 gen_faked_interword_space := false;
37045 pdf_fake_space_node:
37046 pdf_insert_fake_space;
37047 pdf_running_link_off_node:
37048 gen_running_link := false;
37049 pdf_running_link_on_node:
37050 gen_running_link := true;
37051 othercases out_what(p);
37052 endcases
37053
37054 @ @<Glob...@>=
37055 @!is_shipping_page: boolean; {set to |shipping_page| when |pdf_ship_out| starts}
37056
37057 @ @<Save current position to |pdf_last_x_pos|, |pdf_last_y_pos|@>=
37058 begin
37059 pdf_last_x_pos := cur_h;
37060 if is_shipping_page then
37061 pdf_last_y_pos := cur_page_height - cur_v
37062 else
37063 pdf_last_y_pos := pdf_xform_height + pdf_xform_depth - cur_v;
37064 end
37065
37066 @ @<Save current position to |pdf_snapx_refpos|, |pdf_snapy_refpos|@>=
37067 begin
37068 pdf_snapx_refpos := cur_h;
37069 pdf_snapy_refpos := cur_v;
37070 end
37071
37072 @ @<Output a Image node in a vlist@>=
37073 begin cur_v:=cur_v+pdf_height(p)+pdf_depth(p); save_v:=cur_v;
37074 cur_h:=left_edge;
37075 out_image(p);
37076 cur_v:=save_v; cur_h:=left_edge;
37077 end
37078
37079 @ @<Output a Form node in a vlist@>=
37080 begin cur_v:=cur_v+pdf_height(p); save_v:=cur_v;
37081 cur_h:=left_edge;
37082 out_form(p);
37083 cur_v:=save_v+pdf_depth(p); cur_h:=left_edge;
37084 end
37085
37086 @ @<Output the whatsit node |p| in |pdf_hlist_out|@>=
37087 case subtype(p) of
37088 pdf_literal_node,pdf_lateliteral_node:
37089 pdf_out_literal(p);
37090 pdf_colorstack_node:
37091 pdf_out_colorstack(p);
37092 pdf_setmatrix_node:
37093 pdf_out_setmatrix(p);
37094 pdf_save_node:
37095 pdf_out_save(p);
37096 pdf_restore_node:
37097 pdf_out_restore(p);
37098 pdf_refobj_node:
37099 pdf_append_list(pdf_obj_objnum(p))(pdf_obj_list);
37100 pdf_refxform_node:
37101 @<Output a Form node in a hlist@>;
37102 pdf_refximage_node:
37103 @<Output a Image node in a hlist@>;
37104 pdf_annot_node:
37105 do_annot(p, this_box, left_edge, base_line);
37106 pdf_start_link_node:
37107 do_link(p, this_box, left_edge, base_line);
37108 pdf_end_link_node:
37109 end_link;
37110 pdf_dest_node:
37111 do_dest(p, this_box, left_edge, base_line);
37112 pdf_thread_node:
37113 do_thread(p, this_box, left_edge, base_line);
37114 pdf_start_thread_node:
37115 pdf_error("ext4", "\pdfstartthread ended up in hlist");
37116 pdf_end_thread_node:
37117 pdf_error("ext4", "\pdfendthread ended up in hlist");
37118 pdf_save_pos_node:
37119 @<Save current position to |pdf_last_x_pos|, |pdf_last_y_pos|@>;
37120 special_node,latespecial_node:
37121 pdf_special(p);
37122 pdf_snap_ref_point_node:
37123 @<Save current position to |pdf_snapx_refpos|, |pdf_snapy_refpos|@>;
37124 pdf_snapy_comp_node,
37125 pdf_snapy_node: do_nothing; {snapy nodes do nothing in hlist}
37126 pdf_interword_space_on_node:
37127 gen_faked_interword_space := true;
37128 pdf_interword_space_off_node:
37129 gen_faked_interword_space := false;
37130 pdf_fake_space_node:
37131 pdf_insert_fake_space;
37132 pdf_running_link_off_node:
37133 gen_running_link := false;
37134 pdf_running_link_on_node:
37135 gen_running_link := true;
37136 othercases out_what(p);
37137 endcases
37138
37139 @ @<Output a Image node in a hlist@>=
37140 begin
37141 cur_v:=base_line+pdf_depth(p);
37142 edge:=cur_h;
37143 out_image(p);
37144 cur_h:=edge+pdf_width(p); cur_v:=base_line;
37145 end
37146
37147 @ @<Output a Form node in a hlist@>=
37148 begin
37149 cur_v:=base_line;
37150 edge:=cur_h;
37151 out_form(p);
37152 cur_h:=edge+pdf_width(p); cur_v:=base_line;
37153 end
37154
37155 @* \[53a] The extended features of \eTeX.
37156 The program has two modes of operation: (1)~In \TeX\ compatibility mode
37157 it fully deserves the name \TeX\ and there are neither extended features
37158 nor additional primitive commands. There are, however, a few
37159 modifications that would be legitimate in any implementation of \TeX\
37160 such as, e.g., preventing inadequate results of the glue to \.{DVI}
37161 unit conversion during |ship_out|. (2)~In extended mode there are
37162 additional primitive commands and the extended features of \eTeX\ are
37163 available.
37164
37165 The distinction between these two modes of operation initially takes
37166 place when a `virgin' \.{eINITEX} starts without reading a format file.
37167 Later on the values of all \eTeX\ state variables are inherited when
37168 \.{eVIRTEX} (or \.{eINITEX}) reads a format file.
37169
37170 The code below is designed to work for cases where `$|init|\ldots|tini|$'
37171 is a run-time switch.
37172
37173 @<Enable \eTeX, if requested@>=
37174 @!init if (buffer[loc]="*")and(format_ident=" (INITEX)") then
37175 begin no_new_control_sequence:=false;
37176 @<Generate all \eTeX\ primitives@>@;
37177 incr(loc); eTeX_mode:=1; {enter extended mode}
37178 @<Initialize variables for \eTeX\ extended mode@>@;
37179 end;
37180 tini@;@/
37181 if not no_new_control_sequence then {just entered extended mode ?}
37182 no_new_control_sequence:=true@+else
37183
37184 @ The \eTeX\ features available in extended mode are grouped into two
37185 categories: (1)~Some of them are permanently enabled and have no
37186 semantic effect as long as none of the additional primitives are
37187 executed. (2)~The remaining \eTeX\ features are optional and can be
37188 individually enabled and disabled. For each optional feature there is
37189 an \eTeX\ state variable named \.{\\...state}; the feature is enabled,
37190 resp.\ disabled by assigning a positive, resp.\ non-positive value to
37191 that integer.
37192
37193 @d eTeX_state_base=int_base+eTeX_state_code
37194 @d eTeX_state(#)==eqtb[eTeX_state_base+#].int {an \eTeX\ state variable}
37195 @#
37196 @d eTeX_version_code=eTeX_int {code for \.{\\eTeXversion}}
37197
37198 @<Generate all \eTeX...@>=
37199 primitive("lastnodetype",last_item,last_node_type_code);
37200 @!@:last_node_type_}{\.{\\lastnodetype} primitive@>
37201 primitive("eTeXversion",last_item,eTeX_version_code);
37202 @!@:eTeX_version_}{\.{\\eTeXversion} primitive@>
37203 primitive("eTeXrevision",convert,eTeX_revision_code);@/
37204 @!@:eTeX_revision_}{\.{\\eTeXrevision} primitive@>
37205
37206 @ @<Cases of |last_item| for |print_cmd_chr|@>=
37207 last_node_type_code: print_esc("lastnodetype");
37208 eTeX_version_code: print_esc("eTeXversion");
37209
37210 @ @<Cases for fetching an integer value@>=
37211 eTeX_version_code: cur_val:=eTeX_version;
37212
37213 @ @d eTeX_ex==(eTeX_mode=1) {is this extended mode?}
37214
37215 @<Glob...@>=
37216 @!eTeX_mode: 0..1; {identifies compatibility and extended mode}
37217
37218 @ @<Initialize table entries...@>=
37219 eTeX_mode:=0; {initially we are in compatibility mode}
37220 @<Initialize variables for \eTeX\ compatibility mode@>@;
37221
37222 @ @<Dump the \eTeX\ state@>=
37223 dump_int(eTeX_mode);
37224 for j:=0 to eTeX_states-1 do eTeX_state(j):=0; {disable all enhancements}
37225
37226 @ @<Undump the \eTeX\ state@>=
37227 undump(0)(1)(eTeX_mode);
37228 if eTeX_ex then
37229 begin @<Initialize variables for \eTeX\ extended mode@>@;
37230 end
37231 else begin @<Initialize variables for \eTeX\ compatibility mode@>@;
37232 end;
37233
37234 @ The |eTeX_enabled| function simply returns its first argument as
37235 result. This argument is |true| if an optional \eTeX\ feature is
37236 currently enabled; otherwise, if the argument is |false|, the function
37237 gives an error message.
37238
37239 @<Declare \eTeX\ procedures for use...@>=
37240 function eTeX_enabled(@!b:boolean;@!j:quarterword;@!k:halfword):boolean;
37241 begin if not b then
37242 begin print_err("Improper "); print_cmd_chr(j,k);
37243 help1("Sorry, this optional e-TeX feature has been disabled."); error;
37244 end;
37245 eTeX_enabled:=b;
37246 end;
37247
37248 @ First we implement the additional \eTeX\ parameters in the table of
37249 equivalents.
37250
37251 @<Generate all \eTeX...@>=
37252 primitive("everyeof",assign_toks,every_eof_loc);
37253 @!@:every_eof_}{\.{\\everyeof} primitive@>
37254 primitive("tracingassigns",assign_int,int_base+tracing_assigns_code);@/
37255 @!@:tracing_assigns_}{\.{\\tracingassigns} primitive@>
37256 primitive("tracinggroups",assign_int,int_base+tracing_groups_code);@/
37257 @!@:tracing_groups_}{\.{\\tracinggroups} primitive@>
37258 primitive("tracingifs",assign_int,int_base+tracing_ifs_code);@/
37259 @!@:tracing_ifs_}{\.{\\tracingifs} primitive@>
37260 primitive("tracingscantokens",assign_int,int_base+tracing_scan_tokens_code);@/
37261 @!@:tracing_scan_tokens_}{\.{\\tracingscantokens} primitive@>
37262 primitive("tracingnesting",assign_int,int_base+tracing_nesting_code);@/
37263 @!@:tracing_nesting_}{\.{\\tracingnesting} primitive@>
37264 primitive("predisplaydirection",
37265 assign_int,int_base+pre_display_direction_code);@/
37266 @!@:pre_display_direction_}{\.{\\predisplaydirection} primitive@>
37267 primitive("lastlinefit",assign_int,int_base+last_line_fit_code);@/
37268 @!@:last_line_fit_}{\.{\\lastlinefit} primitive@>
37269 primitive("savingvdiscards",assign_int,int_base+saving_vdiscards_code);@/
37270 @!@:saving_vdiscards_}{\.{\\savingvdiscards} primitive@>
37271 primitive("savinghyphcodes",assign_int,int_base+saving_hyph_codes_code);@/
37272 @!@:saving_hyph_codes_}{\.{\\savinghyphcodes} primitive@>
37273 primitive("ignoreprimitiveerror",assign_int,int_base+ignore_primitive_error_code);@/
37274 @!@:ignore_primitive_error_}{\.{\\ignoreprimitiveerror} primitive@>
37275
37276 @ @d every_eof==equiv(every_eof_loc)
37277
37278 @<Cases of |assign_toks| for |print_cmd_chr|@>=
37279 every_eof_loc: print_esc("everyeof");
37280
37281 @ @<Cases for |print_param|@>=
37282 tracing_assigns_code:print_esc("tracingassigns");
37283 tracing_groups_code:print_esc("tracinggroups");
37284 tracing_ifs_code:print_esc("tracingifs");
37285 tracing_scan_tokens_code:print_esc("tracingscantokens");
37286 tracing_nesting_code:print_esc("tracingnesting");
37287 pre_display_direction_code:print_esc("predisplaydirection");
37288 last_line_fit_code:print_esc("lastlinefit");
37289 saving_vdiscards_code:print_esc("savingvdiscards");
37290 saving_hyph_codes_code:print_esc("savinghyphcodes");
37291 ignore_primitive_error_code:print_esc("ignoreprimitiveerror");
37292
37293 @ In order to handle \.{\\everyeof} we need an array |eof_seen| of
37294 boolean variables.
37295
37296 @<Glob...@>=
37297 @!eof_seen : array[1..max_in_open] of boolean; {has eof been seen?}
37298
37299 @ The |print_group| procedure prints the current level of grouping and
37300 the name corresponding to |cur_group|.
37301
37302 @<Declare \eTeX\ procedures for tr...@>=
37303 procedure print_group(@!e:boolean);
37304 label exit;
37305 begin case cur_group of
37306 bottom_level: begin print("bottom level"); return;
37307 end;
37308 simple_group,semi_simple_group:
37309 begin if cur_group=semi_simple_group then print("semi ");
37310 print("simple");
37311 end;
37312 hbox_group,adjusted_hbox_group:
37313 begin if cur_group=adjusted_hbox_group then print("adjusted ");
37314 print("hbox");
37315 end;
37316 vbox_group: print("vbox");
37317 vtop_group: print("vtop");
37318 align_group,no_align_group:
37319 begin if cur_group=no_align_group then print("no ");
37320 print("align");
37321 end;
37322 output_group: print("output");
37323 disc_group: print("disc");
37324 insert_group: print("insert");
37325 vcenter_group: print("vcenter");
37326 math_group,math_choice_group,math_shift_group,math_left_group:
37327 begin print("math");
37328 if cur_group=math_choice_group then print(" choice")
37329 else if cur_group=math_shift_group then print(" shift")
37330 else if cur_group=math_left_group then print(" left");
37331 end;
37332 end; {there are no other cases}
37333 print(" group (level "); print_int(qo(cur_level)); print_char(")");
37334 if saved(-1)<>0 then
37335 begin if e then print(" entered at line ") else print(" at line ");
37336 print_int(saved(-1));
37337 end;
37338 exit:end;
37339
37340 @ The |group_trace| procedure is called when a new level of grouping
37341 begins (|e=false|) or ends (|e=true|) with |saved(-1)| containing the
37342 line number.
37343
37344 @<Declare \eTeX\ procedures for tr...@>=
37345 @!stat procedure group_trace(@!e:boolean);
37346 begin begin_diagnostic; print_char("{");
37347 if e then print("leaving ") else print("entering ");
37348 print_group(e); print_char("}"); end_diagnostic(false);
37349 end;
37350 tats
37351
37352 @ The \.{\\currentgrouplevel} and \.{\\currentgrouptype} commands return
37353 the current level of grouping and the type of the current group
37354 respectively.
37355
37356 @d current_group_level_code=eTeX_int+1 {code for \.{\\currentgrouplevel}}
37357 @d current_group_type_code=eTeX_int+2 {code for \.{\\currentgrouptype}}
37358
37359 @<Generate all \eTeX...@>=
37360 primitive("currentgrouplevel",last_item,current_group_level_code);
37361 @!@:current_group_level_}{\.{\\currentgrouplevel} primitive@>
37362 primitive("currentgrouptype",last_item,current_group_type_code);
37363 @!@:current_group_type_}{\.{\\currentgrouptype} primitive@>
37364
37365 @ @<Cases of |last_item| for |print_cmd_chr|@>=
37366 current_group_level_code: print_esc("currentgrouplevel");
37367 current_group_type_code: print_esc("currentgrouptype");
37368
37369 @ @<Cases for fetching an integer value@>=
37370 current_group_level_code: cur_val:=cur_level-level_one;
37371 current_group_type_code: cur_val:=cur_group;
37372
37373 @ The \.{\\currentiflevel}, \.{\\currentiftype}, and
37374 \.{\\currentifbranch} commands return the current level of conditionals
37375 and the type and branch of the current conditional.
37376
37377 @d current_if_level_code=eTeX_int+3 {code for \.{\\currentiflevel}}
37378 @d current_if_type_code=eTeX_int+4 {code for \.{\\currentiftype}}
37379 @d current_if_branch_code=eTeX_int+5 {code for \.{\\currentifbranch}}
37380
37381 @<Generate all \eTeX...@>=
37382 primitive("currentiflevel",last_item,current_if_level_code);
37383 @!@:current_if_level_}{\.{\\currentiflevel} primitive@>
37384 primitive("currentiftype",last_item,current_if_type_code);
37385 @!@:current_if_type_}{\.{\\currentiftype} primitive@>
37386 primitive("currentifbranch",last_item,current_if_branch_code);
37387 @!@:current_if_branch_}{\.{\\currentifbranch} primitive@>
37388
37389 @ @<Cases of |last_item| for |print_cmd_chr|@>=
37390 current_if_level_code: print_esc("currentiflevel");
37391 current_if_type_code: print_esc("currentiftype");
37392 current_if_branch_code: print_esc("currentifbranch");
37393
37394 @ @<Cases for fetching an integer value@>=
37395 current_if_level_code: begin q:=cond_ptr; cur_val:=0;
37396 while q<>null do
37397 begin incr(cur_val); q:=link(q);
37398 end;
37399 end;
37400 current_if_type_code: if cond_ptr=null then cur_val:=0
37401 else if cur_if<unless_code then cur_val:=cur_if+1
37402 else cur_val:=-(cur_if-unless_code+1);
37403 current_if_branch_code:
37404 if (if_limit=or_code)or(if_limit=else_code) then cur_val:=1
37405 else if if_limit=fi_code then cur_val:=-1
37406 else cur_val:=0;
37407
37408 @ The \.{\\fontcharwd}, \.{\\fontcharht}, \.{\\fontchardp}, and
37409 \.{\\fontcharic} commands return information about a character in a
37410 font.
37411
37412 @d font_char_wd_code=eTeX_dim {code for \.{\\fontcharwd}}
37413 @d font_char_ht_code=eTeX_dim+1 {code for \.{\\fontcharht}}
37414 @d font_char_dp_code=eTeX_dim+2 {code for \.{\\fontchardp}}
37415 @d font_char_ic_code=eTeX_dim+3 {code for \.{\\fontcharic}}
37416
37417 @<Generate all \eTeX...@>=
37418 primitive("fontcharwd",last_item,font_char_wd_code);
37419 @!@:font_char_wd_}{\.{\\fontcharwd} primitive@>
37420 primitive("fontcharht",last_item,font_char_ht_code);
37421 @!@:font_char_ht_}{\.{\\fontcharht} primitive@>
37422 primitive("fontchardp",last_item,font_char_dp_code);
37423 @!@:font_char_dp_}{\.{\\fontchardp} primitive@>
37424 primitive("fontcharic",last_item,font_char_ic_code);
37425 @!@:font_char_ic_}{\.{\\fontcharic} primitive@>
37426
37427 @ @<Cases of |last_item| for |print_cmd_chr|@>=
37428 font_char_wd_code: print_esc("fontcharwd");
37429 font_char_ht_code: print_esc("fontcharht");
37430 font_char_dp_code: print_esc("fontchardp");
37431 font_char_ic_code: print_esc("fontcharic");
37432
37433 @ @<Cases for fetching a dimension value@>=
37434 font_char_wd_code,
37435 font_char_ht_code,
37436 font_char_dp_code,
37437 font_char_ic_code: begin scan_font_ident; q:=cur_val; scan_char_num;
37438 if (font_bc[q]<=cur_val)and(font_ec[q]>=cur_val) then
37439 begin i:=char_info(q)(qi(cur_val));
37440 case m of
37441 font_char_wd_code: cur_val:=char_width(q)(i);
37442 font_char_ht_code: cur_val:=char_height(q)(height_depth(i));
37443 font_char_dp_code: cur_val:=char_depth(q)(height_depth(i));
37444 font_char_ic_code: cur_val:=char_italic(q)(i);
37445 end; {there are no other cases}
37446 end
37447 else cur_val:=0;
37448 end;
37449
37450 @ The \.{\\parshapedimen}, \.{\\parshapeindent}, and \.{\\parshapelength}
37451 commands return the indent and length parameters of the current
37452 \.{\\parshape} specification.
37453
37454 @d par_shape_length_code=eTeX_dim+4 {code for \.{\\parshapelength}}
37455 @d par_shape_indent_code=eTeX_dim+5 {code for \.{\\parshapeindent}}
37456 @d par_shape_dimen_code=eTeX_dim+6 {code for \.{\\parshapedimen}}
37457
37458 @<Generate all \eTeX...@>=
37459 primitive("parshapelength",last_item,par_shape_length_code);
37460 @!@:par_shape_length_}{\.{\\parshapelength} primitive@>
37461 primitive("parshapeindent",last_item,par_shape_indent_code);
37462 @!@:par_shape_indent_}{\.{\\parshapeindent} primitive@>
37463 primitive("parshapedimen",last_item,par_shape_dimen_code);
37464 @!@:par_shape_dimen_}{\.{\\parshapedimen} primitive@>
37465
37466 @ @<Cases of |last_item| for |print_cmd_chr|@>=
37467 par_shape_length_code: print_esc("parshapelength");
37468 par_shape_indent_code: print_esc("parshapeindent");
37469 par_shape_dimen_code: print_esc("parshapedimen");
37470
37471 @ @<Cases for fetching a dimension value@>=
37472 par_shape_length_code,
37473 par_shape_indent_code,
37474 par_shape_dimen_code: begin q:=cur_chr-par_shape_length_code; scan_int;
37475 if (par_shape_ptr=null)or(cur_val<=0) then cur_val:=0
37476 else begin if q=2 then
37477 begin q:=cur_val mod 2; cur_val:=(cur_val+q)div 2;
37478 end;
37479 if cur_val>info(par_shape_ptr) then cur_val:=info(par_shape_ptr);
37480 cur_val:=mem[par_shape_ptr+2*cur_val-q].sc;
37481 end;
37482 cur_val_level:=dimen_val;
37483 end;
37484
37485 @ The \.{\\showgroups} command displays all currently active grouping
37486 levels.
37487
37488 @d show_groups=4 { \.{\\showgroups} }
37489
37490 @<Generate all \eTeX...@>=
37491 primitive("showgroups",xray,show_groups);
37492 @!@:show_groups_}{\.{\\showgroups} primitive@>
37493
37494 @ @<Cases of |xray| for |print_cmd_chr|@>=
37495 show_groups:print_esc("showgroups");
37496
37497 @ @<Cases for |show_whatever|@>=
37498 show_groups: begin begin_diagnostic; show_save_groups;
37499 end;
37500
37501 @ @<Types...@>=
37502 @!save_pointer=0..save_size; {index into |save_stack|}
37503
37504 @ The modifications of \TeX\ required for the display produced by the
37505 |show_save_groups| procedure were first discussed by Donald~E. Knuth in
37506 {\sl TUGboat\/} {\bf 11}, 165--170 and 499--511, 1990.
37507 @^Knuth, Donald Ervin@>
37508
37509 In order to understand a group type we also have to know its mode.
37510 Since unrestricted horizontal modes are not associated with grouping,
37511 they are skipped when traversing the semantic nest.
37512
37513 @<Declare \eTeX\ procedures for use...@>=
37514 procedure show_save_groups;
37515 label found1,found2,found,done;
37516 var p:0..nest_size; {index into |nest|}
37517 @!m:-mmode..mmode; {mode}
37518 @!v:save_pointer; {saved value of |save_ptr|}
37519 @!l:quarterword; {saved value of |cur_level|}
37520 @!c:group_code; {saved value of |cur_group|}
37521 @!a:-1..1; {to keep track of alignments}
37522 @!i:integer;
37523 @!j:quarterword;
37524 @!s:str_number;
37525 begin p:=nest_ptr; nest[p]:=cur_list; {put the top level into the array}
37526 v:=save_ptr; l:=cur_level; c:=cur_group;
37527 save_ptr:=cur_boundary; decr(cur_level);@/
37528 a:=1;
37529 print_nl(""); print_ln;
37530 loop@+begin print_nl("### "); print_group(true);
37531 if cur_group=bottom_level then goto done;
37532 repeat m:=nest[p].mode_field;
37533 if p>0 then decr(p) else m:=vmode;
37534 until m<>hmode;
37535 print(" (");
37536 case cur_group of
37537 simple_group: begin incr(p); goto found2;
37538 end;
37539 hbox_group,adjusted_hbox_group: s:="hbox";
37540 vbox_group: s:="vbox";
37541 vtop_group: s:="vtop";
37542 align_group: if a=0 then
37543 begin if m=-vmode then s:="halign" else s:="valign";
37544 a:=1; goto found1;
37545 end
37546 else begin if a=1 then print("align entry") else print_esc("cr");
37547 if p>=a then p:=p-a;
37548 a:=0; goto found;
37549 end;
37550 no_align_group:
37551 begin incr(p); a:=-1; print_esc("noalign"); goto found2;
37552 end;
37553 output_group:
37554 begin print_esc("output"); goto found;
37555 end;
37556 math_group: goto found2;
37557 disc_group,math_choice_group:
37558 begin if cur_group=disc_group then print_esc("discretionary")
37559 else print_esc("mathchoice");
37560 for i:=1 to 3 do if i<=saved(-2) then print("{}");
37561 goto found2;
37562 end;
37563 insert_group:
37564 begin if saved(-2)=255 then print_esc("vadjust")
37565 else begin print_esc("insert"); print_int(saved(-2));
37566 end;
37567 goto found2;
37568 end;
37569 vcenter_group: begin s:="vcenter"; goto found1;
37570 end;
37571 semi_simple_group: begin incr(p); print_esc("begingroup"); goto found;
37572 end;
37573 math_shift_group:
37574 begin if m=mmode then print_char("$")
37575 else if nest[p].mode_field=mmode then
37576 begin print_cmd_chr(eq_no,saved(-2)); goto found;
37577 end;
37578 print_char("$"); goto found;
37579 end;
37580 math_left_group:
37581 begin if type(nest[p+1].eTeX_aux_field)=left_noad then print_esc("left")
37582 else print_esc("middle");
37583 goto found;
37584 end;
37585 end; {there are no other cases}
37586 @<Show the box context@>;
37587 found1: print_esc(s); @<Show the box packaging info@>;
37588 found2: print_char("{");
37589 found: print_char(")"); decr(cur_level);
37590 cur_group:=save_level(save_ptr); save_ptr:=save_index(save_ptr)
37591 end;
37592 done: save_ptr:=v; cur_level:=l; cur_group:=c;
37593 end;
37594
37595 @ @<Show the box packaging info@>=
37596 if saved(-2)<>0 then
37597 begin print_char(" ");
37598 if saved(-3)=exactly then print("to") else print("spread");
37599 print_scaled(saved(-2)); print("pt");
37600 end
37601
37602 @ @<Show the box context@>=
37603 i:=saved(-4);
37604 if i<>0 then
37605 if i<box_flag then
37606 begin if abs(nest[p].mode_field)=vmode then j:=hmove else j:=vmove;
37607 if i>0 then print_cmd_chr(j,0) else print_cmd_chr(j,1);
37608 print_scaled(abs(i)); print("pt");
37609 end
37610 else if i<ship_out_flag then
37611 begin if i>=global_box_flag then
37612 begin print_esc("global"); i:=i-(global_box_flag-box_flag);
37613 end;
37614 print_esc("setbox"); print_int(i-box_flag); print_char("=");
37615 end
37616 else print_cmd_chr(leader_ship,i-(leader_flag-a_leaders))
37617
37618 @ The |scan_general_text| procedure is much like |scan_toks(false,false)|,
37619 but will be invoked via |expand|, i.e., recursively.
37620 @^recursion@>
37621
37622 @<Declare \eTeX\ procedures for sc...@>=
37623 procedure@?scan_general_text; forward;@t\2@>
37624
37625 @ The token list (balanced text) created by |scan_general_text| begins
37626 at |link(temp_head)| and ends at |cur_val|. (If |cur_val=temp_head|,
37627 the list is empty.)
37628
37629 @<Declare \eTeX\ procedures for tok...@>=
37630 procedure scan_general_text;
37631 label found;
37632 var s:normal..absorbing; {to save |scanner_status|}
37633 @!w:pointer; {to save |warning_index|}
37634 @!d:pointer; {to save |def_ref|}
37635 @!p:pointer; {tail of the token list being built}
37636 @!q:pointer; {new node being added to the token list via |store_new_token|}
37637 @!unbalance:halfword; {number of unmatched left braces}
37638 begin s:=scanner_status; w:=warning_index; d:=def_ref;
37639 scanner_status:=absorbing; warning_index:=cur_cs;
37640 def_ref:=get_avail; token_ref_count(def_ref):=null; p:=def_ref;
37641 scan_left_brace; {remove the compulsory left brace}
37642 unbalance:=1;
37643 loop@+ begin get_token;
37644 if cur_tok<right_brace_limit then
37645 if cur_cmd<right_brace then incr(unbalance)
37646 else begin decr(unbalance);
37647 if unbalance=0 then goto found;
37648 end;
37649 store_new_token(cur_tok);
37650 end;
37651 found: q:=link(def_ref); free_avail(def_ref); {discard reference count}
37652 if q=null then cur_val:=temp_head @+ else cur_val:=p;
37653 link(temp_head):=q;
37654 scanner_status:=s; warning_index:=w; def_ref:=d;
37655 end;
37656
37657 @ The \.{\\showtokens} command displays a token list.
37658
37659 @d show_tokens=5 { \.{\\showtokens} , must be odd! }
37660
37661 @<Generate all \eTeX...@>=
37662 primitive("showtokens",xray,show_tokens);
37663 @!@:show_tokens_}{\.{\\showtokens} primitive@>
37664
37665 @ @<Cases of |xray| for |print_cmd_chr|@>=
37666 show_tokens:print_esc("showtokens");
37667
37668 @ The \.{\\unexpanded} primitive prevents expansion of tokens much as
37669 the result from \.{\\the} applied to a token variable. The
37670 \.{\\detokenize} primitive converts a token list into a list of
37671 character tokens much as if the token list were written to a file. We
37672 use the fact that the command modifiers for \.{\\unexpanded} and
37673 \.{\\detokenize} are odd whereas those for \.{\\the} and \.{\\showthe}
37674 are even.
37675
37676 @<Generate all \eTeX...@>=
37677 primitive("unexpanded",the,1);@/
37678 @!@:unexpanded_}{\.{\\unexpanded} primitive@>
37679 primitive("detokenize",the,show_tokens);@/
37680 @!@:detokenize_}{\.{\\detokenize} primitive@>
37681
37682 @ @<Cases of |the| for |print_cmd_chr|@>=
37683 else if chr_code=1 then print_esc("unexpanded")
37684 else print_esc("detokenize")
37685
37686 @ @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>=
37687 if odd(cur_chr) then
37688 begin c:=cur_chr; scan_general_text;
37689 if c=1 then the_toks:=cur_val
37690 else begin old_setting:=selector; selector:=new_string; b:=pool_ptr;
37691 p:=get_avail; link(p):=link(temp_head);
37692 token_show(p); flush_list(p);
37693 selector:=old_setting; the_toks:=str_toks(b);
37694 end;
37695 return;
37696 end
37697
37698 @ The \.{\\showifs} command displays all currently active conditionals.
37699
37700 @d show_ifs=6 { \.{\\showifs} }
37701
37702 @<Generate all \eTeX...@>=
37703 primitive("showifs",xray,show_ifs);
37704 @!@:show_ifs_}{\.{\\showifs} primitive@>
37705
37706 @ @<Cases of |xray| for |print_cmd_chr|@>=
37707 show_ifs:print_esc("showifs");
37708
37709 @
37710 @d print_if_line(#)==if #<>0 then
37711 begin print(" entered on line "); print_int(#);
37712 end
37713
37714 @<Cases for |show_whatever|@>=
37715 show_ifs: begin begin_diagnostic; print_nl(""); print_ln;
37716 if cond_ptr=null then
37717 begin print_nl("### "); print("no active conditionals");
37718 end
37719 else begin p:=cond_ptr; n:=0;
37720 repeat incr(n); p:=link(p);@+until p=null;
37721 p:=cond_ptr; t:=cur_if; l:=if_line; m:=if_limit;
37722 repeat print_nl("### level "); print_int(n); print(": ");
37723 print_cmd_chr(if_test,t);
37724 if m=fi_code then print_esc("else");
37725 print_if_line(l);
37726 decr(n); t:=subtype(p); l:=if_line_field(p); m:=type(p); p:=link(p);
37727 until p=null;
37728 end;
37729 end;
37730
37731 @ The \.{\\interactionmode} primitive allows to query and set the
37732 interaction mode.
37733
37734 @<Generate all \eTeX...@>=
37735 primitive("interactionmode",set_page_int,2);
37736 @!@:interaction_mode_}{\.{\\interactionmode} primitive@>
37737
37738 @ @<Cases of |set_page_int| for |print_cmd_chr|@>=
37739 else if chr_code=2 then print_esc("interactionmode")
37740
37741 @ @<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>=
37742 else if m=2 then cur_val:=interaction
37743
37744 @ @<Declare \eTeX\ procedures for use...@>=
37745 procedure@?new_interaction; forward;@t\2@>
37746
37747 @ @<Cases for |alter_integer|@>=
37748 else if c=2 then
37749 begin if (cur_val<batch_mode)or(cur_val>error_stop_mode) then
37750 begin print_err("Bad interaction mode");
37751 @.Bad interaction mode@>
37752 help2("Modes are 0=batch, 1=nonstop, 2=scroll, and")@/
37753 ("3=errorstop. Proceed, and I'll ignore this case.");
37754 int_error(cur_val);
37755 end
37756 else begin cur_chr:=cur_val; new_interaction;
37757 end;
37758 end
37759
37760 @ The |middle| feature of \eTeX\ allows one ore several \.{\\middle}
37761 delimiters to appear between \.{\\left} and \.{\\right}.
37762
37763 @<Generate all \eTeX...@>=
37764 primitive("middle",left_right,middle_noad);
37765 @!@:middle_}{\.{\\middle} primitive@>
37766
37767 @ @<Cases of |left_right| for |print_cmd_chr|@>=
37768 else if chr_code=middle_noad then print_esc("middle")
37769
37770 @ In constructions such as
37771 $$\vbox{\halign{\.{#}\hfil\cr
37772 {}\\hbox to \\hsize\{\cr
37773 \hskip 25pt \\hskip 0pt plus 0.0001fil\cr
37774 \hskip 25pt ...\cr
37775 \hskip 25pt \\hfil\\penalty-200\\hfilneg\cr
37776 \hskip 25pt ...\}\cr}}$$
37777 the stretch components of \.{\\hfil} and \.{\\hfilneg} compensate; they may,
37778 however, get modified in order to prevent arithmetic overflow during
37779 |hlist_out| when each of them is multiplied by a large |glue_set| value.
37780
37781 Since this ``glue rounding'' depends on state variables |cur_g| and
37782 |cur_glue| and \TeXXeT\ is supposed to emulate the behavior of \TeXeT\
37783 (plus a suitable postprocessor) as close as possible the glue rounding
37784 cannot be postponed until (segments of) an hlist has been reversed.
37785
37786 The code below is invoked after the effective width, |rule_wd|, of a glue
37787 node has been computed. The glue node is either converted into a kern node
37788 or, for leaders, the glue specification is replaced by an equivalent rigid
37789 one; the subtype of the glue node remains unchanged.
37790
37791 @<Handle a glue node for mixed...@>=
37792 if (((g_sign=stretching) and (stretch_order(g)=g_order)) or
37793 ((g_sign=shrinking) and (shrink_order(g)=g_order))) then
37794 begin fast_delete_glue_ref(g);
37795 if subtype(p)<a_leaders then
37796 begin type(p):=kern_node; width(p):=rule_wd;
37797 end
37798 else begin g:=get_node(glue_spec_size);@/
37799 stretch_order(g):=filll+1; shrink_order(g):=filll+1; {will never match}
37800 width(g):=rule_wd; stretch(g):=0; shrink(g):=0; glue_ptr(p):=g;
37801 end;
37802 end
37803
37804 @ The optional |TeXXeT| feature of \eTeX\ contains the code for mixed
37805 left-to-right and right-to-left typesetting. This code is inspired by
37806 but different from \TeXeT\ as presented by Donald~E. Knuth and Pierre
37807 MacKay in {\sl TUGboat\/} {\bf 8}, 14--25, 1987.
37808 @^Knuth, Donald Ervin@>
37809 @^MacKay, Pierre@>
37810
37811 In order to avoid confusion with \TeXeT\ the present implementation of
37812 mixed direction typesetting is called \TeXXeT. It differs from \TeXeT\
37813 in several important aspects: (1)~Right-to-left text is reversed
37814 explicitly by the |ship_out| routine and is written to a normal \.{DVI}
37815 file without any |begin_reflect| or |end_reflect| commands; (2)~a
37816 |math_node| is (ab)used instead of a |whatsit_node| to record the
37817 \.{\\beginL}, \.{\\endL}, \.{\\beginR}, and \.{\\endR} text direction
37818 primitives in order to keep the influence on the line breaking algorithm
37819 for pure left-to-right text as small as possible; (3)~right-to-left text
37820 interrupted by a displayed equation is automatically resumed after that
37821 equation; and (4)~the |valign| command code with a non-zero command
37822 modifier is (ab)used for the text direction primitives.
37823
37824 Nevertheless there is a subtle difference between \TeX\ and \TeXXeT\
37825 that may influence the line breaking algorithm for pure left-to-right
37826 text. When a paragraph containing math mode material is broken into
37827 lines \TeX\ may generate lines where math mode material is not enclosed
37828 by properly nested \.{\\mathon} and \.{\\mathoff} nodes. Unboxing such
37829 lines as part of a new paragraph may have the effect that hyphenation is
37830 attempted for `words' originating from math mode or that hyphenation is
37831 inhibited for words originating from horizontal mode.
37832
37833 In \TeXXeT\ additional \.{\\beginM}, resp.\ \.{\\endM} math nodes are
37834 supplied at the start, resp.\ end of lines such that math mode material
37835 inside a horizontal list always starts with either \.{\\mathon} or
37836 \.{\\beginM} and ends with \.{\\mathoff} or \.{\\endM}. These
37837 additional nodes are transparent to operations such as \.{\\unskip},
37838 \.{\\lastpenalty}, or \.{\\lastbox} but they do have the effect that
37839 hyphenation is never attempted for `words' originating from math mode
37840 and is never inhibited for words originating from horizontal mode.
37841
37842 @d TeXXeT_state==eTeX_state(TeXXeT_code)
37843 @d TeXXeT_en==(TeXXeT_state>0) {is \TeXXeT\ enabled?}
37844
37845 @<Cases for |print_param|@>=
37846 eTeX_state_code+TeXXeT_code:print_esc("TeXXeTstate");
37847
37848 @ @<Generate all \eTeX...@>=
37849 primitive("TeXXeTstate",assign_int,eTeX_state_base+TeXXeT_code);
37850 @!@:TeXXeT_state_}{\.{\\TeXXeT_state} primitive@>
37851 primitive("beginL",valign,begin_L_code);
37852 @!@:beginL_}{\.{\\beginL} primitive@>
37853 primitive("endL",valign,end_L_code);
37854 @!@:endL_}{\.{\\endL} primitive@>
37855 primitive("beginR",valign,begin_R_code);
37856 @!@:beginR_}{\.{\\beginR} primitive@>
37857 primitive("endR",valign,end_R_code);
37858 @!@:endR_}{\.{\\endR} primitive@>
37859
37860 @ @<Cases of |valign| for |print_cmd_chr|@>=
37861 else case chr_code of
37862 begin_L_code: print_esc("beginL");
37863 end_L_code: print_esc("endL");
37864 begin_R_code: print_esc("beginR");
37865 othercases print_esc("endR")
37866 endcases
37867
37868 @ @<Cases of |main_control| for |hmode+valign|@>=
37869 if cur_chr>0 then
37870 begin if eTeX_enabled(TeXXeT_en,cur_cmd,cur_chr) then
37871 @.Improper \\beginL@>
37872 @.Improper \\endL@>
37873 @.Improper \\beginR@>
37874 @.Improper \\endR@>
37875 tail_append(new_math(0,cur_chr));
37876 end
37877 else
37878
37879 @ An hbox with subtype dlist will never be reversed, even when embedded
37880 in right-to-left text.
37881
37882 @<Display if this box is never to be reversed@>=
37883 if (type(p)=hlist_node)and(box_lr(p)=dlist) then print(", display")
37884
37885 @ A number of routines are based on a stack of one-word nodes whose
37886 |info| fields contain |end_M_code|, |end_L_code|, or |end_R_code|. The
37887 top of the stack is pointed to by |LR_ptr|.
37888
37889 When the stack manipulation macros of this section are used below,
37890 variable |LR_ptr| might be the global variable declared here for |hpack|
37891 and |ship_out|, or might be local to |post_line_break|.
37892
37893 @d put_LR(#)==begin temp_ptr:=get_avail; info(temp_ptr):=#;
37894 link(temp_ptr):=LR_ptr; LR_ptr:=temp_ptr;
37895 end
37896 @#
37897 @d push_LR(#)==put_LR(end_LR_type(#))
37898 @#
37899 @d pop_LR==begin temp_ptr:=LR_ptr; LR_ptr:=link(temp_ptr);
37900 free_avail(temp_ptr);
37901 end
37902
37903 @<Glob...@>=
37904 @!LR_ptr:pointer; {stack of LR codes for |hpack|, |ship_out|, and |init_math|}
37905 @!LR_problems:integer; {counts missing begins and ends}
37906 @!cur_dir:small_number; {current text direction}
37907
37908 @ @<Set init...@>=
37909 LR_ptr:=null; LR_problems:=0; cur_dir:=left_to_right;
37910
37911 @ @<Insert LR nodes at the beg...@>=
37912 begin q:=link(temp_head);
37913 if LR_ptr<>null then
37914 begin temp_ptr:=LR_ptr; r:=q;
37915 repeat s:=new_math(0,begin_LR_type(info(temp_ptr))); link(s):=r; r:=s;
37916 temp_ptr:=link(temp_ptr);
37917 until temp_ptr=null;
37918 link(temp_head):=r;
37919 end;
37920 while q<>cur_break(cur_p) do
37921 begin if not is_char_node(q) then
37922 if type(q)=math_node then @<Adjust \(t)the LR stack for the |p...@>;
37923 q:=link(q);
37924 end;
37925 end
37926
37927 @ @<Adjust \(t)the LR stack for the |p...@>=
37928 if end_LR(q) then
37929 begin if LR_ptr<>null then if info(LR_ptr)=end_LR_type(q) then pop_LR;
37930 end
37931 else push_LR(q)
37932
37933 @ We use the fact that |q| now points to the node with \.{\\rightskip} glue.
37934
37935 @<Insert LR nodes at the end...@>=
37936 if LR_ptr<>null then
37937 begin s:=temp_head; r:=link(s);
37938 while r<>q do
37939 begin s:=r; r:=link(s);
37940 end;
37941 r:=LR_ptr;
37942 while r<>null do
37943 begin temp_ptr:=new_math(0,info(r));
37944 link(s):=temp_ptr; s:=temp_ptr; r:=link(r);
37945 end;
37946 link(s):=q;
37947 end
37948
37949 @ @<Initialize the LR stack@>=
37950 put_LR(before) {this will never match}
37951
37952 @ @<Adjust \(t)the LR stack for the |hp...@>=
37953 if end_LR(p) then
37954 if info(LR_ptr)=end_LR_type(p) then pop_LR
37955 else begin incr(LR_problems); type(p):=kern_node; subtype(p):=explicit;
37956 end
37957 else push_LR(p)
37958
37959 @ @<Check for LR anomalies at the end of |hp...@>=
37960 begin if info(LR_ptr)<>before then
37961 begin while link(q)<>null do q:=link(q);
37962 repeat temp_ptr:=q; q:=new_math(0,info(LR_ptr)); link(temp_ptr):=q;
37963 LR_problems:=LR_problems+10000; pop_LR;
37964 until info(LR_ptr)=before;
37965 end;
37966 if LR_problems>0 then
37967 begin @<Report LR problems@>; goto common_ending;
37968 end;
37969 pop_LR;
37970 if LR_ptr<>null then confusion("LR1");
37971 @:this can't happen LR1}{\quad LR1@>
37972 end
37973
37974 @ @<Report LR problems@>=
37975 begin print_ln; print_nl("\endL or \endR problem (");@/
37976 print_int(LR_problems div 10000); print(" missing, ");@/
37977 print_int(LR_problems mod 10000); print(" extra");@/
37978 LR_problems:=0;
37979 end
37980
37981 @ @<Initialize |hlist_out| for mixed...@>=
37982 if eTeX_ex then
37983 begin @<Initialize the LR stack@>;
37984 if box_lr(this_box)=dlist then
37985 if cur_dir=right_to_left then
37986 begin cur_dir:=left_to_right; cur_h:=cur_h-width(this_box);
37987 end
37988 else set_box_lr(this_box)(0);
37989 if (cur_dir=right_to_left)and(box_lr(this_box)<>reversed) then
37990 @<Reverse the complete hlist and set the subtype to |reversed|@>;
37991 end
37992
37993 @ @<Finish |hlist_out| for mixed...@>=
37994 if eTeX_ex then
37995 begin @<Check for LR anomalies at the end of |hlist_out|@>;
37996 if box_lr(this_box)=dlist then cur_dir:=right_to_left;
37997 end
37998
37999 @ @<Handle a math node in |hlist_out|@>=
38000 begin if eTeX_ex then
38001 @<Adjust \(t)the LR stack for the |hlist_out| routine; if necessary
38002 reverse an hlist segment and |goto reswitch|@>;
38003 cur_h:=cur_h+width(p);
38004 end
38005
38006 @ Breaking a paragraph into lines while \TeXXeT\ is disabled may result
38007 in lines with unpaired math nodes. Such hlists are silently accepted
38008 in the absence of text direction directives.
38009
38010 @d LR_dir(#)==(subtype(#) div R_code) {text direction of a `math node'}
38011
38012 @<Adjust \(t)the LR stack for the |hl...@>=
38013 begin if end_LR(p) then
38014 if info(LR_ptr)=end_LR_type(p) then pop_LR
38015 else begin if subtype(p)>L_code then incr(LR_problems);
38016 end
38017 else begin push_LR(p);
38018 if LR_dir(p)<>cur_dir then
38019 @<Reverse an hlist segment and |goto reswitch|@>;
38020 end;
38021 type(p):=kern_node;
38022 end
38023
38024 @ @<Check for LR anomalies at the end of |hl...@>=
38025 begin while info(LR_ptr)<>before do
38026 begin if info(LR_ptr)>L_code then LR_problems:=LR_problems+10000;
38027 pop_LR;
38028 end;
38029 pop_LR;
38030 end
38031
38032 @ @d edge_node=style_node {a |style_node| does not occur in hlists}
38033 @d edge_node_size=style_node_size {number of words in an edge node}
38034 @d edge_dist(#)==depth(#) {new |left_edge| position relative to |cur_h|
38035 (after |width| has been taken into account)}
38036
38037 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
38038 function new_edge(@!s:small_number;@!w:scaled):pointer;
38039 {create an edge node}
38040 var p:pointer; {the new node}
38041 begin p:=get_node(edge_node_size); type(p):=edge_node; subtype(p):=s;
38042 width(p):=w; edge_dist(p):=0; {the |edge_dist| field will be set later}
38043 new_edge:=p;
38044 end;
38045
38046 @ @<Cases of |hlist_out| that arise...@>=
38047 edge_node: begin cur_h:=cur_h+width(p);
38048 left_edge:=cur_h+edge_dist(p); cur_dir:=subtype(p);
38049 end;
38050
38051 @ We detach the hlist, start a new one consisting of just one kern node,
38052 append the reversed list, and set the width of the kern node.
38053
38054 @<Reverse the complete hlist...@>=
38055 begin save_h:=cur_h; temp_ptr:=p; p:=new_kern(0); link(prev_p):=p;
38056 cur_h:=0; link(p):=reverse(this_box,null,cur_g,cur_glue); width(p):=-cur_h;
38057 cur_h:=save_h; set_box_lr(this_box)(reversed);
38058 end
38059
38060 @ We detach the remainder of the hlist, replace the math node by
38061 an edge node, and append the reversed hlist segment to it; the tail of
38062 the reversed segment is another edge node and the remainder of the
38063 original list is attached to it.
38064
38065 @<Reverse an hlist segment...@>=
38066 begin save_h:=cur_h; temp_ptr:=link(p); rule_wd:=width(p);
38067 free_node(p,small_node_size);
38068 cur_dir:=reflected; p:=new_edge(cur_dir,rule_wd); link(prev_p):=p;
38069 cur_h:=cur_h-left_edge+rule_wd;
38070 link(p):=reverse(this_box,new_edge(reflected,0),cur_g,cur_glue);
38071 edge_dist(p):=cur_h; cur_dir:=reflected; cur_h:=save_h;
38072 goto reswitch;
38073 end
38074
38075 @ The |reverse| function defined here is responsible to reverse the
38076 nodes of an hlist (segment). The first parameter |this_box| is the enclosing
38077 hlist node, the second parameter |t| is to become the tail of the reversed
38078 list, and the global variable |temp_ptr| is the head of the list to be
38079 reversed. Finally |cur_g| and |cur_glue| are the current glue rounding state
38080 variables, to be updated by this function. We remove nodes from the original
38081 list and add them to the head of the new one.
38082
38083 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
38084 function reverse(@!this_box,@!t:pointer; var cur_g:scaled;
38085 var cur_glue:real):pointer;
38086 label reswitch,next_p,done;
38087 var l:pointer; {the new list}
38088 @!p:pointer; {the current node}
38089 @!q:pointer; {the next node}
38090 @!g_order: glue_ord; {applicable order of infinity for glue}
38091 @!g_sign: normal..shrinking; {selects type of glue}
38092 @!glue_temp:real; {glue value before rounding}
38093 @!m,@!n:halfword; {count of unmatched math nodes}
38094 begin g_order:=glue_order(this_box); g_sign:=glue_sign(this_box);
38095 l:=t; p:=temp_ptr; m:=min_halfword; n:=min_halfword;
38096 loop@+ begin while p<>null do
38097 @<Move node |p| to the new list and go to the next node;
38098 or |goto done| if the end of the reflected segment has been reached@>;
38099 if (t=null)and(m=min_halfword)and(n=min_halfword) then goto done;
38100 p:=new_math(0,info(LR_ptr)); LR_problems:=LR_problems+10000;
38101 {manufacture one missing math node}
38102 end;
38103 done:reverse:=l;
38104 end;
38105
38106 @ @<Move node |p| to the new list...@>=
38107 reswitch: if is_char_node(p) then
38108 repeat f:=font(p); c:=character(p);
38109 cur_h:=cur_h+char_width(f)(char_info(f)(c));
38110 q:=link(p); link(p):=l; l:=p; p:=q;
38111 until not is_char_node(p)
38112 else @<Move the non-|char_node| |p| to the new list@>
38113
38114 @ @<Move the non-|char_node| |p| to the new list@>=
38115 begin q:=link(p);
38116 case type(p) of
38117 hlist_node,vlist_node,rule_node,kern_node: rule_wd:=width(p);
38118 @t\4@>@<Cases of |reverse| that need special treatment@>@;
38119 edge_node: confusion("LR2");
38120 @:this can't happen LR2}{\quad LR2@>
38121 othercases goto next_p
38122 endcases;@/
38123 cur_h:=cur_h+rule_wd;
38124 next_p: link(p):=l;
38125 if type(p)=kern_node then if (rule_wd=0)or(l=null) then
38126 begin free_node(p,small_node_size); p:=l;
38127 end;
38128 l:=p; p:=q;
38129 end
38130
38131 @ Here we compute the effective width of a glue node as in |hlist_out|.
38132
38133 @<Cases of |reverse|...@>=
38134 glue_node: begin round_glue;
38135 @<Handle a glue node for mixed...@>;
38136 end;
38137
38138 @ A ligature node is replaced by a char node.
38139
38140 @<Cases of |reverse|...@>=
38141 ligature_node: begin flush_node_list(lig_ptr(p));
38142 temp_ptr:=p; p:=get_avail; mem[p]:=mem[lig_char(temp_ptr)]; link(p):=q;
38143 free_node(temp_ptr,small_node_size); goto reswitch;
38144 end;
38145
38146 @ Math nodes in an inner reflected segment are modified, those at the
38147 outer level are changed into kern nodes.
38148
38149 @<Cases of |reverse|...@>=
38150 math_node: begin rule_wd:=width(p);
38151 if end_LR(p) then
38152 if info(LR_ptr)<>end_LR_type(p) then
38153 begin type(p):=kern_node; incr(LR_problems);
38154 end
38155 else begin pop_LR;
38156 if n>min_halfword then
38157 begin decr(n); decr(subtype(p)); {change |after| into |before|}
38158 end
38159 else begin type(p):=kern_node;
38160 if m>min_halfword then decr(m)
38161 else @<Finish the reversed hlist segment and |goto done|@>;
38162 end;
38163 end
38164 else begin push_LR(p);
38165 if (n>min_halfword)or(LR_dir(p)<>cur_dir) then
38166 begin incr(n); incr(subtype(p)); {change |before| into |after|}
38167 end
38168 else begin type(p):=kern_node; incr(m);
38169 end;
38170 end;
38171 end;
38172
38173 @ Finally we have found the end of the hlist segment to be reversed; the
38174 final math node is released and the remaining list attached to the
38175 edge node terminating the reversed segment.
38176
38177 @<Finish the reversed...@>=
38178 begin free_node(p,small_node_size);
38179 link(t):=q; width(t):=rule_wd; edge_dist(t):=-cur_h-rule_wd; goto done;
38180 end
38181
38182 @ @<Check for LR anomalies at the end of |s...@>=
38183 begin if LR_problems>0 then
38184 begin @<Report LR problems@>; print_char(")"); print_ln;
38185 end;
38186 if (LR_ptr<>null)or(cur_dir<>left_to_right) then confusion("LR3");
38187 @:this can't happen LR3}{\quad LR3@>
38188 end
38189
38190 @ Some special actions are required for displayed equation in paragraphs
38191 with mixed direction texts. First of all we have to set the text
38192 direction preceding the display.
38193
38194 @<Set the value of |x| to the text direction before the display@>=
38195 if LR_save=null then x:=0
38196 else if info(LR_save)>=R_code then x:=-1@+else x:=1
38197
38198 @ @<Prepare for display after an empty...@>=
38199 begin pop_nest; @<Set the value of |x|...@>;
38200 end
38201
38202 @ When calculating the natural width, |w|, of the final line preceding
38203 the display, we may have to copy all or part of its hlist. We copy,
38204 however, only those parts of the original list that are relevant for the
38205 computation of |pre_display_size|.
38206 @^data structure assumptions@>
38207
38208 @<Declare subprocedures for |init_math|@>=
38209 procedure just_copy(@!p,@!h,@!t:pointer);
38210 label found,not_found;
38211 var @!r:pointer; {current node being fabricated for new list}
38212 @!words:0..5; {number of words remaining to be copied}
38213 begin while p<>null do
38214 begin words:=1; {this setting occurs in more branches than any other}
38215 if is_char_node(p) then r:=get_avail
38216 else case type(p) of
38217 hlist_node,vlist_node: begin r:=get_node(box_node_size);
38218 mem[r+6]:=mem[p+6]; mem[r+5]:=mem[p+5]; {copy the last two words}
38219 words:=5; list_ptr(r):=null; {this affects |mem[r+5]|}
38220 end;
38221 rule_node: begin r:=get_node(rule_node_size); words:=rule_node_size;
38222 end;
38223 ligature_node: begin r:=get_avail; {only |font| and |character| are needed}
38224 mem[r]:=mem[lig_char(p)]; goto found;
38225 end;
38226 kern_node,math_node: begin r:=get_node(small_node_size);
38227 words:=small_node_size;
38228 end;
38229 glue_node: begin r:=get_node(small_node_size); add_glue_ref(glue_ptr(p));
38230 glue_ptr(r):=glue_ptr(p); leader_ptr(r):=null;
38231 end;
38232 whatsit_node:@<Make a partial copy of the whatsit...@>;
38233 othercases goto not_found
38234 endcases;
38235 while words>0 do
38236 begin decr(words); mem[r+words]:=mem[p+words];
38237 end;
38238 found: link(h):=r; h:=r;
38239 not_found: p:=link(p);
38240 end;
38241 link(h):=t;
38242 end;
38243
38244 @ When the final line ends with R-text, the value |w| refers to the line
38245 reflected with respect to the left edge of the enclosing vertical list.
38246
38247 @<Prepare for display after a non-empty...@>=
38248 if eTeX_ex then @<Let |j| be the prototype box for the display@>;
38249 v:=shift_amount(just_box);
38250 @<Set the value of |x|...@>;
38251 if x>=0 then
38252 begin p:=list_ptr(just_box); link(temp_head):=null;
38253 end
38254 else begin v:=-v-width(just_box);
38255 p:=new_math(0,begin_L_code); link(temp_head):=p;
38256 just_copy(list_ptr(just_box),p,new_math(0,end_L_code));
38257 cur_dir:=right_to_left;
38258 end;
38259 v:=v+2*quad(cur_font);
38260 if TeXXeT_en then @<Initialize the LR stack@>
38261
38262 @ @<Finish the natural width computation@>=
38263 if TeXXeT_en then
38264 begin while LR_ptr<>null do pop_LR;
38265 if LR_problems<>0 then
38266 begin w:=max_dimen; LR_problems:=0;
38267 end;
38268 end;
38269 cur_dir:=left_to_right; flush_node_list(link(temp_head))
38270
38271 @ In the presence of text direction directives we assume that any LR
38272 problems have been fixed by the |hpack| routine. If the final line
38273 contains, however, text direction directives while \TeXXeT\ is disabled,
38274 then we set |w:=max_dimen|.
38275
38276 @<Cases of `Let |d| be the natural...@>=
38277 math_node: begin d:=width(p);
38278 if TeXXeT_en then @<Adjust \(t)the LR stack for the |init_math| routine@>
38279 else if subtype(p)>=L_code then
38280 begin w:=max_dimen; goto done;
38281 end;
38282 end;
38283 edge_node: begin d:=width(p); cur_dir:=subtype(p);
38284 end;
38285
38286 @ @<Adjust \(t)the LR stack for the |i...@>=
38287 if end_LR(p) then
38288 begin if info(LR_ptr)=end_LR_type(p) then pop_LR
38289 else if subtype(p)>L_code then
38290 begin w:=max_dimen; goto done;
38291 end
38292 end
38293 else begin push_LR(p);
38294 if LR_dir(p)<>cur_dir then
38295 begin just_reverse(p); p:=temp_head;
38296 end;
38297 end
38298
38299 @ @<Declare subprocedures for |init_math|@>=
38300 procedure just_reverse(@!p:pointer);
38301 label found,done;
38302 var l:pointer; {the new list}
38303 @!t:pointer; {tail of reversed segment}
38304 @!q:pointer; {the next node}
38305 @!m,@!n:halfword; {count of unmatched math nodes}
38306 begin m:=min_halfword; n:=min_halfword;
38307 if link(temp_head)=null then
38308 begin just_copy(link(p),temp_head,null); q:=link(temp_head);
38309 end
38310 else begin q:=link(p); link(p):=null; flush_node_list(link(temp_head));
38311 end;
38312 t:=new_edge(cur_dir,0); l:=t; cur_dir:=reflected;
38313 while q<>null do
38314 if is_char_node(q) then
38315 repeat p:=q; q:=link(p); link(p):=l; l:=p;
38316 until not is_char_node(q)
38317 else begin p:=q; q:=link(p);
38318 if type(p)=math_node then
38319 @<Adjust \(t)the LR stack for the |just_reverse| routine@>;
38320 link(p):=l; l:=p;
38321 end;
38322 goto done;
38323 found:width(t):=width(p); link(t):=q; free_node(p,small_node_size);
38324 done:link(temp_head):=l;
38325 end;
38326
38327 @ @<Adjust \(t)the LR stack for the |j...@>=
38328 if end_LR(p) then
38329 if info(LR_ptr)<>end_LR_type(p) then
38330 begin type(p):=kern_node; incr(LR_problems);
38331 end
38332 else begin pop_LR;
38333 if n>min_halfword then
38334 begin decr(n); decr(subtype(p)); {change |after| into |before|}
38335 end
38336 else begin if m>min_halfword then decr(m)@+else goto found;
38337 type(p):=kern_node;
38338 end;
38339 end
38340 else begin push_LR(p);
38341 if (n>min_halfword)or(LR_dir(p)<>cur_dir) then
38342 begin incr(n); incr(subtype(p)); {change |before| into |after|}
38343 end
38344 else begin type(p):=kern_node; incr(m);
38345 end;
38346 end
38347
38348 @ The prototype box is an hlist node with the width, glue set, and shift
38349 amount of |just_box|, i.e., the last line preceding the display. Its
38350 hlist reflects the current \.{\\leftskip} and \.{\\rightskip}.
38351
38352 @<Let |j| be the prototype box for the display@>=
38353 begin if right_skip=zero_glue then j:=new_kern(0)
38354 else j:=new_param_glue(right_skip_code);
38355 if left_skip=zero_glue then p:=new_kern(0)
38356 else p:=new_param_glue(left_skip_code);
38357 link(p):=j; j:=new_null_box; width(j):=width(just_box);
38358 shift_amount(j):=shift_amount(just_box); list_ptr(j):=p;
38359 glue_order(j):=glue_order(just_box); glue_sign(j):=glue_sign(just_box);
38360 glue_set(j):=glue_set(just_box);
38361 end
38362
38363 @ At the end of a displayed equation we retrieve the prototype box.
38364
38365 @<Local variables for finishing...@>=
38366 @!j:pointer; {prototype box}
38367
38368 @ @<Retrieve the prototype box@>=
38369 if mode=mmode then j:=LR_box
38370
38371 @ @<Flush the prototype box@>=
38372 flush_node_list(j)
38373
38374 @ The |app_display| procedure used to append the displayed equation
38375 and\slash or equation number to the current vertical list has three
38376 parameters: the prototype box, the hbox to be appended, and the
38377 displacement of the hbox in the display line.
38378
38379 @<Declare subprocedures for |after_math|@>=
38380 procedure app_display(@!j,@!b:pointer;@!d:scaled);
38381 var z:scaled; {width of the line}
38382 @!s:scaled; {move the line right this much}
38383 @!e:scaled; {distance from right edge of box to end of line}
38384 @!x:integer; {|pre_display_direction|}
38385 @!p,@!q,@!r,@!t,@!u:pointer; {for list manipulation}
38386 begin s:=display_indent; x:=pre_display_direction;
38387 if x=0 then shift_amount(b):=s+d
38388 else begin z:=display_width; p:=b;
38389 @<Set up the hlist for the display line@>;
38390 @<Package the display line@>;
38391 end;
38392 append_to_vlist(b);
38393 end;
38394
38395 @ Here we construct the hlist for the display, starting with node |p|
38396 and ending with node |q|. We also set |d| and |e| to the amount of
38397 kerning to be added before and after the hlist (adjusted for the
38398 prototype box).
38399
38400 @<Set up the hlist for the display line@>=
38401 if x>0 then e:=z-d-width(p)
38402 else begin e:=d; d:=z-e-width(p);
38403 end;
38404 if j<>null then
38405 begin b:=copy_node_list(j); height(b):=height(p); depth(b):=depth(p);
38406 s:=s-shift_amount(b); d:=d+s; e:=e+width(b)-z-s;
38407 end;
38408 if box_lr(p)=dlist then q:=p {display or equation number}
38409 else begin {display and equation number}
38410 r:=list_ptr(p); free_node(p,box_node_size);
38411 if r=null then confusion("LR4");
38412 if x>0 then
38413 begin p:=r;
38414 repeat q:=r; r:=link(r); {find tail of list}
38415 until r=null;
38416 end
38417 else begin p:=null; q:=r;
38418 repeat t:=link(r); link(r):=p; p:=r; r:=t; {reverse list}
38419 until r=null;
38420 end;
38421 end
38422
38423 @ In the presence of a prototype box we use its shift amount and width
38424 to adjust the values of kerning and add these values to the glue nodes
38425 inserted to cancel the \.{\\leftskip} and \.{\\rightskip}. If there is
38426 no prototype box (because the display is preceded by an empty
38427 paragraph), or if the skip parameters are zero, we just add kerns.
38428
38429 The |cancel_glue| macro creates and links a glue node that is, together
38430 with another glue node, equivalent to a given amount of kerning. We can
38431 use |j| as temporary pointer, since all we need is |j<>null|.
38432
38433 @d cancel_glue(#)==j:=new_skip_param(#); cancel_glue_cont
38434 @d cancel_glue_cont(#)==link(#):=j; cancel_glue_cont_cont
38435 @d cancel_glue_cont_cont(#)==link(j):=#; cancel_glue_end
38436 @d cancel_glue_end(#)==j:=glue_ptr(#); cancel_glue_end_end
38437 @d cancel_glue_end_end(#)==
38438 stretch_order(temp_ptr):=stretch_order(j);
38439 shrink_order(temp_ptr):=shrink_order(j); width(temp_ptr):=#-width(j);
38440 stretch(temp_ptr):=-stretch(j); shrink(temp_ptr):=-shrink(j)
38441
38442 @<Package the display line@>=
38443 if j=null then
38444 begin r:=new_kern(0); t:=new_kern(0); {the widths will be set later}
38445 end
38446 else begin r:=list_ptr(b); t:=link(r);
38447 end;
38448 u:=new_math(0,end_M_code);
38449 if type(t)=glue_node then {|t| is \.{\\rightskip} glue}
38450 begin cancel_glue(right_skip_code)(q)(u)(t)(e); link(u):=t;
38451 end
38452 else begin width(t):=e; link(t):=u; link(q):=t;
38453 end;
38454 u:=new_math(0,begin_M_code);
38455 if type(r)=glue_node then {|r| is \.{\\leftskip} glue}
38456 begin cancel_glue(left_skip_code)(u)(p)(r)(d); link(r):=u;
38457 end
38458 else begin width(r):=d; link(r):=p; link(u):=r;
38459 if j=null then
38460 begin b:=hpack(u,natural); shift_amount(b):=s;
38461 end
38462 else list_ptr(b):=u;
38463 end
38464
38465 @ The |scan_tokens| feature of \eTeX\ defines the \.{\\scantokens}
38466 primitive.
38467
38468 @<Generate all \eTeX...@>=
38469 primitive("scantokens",input,2);
38470 @!@:scan_tokens_}{\.{\\scantokens} primitive@>
38471
38472 @ @<Cases of |input| for |print_cmd_chr|@>=
38473 else if chr_code=2 then print_esc("scantokens")
38474
38475 @ @<Cases for |input|@>=
38476 else if cur_chr=2 then pseudo_start
38477
38478 @ The global variable |pseudo_files| is used to maintain a stack of
38479 pseudo files. The |info| field of each pseudo file points to a linked
38480 list of variable size nodes representing lines not yet processed: the
38481 |info| field of the first word contains the size of this node, all the
38482 following words contain ASCII codes.
38483
38484 @<Glob...@>=
38485 @!pseudo_files:pointer; {stack of pseudo files}
38486
38487 @ @<Set init...@>=
38488 pseudo_files:=null;
38489
38490 @ The |pseudo_start| procedure initiates reading from a pseudo file.
38491
38492 @<Declare \eTeX\ procedures for ex...@>=
38493 procedure@?pseudo_start; forward;@t\2@>
38494
38495 @ @<Declare \eTeX\ procedures for tok...@>=
38496 procedure pseudo_start;
38497 var old_setting:0..max_selector; {holds |selector| setting}
38498 @!s:str_number; {string to be converted into a pseudo file}
38499 @!l,@!m:pool_pointer; {indices into |str_pool|}
38500 @!p,@!q,@!r:pointer; {for list construction}
38501 @!w: four_quarters; {four ASCII codes}
38502 @!nl,@!sz:integer;
38503 begin scan_general_text;
38504 old_setting:=selector; selector:=new_string;
38505 token_show(temp_head); selector:=old_setting;
38506 flush_list(link(temp_head));
38507 str_room(1); s:=make_string;
38508 @<Convert string |s| into a new pseudo file@>;
38509 flush_string;
38510 @<Initiate input from new pseudo file@>;
38511 end;
38512
38513 @ @<Convert string |s| into a new pseudo file@>=
38514 str_pool[pool_ptr]:=si(" "); l:=str_start[s];
38515 nl:=si(new_line_char);
38516 p:=get_avail; q:=p;
38517 while l<pool_ptr do
38518 begin m:=l;
38519 while (l<pool_ptr)and(str_pool[l]<>nl) do incr(l);
38520 sz:=(l-m+7)div 4;
38521 if sz=1 then sz:=2;
38522 r:=get_node(sz); link(q):=r; q:=r; info(q):=hi(sz);
38523 while sz>2 do
38524 begin decr(sz); incr(r);
38525 w.b0:=qi(so(str_pool[m])); w.b1:=qi(so(str_pool[m+1]));
38526 w.b2:=qi(so(str_pool[m+2])); w.b3:=qi(so(str_pool[m+3]));
38527 mem[r].qqqq:=w; m:=m+4;
38528 end;
38529 w.b0:=qi(" "); w.b1:=qi(" "); w.b2:=qi(" "); w.b3:=qi(" ");
38530 if l>m then
38531 begin w.b0:=qi(so(str_pool[m]));
38532 if l>m+1 then
38533 begin w.b1:=qi(so(str_pool[m+1]));
38534 if l>m+2 then
38535 begin w.b2:=qi(so(str_pool[m+2]));
38536 if l>m+3 then w.b3:=qi(so(str_pool[m+3]));
38537 end;
38538 end;
38539 end;
38540 mem[r+1].qqqq:=w;
38541 if str_pool[l]=nl then incr(l);
38542 end;
38543 info(p):=link(p); link(p):=pseudo_files; pseudo_files:=p
38544
38545 @ @<Initiate input from new pseudo file@>=
38546 begin_file_reading; {set up |cur_file| and new level of input}
38547 line:=0; limit:=start; loc:=limit+1; {force line read}
38548 if tracing_scan_tokens>0 then
38549 begin if term_offset>max_print_line-3 then print_ln
38550 else if (term_offset>0)or(file_offset>0) then print_char(" ");
38551 name:=19; print("( "); incr(open_parens); update_terminal;
38552 end
38553 else name:=18
38554
38555 @ Here we read a line from the current pseudo file into |buffer|.
38556
38557 @<Declare \eTeX\ procedures for tr...@>=
38558 function pseudo_input: boolean; {inputs the next line or returns |false|}
38559 var p:pointer; {current line from pseudo file}
38560 @!sz:integer; {size of node |p|}
38561 @!w:four_quarters; {four ASCII codes}
38562 @!r:pointer; {loop index}
38563 begin last:=first; {cf.\ Matthew 19\thinspace:\thinspace30}
38564 p:=info(pseudo_files);
38565 if p=null then pseudo_input:=false
38566 else begin info(pseudo_files):=link(p); sz:=ho(info(p));
38567 if 4*sz-3>=buf_size-last then
38568 @<Report overflow of the input buffer, and abort@>;
38569 last:=first;
38570 for r:=p+1 to p+sz-1 do
38571 begin w:=mem[r].qqqq;
38572 buffer[last]:=w.b0; buffer[last+1]:=w.b1;
38573 buffer[last+2]:=w.b2; buffer[last+3]:=w.b3;
38574 last:=last+4;
38575 end;
38576 if last>=max_buf_stack then max_buf_stack:=last+1;
38577 while (last>first)and(buffer[last-1]=" ") do decr(last);
38578 free_node(p,sz);
38579 pseudo_input:=true;
38580 end;
38581 end;
38582
38583 @ When we are done with a pseudo file we `close' it.
38584
38585 @<Declare \eTeX\ procedures for tr...@>=
38586 procedure pseudo_close; {close the top level pseudo file}
38587 var p,@!q: pointer;
38588 begin p:=link(pseudo_files); q:=info(pseudo_files);
38589 free_avail(pseudo_files); pseudo_files:=p;
38590 while q<>null do
38591 begin p:=q; q:=link(p); free_node(p,ho(info(p)));
38592 end;
38593 end;
38594
38595 @ @<Dump the \eTeX\ state@>=
38596 while pseudo_files<>null do pseudo_close; {flush pseudo files}
38597
38598 @ @<Generate all \eTeX...@>=
38599 primitive("readline",read_to_cs,1);@/
38600 @!@:read_line_}{\.{\\readline} primitive@>
38601
38602 @ @<Cases of |read| for |print_cmd_chr|@>=
38603 else print_esc("readline")
38604
38605 @ @<Handle \.{\\readline} and |goto done|@>=
38606 if j=1 then
38607 begin while loc<=limit do {current line not yet finished}
38608 begin cur_chr:=buffer[loc]; incr(loc);
38609 if cur_chr=" " then cur_tok:=space_token
38610 @+else cur_tok:=cur_chr+other_token;
38611 store_new_token(cur_tok);
38612 end;
38613 goto done;
38614 end
38615
38616 @ Here we define the additional conditionals of \eTeX\ as well as the
38617 \.{\\unless} prefix.
38618
38619 @d if_def_code=17 { `\.{\\ifdefined}' }
38620 @d if_cs_code=18 { `\.{\\ifcsname}' }
38621 @d if_font_char_code=19 { `\.{\\iffontchar}' }
38622 @d if_in_csname_code=20 { `\.{\\ifincsname}' }
38623 @d if_pdfabs_num_code=22 { `\.{\\ifpdfabsnum}' } { 21 = |if_pdfprimitive|}
38624 @d if_pdfabs_dim_code=23 { `\.{\\ifpdfabsdim}' }
38625
38626 @<Generate all \eTeX...@>=
38627 primitive("unless",expand_after,1);@/
38628 @!@:unless_}{\.{\\unless} primitive@>
38629 primitive("ifdefined",if_test,if_def_code);
38630 @!@:if_defined_}{\.{\\ifdefined} primitive@>
38631 primitive("ifcsname",if_test,if_cs_code);
38632 @!@:if_cs_name_}{\.{\\ifcsname} primitive@>
38633 primitive("iffontchar",if_test,if_font_char_code);
38634 @!@:if_font_char_}{\.{\\iffontchar} primitive@>
38635 primitive("ifincsname",if_test,if_in_csname_code);
38636 @!@:if_in_csname_}{\.{\\ifincsname} primitive@>
38637 primitive("ifpdfabsnum",if_test,if_pdfabs_num_code);
38638 @!@:if_pdfabs_num_}{\.{\\ifpdfabsnum} primitive@>
38639 primitive("ifpdfabsdim",if_test,if_pdfabs_dim_code);
38640 @!@:if_pdfabs_dim_}{\.{\\ifpdfabsdim} primitive@>
38641
38642 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
38643 else print_esc("unless")
38644
38645 @ @<Cases of |if_test| for |print_cmd_chr|@>=
38646 if_def_code:print_esc("ifdefined");
38647 if_cs_code:print_esc("ifcsname");
38648 if_font_char_code:print_esc("iffontchar");
38649 if_in_csname_code:print_esc("ifincsname");
38650 if_pdfabs_num_code:print_esc("ifpdfabsnum");
38651 if_pdfabs_dim_code:print_esc("ifpdfabsdim");
38652
38653 @ The result of a boolean condition is reversed when the conditional is
38654 preceded by \.{\\unless}.
38655
38656 @<Negate a boolean conditional and |goto reswitch|@>=
38657 begin get_token;
38658 if (cur_cmd=if_test)and(cur_chr<>if_case_code) then
38659 begin cur_chr:=cur_chr+unless_code; goto reswitch;
38660 end;
38661 print_err("You can't use `"); print_esc("unless"); print("' before `");
38662 @.You can't use \\unless...@>
38663 print_cmd_chr(cur_cmd,cur_chr); print_char("'");
38664 help1("Continue, and I'll forget that it ever happened.");
38665 back_error;
38666 end
38667
38668 @ The conditional \.{\\ifdefined} tests if a control sequence is
38669 defined.
38670
38671 We need to reset |scanner_status|, since \.{\\outer} control sequences
38672 are allowed, but we might be scanning a macro definition or preamble.
38673
38674 @<Cases for |conditional|@>=
38675 if_def_code:begin save_scanner_status:=scanner_status;
38676 scanner_status:=normal;
38677 get_next; b:=(cur_cmd<>undefined_cs);
38678 scanner_status:=save_scanner_status;
38679 end;
38680
38681 @ The conditional \.{\\ifcsname} is equivalent to \.{\{\\expandafter}
38682 \.{\}\\expandafter} \.{\\ifdefined} \.{\\csname}, except that no new
38683 control sequence will be entered into the hash table (once all tokens
38684 preceding the mandatory \.{\\endcsname} have been expanded).
38685
38686 @<Cases for |conditional|@>=
38687 if_cs_code:begin n:=get_avail; p:=n; {head of the list of characters}
38688 e := is_in_csname; is_in_csname := true;
38689 repeat get_x_token;
38690 if cur_cs=0 then store_new_token(cur_tok);
38691 until cur_cs<>0;
38692 if cur_cmd<>end_cs_name then @<Complain about missing \.{\\endcsname}@>;
38693 @<Look up the characters of list |n| in the hash table, and set |cur_cs|@>;
38694 flush_list(n);
38695 b:=(eq_type(cur_cs)<>undefined_cs);
38696 is_in_csname := e;
38697 end;
38698
38699 @ @<Look up the characters of list |n| in the hash table...@>=
38700 m:=first; p:=link(n);
38701 while p<>null do
38702 begin if m>=max_buf_stack then
38703 begin max_buf_stack:=m+1;
38704 if max_buf_stack=buf_size then
38705 overflow("buffer size",buf_size);
38706 @:TeX capacity exceeded buffer size}{\quad buffer size@>
38707 end;
38708 buffer[m]:=info(p) mod @'400; incr(m); p:=link(p);
38709 end;
38710 if m>first+1 then
38711 cur_cs:=id_lookup(first,m-first) {|no_new_control_sequence| is |true|}
38712 else if m=first then cur_cs:=null_cs {the list is empty}
38713 else cur_cs:=single_base+buffer[first] {the list has length one}
38714
38715 @ The conditional \.{\\iffontchar} tests the existence of a character in
38716 a font.
38717
38718 @<Cases for |conditional|@>=
38719 if_in_csname_code: b := is_in_csname;
38720 if_pdfabs_dim_code, if_pdfabs_num_code: begin
38721 if this_if=if_pdfabs_num_code then scan_int@+else scan_normal_dimen;
38722 n:=cur_val;
38723 if n < 0 then negate(n);
38724 @<Get the next non-blank non-call...@>;
38725 if (cur_tok>=other_token+"<")and(cur_tok<=other_token+">") then
38726 r:=cur_tok-other_token
38727 else begin print_err("Missing = inserted for ");
38728 @.Missing = inserted@>
38729 print_cmd_chr(if_test,this_if);
38730 help1("I was expecting to see `<', `=', or `>'. Didn't.");
38731 back_error; r:="=";
38732 end;
38733 if this_if=if_pdfabs_num_code then scan_int@+else scan_normal_dimen;
38734 if cur_val < 0 then negate(cur_val);
38735 case r of
38736 "<": b:=(n<cur_val);
38737 "=": b:=(n=cur_val);
38738 ">": b:=(n>cur_val);
38739 end;
38740 end;
38741 if_font_char_code:begin scan_font_ident; n:=cur_val; scan_char_num;
38742 if (font_bc[n]<=cur_val)and(font_ec[n]>=cur_val) then
38743 b:=char_exists(char_info(n)(qi(cur_val)))
38744 else b:=false;
38745 end;
38746
38747 @ The |protected| feature of \eTeX\ defines the \.{\\protected} prefix
38748 command for macro definitions. Such macros are protected against
38749 expansions when lists of expanded tokens are built, e.g., for \.{\\edef}
38750 or during \.{\\write}.
38751
38752 @<Generate all \eTeX...@>=
38753 primitive("protected",prefix,8);
38754 @!@:protected_}{\.{\\protected} primitive@>
38755
38756 @ @<Cases of |prefix| for |print_cmd_chr|@>=
38757 else if chr_code=8 then print_esc("protected")
38758
38759 @ The |get_x_or_protected| procedure is like |get_x_token| except that
38760 protected macros are not expanded.
38761
38762 @<Declare \eTeX\ procedures for sc...@>=
38763 procedure get_x_or_protected; {sets |cur_cmd|, |cur_chr|, |cur_tok|,
38764 and expands non-protected macros}
38765 label exit;
38766 begin loop@+begin get_token;
38767 if cur_cmd<=max_command then return;
38768 if (cur_cmd>=call)and(cur_cmd<end_template) then
38769 if info(link(cur_chr))=protected_token then return;
38770 expand;
38771 end;
38772 exit:end;
38773
38774 @ A group entered (or a conditional started) in one file may end in a
38775 different file. Such slight anomalies, although perfectly legitimate,
38776 may cause errors that are difficult to locate. In order to be able to
38777 give a warning message when such anomalies occur, \eTeX\ uses the
38778 |grp_stack| and |if_stack| arrays to record the initial |cur_boundary|
38779 and |cond_ptr| values for each input file.
38780
38781 @<Glob...@>=
38782 @!grp_stack : array[0..max_in_open] of save_pointer; {initial |cur_boundary|}
38783 @!if_stack : array[0..max_in_open] of pointer; {initial |cond_ptr|}
38784
38785 @ When a group ends that was apparently entered in a different input
38786 file, the |group_warning| procedure is invoked in order to update the
38787 |grp_stack|. If moreover \.{\\tracingnesting} is positive we want to
38788 give a warning message. The situation is, however, somewhat complicated
38789 by two facts: (1)~There may be |grp_stack| elements without a
38790 corresponding \.{\\input} file or \.{\\scantokens} pseudo file (e.g.,
38791 error insertions from the terminal); and (2)~the relevant information is
38792 recorded in the |name_field| of the |input_stack| only loosely
38793 synchronized with the |in_open| variable indexing |grp_stack|.
38794
38795 @<Declare \eTeX\ procedures for tr...@>=
38796 procedure group_warning;
38797 var i:0..max_in_open; {index into |grp_stack|}
38798 @!w:boolean; {do we need a warning?}
38799 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
38800 {store current state}
38801 i:=in_open; w:=false;
38802 while (grp_stack[i]=cur_boundary)and(i>0) do
38803 begin @<Set variable |w| to indicate if this case should be reported@>;
38804 grp_stack[i]:=save_index(save_ptr); decr(i);
38805 end;
38806 if w then
38807 begin print_nl("Warning: end of "); print_group(true);
38808 @.Warning: end of...@>
38809 print(" of a different file"); print_ln;
38810 if tracing_nesting>1 then show_context;
38811 if history=spotless then history:=warning_issued;
38812 end;
38813 end;
38814
38815 @ This code scans the input stack in order to determine the type of the
38816 current input file.
38817
38818 @<Set variable |w| to...@>=
38819 if tracing_nesting>0 then
38820 begin while (input_stack[base_ptr].state_field=token_list)or@|
38821 (input_stack[base_ptr].index_field>i) do decr(base_ptr);
38822 if input_stack[base_ptr].name_field>17 then w:=true;
38823 end
38824
38825 @ When a conditional ends that was apparently started in a different
38826 input file, the |if_warning| procedure is invoked in order to update the
38827 |if_stack|. If moreover \.{\\tracingnesting} is positive we want to
38828 give a warning message (with the same complications as above).
38829
38830 @<Declare \eTeX\ procedures for tr...@>=
38831 procedure if_warning;
38832 var i:0..max_in_open; {index into |if_stack|}
38833 @!w:boolean; {do we need a warning?}
38834 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
38835 {store current state}
38836 i:=in_open; w:=false;
38837 while if_stack[i]=cond_ptr do
38838 begin @<Set variable |w| to...@>;
38839 if_stack[i]:=link(cond_ptr); decr(i);
38840 end;
38841 if w then
38842 begin print_nl("Warning: end of "); print_cmd_chr(if_test,cur_if);
38843 @.Warning: end of...@>
38844 print_if_line(if_line); print(" of a different file"); print_ln;
38845 if tracing_nesting>1 then show_context;
38846 if history=spotless then history:=warning_issued;
38847 end;
38848 end;
38849
38850 @ Conversely, the |file_warning| procedure is invoked when a file ends
38851 and some groups entered or conditionals started while reading from that
38852 file are still incomplete.
38853
38854 @<Declare \eTeX\ procedures for tr...@>=
38855 procedure file_warning;
38856 var p:pointer; {saved value of |save_ptr| or |cond_ptr|}
38857 @!l:quarterword; {saved value of |cur_level| or |if_limit|}
38858 @!c:quarterword; {saved value of |cur_group| or |cur_if|}
38859 @!i:integer; {saved value of |if_line|}
38860 begin p:=save_ptr; l:=cur_level; c:=cur_group; save_ptr:=cur_boundary;
38861 while grp_stack[in_open]<>save_ptr do
38862 begin decr(cur_level);
38863 print_nl("Warning: end of file when ");
38864 @.Warning: end of file when...@>
38865 print_group(true); print(" is incomplete");@/
38866 cur_group:=save_level(save_ptr); save_ptr:=save_index(save_ptr)
38867 end;
38868 save_ptr:=p; cur_level:=l; cur_group:=c; {restore old values}
38869 p:=cond_ptr; l:=if_limit; c:=cur_if; i:=if_line;
38870 while if_stack[in_open]<>cond_ptr do
38871 begin print_nl("Warning: end of file when ");
38872 @.Warning: end of file when...@>
38873 print_cmd_chr(if_test,cur_if);
38874 if if_limit=fi_code then print_esc("else");
38875 print_if_line(if_line); print(" is incomplete");@/
38876 if_line:=if_line_field(cond_ptr); cur_if:=subtype(cond_ptr);
38877 if_limit:=type(cond_ptr); cond_ptr:=link(cond_ptr);
38878 end;
38879 cond_ptr:=p; if_limit:=l; cur_if:=c; if_line:=i; {restore old values}
38880 print_ln;
38881 if tracing_nesting>1 then show_context;
38882 if history=spotless then history:=warning_issued;
38883 end;
38884
38885 @ Here are the additional \eTeX\ primitives for expressions.
38886
38887 @<Generate all \eTeX...@>=
38888 primitive("numexpr",last_item,eTeX_expr-int_val+int_val);
38889 @!@:num_expr_}{\.{\\numexpr} primitive@>
38890 primitive("dimexpr",last_item,eTeX_expr-int_val+dimen_val);
38891 @!@:dim_expr_}{\.{\\dimexpr} primitive@>
38892 primitive("glueexpr",last_item,eTeX_expr-int_val+glue_val);
38893 @!@:glue_expr_}{\.{\\glueexpr} primitive@>
38894 primitive("muexpr",last_item,eTeX_expr-int_val+mu_val);
38895 @!@:mu_expr_}{\.{\\muexpr} primitive@>
38896
38897 @ @<Cases of |last_item| for |print_cmd_chr|@>=
38898 eTeX_expr-int_val+int_val: print_esc("numexpr");
38899 eTeX_expr-int_val+dimen_val: print_esc("dimexpr");
38900 eTeX_expr-int_val+glue_val: print_esc("glueexpr");
38901 eTeX_expr-int_val+mu_val: print_esc("muexpr");
38902
38903 @ This code for reducing |cur_val_level| and\slash or negating the
38904 result is similar to the one for all the other cases of
38905 |scan_something_internal|, with the difference that |scan_expr| has
38906 already increased the reference count of a glue specification.
38907
38908 @<Process an expression and |return|@>=
38909 begin if m<eTeX_mu then
38910 begin case m of
38911 @/@<Cases for fetching a glue value@>@/
38912 end; {there are no other cases}
38913 cur_val_level:=glue_val;
38914 end
38915 else if m<eTeX_expr then
38916 begin case m of
38917 @/@<Cases for fetching a mu value@>@/
38918 end; {there are no other cases}
38919 cur_val_level:=mu_val;
38920 end
38921 else begin cur_val_level:=m-eTeX_expr+int_val; scan_expr;
38922 end;
38923 while cur_val_level>level do
38924 begin if cur_val_level=glue_val then
38925 begin m:=cur_val; cur_val:=width(m); delete_glue_ref(m);
38926 end
38927 else if cur_val_level=mu_val then mu_error;
38928 decr(cur_val_level);
38929 end;
38930 if negative then
38931 if cur_val_level>=glue_val then
38932 begin m:=cur_val; cur_val:=new_spec(m); delete_glue_ref(m);
38933 @<Negate all three glue components of |cur_val|@>;
38934 end
38935 else negate(cur_val);
38936 return;
38937 end
38938
38939 @ @<Declare \eTeX\ procedures for sc...@>=
38940 procedure@?scan_expr; forward;@t\2@>
38941
38942 @ The |scan_expr| procedure scans and evaluates an expression.
38943
38944 @<Declare procedures needed for expressions@>=
38945 @t\4@>@<Declare subprocedures for |scan_expr|@>
38946 procedure scan_expr; {scans and evaluates an expression}
38947 label restart, continue, found;
38948 var a,@!b:boolean; {saved values of |arith_error|}
38949 @!l:small_number; {type of expression}
38950 @!r:small_number; {state of expression so far}
38951 @!s:small_number; {state of term so far}
38952 @!o:small_number; {next operation or type of next factor}
38953 @!e:integer; {expression so far}
38954 @!t:integer; {term so far}
38955 @!f:integer; {current factor}
38956 @!n:integer; {numerator of combined multiplication and division}
38957 @!p:pointer; {top of expression stack}
38958 @!q:pointer; {for stack manipulations}
38959 begin l:=cur_val_level; a:=arith_error; b:=false; p:=null;
38960 incr(expand_depth_count);
38961 if expand_depth_count>=expand_depth then overflow("expansion depth",expand_depth);
38962 @<Scan and evaluate an expression |e| of type |l|@>;
38963 decr(expand_depth_count);
38964 if b then
38965 begin print_err("Arithmetic overflow");
38966 @.Arithmetic overflow@>
38967 help2("I can't evaluate this expression,")@/
38968 ("since the result is out of range.");
38969 error;
38970 if l>=glue_val then
38971 begin delete_glue_ref(e); e:=zero_glue; add_glue_ref(e);
38972 end
38973 else e:=0;
38974 end;
38975 arith_error:=a; cur_val:=e; cur_val_level:=l;
38976 end;
38977
38978 @ Evaluating an expression is a recursive process: When the left
38979 parenthesis of a subexpression is scanned we descend to the next level
38980 of recursion; the previous level is resumed with the matching right
38981 parenthesis.
38982
38983 @d expr_none=0 {\.( seen, or \.( $\langle\it expr\rangle$ \.) seen}
38984 @d expr_add=1 {\.( $\langle\it expr\rangle$ \.+ seen}
38985 @d expr_sub=2 {\.( $\langle\it expr\rangle$ \.- seen}
38986 @d expr_mult=3 {$\langle\it term\rangle$ \.* seen}
38987 @d expr_div=4 {$\langle\it term\rangle$ \./ seen}
38988 @d expr_scale=5 {$\langle\it term\rangle$ \.*
38989 $\langle\it factor\rangle$ \./ seen}
38990
38991 @<Scan and eval...@>=
38992 restart: r:=expr_none; e:=0; s:=expr_none; t:=0; n:=0;
38993 continue: if s=expr_none then o:=l@+else o:=int_val;
38994 @<Scan a factor |f| of type |o| or start a subexpression@>;
38995 found: @<Scan the next operator and set |o|@>;
38996 arith_error:=b;
38997 @<Make sure that |f| is in the proper range@>;
38998 case s of @<Cases for evaluation of the current term@>@;
38999 end; {there are no other cases}
39000 if o>expr_sub then s:=o@+else @<Evaluate the current expression@>;
39001 b:=arith_error;
39002 if o<>expr_none then goto continue;
39003 if p<>null then @<Pop the expression stack and |goto found|@>
39004
39005 @ @<Scan the next op...@>=
39006 @<Get the next non-blank non-call token@>;
39007 if cur_tok=other_token+"+" then o:=expr_add
39008 else if cur_tok=other_token+"-" then o:=expr_sub
39009 else if cur_tok=other_token+"*" then o:=expr_mult
39010 else if cur_tok=other_token+"/" then o:=expr_div
39011 else begin o:=expr_none;
39012 if p=null then
39013 begin if cur_cmd<>relax then back_input;
39014 end
39015 else if cur_tok<>other_token+")" then
39016 begin print_err("Missing ) inserted for expression");
39017 @.Missing ) inserted@>
39018 help1("I was expecting to see `+', `-', `*', `/', or `)'. Didn't.");
39019 back_error;
39020 end;
39021 end
39022
39023 @ @<Scan a factor...@>=
39024 @<Get the next non-blank non-call token@>;
39025 if cur_tok=other_token+"(" then
39026 @<Push the expression stack and |goto restart|@>;
39027 back_input;
39028 if o=int_val then scan_int
39029 else if o=dimen_val then scan_normal_dimen
39030 else if o=glue_val then scan_normal_glue
39031 else scan_mu_glue;
39032 f:=cur_val
39033
39034 @ @<Declare \eTeX\ procedures for sc...@>=
39035 procedure@?scan_normal_glue; forward;@t\2@>@/
39036 procedure@?scan_mu_glue; forward;@t\2@>
39037
39038 @ Here we declare two trivial procedures in order to avoid mutually
39039 recursive procedures with parameters.
39040
39041 @<Declare procedures needed for expressions@>=
39042 procedure scan_normal_glue;
39043 begin scan_glue(glue_val);
39044 end;
39045 @#
39046 procedure scan_mu_glue;
39047 begin scan_glue(mu_val);
39048 end;
39049
39050 @ Parenthesized subexpressions can be inside expressions, and this
39051 nesting has a stack. Seven local variables represent the top of the
39052 expression stack: |p| points to pushed-down entries, if any; |l|
39053 specifies the type of expression currently being evaluated; |e| is the
39054 expression so far and |r| is the state of its evaluation; |t| is the
39055 term so far and |s| is the state of its evaluation; finally |n| is the
39056 numerator for a combined multiplication and division, if any.
39057
39058 @d expr_node_size=4 {number of words in stack entry for subexpressions}
39059 @d expr_e_field(#)==mem[#+1].int {saved expression so far}
39060 @d expr_t_field(#)==mem[#+2].int {saved term so far}
39061 @d expr_n_field(#)==mem[#+3].int {saved numerator}
39062
39063 @<Push the expression...@>=
39064 begin q:=get_node(expr_node_size); link(q):=p; type(q):=l;
39065 subtype(q):=4*s+r;
39066 expr_e_field(q):=e; expr_t_field(q):=t; expr_n_field(q):=n;
39067 p:=q; l:=o; goto restart;
39068 end
39069
39070 @ @<Pop the expression...@>=
39071 begin f:=e; q:=p;
39072 e:=expr_e_field(q); t:=expr_t_field(q); n:=expr_n_field(q);
39073 s:=subtype(q) div 4; r:=subtype(q) mod 4;
39074 l:=type(q); p:=link(q); free_node(q,expr_node_size);
39075 goto found;
39076 end
39077
39078 @ We want to make sure that each term and (intermediate) result is in
39079 the proper range. Integer values must not exceed |infinity|
39080 ($2^{31}-1$) in absolute value, dimensions must not exceed |max_dimen|
39081 ($2^{30}-1$). We avoid the absolute value of an integer, because this
39082 might fail for the value $-2^{31}$ using 32-bit arithmetic.
39083
39084 @d num_error(#)== {clear a number or dimension and set |arith_error|}
39085 begin arith_error:=true; #:=0;
39086 end
39087 @d glue_error(#)== {clear a glue spec and set |arith_error|}
39088 begin arith_error:=true; delete_glue_ref(#); #:=new_spec(zero_glue);
39089 end
39090
39091 @<Make sure that |f|...@>=
39092 if (l=int_val)or(s>expr_sub) then
39093 begin if (f>infinity)or(f<-infinity) then num_error(f);
39094 end
39095 else if l=dimen_val then
39096 begin if abs(f)>max_dimen then num_error(f);
39097 end
39098 else begin if (abs(width(f))>max_dimen)or@|
39099 (abs(stretch(f))>max_dimen)or@|
39100 (abs(shrink(f))>max_dimen) then glue_error(f);
39101 end
39102
39103 @ Applying the factor |f| to the partial term |t| (with the operator
39104 |s|) is delayed until the next operator |o| has been scanned. Here we
39105 handle the first factor of a partial term. A glue spec has to be copied
39106 unless the next operator is a right parenthesis; this allows us later on
39107 to simply modify the glue components.
39108
39109 @d normalize_glue(#)==
39110 if stretch(#)=0 then stretch_order(#):=normal;
39111 if shrink(#)=0 then shrink_order(#):=normal
39112
39113 @<Cases for evaluation of the current term@>=
39114 expr_none: if (l>=glue_val)and(o<>expr_none) then
39115 begin t:=new_spec(f); delete_glue_ref(f); normalize_glue(t);
39116 end
39117 else t:=f;
39118
39119 @ When a term |t| has been completed it is copied to, added to, or
39120 subtracted from the expression |e|.
39121
39122 @d expr_add_sub(#)==add_or_sub(#,r=expr_sub)
39123 @d expr_a(#)==expr_add_sub(#,max_dimen)
39124
39125 @<Evaluate the current expression@>=
39126 begin s:=expr_none;
39127 if r=expr_none then e:=t
39128 else if l=int_val then e:=expr_add_sub(e,t,infinity)
39129 else if l=dimen_val then e:=expr_a(e,t)
39130 else @<Compute the sum or difference of two glue specs@>;
39131 r:=o;
39132 end
39133
39134 @ The function |add_or_sub(x,y,max_answer,negative)| computes the sum
39135 (for |negative=false|) or difference (for |negative=true|) of |x| and
39136 |y|, provided the absolute value of the result does not exceed
39137 |max_answer|.
39138
39139 @<Declare subprocedures for |scan_expr|@>=
39140 function add_or_sub(@!x,@!y,@!max_answer:integer;@!negative:boolean):integer;
39141 var a:integer; {the answer}
39142 begin if negative then negate(y);
39143 if x>=0 then
39144 if y<=max_answer-x then a:=x+y@+else num_error(a)
39145 else if y>=-max_answer-x then a:=x+y@+else num_error(a);
39146 add_or_sub:=a;
39147 end;
39148
39149 @ We know that |stretch_order(e)>normal| implies |stretch(e)<>0| and
39150 |shrink_order(e)>normal| implies |shrink(e)<>0|.
39151
39152 @<Compute the sum or diff...@>=
39153 begin width(e):=expr_a(width(e),width(t));
39154 if stretch_order(e)=stretch_order(t) then
39155 stretch(e):=expr_a(stretch(e),stretch(t))
39156 else if (stretch_order(e)<stretch_order(t))and(stretch(t)<>0) then
39157 begin stretch(e):=stretch(t); stretch_order(e):=stretch_order(t);
39158 end;
39159 if shrink_order(e)=shrink_order(t) then
39160 shrink(e):=expr_a(shrink(e),shrink(t))
39161 else if (shrink_order(e)<shrink_order(t))and(shrink(t)<>0) then
39162 begin shrink(e):=shrink(t); shrink_order(e):=shrink_order(t);
39163 end;
39164 delete_glue_ref(t); normalize_glue(e);
39165 end
39166
39167 @ If a multiplication is followed by a division, the two operations are
39168 combined into a `scaling' operation. Otherwise the term |t| is
39169 multiplied by the factor |f|.
39170
39171 @d expr_m(#)==#:=nx_plus_y(#,f,0)
39172
39173 @<Cases for evaluation of the current term@>=
39174 expr_mult: if o=expr_div then
39175 begin n:=f; o:=expr_scale;
39176 end
39177 else if l=int_val then t:=mult_integers(t,f)
39178 else if l=dimen_val then expr_m(t)
39179 else begin expr_m(width(t)); expr_m(stretch(t)); expr_m(shrink(t));
39180 end;
39181
39182 @ Here we divide the term |t| by the factor |f|.
39183
39184 @d expr_d(#)==#:=quotient(#,f)
39185
39186 @<Cases for evaluation of the current term@>=
39187 expr_div: if l<glue_val then expr_d(t)
39188 else begin expr_d(width(t)); expr_d(stretch(t)); expr_d(shrink(t));
39189 end;
39190
39191 @ The function |quotient(n,d)| computes the rounded quotient
39192 $q=\lfloor n/d+{1\over2}\rfloor$, when $n$ and $d$ are positive.
39193
39194 @<Declare subprocedures for |scan_expr|@>=
39195 function quotient(@!n,@!d:integer):integer;
39196 var negative:boolean; {should the answer be negated?}
39197 @!a:integer; {the answer}
39198 begin if d=0 then num_error(a)
39199 else begin if d>0 then negative:=false
39200 else begin negate(d); negative:=true;
39201 end;
39202 if n<0 then
39203 begin negate(n); negative:=not negative;
39204 end;
39205 a:=n div d; n:=n-a*d; d:=n-d; {avoid certain compiler optimizations!}
39206 if d+n>=0 then incr(a);
39207 if negative then negate(a);
39208 end;
39209 quotient:=a;
39210 end;
39211
39212 @ Here the term |t| is multiplied by the quotient $n/f$.
39213
39214 @d expr_s(#)==#:=fract(#,n,f,max_dimen)
39215
39216 @<Cases for evaluation of the current term@>=
39217 expr_scale: if l=int_val then t:=fract(t,n,f,infinity)
39218 else if l=dimen_val then expr_s(t)
39219 else begin expr_s(width(t)); expr_s(stretch(t)); expr_s(shrink(t));
39220 end;
39221
39222 @ Finally, the function |fract(x,n,d,max_answer)| computes the integer
39223 $q=\lfloor xn/d+{1\over2}\rfloor$, when $x$, $n$, and $d$ are positive
39224 and the result does not exceed |max_answer|. We can't use floating
39225 point arithmetic since the routine must produce identical results in all
39226 cases; and it would be too dangerous to multiply by~|n| and then divide
39227 by~|d|, in separate operations, since overflow might well occur. Hence
39228 this subroutine simulates double precision arithmetic, somewhat
39229 analogous to \MF's |make_fraction| and |take_fraction| routines.
39230
39231 @d too_big=88 {go here when the result is too big}
39232
39233 @<Declare subprocedures for |scan_expr|@>=
39234 function fract(@!x,@!n,@!d,@!max_answer:integer):integer;
39235 label found, found1, too_big, done;
39236 var negative:boolean; {should the answer be negated?}
39237 @!a:integer; {the answer}
39238 @!f:integer; {a proper fraction}
39239 @!h:integer; {smallest integer such that |2*h>=d|}
39240 @!r:integer; {intermediate remainder}
39241 @!t:integer; {temp variable}
39242 begin if d=0 then goto too_big;
39243 a:=0;
39244 if d>0 then negative:=false
39245 else begin negate(d); negative:=true;
39246 end;
39247 if x<0 then
39248 begin negate(x); negative:=not negative;
39249 end
39250 else if x=0 then goto done;
39251 if n<0 then
39252 begin negate(n); negative:=not negative;
39253 end;
39254 t:=n div d;
39255 if t>max_answer div x then goto too_big;
39256 a:=t*x; n:=n-t*d;
39257 if n=0 then goto found;
39258 t:=x div d;
39259 if t>(max_answer-a) div n then goto too_big;
39260 a:=a+t*n; x:=x-t*d;
39261 if x=0 then goto found;
39262 if x<n then
39263 begin t:=x; x:=n; n:=t;
39264 end; {now |0<n<=x<d|}
39265 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>@;
39266 if f>(max_answer-a) then goto too_big;
39267 a:=a+f;
39268 found: if negative then negate(a);
39269 goto done;
39270 too_big: num_error(a);
39271 done: fract:=a;
39272 end;
39273
39274 @ The loop here preserves the following invariant relations
39275 between |f|, |x|, |n|, and~|r|:
39276 (i)~$f+\lfloor(xn+(r+d))/d\rfloor=\lfloor x_0n_0/d+{1\over2}\rfloor$;
39277 (ii)~|-d<=r<0<n<=x<d|, where $x_0$, $n_0$ are the original values of~$x$
39278 and $n$.
39279
39280 Notice that the computation specifies |(x-d)+x| instead of |(x+x)-d|,
39281 because the latter could overflow.
39282
39283 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>=
39284 f:=0; r:=(d div 2)-d; h:=-r;
39285 loop@+begin if odd(n) then
39286 begin r:=r+x;
39287 if r>=0 then
39288 begin r:=r-d; incr(f);
39289 end;
39290 end;
39291 n:=n div 2;
39292 if n=0 then goto found1;
39293 if x<h then x:=x+x
39294 else begin t:=x-d; x:=t+x; f:=f+n;
39295 if x<n then
39296 begin if x=0 then goto found1;
39297 t:=x; x:=n; n:=t;
39298 end;
39299 end;
39300 end;
39301 found1:
39302
39303 @ The \.{\\gluestretch}, \.{\\glueshrink}, \.{\\gluestretchorder}, and
39304 \.{\\glueshrinkorder} commands return the stretch and shrink components
39305 and their orders of ``infinity'' of a glue specification.
39306
39307 @d glue_stretch_order_code=eTeX_int+6 {code for \.{\\gluestretchorder}}
39308 @d glue_shrink_order_code=eTeX_int+7 {code for \.{\\glueshrinkorder}}
39309 @d glue_stretch_code=eTeX_dim+7 {code for \.{\\gluestretch}}
39310 @d glue_shrink_code=eTeX_dim+8 {code for \.{\\glueshrink}}
39311
39312 @<Generate all \eTeX...@>=
39313 primitive("gluestretchorder",last_item,glue_stretch_order_code);
39314 @!@:glue_stretch_order_}{\.{\\gluestretchorder} primitive@>
39315 primitive("glueshrinkorder",last_item,glue_shrink_order_code);
39316 @!@:glue_shrink_order_}{\.{\\glueshrinkorder} primitive@>
39317 primitive("gluestretch",last_item,glue_stretch_code);
39318 @!@:glue_stretch_}{\.{\\gluestretch} primitive@>
39319 primitive("glueshrink",last_item,glue_shrink_code);
39320 @!@:glue_shrink_}{\.{\\glueshrink} primitive@>
39321
39322 @ @<Cases of |last_item| for |print_cmd_chr|@>=
39323 glue_stretch_order_code: print_esc("gluestretchorder");
39324 glue_shrink_order_code: print_esc("glueshrinkorder");
39325 glue_stretch_code: print_esc("gluestretch");
39326 glue_shrink_code: print_esc("glueshrink");
39327
39328 @ @<Cases for fetching an integer value@>=
39329 glue_stretch_order_code, glue_shrink_order_code:
39330 begin scan_normal_glue; q:=cur_val;
39331 if m=glue_stretch_order_code then cur_val:=stretch_order(q)
39332 else cur_val:=shrink_order(q);
39333 delete_glue_ref(q);
39334 end;
39335
39336 @ @<Cases for fetching a dimension value@>=
39337 glue_stretch_code, glue_shrink_code:
39338 begin scan_normal_glue; q:=cur_val;
39339 if m=glue_stretch_code then cur_val:=stretch(q)
39340 else cur_val:=shrink(q);
39341 delete_glue_ref(q);
39342 end;
39343
39344 @ The \.{\\mutoglue} and \.{\\gluetomu} commands convert ``math'' glue
39345 into normal glue and vice versa; they allow to manipulate math glue with
39346 \.{\\gluestretch} etc.
39347
39348 @d mu_to_glue_code=eTeX_glue {code for \.{\\mutoglue}}
39349 @d glue_to_mu_code=eTeX_mu {code for \.{\\gluetomu}}
39350
39351 @<Generate all \eTeX...@>=
39352 primitive("mutoglue",last_item,mu_to_glue_code);
39353 @!@:mu_to_glue_}{\.{\\mutoglue} primitive@>
39354 primitive("gluetomu",last_item,glue_to_mu_code);
39355 @!@:glue_to_mu_}{\.{\\gluetomu} primitive@>
39356
39357 @ @<Cases of |last_item| for |print_cmd_chr|@>=
39358 mu_to_glue_code: print_esc("mutoglue");
39359 glue_to_mu_code: print_esc("gluetomu");
39360
39361 @ @<Cases for fetching a glue value@>=
39362 mu_to_glue_code: scan_mu_glue;
39363
39364 @ @<Cases for fetching a mu value@>=
39365 glue_to_mu_code: scan_normal_glue;
39366
39367 @ \eTeX\ (in extended mode) supports 32768 (i.e., $2^{15}$) count,
39368 dimen, skip, muskip, box, and token registers. As in \TeX\ the first
39369 256 registers of each kind are realized as arrays in the table of
39370 equivalents; the additional registers are realized as tree structures
39371 built from variable-size nodes with individual registers existing only
39372 when needed. Default values are used for nonexistent registers: zero
39373 for count and dimen values, |zero_glue| for glue (skip and muskip)
39374 values, void for boxes, and |null| for token lists (and current marks
39375 discussed below).
39376
39377 Similarly there are 32768 mark classes; the command \.{\\marks}|n|
39378 creates a mark node for a given mark class |0<=n<=32767| (where
39379 \.{\\marks0} is synonymous to \.{\\mark}). The page builder (actually
39380 the |fire_up| routine) and the |vsplit| routine maintain the current
39381 values of |top_mark|, |first_mark|, |bot_mark|, |split_first_mark|, and
39382 |split_bot_mark| for each mark class. They are accessed as
39383 \.{\\topmarks}|n| etc., and \.{\\topmarks0} is again synonymous to
39384 \.{\\topmark}. As in \TeX\ the five current marks for mark class zero
39385 are realized as |cur_mark| array. The additional current marks are
39386 again realized as tree structure with individual mark classes existing
39387 only when needed.
39388
39389 @<Generate all \eTeX...@>=
39390 primitive("marks",mark,marks_code);
39391 @!@:marks_}{\.{\\marks} primitive@>
39392 primitive("topmarks",top_bot_mark,top_mark_code+marks_code);
39393 @!@:top_marks_}{\.{\\topmarks} primitive@>
39394 primitive("firstmarks",top_bot_mark,first_mark_code+marks_code);
39395 @!@:first_marks_}{\.{\\firstmarks} primitive@>
39396 primitive("botmarks",top_bot_mark,bot_mark_code+marks_code);
39397 @!@:bot_marks_}{\.{\\botmarks} primitive@>
39398 primitive("splitfirstmarks",top_bot_mark,split_first_mark_code+marks_code);
39399 @!@:split_first_marks_}{\.{\\splitfirstmarks} primitive@>
39400 primitive("splitbotmarks",top_bot_mark,split_bot_mark_code+marks_code);
39401 @!@:split_bot_marks_}{\.{\\splitbotmarks} primitive@>
39402
39403 @ The |scan_register_num| procedure scans a register number that must
39404 not exceed 255 in compatibility mode resp.\ 32767 in extended mode.
39405
39406 @<Declare \eTeX\ procedures for ex...@>=
39407 procedure@?scan_register_num; forward;@t\2@>
39408
39409 @ @<Declare procedures that scan restricted classes of integers@>=
39410 procedure scan_register_num;
39411 begin scan_int;
39412 if (cur_val<0)or(cur_val>max_reg_num) then
39413 begin print_err("Bad register code");
39414 @.Bad register code@>
39415 help2(max_reg_help_line)("I changed this one to zero.");
39416 int_error(cur_val); cur_val:=0;
39417 end;
39418 end;
39419
39420 @ @<Initialize variables for \eTeX\ comp...@>=
39421 max_reg_num:=255;
39422 max_reg_help_line:="A register number must be between 0 and 255.";
39423
39424 @ @<Initialize variables for \eTeX\ ext...@>=
39425 max_reg_num:=32767;
39426 max_reg_help_line:="A register number must be between 0 and 32767.";
39427
39428 @ @<Glob...@>=
39429 @!max_reg_num: halfword; {largest allowed register number}
39430 @!max_reg_help_line: str_number; {first line of help message}
39431
39432 @ There are seven almost identical doubly linked trees, one for the
39433 sparse array of the up to 32512 additional registers of each kind and
39434 one for the sparse array of the up to 32767 additional mark classes.
39435 The root of each such tree, if it exists, is an index node containing 16
39436 pointers to subtrees for 4096 consecutive array elements. Similar index
39437 nodes are the starting points for all nonempty subtrees for 4096, 256,
39438 and 16 consecutive array elements. These four levels of index nodes are
39439 followed by a fifth level with nodes for the individual array elements.
39440
39441 Each index node is nine words long. The pointers to the 16 possible
39442 subtrees or are kept in the |info| and |link| fields of the last eight
39443 words. (It would be both elegant and efficient to declare them as
39444 array, unfortunately \PASCAL\ doesn't allow this.)
39445
39446 The fields in the first word of each index node and in the nodes for the
39447 array elements are closely related. The |link| field points to the next
39448 lower index node and the |sa_index| field contains four bits (one
39449 hexadecimal digit) of the register number or mark class. For the lowest
39450 index node the |link| field is |null| and the |sa_index| field indicates
39451 the type of quantity (|int_val|, |dimen_val|, |glue_val|, |mu_val|,
39452 |box_val|, |tok_val|, or |mark_val|). The |sa_used| field in the index
39453 nodes counts how many of the 16 pointers are non-null.
39454
39455 The |sa_index| field in the nodes for array elements contains the four
39456 bits plus 16 times the type. Therefore such a node represents a count
39457 or dimen register if and only if |sa_index<dimen_val_limit|; it
39458 represents a skip or muskip register if and only if
39459 |dimen_val_limit<=sa_index<mu_val_limit|; it represents a box register
39460 if and only if |mu_val_limit<=sa_index<box_val_limit|; it represents a
39461 token list register if and only if
39462 |box_val_limit<=sa_index<tok_val_limit|; finally it represents a mark
39463 class if and only if |tok_val_limit<=sa_index|.
39464
39465 The |new_index| procedure creates an index node (returned in |cur_ptr|)
39466 having given contents of the |sa_index| and |link| fields.
39467
39468 @d box_val==4 {the additional box registers}
39469 @d mark_val=6 {the additional mark classes}
39470 @#
39471 @d dimen_val_limit=@"20 {$2^4\cdot(|dimen_val|+1)$}
39472 @d mu_val_limit=@"40 {$2^4\cdot(|mu_val|+1)$}
39473 @d box_val_limit=@"50 {$2^4\cdot(|box_val|+1)$}
39474 @d tok_val_limit=@"60 {$2^4\cdot(|tok_val|+1)$}
39475 @#
39476 @d index_node_size=9 {size of an index node}
39477 @d sa_index==type {a four-bit address or a type or both}
39478 @d sa_used==subtype {count of non-null pointers}
39479
39480 @<Declare \eTeX\ procedures for ex...@>=
39481 procedure new_index(@!i:quarterword; @!q:pointer);
39482 var k:small_number; {loop index}
39483 begin cur_ptr:=get_node(index_node_size); sa_index(cur_ptr):=i;
39484 sa_used(cur_ptr):=0; link(cur_ptr):=q;
39485 for k:=1 to index_node_size-1 do {clear all 16 pointers}
39486 mem[cur_ptr+k]:=sa_null;
39487 end;
39488
39489 @ The roots of the seven trees for the additional registers and mark
39490 classes are kept in the |sa_root| array. The first six locations must
39491 be dumped and undumped; the last one is also known as |sa_mark|.
39492
39493 @d sa_mark==sa_root[mark_val] {root for mark classes}
39494
39495 @<Glob...@>=
39496 @!sa_root:array[int_val..mark_val] of pointer; {roots of sparse arrays}
39497 @!cur_ptr:pointer; {value returned by |new_index| and |find_sa_element|}
39498 @!sa_null:memory_word; {two |null| pointers}
39499
39500 @ @<Set init...@>=
39501 sa_mark:=null; sa_null.hh.lh:=null; sa_null.hh.rh:=null;
39502
39503 @ @<Initialize table...@>=
39504 for i:=int_val to tok_val do sa_root[i]:=null;
39505
39506 @ Given a type |t| and a sixteen-bit number |n|, the |find_sa_element|
39507 procedure returns (in |cur_ptr|) a pointer to the node for the
39508 corresponding array element, or |null| when no such element exists. The
39509 third parameter |w| is set |true| if the element must exist, e.g.,
39510 because it is about to be modified. The procedure has two main
39511 branches: one follows the existing tree structure, the other (only used
39512 when |w| is |true|) creates the missing nodes.
39513
39514 We use macros to extract the four-bit pieces from a sixteen-bit register
39515 number or mark class and to fetch or store one of the 16 pointers from
39516 an index node.
39517
39518 @d if_cur_ptr_is_null_then_return_or_goto(#)== {some tree element is missing}
39519 begin if cur_ptr=null then
39520 if w then goto #@+else return;
39521 end
39522 @#
39523 @d hex_dig1(#)==# div 4096 {the fourth lowest hexadecimal digit}
39524 @d hex_dig2(#)==(# div 256) mod 16 {the third lowest hexadecimal digit}
39525 @d hex_dig3(#)==(# div 16) mod 16 {the second lowest hexadecimal digit}
39526 @d hex_dig4(#)==# mod 16 {the lowest hexadecimal digit}
39527 @#
39528 @d get_sa_ptr==if odd(i) then cur_ptr:=link(q+(i div 2)+1)
39529 else cur_ptr:=info(q+(i div 2)+1)
39530 {set |cur_ptr| to the pointer indexed by |i| from index node |q|}
39531 @d put_sa_ptr(#)==if odd(i) then link(q+(i div 2)+1):=#
39532 else info(q+(i div 2)+1):=#
39533 {store the pointer indexed by |i| in index node |q|}
39534 @d add_sa_ptr==begin put_sa_ptr(cur_ptr); incr(sa_used(q));
39535 end {add |cur_ptr| as the pointer indexed by |i| in index node |q|}
39536 @d delete_sa_ptr==begin put_sa_ptr(null); decr(sa_used(q));
39537 end {delete the pointer indexed by |i| in index node |q|}
39538
39539 @<Declare \eTeX\ procedures for ex...@>=
39540 procedure find_sa_element(@!t:small_number;@!n:halfword;@!w:boolean);
39541 {sets |cur_val| to sparse array element location or |null|}
39542 label not_found,not_found1,not_found2,not_found3,not_found4,exit;
39543 var q:pointer; {for list manipulations}
39544 @!i:small_number; {a four bit index}
39545 begin cur_ptr:=sa_root[t];
39546 if_cur_ptr_is_null_then_return_or_goto(not_found);@/
39547 q:=cur_ptr; i:=hex_dig1(n); get_sa_ptr;
39548 if_cur_ptr_is_null_then_return_or_goto(not_found1);@/
39549 q:=cur_ptr; i:=hex_dig2(n); get_sa_ptr;
39550 if_cur_ptr_is_null_then_return_or_goto(not_found2);@/
39551 q:=cur_ptr; i:=hex_dig3(n); get_sa_ptr;
39552 if_cur_ptr_is_null_then_return_or_goto(not_found3);@/
39553 q:=cur_ptr; i:=hex_dig4(n); get_sa_ptr;
39554 if (cur_ptr=null)and w then goto not_found4;
39555 return;
39556 not_found: new_index(t,null); {create first level index node}
39557 sa_root[t]:=cur_ptr; q:=cur_ptr; i:=hex_dig1(n);
39558 not_found1: new_index(i,q); {create second level index node}
39559 add_sa_ptr; q:=cur_ptr; i:=hex_dig2(n);
39560 not_found2: new_index(i,q); {create third level index node}
39561 add_sa_ptr; q:=cur_ptr; i:=hex_dig3(n);
39562 not_found3: new_index(i,q); {create fourth level index node}
39563 add_sa_ptr; q:=cur_ptr; i:=hex_dig4(n);
39564 not_found4: @<Create a new array element of type |t| with index |i|@>;
39565 link(cur_ptr):=q; add_sa_ptr;
39566 exit:end;
39567
39568 @ The array elements for registers are subject to grouping and have an
39569 |sa_lev| field (quite analogous to |eq_level|) instead of |sa_used|.
39570 Since saved values as well as shorthand definitions (created by e.g.,
39571 \.{\\countdef}) refer to the location of the respective array element,
39572 we need a reference count that is kept in the |sa_ref| field. An array
39573 element can be deleted (together with all references to it) when its
39574 |sa_ref| value is |null| and its value is the default value.
39575 @^reference counts@>
39576
39577 Skip, muskip, box, and token registers use two word nodes, their values
39578 are stored in the |sa_ptr| field.
39579 Count and dimen registers use three word nodes, their
39580 values are stored in the |sa_int| resp.\ |sa_dim| field in the third
39581 word; the |sa_ptr| field is used under the name |sa_num| to store
39582 the register number. Mark classes use four word nodes. The last three
39583 words contain the five types of current marks
39584
39585 @d sa_lev==sa_used {grouping level for the current value}
39586 @d pointer_node_size=2 {size of an element with a pointer value}
39587 @d sa_type(#)==(sa_index(#) div 16) {type part of combined type/index}
39588 @d sa_ref(#)==info(#+1) {reference count of a sparse array element}
39589 @d sa_ptr(#)==link(#+1) {a pointer value}
39590 @#
39591 @d word_node_size=3 {size of an element with a word value}
39592 @d sa_num==sa_ptr {the register number}
39593 @d sa_int(#)==mem[#+2].int {an integer}
39594 @d sa_dim(#)==mem[#+2].sc {a dimension (a somewhat esoteric distinction)}
39595 @#
39596 @d mark_class_node_size=4 {size of an element for a mark class}
39597 @#
39598 @d fetch_box(#)== {fetch |box(cur_val)|}
39599 if cur_val<256 then #:=box(cur_val)
39600 else begin find_sa_element(box_val,cur_val,false);
39601 if cur_ptr=null then #:=null@+else #:=sa_ptr(cur_ptr);
39602 end
39603
39604 @<Create a new array element...@>=
39605 if t=mark_val then {a mark class}
39606 begin cur_ptr:=get_node(mark_class_node_size);
39607 mem[cur_ptr+1]:=sa_null; mem[cur_ptr+2]:=sa_null; mem[cur_ptr+3]:=sa_null;
39608 end
39609 else begin if t<=dimen_val then {a count or dimen register}
39610 begin cur_ptr:=get_node(word_node_size); sa_int(cur_ptr):=0;
39611 sa_num(cur_ptr):=n;
39612 end
39613 else begin cur_ptr:=get_node(pointer_node_size);
39614 if t<=mu_val then {a skip or muskip register}
39615 begin sa_ptr(cur_ptr):=zero_glue; add_glue_ref(zero_glue);
39616 end
39617 else sa_ptr(cur_ptr):=null; {a box or token list register}
39618 end;
39619 sa_ref(cur_ptr):=null; {all registers have a reference count}
39620 end;
39621 sa_index(cur_ptr):=16*t+i; sa_lev(cur_ptr):=level_one
39622
39623 @ The |delete_sa_ref| procedure is called when a pointer to an array
39624 element representing a register is being removed; this means that the
39625 reference count should be decreased by one. If the reduced reference
39626 count is |null| and the register has been (globally) assigned its
39627 default value the array element should disappear, possibly together with
39628 some index nodes. This procedure will never be used for mark class
39629 nodes.
39630 @^reference counts@>
39631
39632 @d add_sa_ref(#)==incr(sa_ref(#)) {increase reference count}
39633 @#
39634 @d change_box(#)== {change |box(cur_val)|, the |eq_level| stays the same}
39635 if cur_val<256 then box(cur_val):=#@+else set_sa_box(#)
39636 @#
39637 @d set_sa_box(#)==begin find_sa_element(box_val,cur_val,false);
39638 if cur_ptr<>null then
39639 begin sa_ptr(cur_ptr):=#; add_sa_ref(cur_ptr); delete_sa_ref(cur_ptr);
39640 end;
39641 end
39642
39643 @<Declare \eTeX\ procedures for tr...@>=
39644 procedure delete_sa_ref(@!q:pointer); {reduce reference count}
39645 label exit;
39646 var p:pointer; {for list manipulations}
39647 @!i:small_number; {a four bit index}
39648 @!s:small_number; {size of a node}
39649 begin decr(sa_ref(q));
39650 if sa_ref(q)<>null then return;
39651 if sa_index(q)<dimen_val_limit then
39652 if sa_int(q)=0 then s:=word_node_size
39653 else return
39654 else begin if sa_index(q)<mu_val_limit then
39655 if sa_ptr(q)=zero_glue then delete_glue_ref(zero_glue)
39656 else return
39657 else if sa_ptr(q)<>null then return;
39658 s:=pointer_node_size;
39659 end;
39660 repeat i:=hex_dig4(sa_index(q)); p:=q; q:=link(p); free_node(p,s);
39661 if q=null then {the whole tree has been freed}
39662 begin sa_root[i]:=null; return;
39663 end;
39664 delete_sa_ptr; s:=index_node_size; {node |q| is an index node}
39665 until sa_used(q)>0;
39666 exit:end;
39667
39668 @ The |print_sa_num| procedure prints the register number corresponding
39669 to an array element.
39670
39671 @<Basic print...@>=
39672 procedure print_sa_num(@!q:pointer); {print register number}
39673 var @!n:halfword; {the register number}
39674 begin if sa_index(q)<dimen_val_limit then n:=sa_num(q) {the easy case}
39675 else begin n:=hex_dig4(sa_index(q)); q:=link(q); n:=n+16*sa_index(q);
39676 q:=link(q); n:=n+256*(sa_index(q)+16*sa_index(link(q)));
39677 end;
39678 print_int(n);
39679 end;
39680
39681 @ Here is a procedure that displays the contents of an array element
39682 symbolically. It is used under similar circumstances as is
39683 |restore_trace| (together with |show_eqtb|) for the quantities kept in
39684 the |eqtb| array.
39685
39686 @<Declare \eTeX\ procedures for tr...@>=
39687 @!stat procedure show_sa(@!p:pointer;@!s:str_number);
39688 var t:small_number; {the type of element}
39689 begin begin_diagnostic; print_char("{"); print(s); print_char(" ");
39690 if p=null then print_char("?") {this can't happen}
39691 else begin t:=sa_type(p);
39692 if t<box_val then print_cmd_chr(register,p)
39693 else if t=box_val then
39694 begin print_esc("box"); print_sa_num(p);
39695 end
39696 else if t=tok_val then print_cmd_chr(toks_register,p)
39697 else print_char("?"); {this can't happen either}
39698 print_char("=");
39699 if t=int_val then print_int(sa_int(p))
39700 else if t=dimen_val then
39701 begin print_scaled(sa_dim(p)); print("pt");
39702 end
39703 else begin p:=sa_ptr(p);
39704 if t=glue_val then print_spec(p,"pt")
39705 else if t=mu_val then print_spec(p,"mu")
39706 else if t=box_val then
39707 if p=null then print("void")
39708 else begin depth_threshold:=0; breadth_max:=1; show_node_list(p);
39709 end
39710 else if t=tok_val then
39711 begin if p<>null then show_token_list(link(p),null,32);
39712 end
39713 else print_char("?"); {this can't happen either}
39714 end;
39715 end;
39716 print_char("}"); end_diagnostic(false);
39717 end;
39718 tats
39719
39720 @ Here we compute the pointer to the current mark of type |t| and mark
39721 class |cur_val|.
39722
39723 @<Compute the mark pointer...@>=
39724 begin find_sa_element(mark_val,cur_val,false);
39725 if cur_ptr<>null then
39726 if odd(t) then cur_ptr:=link(cur_ptr+(t div 2)+1)
39727 else cur_ptr:=info(cur_ptr+(t div 2)+1);
39728 end
39729
39730 @ The current marks for all mark classes are maintained by the |vsplit|
39731 and |fire_up| routines and are finally destroyed (for \.{INITEX} only)
39732 @.INITEX@>
39733 by the |final_cleanup| routine. Apart from updating the current marks
39734 when mark nodes are encountered, these routines perform certain actions
39735 on all existing mark classes. The recursive |do_marks| procedure walks
39736 through the whole tree or a subtree of existing mark class nodes and
39737 preforms certain actions indicted by its first parameter |a|, the action
39738 code. The second parameter |l| indicates the level of recursion (at
39739 most four); the third parameter points to a nonempty tree or subtree.
39740 The result is |true| if the complete tree or subtree has been deleted.
39741
39742 @d vsplit_init==0 {action code for |vsplit| initialization}
39743 @d fire_up_init==1 {action code for |fire_up| initialization}
39744 @d fire_up_done==2 {action code for |fire_up| completion}
39745 @d destroy_marks==3 {action code for |final_cleanup|}
39746 @#
39747 @d sa_top_mark(#)==info(#+1) {\.{\\topmarks}|n|}
39748 @d sa_first_mark(#)==link(#+1) {\.{\\firstmarks}|n|}
39749 @d sa_bot_mark(#)==info(#+2) {\.{\\botmarks}|n|}
39750 @d sa_split_first_mark(#)==link(#+2) {\.{\\splitfirstmarks}|n|}
39751 @d sa_split_bot_mark(#)==info(#+3) {\.{\\splitbotmarks}|n|}
39752
39753 @<Declare the function called |do_marks|@>=
39754 function do_marks(@!a,@!l:small_number;@!q:pointer):boolean;
39755 var i:small_number; {a four bit index}
39756 begin if l<4 then {|q| is an index node}
39757 begin for i:=0 to 15 do
39758 begin get_sa_ptr;
39759 if cur_ptr<>null then if do_marks(a,l+1,cur_ptr) then delete_sa_ptr;
39760 end;
39761 if sa_used(q)=0 then
39762 begin free_node(q,index_node_size); q:=null;
39763 end;
39764 end
39765 else {|q| is the node for a mark class}
39766 begin case a of
39767 @<Cases for |do_marks|@>@;
39768 end; {there are no other cases}
39769 if sa_bot_mark(q)=null then if sa_split_bot_mark(q)=null then
39770 begin free_node(q,mark_class_node_size); q:=null;
39771 end;
39772 end;
39773 do_marks:=(q=null);
39774 end;
39775
39776 @ At the start of the |vsplit| routine the existing |split_fist_mark|
39777 and |split_bot_mark| are discarded.
39778
39779 @<Cases for |do_marks|@>=
39780 vsplit_init: if sa_split_first_mark(q)<>null then
39781 begin delete_token_ref(sa_split_first_mark(q)); sa_split_first_mark(q):=null;
39782 delete_token_ref(sa_split_bot_mark(q)); sa_split_bot_mark(q):=null;
39783 end;
39784
39785 @ We use again the fact that |split_first_mark=null| if and only if
39786 |split_bot_mark=null|.
39787
39788 @<Update the current marks for |vsplit|@>=
39789 begin find_sa_element(mark_val,mark_class(p),true);
39790 if sa_split_first_mark(cur_ptr)=null then
39791 begin sa_split_first_mark(cur_ptr):=mark_ptr(p);
39792 add_token_ref(mark_ptr(p));
39793 end
39794 else delete_token_ref(sa_split_bot_mark(cur_ptr));
39795 sa_split_bot_mark(cur_ptr):=mark_ptr(p);
39796 add_token_ref(mark_ptr(p));
39797 end
39798
39799 @ At the start of the |fire_up| routine the old |top_mark| and
39800 |first_mark| are discarded, whereas the old |bot_mark| becomes the new
39801 |top_mark|. An empty new |top_mark| token list is, however, discarded
39802 as well in order that mark class nodes can eventually be released. We
39803 use again the fact that |bot_mark<>null| implies |first_mark<>null|; it
39804 also knows that |bot_mark=null| implies |top_mark=first_mark=null|.
39805
39806 @<Cases for |do_marks|@>=
39807 fire_up_init: if sa_bot_mark(q)<>null then
39808 begin if sa_top_mark(q)<>null then delete_token_ref(sa_top_mark(q));
39809 delete_token_ref(sa_first_mark(q)); sa_first_mark(q):=null;
39810 if link(sa_bot_mark(q))=null then {an empty token list}
39811 begin delete_token_ref(sa_bot_mark(q)); sa_bot_mark(q):=null;
39812 end
39813 else add_token_ref(sa_bot_mark(q));
39814 sa_top_mark(q):=sa_bot_mark(q);
39815 end;
39816
39817 @ @<Cases for |do_marks|@>=
39818 fire_up_done: if (sa_top_mark(q)<>null)and(sa_first_mark(q)=null) then
39819 begin sa_first_mark(q):=sa_top_mark(q); add_token_ref(sa_top_mark(q));
39820 end;
39821
39822 @ @<Update the current marks for |fire_up|@>=
39823 begin find_sa_element(mark_val,mark_class(p),true);
39824 if sa_first_mark(cur_ptr)=null then
39825 begin sa_first_mark(cur_ptr):=mark_ptr(p);
39826 add_token_ref(mark_ptr(p));
39827 end;
39828 if sa_bot_mark(cur_ptr)<>null then delete_token_ref(sa_bot_mark(cur_ptr));
39829 sa_bot_mark(cur_ptr):=mark_ptr(p); add_token_ref(mark_ptr(p));
39830 end
39831
39832 @ Here we use the fact that the five current mark pointers in a mark
39833 class node occupy the same locations as the the first five pointers of
39834 an index node. For systems using a run-time switch to distinguish
39835 between \.{VIRTEX} and \.{INITEX}, the codewords `$|init|\ldots|tini|$'
39836 surrounding the following piece of code should be removed.
39837 @.INITEX@>
39838 @^system dependencies@>
39839
39840 @<Cases for |do_marks|@>=
39841 @!init destroy_marks: for i:=top_mark_code to split_bot_mark_code do
39842 begin get_sa_ptr;
39843 if cur_ptr<>null then
39844 begin delete_token_ref(cur_ptr); put_sa_ptr(null);
39845 end;
39846 end;
39847 tini
39848
39849 @ The command code |register| is used for `\.{\\count}', `\.{\\dimen}',
39850 etc., as well as for references to sparse array elements defined by
39851 `\.{\\countdef}', etc.
39852
39853 @<Cases of |register| for |print_cmd_chr|@>=
39854 begin if (chr_code<mem_bot)or(chr_code>lo_mem_stat_max) then
39855 cmd:=sa_type(chr_code)
39856 else begin cmd:=chr_code-mem_bot; chr_code:=null;
39857 end;
39858 if cmd=int_val then print_esc("count")
39859 else if cmd=dimen_val then print_esc("dimen")
39860 else if cmd=glue_val then print_esc("skip")
39861 else print_esc("muskip");
39862 if chr_code<>null then print_sa_num(chr_code);
39863 end
39864
39865 @ Similarly the command code |toks_register| is used for `\.{\\toks}' as
39866 well as for references to sparse array elements defined by
39867 `\.{\\toksdef}'.
39868
39869 @<Cases of |toks_register| for |print_cmd_chr|@>=
39870 begin print_esc("toks");
39871 if chr_code<>mem_bot then print_sa_num(chr_code);
39872 end
39873
39874 @ When a shorthand definition for an element of one of the sparse arrays
39875 is destroyed, we must reduce the reference count.
39876
39877 @<Cases for |eq_destroy|@>=
39878 toks_register,register:
39879 if (equiv_field(w)<mem_bot)or(equiv_field(w)>lo_mem_stat_max) then
39880 delete_sa_ref(equiv_field(w));
39881
39882 @ The task to maintain (change, save, and restore) register values is
39883 essentially the same when the register is realized as sparse array
39884 element or entry in |eqtb|. The global variable |sa_chain| is the head
39885 of a linked list of entries saved at the topmost level |sa_level|; the
39886 lists for lower levels are kept in special save stack entries.
39887
39888 @<Glob...@>=
39889 @!sa_chain: pointer; {chain of saved sparse array entries}
39890 @!sa_level: quarterword; {group level for |sa_chain|}
39891
39892 @ @<Set init...@>=
39893 sa_chain:=null; sa_level:=level_zero;
39894
39895 @ The individual saved items are kept in pointer or word nodes similar
39896 to those used for the array elements: a word node with value zero is,
39897 however, saved as pointer node with the otherwise impossible |sa_index|
39898 value |tok_val_limit|.
39899
39900 @d sa_loc==sa_ref {location of saved item}
39901
39902 @<Declare \eTeX\ procedures for tr...@>=
39903 procedure sa_save(@!p:pointer); {saves value of |p|}
39904 var q:pointer; {the new save node}
39905 @!i:quarterword; {index field of node}
39906 begin if cur_level<>sa_level then
39907 begin check_full_save_stack; save_type(save_ptr):=restore_sa;
39908 save_level(save_ptr):=sa_level; save_index(save_ptr):=sa_chain;
39909 incr(save_ptr); sa_chain:=null; sa_level:=cur_level;
39910 end;
39911 i:=sa_index(p);
39912 if i<dimen_val_limit then
39913 begin if sa_int(p)=0 then
39914 begin q:=get_node(pointer_node_size); i:=tok_val_limit;
39915 end
39916 else begin q:=get_node(word_node_size); sa_int(q):=sa_int(p);
39917 end;
39918 sa_ptr(q):=null;
39919 end
39920 else begin q:=get_node(pointer_node_size); sa_ptr(q):=sa_ptr(p);
39921 end;
39922 sa_loc(q):=p; sa_index(q):=i; sa_lev(q):=sa_lev(p);
39923 link(q):=sa_chain; sa_chain:=q; add_sa_ref(p);
39924 end;
39925
39926 @ @<Declare \eTeX\ procedures for tr...@>=
39927 procedure sa_destroy(@!p:pointer); {destroy value of |p|}
39928 begin if sa_index(p)<mu_val_limit then delete_glue_ref(sa_ptr(p))
39929 else if sa_ptr(p)<>null then
39930 if sa_index(p)<box_val_limit then flush_node_list(sa_ptr(p))
39931 else delete_token_ref(sa_ptr(p));
39932 end;
39933
39934 @ The procedure |sa_def| assigns a new value to sparse array elements,
39935 and saves the former value if appropriate. This procedure is used only
39936 for skip, muskip, box, and token list registers. The counterpart of
39937 |sa_def| for count and dimen registers is called |sa_w_def|.
39938
39939 @d sa_define(#)==if e then
39940 if global then gsa_def(#)@+else sa_def(#)
39941 else define
39942 @#
39943 @d sa_def_box== {assign |cur_box| to |box(cur_val)|}
39944 begin find_sa_element(box_val,cur_val,true);
39945 if global then gsa_def(cur_ptr,cur_box)@+else sa_def(cur_ptr,cur_box);
39946 end
39947 @#
39948 @d sa_word_define(#)==if e then
39949 if global then gsa_w_def(#)@+else sa_w_def(#)
39950 else word_define(#)
39951
39952 @<Declare \eTeX\ procedures for tr...@>=
39953 procedure sa_def(@!p:pointer;@!e:halfword);
39954 {new data for sparse array elements}
39955 begin add_sa_ref(p);
39956 if sa_ptr(p)=e then
39957 begin @!stat if tracing_assigns>0 then show_sa(p,"reassigning");@+tats@;@/
39958 sa_destroy(p);
39959 end
39960 else begin @!stat if tracing_assigns>0 then show_sa(p,"changing");@+tats@;@/
39961 if sa_lev(p)=cur_level then sa_destroy(p)@+else sa_save(p);
39962 sa_lev(p):=cur_level; sa_ptr(p):=e;
39963 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
39964 end;
39965 delete_sa_ref(p);
39966 end;
39967 @#
39968 procedure sa_w_def(@!p:pointer;@!w:integer);
39969 begin add_sa_ref(p);
39970 if sa_int(p)=w then
39971 begin @!stat if tracing_assigns>0 then show_sa(p,"reassigning");@+tats@;@/
39972 end
39973 else begin @!stat if tracing_assigns>0 then show_sa(p,"changing");@+tats@;@/
39974 if sa_lev(p)<>cur_level then sa_save(p);
39975 sa_lev(p):=cur_level; sa_int(p):=w;
39976 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
39977 end;
39978 delete_sa_ref(p);
39979 end;
39980
39981 @ The |sa_def| and |sa_w_def| routines take care of local definitions.
39982 @^global definitions@>
39983 Global definitions are done in almost the same way, but there is no need
39984 to save old values, and the new value is associated with |level_one|.
39985
39986 @<Declare \eTeX\ procedures for tr...@>=
39987 procedure gsa_def(@!p:pointer;@!e:halfword); {global |sa_def|}
39988 begin add_sa_ref(p);
39989 @!stat if tracing_assigns>0 then show_sa(p,"globally changing");@+tats@;@/
39990 sa_destroy(p); sa_lev(p):=level_one; sa_ptr(p):=e;
39991 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
39992 delete_sa_ref(p);
39993 end;
39994 @#
39995 procedure gsa_w_def(@!p:pointer;@!w:integer); {global |sa_w_def|}
39996 begin add_sa_ref(p);
39997 @!stat if tracing_assigns>0 then show_sa(p,"globally changing");@+tats@;@/
39998 sa_lev(p):=level_one; sa_int(p):=w;
39999 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
40000 delete_sa_ref(p);
40001 end;
40002
40003 @ The |sa_restore| procedure restores the sparse array entries pointed
40004 at by |sa_chain|.
40005
40006 @<Declare \eTeX\ procedures for tr...@>=
40007 procedure sa_restore;
40008 var p:pointer; {sparse array element}
40009 begin repeat p:=sa_loc(sa_chain);
40010 if sa_lev(p)=level_one then
40011 begin if sa_index(p)>=dimen_val_limit then sa_destroy(sa_chain);
40012 @!stat if tracing_restores>0 then show_sa(p,"retaining");@+tats@;@/
40013 end
40014 else begin if sa_index(p)<dimen_val_limit then
40015 if sa_index(sa_chain)<dimen_val_limit then sa_int(p):=sa_int(sa_chain)
40016 else sa_int(p):=0
40017 else begin sa_destroy(p); sa_ptr(p):=sa_ptr(sa_chain);
40018 end;
40019 sa_lev(p):=sa_lev(sa_chain);
40020 @!stat if tracing_restores>0 then show_sa(p,"restoring");@+tats@;@/
40021 end;
40022 delete_sa_ref(p);
40023 p:=sa_chain; sa_chain:=link(p);
40024 if sa_index(p)<dimen_val_limit then free_node(p,word_node_size)
40025 else free_node(p,pointer_node_size);
40026 until sa_chain=null;
40027 end;
40028
40029 @ When the value of |last_line_fit| is positive, the last line of a
40030 (partial) paragraph is treated in a special way and we need additional
40031 fields in the active nodes.
40032
40033 @d active_node_size_extended=5 {number of words in extended active nodes}
40034 @d active_short(#)==mem[#+3].sc {|shortfall| of this line}
40035 @d active_glue(#)==mem[#+4].sc {corresponding glue stretch or shrink}
40036
40037 @<Glob...@>=
40038 @!last_line_fill:pointer; {the |par_fill_skip| glue node of the new paragraph}
40039 @!do_last_line_fit:boolean; {special algorithm for last line of paragraph?}
40040 @!active_node_size:small_number; {number of words in active nodes}
40041 @!fill_width:array[0..2] of scaled; {infinite stretch components of
40042 |par_fill_skip|}
40043 @!best_pl_short:array[very_loose_fit..tight_fit] of scaled; {|shortfall|
40044 corresponding to |minimal_demerits|}
40045 @!best_pl_glue:array[very_loose_fit..tight_fit] of scaled; {corresponding
40046 glue stretch or shrink}
40047
40048 @ The new algorithm for the last line requires that the stretchability of
40049 |par_fill_skip| is infinite and the stretchability of |left_skip| plus
40050 |right_skip| is finite.
40051
40052 @<Check for special...@>=
40053 do_last_line_fit:=false; active_node_size:=active_node_size_normal;
40054 {just in case}
40055 if last_line_fit>0 then
40056 begin q:=glue_ptr(last_line_fill);
40057 if (stretch(q)>0)and(stretch_order(q)>normal) then
40058 if (background[3]=0)and(background[4]=0)and(background[5]=0) then
40059 begin do_last_line_fit:=true;
40060 active_node_size:=active_node_size_extended;
40061 fill_width[0]:=0; fill_width[1]:=0; fill_width[2]:=0;
40062 fill_width[stretch_order(q)-1]:=stretch(q);
40063 end;
40064 end
40065
40066 @ @<Other local variables for |try_break|@>=
40067 @!g:scaled; {glue stretch or shrink of test line, adjustment for last line}
40068
40069 @ Here we initialize the additional fields of the first active node
40070 representing the beginning of the paragraph.
40071
40072 @<Initialize additional fields of the first active node@>=
40073 begin active_short(q):=0; active_glue(q):=0;
40074 end
40075
40076 @ Here we compute the adjustment |g| and badness |b| for a line from |r|
40077 to the end of the paragraph. When any of the criteria for adjustment is
40078 violated we fall through to the normal algorithm.
40079
40080 The last line must be too short, and have infinite stretch entirely due
40081 to |par_fill_skip|.
40082
40083 @<Perform computations for last line and |goto found|@>=
40084 begin if (active_short(r)=0)or(active_glue(r)<=0) then goto not_found;
40085 {previous line was neither stretched nor shrunk, or was infinitely bad}
40086 if (cur_active_width[3]<>fill_width[0])or@|
40087 (cur_active_width[4]<>fill_width[1])or@|
40088 (cur_active_width[5]<>fill_width[2]) then goto not_found;
40089 {infinite stretch of this line not entirely due to |par_fill_skip|}
40090 if active_short(r)>0 then g:=cur_active_width[2]
40091 else g:=cur_active_width[6];
40092 if g<=0 then goto not_found; {no finite stretch resp.\ no shrink}
40093 arith_error:=false; g:=fract(g,active_short(r),active_glue(r),max_dimen);
40094 if last_line_fit<1000 then g:=fract(g,last_line_fit,1000,max_dimen);
40095 if arith_error then
40096 if active_short(r)>0 then g:=max_dimen@+else g:=-max_dimen;
40097 if g>0 then
40098 @<Set the value of |b| to the badness of the last line for stretching,
40099 compute the corresponding |fit_class|, and |goto found|@>
40100 else if g<0 then
40101 @<Set the value of |b| to the badness of the last line for shrinking,
40102 compute the corresponding |fit_class|, and |goto found|@>;
40103 not_found:end
40104
40105 @ These badness computations are rather similar to those of the standard
40106 algorithm, with the adjustment amount |g| replacing the |shortfall|.
40107
40108 @<Set the value of |b| to the badness of the last line for str...@>=
40109 begin if g>shortfall then g:=shortfall;
40110 if g>7230584 then if cur_active_width[2]<1663497 then
40111 begin b:=inf_bad; fit_class:=very_loose_fit; goto found;
40112 end;
40113 b:=badness(g,cur_active_width[2]);
40114 if b>12 then
40115 if b>99 then fit_class:=very_loose_fit
40116 else fit_class:=loose_fit
40117 else fit_class:=decent_fit;
40118 goto found;
40119 end
40120
40121 @ @<Set the value of |b| to the badness of the last line for shr...@>=
40122 begin if -g>cur_active_width[6] then g:=-cur_active_width[6];
40123 b:=badness(-g,cur_active_width[6]);
40124 if b>12 then fit_class:=tight_fit@+else fit_class:=decent_fit;
40125 goto found;
40126 end
40127
40128 @ Vanishing values of |shortfall| and |g| indicate that the last line is
40129 not adjusted.
40130
40131 @<Adjust \(t)the additional data for last line@>=
40132 begin if cur_p=null then shortfall:=0;
40133 if shortfall>0 then g:=cur_active_width[2]
40134 else if shortfall<0 then g:=cur_active_width[6]
40135 else g:=0;
40136 end
40137
40138 @ For each feasible break we record the shortfall and glue stretch or
40139 shrink (or adjustment).
40140
40141 @<Store \(a)additional data for this feasible break@>=
40142 begin best_pl_short[fit_class]:=shortfall; best_pl_glue[fit_class]:=g;
40143 end
40144
40145 @ Here we save these data in the active node representing a potential
40146 line break.
40147
40148 @<Store \(a)additional data in the new active node@>=
40149 begin active_short(q):=best_pl_short[fit_class];
40150 active_glue(q):=best_pl_glue[fit_class];
40151 end
40152
40153 @ @<Print additional data in the new active node@>=
40154 begin print(" s="); print_scaled(active_short(q));
40155 if cur_p=null then print(" a=")@+else print(" g=");
40156 print_scaled(active_glue(q));
40157 end
40158
40159 @ Here we either reset |do_last_line_fit| or adjust the |par_fill_skip|
40160 glue.
40161
40162 @<Adjust \(t)the final line of the paragraph@>=
40163 if active_short(best_bet)=0 then do_last_line_fit:=false
40164 else begin q:=new_spec(glue_ptr(last_line_fill));
40165 delete_glue_ref(glue_ptr(last_line_fill));
40166 width(q):=width(q)+active_short(best_bet)-active_glue(best_bet);
40167 stretch(q):=0; glue_ptr(last_line_fill):=q;
40168 end
40169
40170 @ When reading \.{\\patterns} while \.{\\savinghyphcodes} is positive
40171 the current |lc_code| values are stored together with the hyphenation
40172 patterns for the current language. They will later be used instead of
40173 the |lc_code| values for hyphenation purposes.
40174
40175 The |lc_code| values are stored in the linked trie analogous to patterns
40176 $p_1$ of length~1, with |hyph_root=trie_r[0]| replacing |trie_root| and
40177 |lc_code(p_1)| replacing the |trie_op| code. This allows to compress
40178 and pack them together with the patterns with minimal changes to the
40179 existing code.
40180
40181 @d hyph_root==trie_r[0] {root of the linked trie for |hyph_codes|}
40182
40183 @<Initialize table entries...@>=
40184 hyph_root:=0; hyph_start:=0;
40185
40186 @ @<Store hyphenation codes for current language@>=
40187 begin c:=cur_lang; first_child:=false; p:=0;
40188 repeat q:=p; p:=trie_r[q];
40189 until (p=0)or(c<=so(trie_c[p]));
40190 if (p=0)or(c<so(trie_c[p])) then
40191 @<Insert a new trie node between |q| and |p|, and
40192 make |p| point to it@>;
40193 q:=p; {now node |q| represents |cur_lang|}
40194 @<Store all current |lc_code| values@>;
40195 end
40196
40197 @ We store all nonzero |lc_code| values, overwriting any previously
40198 stored values (and possibly wasting a few trie nodes that were used
40199 previously and are not needed now). We always store at least one
40200 |lc_code| value such that |hyph_index| (defined below) will not be zero.
40201
40202 @<Store all current |lc_code| values@>=
40203 p:=trie_l[q]; first_child:=true;
40204 for c:=0 to 255 do
40205 if (lc_code(c)>0)or((c=255)and first_child) then
40206 begin if p=0 then
40207 @<Insert a new trie node between |q| and |p|, and
40208 make |p| point to it@>
40209 else trie_c[p]:=si(c);
40210 trie_o[p]:=qi(lc_code(c));
40211 q:=p; p:=trie_r[q]; first_child:=false;
40212 end;
40213 if first_child then trie_l[q]:=0@+else trie_r[q]:=0
40214
40215 @ We must avoid to ``take'' location~1, in order to distinguish between
40216 |lc_code| values and patterns.
40217
40218 @<Pack all stored |hyph_codes|@>=
40219 begin if trie_root=0 then for p:=0 to 255 do trie_min[p]:=p+2;
40220 first_fit(hyph_root); trie_pack(hyph_root);
40221 hyph_start:=trie_ref[hyph_root];
40222 end
40223
40224 @ The global variable |hyph_index| will point to the hyphenation codes
40225 for the current language.
40226
40227 @d set_hyph_index== {set |hyph_index| for current language}
40228 if trie_char(hyph_start+cur_lang)<>qi(cur_lang)
40229 then hyph_index:=0 {no hyphenation codes for |cur_lang|}
40230 else hyph_index:=trie_link(hyph_start+cur_lang)
40231 @#
40232 @d set_lc_code(#)== {set |hc[0]| to hyphenation or lc code for |#|}
40233 if hyph_index=0 then hc[0]:=lc_code(#)
40234 else if trie_char(hyph_index+#)<>qi(#) then hc[0]:=0
40235 else hc[0]:=qo(trie_op(hyph_index+#))
40236
40237 @<Glob...@>=
40238 @!hyph_start:trie_pointer; {root of the packed trie for |hyph_codes|}
40239 @!hyph_index:trie_pointer; {pointer to hyphenation codes for |cur_lang|}
40240
40241 @ When |saving_vdiscards| is positive then the glue, kern, and penalty
40242 nodes removed by the page builder or by \.{\\vsplit} from the top of a
40243 vertical list are saved in special lists instead of being discarded.
40244
40245 @d tail_page_disc==disc_ptr[copy_code] {last item removed by page builder}
40246 @d page_disc==disc_ptr[last_box_code] {first item removed by page builder}
40247 @d split_disc==disc_ptr[vsplit_code] {first item removed by \.{\\vsplit}}
40248
40249 @<Glob...@>=
40250 @!disc_ptr:array[copy_code..vsplit_code] of pointer; {list pointers}
40251
40252 @ @<Set init...@>=
40253 page_disc:=null; split_disc:=null;
40254
40255 @ The \.{\\pagediscards} and \.{\\splitdiscards} commands share the
40256 command code |un_vbox| with \.{\\unvbox} and \.{\\unvcopy}, they are
40257 distinguished by their |chr_code| values |last_box_code| and
40258 |vsplit_code|. These |chr_code| values are larger than |box_code| and
40259 |copy_code|.
40260
40261 @<Generate all \eTeX...@>=
40262 primitive("pagediscards",un_vbox,last_box_code);@/
40263 @!@:page_discards_}{\.{\\pagediscards} primitive@>
40264 primitive("splitdiscards",un_vbox,vsplit_code);@/
40265 @!@:split_discards_}{\.{\\splitdiscards} primitive@>
40266
40267 @ @<Cases of |un_vbox| for |print_cmd_chr|@>=
40268 else if chr_code=last_box_code then print_esc("pagediscards")
40269 else if chr_code=vsplit_code then print_esc("splitdiscards")
40270
40271 @ @<Handle saved items and |goto done|@>=
40272 begin link(tail):=disc_ptr[cur_chr]; disc_ptr[cur_chr]:=null;
40273 goto done;
40274 end
40275
40276 @ The \.{\\interlinepenalties}, \.{\\clubpenalties}, \.{\\widowpenalties},
40277 and \.{\\displaywidowpenalties} commands allow to define arrays of
40278 penalty values to be used instead of the corresponding single values.
40279
40280 @d inter_line_penalties_ptr==equiv(inter_line_penalties_loc)
40281 @d club_penalties_ptr==equiv(club_penalties_loc)
40282 @d widow_penalties_ptr==equiv(widow_penalties_loc)
40283 @d display_widow_penalties_ptr==equiv(display_widow_penalties_loc)
40284
40285 @<Generate all \eTeX...@>=
40286 primitive("interlinepenalties",set_shape,inter_line_penalties_loc);@/
40287 @!@:inter_line_penalties_}{\.{\\interlinepenalties} primitive@>
40288 primitive("clubpenalties",set_shape,club_penalties_loc);@/
40289 @!@:club_penalties_}{\.{\\clubpenalties} primitive@>
40290 primitive("widowpenalties",set_shape,widow_penalties_loc);@/
40291 @!@:widow_penalties_}{\.{\\widowpenalties} primitive@>
40292 primitive("displaywidowpenalties",set_shape,display_widow_penalties_loc);@/
40293 @!@:display_widow_penalties_}{\.{\\displaywidowpenalties} primitive@>
40294
40295 @ @<Cases of |set_shape| for |print_cmd_chr|@>=
40296 inter_line_penalties_loc: print_esc("interlinepenalties");
40297 club_penalties_loc: print_esc("clubpenalties");
40298 widow_penalties_loc: print_esc("widowpenalties");
40299 display_widow_penalties_loc: print_esc("displaywidowpenalties");
40300
40301 @ @<Fetch a penalties array element@>=
40302 begin scan_int;
40303 if (equiv(m)=null)or(cur_val<0) then cur_val:=0
40304 else begin if cur_val>penalty(equiv(m)) then cur_val:=penalty(equiv(m));
40305 cur_val:=penalty(equiv(m)+cur_val);
40306 end;
40307 end
40308
40309 @* \[54] System-dependent changes.
40310 This section should be replaced, if necessary, by any special
40311 modifications of the program
40312 that are necessary to make \TeX\ work at a particular installation.
40313 It is usually best to design your change file so that all changes to
40314 previous sections preserve the section numbering; then everybody's version
40315 will be consistent with the published program. More extensive changes,
40316 which introduce new sections, can be inserted here; then only the index
40317 itself will get a new section number.
40318 @^system dependencies@>
40319
40320 @* \[55] Index.
40321 Here is where you can find all uses of each identifier in the program,
40322 with underlined entries pointing to where the identifier was defined.
40323 If the identifier is only one letter long, however, you get to see only
40324 the underlined entries. {\sl All references are to section numbers instead of
40325 page numbers.}
40326
40327 This index also lists error messages and other aspects of the program
40328 that you might want to look up some day. For example, the entry
40329 for ``system dependencies'' lists all sections that should receive
40330 special attention from people who are installing \TeX\ in a new
40331 operating environment. A list of various things that can't happen appears
40332 under ``this can't happen''. Approximately 40 sections are listed under
40333 ``inner loop''; these account for about 60\pct! of \TeX's running time,
40334 exclusive of input and output.