Debian Codegraph @

texk/web2c/xetexdir/xetex.web

raw
1 % Copyright (c) 2009-2026 by Jonathan Kew
2 % Copyright (c) 1994-2008 by SIL International
3 % Copyright (c) 2010-2012 by Han The Thanh
4 % Copyright (c) 2012-2013 by Khaled Hosny
5
6 % SIL Author(s): Jonathan Kew
7
8 % Part of the XeTeX typesetting system
9
10 % Permission is hereby granted, free of charge, to any person obtaining a copy
11 % of this software and associated documentation files (the "Software"), to deal
12 % in the Software without restriction, including without limitation the rights
13 % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14 % copies of the Software, and to permit persons to whom the Software is
15 % furnished to do so, subject to the following conditions:
16
17 % The above copyright notice and this permission notice shall be included in all
18 % copies or substantial portions of the Software.
19
20 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21 % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22 % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23 % COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
24 % IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
25 % CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26
27 % Except as contained in this notice, the name of the copyright holders shall
28 % not be used in advertising or otherwise to promote the sale, use or other
29 % dealings in this Software without prior written authorization from the
30 % copyright holders.
31
32 % e-TeX is copyright (C) 1999-2012 by P. Breitenlohner (1994,98 by the NTS
33 % team); all rights are reserved. Copying of this file is authorized only if
34 % (1) you are P. Breitenlohner, or if (2) you make absolutely no changes to
35 % your copy. (Programs such as TIE allow the application of several change
36 % files to tex.web; the master files tex.web and etex.ch should stay intact.)
37
38 % See etex_gen.tex for hints on how to install this program.
39 % And see etripman.tex for details about how to validate it.
40
41 % e-TeX and NTS are trademarks of the NTS group.
42 % TeX is a trademark of the American Mathematical Society.
43 % METAFONT is a trademark of Addison-Wesley Publishing Company.
44
45 % This program is directly derived from Donald E. Knuth's TeX;
46 % the change history which follows and the reward offered for finders of
47 % bugs refer specifically to TeX; they should not be taken as referring
48 % to e-TeX, although the change history is relevant in that it
49 % demonstrates the evolutionary path followed. This program is not TeX;
50 % that name is reserved strictly for the program which is the creation
51 % and sole responsibility of Professor Knuth.
52
53 % Version 0 was released in September 1982 after it passed a variety of tests.
54 % Version 1 was released in November 1983 after thorough testing.
55 % Version 1.1 fixed ``disappearing font identifiers'' et alia (July 1984).
56 % Version 1.2 allowed `0' in response to an error, et alia (October 1984).
57 % Version 1.3 made memory allocation more flexible and local (November 1984).
58 % Version 1.4 fixed accents right after line breaks, et alia (April 1985).
59 % Version 1.5 fixed \the\toks after other expansion in \edefs (August 1985).
60 % Version 2.0 (almost identical to 1.5) corresponds to "Volume B" (April 1986).
61 % Version 2.1 corrected anomalies in discretionary breaks (January 1987).
62 % Version 2.2 corrected "(Please type...)" with null \endlinechar (April 1987).
63 % Version 2.3 avoided incomplete page in premature termination (August 1987).
64 % Version 2.4 fixed \noaligned rules in indented displays (August 1987).
65 % Version 2.5 saved cur_order when expanding tokens (September 1987).
66 % Version 2.6 added 10sp slop when shipping leaders (November 1987).
67 % Version 2.7 improved rounding of negative-width characters (November 1987).
68 % Version 2.8 fixed weird bug if no \patterns are used (December 1987).
69 % Version 2.9 made \csname\endcsname's "relax" local (December 1987).
70 % Version 2.91 fixed \outer\def\a0{}\a\a bug (April 1988).
71 % Version 2.92 fixed \patterns, also file names with complex macros (May 1988).
72 % Version 2.93 fixed negative halving in allocator when mem_min<0 (June 1988).
73 % Version 2.94 kept open_log_file from calling fatal_error (November 1988).
74 % Version 2.95 solved that problem a better way (December 1988).
75 % Version 2.96 corrected bug in "Infinite shrinkage" recovery (January 1989).
76 % Version 2.97 corrected blunder in creating 2.95 (February 1989).
77 % Version 2.98 omitted save_for_after at outer level (March 1989).
78 % Version 2.99 caught $$\begingroup\halign..$$ (June 1989).
79 % Version 2.991 caught .5\ifdim.6... (June 1989).
80 % Version 2.992 introduced major changes for 8-bit extensions (September 1989).
81 % Version 2.993 fixed a save_stack synchronization bug et alia (December 1989).
82 % Version 3.0 fixed unusual displays; was more \output robust (March 1990).
83 % Version 3.1 fixed nullfont, disabled \write{\the\prevgraf} (September 1990).
84 % Version 3.14 fixed unprintable font names and corrected typos (March 1991).
85 % Version 3.141 more of same; reconstituted ligatures better (March 1992).
86 % Version 3.1415 preserved nonexplicit kerns, tidied up (February 1993).
87 % Version 3.14159 allowed fontmemsize to change; bulletproofing (March 1995).
88 % Version 3.141592 fixed \xleaders, glueset, weird alignments (December 2002).
89 % Version 3.1415926 was a general cleanup with minor fixes (February 2008).
90 % Version 3.14159265 was similar (January 2014).
91 % Version 3.141592653 was similar but more extensive (January 2021).
92
93 % A reward of $327.68 will be paid to the first finder of any remaining bug.
94
95 % A preliminary version of TeX--XeT was released in April 1992.
96 % TeX--XeT version 1.0 was released in June 1992,
97 % version 1.1 prevented arith overflow in glue computation (Oct 1992).
98 % A preliminary e-TeX version 0.95 was operational in March 1994.
99 % Version 1.0beta was released in May 1995.
100 % Version 1.01beta fixed bugs in just_copy and every_eof (December 1995).
101 % Version 1.02beta allowed 256 mark classes (March 1996).
102 % Version 1.1 changed \group{type,level} -> \currentgroup{type,level},
103 % first public release (October 1996).
104 % Version 2.0 development was started in March 1997;
105 % fixed a ligature-\beginR bug in January 1998;
106 % was released in March 1998.
107 % Version 2.1 fixed a \marks bug (when min_halfword<>0) (January 1999).
108 % Version 2.2 development was started in Feb 2003; released in Oct 2004.
109 % fixed a bug in sparse array handling (0=>null), Jun 2002;
110 % fixed a bug in \lastnodetype (cur_val=>cur_val_level)
111 % reported by Hartmut Henkel <hartmut_henkel@@gmx.de>,
112 % fix by Fabrice Popineau <Fabrice.Popineau@@supelec.fr>,
113 % Jan 2004;
114 % another bug in sparse array handling (cur_ptr=>cur_chr)
115 % reported by Taco Hoekwater <taco@@elvenkind.com>, Jul 2004;
116 % fixed a sparse array reference count bug (\let,\futurelet),
117 % fix by Bernd Raichle <berd@@dante.de>, Aug 2004;
118 % reorganized handling of banner, additional token list and
119 % integer parameters, and similar in order to reduce the
120 % interference between eTeX, pdfTeX, and web2c change files.
121 % adapted to tex.web 3.141592, revised glue rounding for mixed
122 % direction typesetting;
123 % fixed a bug in the revised glue rounding code, detected by
124 % Tigran Aivazian <tigran@@aivazian.fsnet.co.uk>, Oct 2004.
125 % Version 2.3 development was started in Feb 2008; released in Apr 2011.
126 % fixed a bug in hyph_code handling (\savinghyphcodes)
127 % reported by Vladimir Volovich <vvv@@vsu.ru>, Feb 2008.
128 % fixed the error messages for improper use of \protected,
129 % reported by Heiko Oberdiek
130 % <heiko.oberdiek@@googlemail.com>, May 2010.
131 % some rearrangements to reduce interferences between
132 % e-TeX and pTeX, in part suggested by Hironori Kitagawa
133 % <h_kitagawa2001@@yahoo.co.jp>, Mar 2011.
134 % Version 2.4 fixed an uninitialized line number bug, released in May 2012.
135 % Version 2.5 development was started in Aug 2012; released in Feb 2013.
136 % better tracing of font definitions, reported by
137 % Bruno Le Floch <blflatex@@gmail.com>, Jul 2012.
138 % Version 2.6 development was started in Mar 2013; released in ??? 201?.
139 % enable hyphenation of text between \beginL and \endL or
140 % between \beginR and \endR, problem reported by
141 % Vafa Khalighi <vafalgk@@gmail.com>, Nov 2013.
142 % better handling of right-to-left text -- to be done.
143
144 % Although considerable effort has been expended to make the e-TeX program
145 % correct and reliable, no warranty is implied; the author disclaims any
146 % obligation or liability for damages, including but not limited to
147 % special, indirect, or consequential damages arising out of or in
148 % connection with the use or performance of this software. This work has
149 % been a ``labor of love'' and the author hopes that users enjoy it.
150
151 % Here is TeX material that gets inserted after \input webmac
152 \input xewebmac
153 \def\hang{\hangindent 3em\noindent\ignorespaces}
154 \def\hangg#1 {\hang\hbox{#1 }}
155 \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
156 \font\ninerm=cmr9
157 \let\mc=\ninerm % medium caps for names like SAIL
158
159 \def\mirror#1{%
160 \phantom{#1}%
161 \rlap{\special{pdf:btrans xscale -1}#1\special{pdf:etrans}}%
162 }
163 \def\XeTeX{X\kern-.125em\lower.5ex\hbox{\mirror{E}}\kern-.1667em\TeX}
164
165 \def\eTeX{$\varepsilon$-\TeX}
166 \font\revrm=xbmc10 % for right-to-left text
167 % to generate xbmc10 (i.e., reflected cmbx10) use a file
168 % xbmc10.mf containing:
169 %+++++++++++++++++++++++++++++++++++++++++++++++++
170 % if unknown cmbase: input cmbase fi
171 % extra_endchar := extra_endchar &
172 % "currentpicture:=currentpicture " &
173 % "reflectedabout((.5[l,r],0),(.5[l,r],1));";
174 % input cmbx10
175 %+++++++++++++++++++++++++++++++++++++++++++++++++
176 \TeXXeTstate=1
177 \def\XeT{X\kern-.125em\lower.424ex\hbox{E}\kern-.1667emT}
178 \def\TeXXeT{\TeX-{}-\XeT} % for TeX--XeT
179 \def\TeXeT{\TeX-{\revrm\beginR\TeX\endR}} % for TeX-XeT
180 \def\PASCAL{Pascal}
181 \def\ph{\hbox{Pascal-H}}
182 \def\pct!{{\char`\%}} % percent sign in ordinary text
183 \def\grp{\.{\char'173...\char'175}}
184 \font\logo=logo10 % font used for the METAFONT logo
185 \def\MF{{\logo META}\-{\logo FONT}}
186 \def\<#1>{$\langle#1\rangle$}
187 \def\section{\mathhexbox278}
188
189 \def\(#1){} % this is used to make section names sort themselves better
190 \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
191
192 \outer\def\N#1. \[#2]#3.{\MN#1.\vfil\eject % begin starred section
193 \def\rhead{PART #2:\uppercase{#3}} % define running headline
194 \message{*\modno} % progress report
195 \edef\next{\write\cont{\Z{\?#2]#3}{\modno}{\the\pageno}}}\next
196 \ifon\startsection{\bf\ignorespaces#3.\quad}\ignorespaces}
197 \let\?=\relax % we want to be able to \write a \?
198
199 \def\title{\XeTeX}
200 % system dependent redefinitions of \title should come later
201 % and should use:
202 % \toks0=\expandafter{\title}
203 % \edef\title{...\the\toks0...}
204 \def\topofcontents{\hsize 5.5in
205 \vglue 0pt plus 1fil minus 1.5in
206 \def\?##1]{\hbox to 1in{\hfil##1.\ }}
207 }
208 \def\botofcontents{\vskip 0pt plus 1fil minus 1.5in}
209 \pageno=3
210 \def\glob{13} % this should be the section number of "<Global...>"
211 \def\gglob{20, 26} % this should be the next two sections of "<Global...>"
212
213 @* \[1] Introduction.
214 This is \XeTeX, a program derived from and extending the capabilities of
215 \TeX, a document compiler intended to produce typesetting of high
216 quality.
217 The \PASCAL\ program that follows is the definition of \TeX82, a standard
218 @:PASCAL}{\PASCAL@>
219 @!@:TeX82}{\TeX82@>
220 version of \TeX\ that is designed to be highly portable so that identical output
221 will be obtainable on a great variety of computers.
222
223 The main purpose of the following program is to explain the algorithms of \TeX\
224 as clearly as possible. As a result, the program will not necessarily be very
225 efficient when a particular \PASCAL\ compiler has translated it into a
226 particular machine language. However, the program has been written so that it
227 can be tuned to run efficiently in a wide variety of operating environments
228 by making comparatively few changes. Such flexibility is possible because
229 the documentation that follows is written in the \.{WEB} language, which is
230 at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
231 to \PASCAL\ is able to introduce most of the necessary refinements.
232 Semi-automatic translation to other languages is also feasible, because the
233 program below does not make extensive use of features that are peculiar to
234 \PASCAL.
235
236 A large piece of software like \TeX\ has inherent complexity that cannot
237 be reduced below a certain level of difficulty, although each individual
238 part is fairly simple by itself. The \.{WEB} language is intended to make
239 the algorithms as readable as possible, by reflecting the way the
240 individual program pieces fit together and by providing the
241 cross-references that connect different parts. Detailed comments about
242 what is going on, and about why things were done in certain ways, have
243 been liberally sprinkled throughout the program. These comments explain
244 features of the implementation, but they rarely attempt to explain the
245 \TeX\ language itself, since the reader is supposed to be familiar with
246 {\sl The \TeX book}.
247 @.WEB@>
248 @:TeXbook}{\sl The \TeX book@>
249
250 @ The present implementation has a long ancestry, beginning in the summer
251 of~1977, when Michael~F. Plass and Frank~M. Liang designed and coded
252 a prototype
253 @^Plass, Michael Frederick@>
254 @^Liang, Franklin Mark@>
255 @^Knuth, Donald Ervin@>
256 based on some specifications that the author had made in May of that year.
257 This original proto\TeX\ included macro definitions and elementary
258 manipulations on boxes and glue, but it did not have line-breaking,
259 page-breaking, mathematical formulas, alignment routines, error recovery,
260 or the present semantic nest; furthermore,
261 it used character lists instead of token lists, so that a control sequence
262 like \.{\\halign} was represented by a list of seven characters. A
263 complete version of \TeX\ was designed and coded by the author in late
264 1977 and early 1978; that program, like its prototype, was written in the
265 {\mc SAIL} language, for which an excellent debugging system was
266 available. Preliminary plans to convert the {\mc SAIL} code into a form
267 somewhat like the present ``web'' were developed by Luis Trabb~Pardo and
268 @^Trabb Pardo, Luis Isidoro@>
269 the author at the beginning of 1979, and a complete implementation was
270 created by Ignacio~A. Zabala in 1979 and 1980. The \TeX82 program, which
271 @^Zabala Salelles, Ignacio Andr\'es@>
272 was written by the author during the latter part of 1981 and the early
273 part of 1982, also incorporates ideas from the 1979 implementation of
274 @^Guibas, Leonidas Ioannis@>
275 @^Sedgewick, Robert@>
276 @^Wyatt, Douglas Kirk@>
277 \TeX\ in {\mc MESA} that was written by Leonidas Guibas, Robert Sedgewick,
278 and Douglas Wyatt at the Xerox Palo Alto Research Center. Several hundred
279 refinements were introduced into \TeX82 based on the experiences gained with
280 the original implementations, so that essentially every part of the system
281 has been substantially improved. After the appearance of ``Version 0'' in
282 September 1982, this program benefited greatly from the comments of
283 many other people, notably David~R. Fuchs and Howard~W. Trickey.
284 A final revision in September 1989 extended the input character set to
285 eight-bit codes and introduced the ability to hyphenate words from
286 different languages, based on some ideas of Michael~J. Ferguson.
287 @^Fuchs, David Raymond@>
288 @^Trickey, Howard Wellington@>
289 @^Ferguson, Michael John@>
290
291 No doubt there still is plenty of room for improvement, but the author
292 is firmly committed to keeping \TeX82 ``frozen'' from now on; stability
293 and reliability are to be its main virtues.
294
295 On the other hand, the \.{WEB} description can be extended without changing
296 the core of \TeX82 itself, and the program has been designed so that such
297 extensions are not extremely difficult to make.
298 The |banner| string defined here should be changed whenever \TeX\
299 undergoes any modifications, so that it will be clear which version of
300 \TeX\ might be the guilty party when a problem arises.
301 @^extensions to \TeX@>
302 @^system dependencies@>
303
304 This program contains code for various features extending \TeX,
305 therefore this program is called `\XeTeX' and not
306 `\TeX'; the official name `\TeX' by itself is reserved
307 for software systems that are fully compatible with each other.
308 A special test suite called the ``\.{TRIP} test'' is available for
309 helping to determine whether a particular implementation deserves to be
310 known as `\TeX' [cf.~Stanford Computer Science report CS1027,
311 November 1984].
312
313 A similar test suite called the ``\.{e-TRIP} test'' is available for
314 helping to determine whether a particular implementation deserves to be
315 known as `\eTeX'.
316
317 @d eTeX_version=2 { \.{\\eTeXversion} }
318 @d eTeX_revision==".6" { \.{\\eTeXrevision} }
319 @d eTeX_version_string=='-2.6' {current \eTeX\ version}
320 @#
321 @d XeTeX_version=0 { \.{\\XeTeXversion} }
322 @d XeTeX_revision==".999998" { \.{\\XeTeXrevision} }
323 @d XeTeX_version_string=='-0.999998' {current \XeTeX\ version}
324 @#
325 @d XeTeX_banner=='This is XeTeX, Version 3.141592653',eTeX_version_string,XeTeX_version_string
326 {printed when \XeTeX\ starts}
327 @#
328 @d banner=='This is TeX, Version 3.141592653' {printed when \TeX\ starts}
329 @#
330 @d TEX==XETEX {change program name into |XETEX|}
331 @#
332 @d TeXXeT_code=0 {the \TeXXeT\ feature is optional}
333 @#
334 @d XeTeX_dash_break_code=1 {non-zero to enable breaks after en- and em-dashes}
335 @#
336 @d XeTeX_upwards_code=2 {non-zero if the main vertical list is being built upwards}
337 @d XeTeX_use_glyph_metrics_code=3 {non-zero to use exact glyph height/depth}
338 @d XeTeX_inter_char_tokens_code=4 {non-zero to enable \.{\\XeTeXinterchartokens} insertion}
339 @#
340 @d XeTeX_input_normalization_code=5 {normalization mode:, 1 for NFC, 2 for NFD, else none}
341 @#
342 @d XeTeX_default_input_mode_code=6 {input mode for newly opened files}
343 @d XeTeX_input_mode_auto=0
344 @d XeTeX_input_mode_utf8=1
345 @d XeTeX_input_mode_utf16be=2
346 @d XeTeX_input_mode_utf16le=3
347 @d XeTeX_input_mode_raw=4
348 @d XeTeX_input_mode_icu_mapping=5
349 @#
350 @d XeTeX_default_input_encoding_code=7 {|str_number| of encoding name if |mode =| ICU}
351 @#
352 @d XeTeX_tracing_fonts_code=8 {non-zero to log native fonts used}
353 @d XeTeX_interword_space_shaping_code=9 { controls shaping of space chars in context when using native fonts;
354 set to 1 for contextual adjustment of space width only,
355 and 2 for full cross-space shaping (e.g. multi-word ligatures) }
356 @d XeTeX_generate_actual_text_code=10 { controls output of /ActualText for native-word nodes }
357 @d XeTeX_hyphenatable_length_code=11 { sets maximum hyphenatable word length }
358 @d eTeX_states=12 {number of \eTeX\ state variables in |eqtb|}
359
360 @ Different \PASCAL s have slightly different conventions, and the present
361 @!@:PASCAL H}{\ph@>
362 program expresses \TeX\ in terms of the \PASCAL\ that was
363 available to the author in 1982. Constructions that apply to
364 this particular compiler, which we shall call \ph, should help the
365 reader see how to make an appropriate interface for other systems
366 if necessary. (\ph\ is Charles Hedrick's modification of a compiler
367 @^Hedrick, Charles Locke@>
368 for the DECsystem-10 that was originally developed at the University of
369 Hamburg; cf.\ {\sl Software---Practice and Experience \bf6} (1976),
370 29--42. The \TeX\ program below is intended to be adaptable, without
371 extensive changes, to most other versions of \PASCAL, so it does not fully
372 use the admirable features of \ph. Indeed, a conscious effort has been
373 made here to avoid using several idiosyncratic features of standard
374 \PASCAL\ itself, so that most of the code can be translated mechanically
375 into other high-level languages. For example, the `\&{with}' and `\\{new}'
376 features are not used, nor are pointer types, set types, or enumerated
377 scalar types; there are no `\&{var}' parameters, except in the case of files
378 --- \eTeX, however, does use `\&{var}' parameters for the |reverse| function;
379 there are no tag fields on variant records; there are no assignments
380 |real:=integer|; no procedures are declared local to other procedures.)
381
382 The portions of this program that involve system-dependent code, where
383 changes might be necessary because of differences between \PASCAL\ compilers
384 and/or differences between
385 operating systems, can be identified by looking at the sections whose
386 numbers are listed under `system dependencies' in the index. Furthermore,
387 the index entries for `dirty \PASCAL' list all places where the restrictions
388 of \PASCAL\ have not been followed perfectly, for one reason or another.
389 @!@^system dependencies@>
390 @!@^dirty \PASCAL@>
391
392 Incidentally, \PASCAL's standard |round| function can be problematical,
393 because it disagrees with the IEEE floating-point standard.
394 Many implementors have
395 therefore chosen to substitute their own home-grown rounding procedure.
396
397 @ The program begins with a normal \PASCAL\ program heading, whose
398 components will be filled in later, using the conventions of \.{WEB}.
399 @.WEB@>
400 For example, the portion of the program called `\X\glob:Global
401 variables\X' below will be replaced by a sequence of variable declarations
402 that starts in $\section\glob$ of this documentation. In this way, we are able
403 to define each individual global variable when we are prepared to
404 understand what it means; we do not have to define all of the globals at
405 once. Cross references in $\section\glob$, where it says ``See also
406 sections \gglob, \dots,'' also make it possible to look at the set of
407 all global variables, if desired. Similar remarks apply to the other
408 portions of the program heading.
409
410 Actually the heading shown here is not quite normal: The |program| line
411 does not mention any |output| file, because \ph\ would ask the \TeX\ user
412 to specify a file name if |output| were specified here.
413 @:PASCAL H}{\ph@>
414 @^system dependencies@>
415
416 @d mtype==t@&y@&p@&e {this is a \.{WEB} coding trick:}
417 @f mtype==type {`\&{mtype}' will be equivalent to `\&{type}'}
418 @f type==true {but `|type|' will not be treated as a reserved word}
419
420 @p @t\4@>@<Compiler directives@>@/
421 program TEX; {all file names are defined dynamically}
422 label @<Labels in the outer block@>@/
423 const @<Constants in the outer block@>@/
424 mtype @<Types in the outer block@>@/
425 var @<Global variables@>@/
426 @#
427 procedure initialize; {this procedure gets things started properly}
428 var @<Local variables for initialization@>@/
429 begin @<Initialize whatever \TeX\ might access@>@;
430 end;@#
431 @t\4@>@<Basic printing procedures@>@/
432 @t\4@>@<Error handling procedures@>@/
433
434 @ The overall \TeX\ program begins with the heading just shown, after which
435 comes a bunch of procedure declarations and function declarations.
436 Finally we will get to the main program, which begins with the
437 comment `|start_here|'. If you want to skip down to the
438 main program now, you can look up `|start_here|' in the index.
439 But the author suggests that the best way to understand this program
440 is to follow pretty much the order of \TeX's components as they appear in the
441 \.{WEB} description you are now reading, since the present ordering is
442 intended to combine the advantages of the ``bottom up'' and ``top down''
443 approaches to the problem of understanding a somewhat complicated system.
444
445 @ Three labels must be declared in the main program, so we give them
446 symbolic names.
447
448 @d start_of_TEX=1 {go here when \TeX's variables are initialized}
449 @d end_of_TEX=9998 {go here to close files and terminate gracefully}
450 @d final_end=9999 {this label marks the ending of the program}
451
452 @<Labels in the out...@>=
453 start_of_TEX@t\hskip-2pt@>, end_of_TEX@t\hskip-2pt@>,@,final_end;
454 {key control points}
455
456 @ Some of the code below is intended to be used only when diagnosing the
457 strange behavior that sometimes occurs when \TeX\ is being installed or
458 when system wizards are fooling around with \TeX\ without quite knowing
459 what they are doing. Such code will not normally be compiled; it is
460 delimited by the codewords `$|debug|\ldots|gubed|$', with apologies
461 to people who wish to preserve the purity of English.
462
463 Similarly, there is some conditional code delimited by
464 `$|stat|\ldots|tats|$' that is intended for use when statistics are to be
465 kept about \TeX's memory usage. The |stat| $\ldots$ |tats| code also
466 implements diagnostic information for \.{\\tracingparagraphs},
467 \.{\\tracingpages}, and \.{\\tracingrestores}.
468 @^debugging@>
469
470 @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
471 @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
472 @f debug==begin
473 @f gubed==end
474 @#
475 @d stat==@{ {change this to `$\\{stat}\equiv\null$' when gathering
476 usage statistics}
477 @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$' when gathering
478 usage statistics}
479 @f stat==begin
480 @f tats==end
481
482 @ This program has two important variations: (1) There is a long and slow
483 version called \.{INITEX}, which does the extra calculations needed to
484 @.INITEX@>
485 initialize \TeX's internal tables; and (2)~there is a shorter and faster
486 production version, which cuts the initialization to a bare minimum.
487 Parts of the program that are needed in (1) but not in (2) are delimited by
488 the codewords `$|init|\ldots|tini|$'.
489
490 @d init== {change this to `$\\{init}\equiv\.{@@\{}$' in the production version}
491 @d tini== {change this to `$\\{tini}\equiv\.{@@\}}$' in the production version}
492 @f init==begin
493 @f tini==end
494
495 @<Initialize whatever...@>=
496 @<Set initial values of key variables@>@/
497 @!init @<Initialize table entries (done by \.{INITEX} only)@>@;@+tini
498
499 @ If the first character of a \PASCAL\ comment is a dollar sign,
500 \ph\ treats the comment as a list of ``compiler directives'' that will
501 affect the translation of this program into machine language. The
502 directives shown below specify full checking and inclusion of the \PASCAL\
503 debugger when \TeX\ is being debugged, but they cause range checking and other
504 redundant code to be eliminated when the production system is being generated.
505 Arithmetic overflow will be detected in all cases.
506 @:PASCAL H}{\ph@>
507 @^system dependencies@>
508 @^overflow in arithmetic@>
509
510 @<Compiler directives@>=
511 @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
512 @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
513
514 @ This \TeX\ implementation conforms to the rules of the {\sl Pascal User
515 @:PASCAL}{\PASCAL@>
516 @^system dependencies@>
517 Manual} published by Jensen and Wirth in 1975, except where system-dependent
518 @^Wirth, Niklaus@>
519 @^Jensen, Kathleen@>
520 code is necessary to make a useful system program, and except in another
521 respect where such conformity would unnecessarily obscure the meaning
522 and clutter up the code: We assume that |case| statements may include a
523 default case that applies if no matching label is found. Thus, we shall use
524 constructions like
525 $$\vbox{\halign{\ignorespaces#\hfil\cr
526 |case x of|\cr
527 1: $\langle\,$code for $x=1\,\rangle$;\cr
528 3: $\langle\,$code for $x=3\,\rangle$;\cr
529 |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
530 |endcases|\cr}}$$
531 since most \PASCAL\ compilers have plugged this hole in the language by
532 incorporating some sort of default mechanism. For example, the \ph\
533 compiler allows `|others|:' as a default label, and other \PASCAL s allow
534 syntaxes like `\&{else}' or `\&{otherwise}' or `\\{otherwise}:', etc. The
535 definitions of |othercases| and |endcases| should be changed to agree with
536 local conventions. Note that no semicolon appears before |endcases| in
537 this program, so the definition of |endcases| should include a semicolon
538 if the compiler wants one. (Of course, if no default mechanism is
539 available, the |case| statements of \TeX\ will have to be laboriously
540 extended by listing all remaining cases. People who are stuck with such
541 \PASCAL s have, in fact, done this, successfully but not happily!)
542 @:PASCAL H}{\ph@>
543
544 @d othercases == others: {default for cases not listed explicitly}
545 @d endcases == @+end {follows the default case in an extended |case| statement}
546 @f othercases == else
547 @f endcases == end
548
549 @ The following parameters can be changed at compile time to extend or
550 reduce \TeX's capacity. They may have different values in \.{INITEX} and
551 in production versions of \TeX.
552 @.INITEX@>
553 @^system dependencies@>
554
555 @<Constants...@>=
556 @!mem_max=30000; {greatest index in \TeX's internal |mem| array;
557 must be strictly less than |max_halfword|;
558 must be equal to |mem_top| in \.{INITEX}, otherwise |>=mem_top|}
559 @!mem_min=0; {smallest index in \TeX's internal |mem| array;
560 must be |min_halfword| or more;
561 must be equal to |mem_bot| in \.{INITEX}, otherwise |<=mem_bot|}
562 @!buf_size=500; {maximum number of characters simultaneously present in
563 current lines of open files and in control sequences between
564 \.{\\csname} and \.{\\endcsname}; must not exceed |max_halfword|}
565 @!error_line=72; {width of context lines on terminal error messages}
566 @!half_error_line=42; {width of first lines of contexts in terminal
567 error messages; should be between 30 and |error_line-15|}
568 @!max_print_line=79; {width of longest text lines output; should be at least 60}
569 @!stack_size=200; {maximum number of simultaneous input sources}
570 @!max_in_open=6; {maximum number of input files and error insertions that
571 can be going on simultaneously}
572 @!font_max=75; {maximum internal font number; must not exceed |max_quarterword|
573 and must be at most |font_base+256|}
574 @!font_mem_size=20000; {number of words of |font_info| for all fonts}
575 @!param_size=60; {maximum number of simultaneous macro parameters}
576 @!nest_size=40; {maximum number of semantic levels simultaneously active}
577 @!max_strings=3000; {maximum number of strings; must not exceed |max_halfword|}
578 @!string_vacancies=8000; {the minimum number of characters that should be
579 available for the user's control sequences and font names,
580 after \TeX's own error messages are stored}
581 @!pool_size=32000; {maximum number of characters in strings, including all
582 error messages and help texts, and the names of all fonts and
583 control sequences; must exceed |string_vacancies| by the total
584 length of \TeX's own strings, which is currently about 23000}
585 @!save_size=600; {space for saving values outside of current group; must be
586 at most |max_halfword|}
587 @!trie_size=8000; {space for hyphenation patterns; should be larger for
588 \.{INITEX} than it is in production versions of \TeX}
589 @!trie_op_size=500; {space for ``opcodes'' in the hyphenation patterns}
590 @!dvi_buf_size=800; {size of the output buffer; must be a multiple of 8}
591 @!file_name_size=40; {file names shouldn't be longer than this}
592 @!pool_name='TeXformats:TEX.POOL ';
593 {string of length |file_name_size|; tells where the string pool appears}
594 @.TeXformats@>
595
596 @ Like the preceding parameters, the following quantities can be changed
597 at compile time to extend or reduce \TeX's capacity. But if they are changed,
598 it is necessary to rerun the initialization program \.{INITEX}
599 @.INITEX@>
600 to generate new tables for the production \TeX\ program.
601 One can't simply make helter-skelter changes to the following constants,
602 since certain rather complex initialization
603 numbers are computed from them. They are defined here using
604 \.{WEB} macros, instead of being put into \PASCAL's |const| list, in order to
605 emphasize this distinction.
606
607 @d mem_bot=0 {smallest index in the |mem| array dumped by \.{INITEX};
608 must not be less than |mem_min|}
609 @d mem_top==30000 {largest index in the |mem| array dumped by \.{INITEX};
610 must be substantially larger than |mem_bot|
611 and not greater than |mem_max|}
612 @d font_base=0 {smallest internal font number; must not be less
613 than |min_quarterword|}
614 @d hash_size=2100 {maximum number of control sequences; it should be at most
615 about |(mem_max-mem_min)/10|}
616 @d hash_prime=1777 {a prime number equal to about 85\pct! of |hash_size|}
617 @d hyph_size=307 {another prime; the number of \.{\\hyphenation} exceptions}
618 @d biggest_char=65535 {the largest allowed character number;
619 must be |<=max_quarterword|, this refers to UTF16 codepoints that we store in strings, etc;
620 actual character codes can exceed this range, up to |biggest_usv|}
621 @d too_big_char=65536 {|biggest_char+1|}
622 @d biggest_usv=@"10FFFF {the largest Unicode Scalar Value}
623 @d too_big_usv=@"110000 {|biggest_usv+1|}
624 @d number_usvs=@"110000 {|biggest_usv+1|}
625 @d special_char=@"110001 {|biggest_usv+2|}
626 @d biggest_reg=255 {the largest allowed register number;
627 must be |<=max_quarterword|}
628 @d number_regs=256 {|biggest_reg+1|}
629 @d font_biggest=255 {the real biggest font}
630 @d number_fonts=font_biggest-font_base+2
631 @d number_math_families=256
632 @d number_math_fonts=number_math_families+number_math_families+number_math_families
633 @d math_font_biggest=number_math_fonts-1
634 @d text_size=0 {size code for the largest size in a family}
635 @d script_size=number_math_families {size code for the medium size in a family}
636 @d script_script_size=number_math_families+number_math_families {size code for the smallest size in a family}
637 @d biggest_lang=255 {the largest hyphenation language}
638 @d too_big_lang=256 {|biggest_lang+1|}
639 @d hyphenatable_length_limit=4095 {hard limit for hyphenatable length; runtime value is |max_hyphenatable_length|}
640 @^system dependencies@>
641
642 @ In case somebody has inadvertently made bad settings of the ``constants,''
643 \TeX\ checks them using a global variable called |bad|.
644
645 This is the first of many sections of \TeX\ where global variables are
646 defined.
647
648 @<Glob...@>=
649 @!bad:integer; {is some ``constant'' wrong?}
650
651 @ Later on we will say `\ignorespaces|if mem_max>=max_halfword then bad:=14|',
652 or something similar. (We can't do that until |max_halfword| has been defined.)
653
654 @<Check the ``constant'' values for consistency@>=
655 bad:=0;
656 if (half_error_line<30)or(half_error_line>error_line-15) then bad:=1;
657 if max_print_line<60 then bad:=2;
658 if dvi_buf_size mod 8<>0 then bad:=3;
659 if mem_bot+1100>mem_top then bad:=4;
660 if hash_prime>hash_size then bad:=5;
661 if max_in_open>=128 then bad:=6;
662 if mem_top<256+11 then bad:=7; {we will want |null_list>255|}
663
664 @ Labels are given symbolic names by the following definitions, so that
665 occasional |goto| statements will be meaningful. We insert the label
666 `|exit|' just before the `\ignorespaces|end|\unskip' of a procedure in
667 which we have used the `|return|' statement defined below; the label
668 `|restart|' is occasionally used at the very beginning of a procedure; and
669 the label `|reswitch|' is occasionally used just prior to a |case|
670 statement in which some cases change the conditions and we wish to branch
671 to the newly applicable case. Loops that are set up with the |loop|
672 construction defined below are commonly exited by going to `|done|' or to
673 `|found|' or to `|not_found|', and they are sometimes repeated by going to
674 `|continue|'. If two or more parts of a subroutine start differently but
675 end up the same, the shared code may be gathered together at
676 `|common_ending|'.
677
678 Incidentally, this program never declares a label that isn't actually used,
679 because some fussy \PASCAL\ compilers will complain about redundant labels.
680
681 @d exit=10 {go here to leave a procedure}
682 @d restart=20 {go here to start a procedure again}
683 @d reswitch=21 {go here to start a case statement again}
684 @d continue=22 {go here to resume a loop}
685 @d done=30 {go here to exit a loop}
686 @d done1=31 {like |done|, when there is more than one loop}
687 @d done2=32 {for exiting the second loop in a long block}
688 @d done3=33 {for exiting the third loop in a very long block}
689 @d done4=34 {for exiting the fourth loop in an extremely long block}
690 @d done5=35 {for exiting the fifth loop in an immense block}
691 @d done6=36 {for exiting the sixth loop in a block}
692 @d found=40 {go here when you've found it}
693 @d found1=41 {like |found|, when there's more than one per routine}
694 @d found2=42 {like |found|, when there's more than two per routine}
695 @d not_found=45 {go here when you've found nothing}
696 @d not_found1=46 {like |not_found|, when there's more than one}
697 @d not_found2=47 {like |not_found|, when there's more than two}
698 @d not_found3=48 {like |not_found|, when there's more than three}
699 @d not_found4=49 {like |not_found|, when there's more than four}
700 @d common_ending=50 {go here when you want to merge with another branch}
701
702 @ Here are some macros for common programming idioms.
703
704 @d incr(#) == #:=#+1 {increase a variable by unity}
705 @d decr(#) == #:=#-1 {decrease a variable by unity}
706 @d negate(#) == #:=-# {change the sign of a variable}
707 @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
708 @f loop == xclause
709 {\.{WEB}'s |xclause| acts like `\ignorespaces|while true do|\unskip'}
710 @d do_nothing == {empty statement}
711 @d return == goto exit {terminate a procedure call}
712 @f return == nil
713 @d empty=0 {symbolic name for a null constant}
714
715 @* \[2] The character set.
716 In order to make \TeX\ readily portable to a wide variety of
717 computers, all of its input text is converted to an internal eight-bit
718 code that includes standard ASCII, the ``American Standard Code for
719 Information Interchange.'' This conversion is done immediately when each
720 character is read in. Conversely, characters are converted from ASCII to
721 the user's external representation just before they are output to a
722 text file.
723
724 Such an internal code is relevant to users of \TeX\ primarily because it
725 governs the positions of characters in the fonts. For example, the
726 character `\.A' has ASCII code $65=@'101$, and when \TeX\ typesets
727 this letter it specifies character number 65 in the current font.
728 If that font actually has `\.A' in a different position, \TeX\ doesn't
729 know what the real position is; the program that does the actual printing from
730 \TeX's device-independent files is responsible for converting from ASCII to
731 a particular font encoding.
732 @^ASCII code@>
733
734 \TeX's internal code also defines the value of constants
735 that begin with a reverse apostrophe; and it provides an index to the
736 \.{\\catcode}, \.{\\mathcode}, \.{\\uccode}, \.{\\lccode}, and \.{\\delcode}
737 tables.
738
739 @ Characters of text that have been converted to \TeX's internal form
740 are said to be of type |ASCII_code|, which is a subrange of the integers.
741 For xetex, we rename |ASCII_code| as |UTF16_code|. But we also have a
742 new type |UTF8_code|, used when we construct filenames to pass to the
743 system libraries.
744
745 @d ASCII_code==UTF16_code
746 @d packed_ASCII_code==packed_UTF16_code
747
748 @<Types...@>=
749 @!ASCII_code=0..biggest_char; {16-bit numbers}
750 @!UTF8_code=0..255; {8-bit numbers}
751 @!UnicodeScalar=0..biggest_usv; {Unicode scalars}
752
753 @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
754 character sets were common, so it did not make provision for lowercase
755 letters. Nowadays, of course, we need to deal with both capital and small
756 letters in a convenient way, especially in a program for typesetting;
757 so the present specification of \TeX\ has been written under the assumption
758 that the \PASCAL\ compiler and run-time system permit the use of text files
759 with more than 64 distinguishable characters. More precisely, we assume that
760 the character set contains at least the letters and symbols associated
761 with ASCII codes @'40 through @'176; all of these characters are now
762 available on most computer terminals.
763
764 Since we are dealing with more characters than were present in the first
765 \PASCAL\ compilers, we have to decide what to call the associated data
766 type. Some \PASCAL s use the original name |char| for the
767 characters in text files, even though there now are more than 64 such
768 characters, while other \PASCAL s consider |char| to be a 64-element
769 subrange of a larger data type that has some other name.
770
771 In order to accommodate this difference, we shall use the name |text_char|
772 to stand for the data type of the characters that are converted to and
773 from |ASCII_code| when they are input and output. We shall also assume
774 that |text_char| consists of the elements |chr(first_text_char)| through
775 |chr(last_text_char)|, inclusive. The following definitions should be
776 adjusted if necessary.
777 @^system dependencies@>
778
779 @d text_char == char {the data type of characters in text files}
780 @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
781 @d last_text_char=biggest_char {ordinal number of the largest element of |text_char|}
782
783 @<Local variables for init...@>=
784 @!i:integer;
785
786 @ The \TeX\ processor converts between ASCII code and
787 the user's external character set by means of arrays |xord| and |xchr|
788 that are analogous to \PASCAL's |ord| and |chr| functions.
789
790 @<Glob...@>=
791 @!xchr: array [ASCII_code] of text_char;
792 {specifies conversion of output characters}
793
794 @ Since we are assuming that our \PASCAL\ system is able to read and
795 write the visible characters of standard ASCII (although not
796 necessarily using the ASCII codes to represent them), the following
797 assignment statements initialize the standard part of the |xchr| array
798 properly, without needing any system-dependent changes. On the other
799 hand, it is possible to implement \TeX\ with less complete character
800 sets, and in such cases it will be necessary to change something here.
801 @^system dependencies@>
802
803 @ Some of the ASCII codes without visible characters have been given symbolic
804 names in this program because they are used with a special meaning.
805
806 @d null_code=@'0 {ASCII code that might disappear}
807 @d carriage_return=@'15 {ASCII code used at end of line}
808 @d invalid_code=@'177 {ASCII code that many systems prohibit in text files}
809
810 @ The ASCII code is ``standard'' only to a certain extent, since many
811 computer installations have found it advantageous to have ready access
812 to more than 94 printing characters. Appendix~C of {\sl The \TeX book\/}
813 gives a complete specification of the intended correspondence between
814 characters and \TeX's internal representation.
815 @:TeXbook}{\sl The \TeX book@>
816
817 If \TeX\ is being used
818 on a garden-variety \PASCAL\ for which only standard ASCII
819 codes will appear in the input and output files, it doesn't really matter
820 what codes are specified in |xchr[0..@'37]|, but the safest policy is to
821 blank everything out by using the code shown below.
822
823 However, other settings of |xchr| will make \TeX\ more friendly on
824 computers that have an extended character set, so that users can type things
825 like `\.^^Z' instead of `\.{\\ne}'. People with extended character sets can
826 assign codes arbitrarily, giving an |xchr| equivalent to whatever
827 characters the users of \TeX\ are allowed to have in their input files.
828 It is best to make the codes correspond to the intended interpretations as
829 shown in Appendix~C whenever possible; but this is not necessary. For
830 example, in countries with an alphabet of more than 26 letters, it is
831 usually best to map the additional letters into codes less than~@'40.
832 To get the most ``permissive'' character set, change |' '| on the
833 right of these assignment statements to |chr(i)|.
834 @^character set dependencies@>
835 @^system dependencies@>
836
837 @<Set init...@>=
838 for i:=0 to @'37 do xchr[i]:=' ';
839 for i:=@'177 to @'377 do xchr[i]:=' ';
840
841 @ The following system-independent code makes the |xord| array contain a
842 suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
843 where |i<j<@'177|, the value of |xord[xchr[i]]| will turn out to be
844 |j| or more; hence, standard ASCII code numbers will be used instead of
845 codes below @'40 in case there is a coincidence.
846
847 @<Set init...@>=
848 for i:=0 to @'176 do xord[xchr[i]]:=i;
849
850 @* \[3] Input and output.
851 The bane of portability is the fact that different operating systems treat
852 input and output quite differently, perhaps because computer scientists
853 have not given sufficient attention to this problem. People have felt somehow
854 that input and output are not part of ``real'' programming. Well, it is true
855 that some kinds of programming are more fun than others. With existing
856 input/output conventions being so diverse and so messy, the only sources of
857 joy in such parts of the code are the rare occasions when one can find a
858 way to make the program a little less bad than it might have been. We have
859 two choices, either to attack I/O now and get it over with, or to postpone
860 I/O until near the end. Neither prospect is very attractive, so let's
861 get it over with.
862
863 The basic operations we need to do are (1)~inputting and outputting of
864 text, to or from a file or the user's terminal; (2)~inputting and
865 outputting of eight-bit bytes, to or from a file; (3)~instructing the
866 operating system to initiate (``open'') or to terminate (``close'') input or
867 output from a specified file; (4)~testing whether the end of an input
868 file has been reached.
869
870 \TeX\ needs to deal with two kinds of files.
871 We shall use the term |alpha_file| for a file that contains textual data,
872 and the term |byte_file| for a file that contains eight-bit binary information.
873 These two types turn out to be the same on many computers, but
874 sometimes there is a significant distinction, so we shall be careful to
875 distinguish between them. Standard protocols for transferring
876 such files from computer to computer, via high-speed networks, are
877 now becoming available to more and more communities of users.
878
879 The program actually makes use also of a third kind of file, called a
880 |word_file|, when dumping and reloading base information for its own
881 initialization. We shall define a word file later; but it will be possible
882 for us to specify simple operations on word files before they are defined.
883
884 @<Types...@>=
885 @!eight_bits=0..255; {unsigned one-byte quantity}
886 @!alpha_file=packed file of text_char; {files that contain textual data}
887 @!byte_file=packed file of eight_bits; {files that contain binary data}
888
889 @ Most of what we need to do with respect to input and output can be handled
890 by the I/O facilities that are standard in \PASCAL, i.e., the routines
891 called |get|, |put|, |eof|, and so on. But
892 standard \PASCAL\ does not allow file variables to be associated with file
893 names that are determined at run time, so it cannot be used to implement
894 \TeX; some sort of extension to \PASCAL's ordinary |reset| and |rewrite|
895 is crucial for our purposes. We shall assume that |name_of_file| is a variable
896 of an appropriate type such that the \PASCAL\ run-time system being used to
897 implement \TeX\ can open a file whose external name is specified by
898 |name_of_file|.
899 @^system dependencies@>
900
901 @<Glob...@>=
902 @!name_of_file:packed array[1..file_name_size] of char;@;@/
903 {on some systems this may be a \&{record} variable}
904 @!name_of_file16:array[1..file_name_size] of UTF16_code;@;@/
905 {but sometimes we need a UTF16 version of the name}
906 @!name_length:0..file_name_size;@/{this many characters are actually
907 relevant in |name_of_file| (the rest are blank)}
908 @!name_length16:0..file_name_size;
909
910 @ The \ph\ compiler with which the present version of \TeX\ was prepared has
911 extended the rules of \PASCAL\ in a very convenient way. To open file~|f|,
912 we can write
913 $$\vbox{\halign{#\hfil\qquad&#\hfil\cr
914 |reset(f,@t\\{name}@>,'/O')|&for input;\cr
915 |rewrite(f,@t\\{name}@>,'/O')|&for output.\cr}}$$
916 The `\\{name}' parameter, which is of type `{\bf packed array
917 $[\langle\\{any}\rangle]$ of \\{char}}', stands for the name of
918 the external file that is being opened for input or output.
919 Blank spaces that might appear in \\{name} are ignored.
920
921 The `\.{/O}' parameter tells the operating system not to issue its own
922 error messages if something goes wrong. If a file of the specified name
923 cannot be found, or if such a file cannot be opened for some other reason
924 (e.g., someone may already be trying to write the same file), we will have
925 |@!erstat(f)<>0| after an unsuccessful |reset| or |rewrite|. This allows
926 \TeX\ to undertake appropriate corrective action.
927 @:PASCAL H}{\ph@>
928 @^system dependencies@>
929
930 \TeX's file-opening procedures return |false| if no file identified by
931 |name_of_file| could be opened.
932
933 @d reset_OK(#)==erstat(#)=0
934 @d rewrite_OK(#)==erstat(#)=0
935
936 @p function a_open_in(var f:alpha_file):boolean;
937 {open a text file for input}
938 begin reset(f,name_of_file,'/O'); a_open_in:=reset_OK(f);
939 end;
940 @#
941 function a_open_out(var f:alpha_file):boolean;
942 {open a text file for output}
943 begin rewrite(f,name_of_file,'/O'); a_open_out:=rewrite_OK(f);
944 end;
945 @#
946 function b_open_in(var f:byte_file):boolean;
947 {open a binary file for input}
948 begin reset(f,name_of_file,'/O'); b_open_in:=reset_OK(f);
949 end;
950 @#
951 function b_open_out(var f:byte_file):boolean;
952 {open a binary file for output}
953 begin rewrite(f,name_of_file,'/O'); b_open_out:=rewrite_OK(f);
954 end;
955 @#
956 function w_open_in(var f:word_file):boolean;
957 {open a word file for input}
958 begin reset(f,name_of_file,'/O'); w_open_in:=reset_OK(f);
959 end;
960 @#
961 function w_open_out(var f:word_file):boolean;
962 {open a word file for output}
963 begin rewrite(f,name_of_file,'/O'); w_open_out:=rewrite_OK(f);
964 end;
965
966 @ Files can be closed with the \ph\ routine `|close(f)|', which
967 @:PASCAL H}{\ph@>
968 @^system dependencies@>
969 should be used when all input or output with respect to |f| has been completed.
970 This makes |f| available to be opened again, if desired; and if |f| was used for
971 output, the |close| operation makes the corresponding external file appear
972 on the user's area, ready to be read.
973
974 These procedures should not generate error messages if a file is
975 being closed before it has been successfully opened.
976
977 @p procedure a_close(var f:alpha_file); {close a text file}
978 begin close(f);
979 end;
980 @#
981 procedure b_close(var f:byte_file); {close a binary file}
982 begin close(f);
983 end;
984 @#
985 procedure w_close(var f:word_file); {close a word file}
986 begin close(f);
987 end;
988
989 @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
990 procedures, so we don't have to make any other special arrangements for
991 binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
992 The treatment of text input is more difficult, however, because
993 of the necessary translation to |ASCII_code| values.
994 \TeX's conventions should be efficient, and they should
995 blend nicely with the user's operating environment.
996
997 @ Input from text files is read one line at a time, using a routine called
998 |input_ln|. This function is defined in terms of global variables called
999 |buffer|, |first|, and |last| that will be described in detail later; for
1000 now, it suffices for us to know that |buffer| is an array of |ASCII_code|
1001 values, and that |first| and |last| are indices into this array
1002 representing the beginning and ending of a line of text.
1003
1004 @<Glob...@>=
1005 @!buffer:array[0..buf_size] of ASCII_code; {lines of characters being read}
1006 @!first:0..buf_size; {the first unused position in |buffer|}
1007 @!last:0..buf_size; {end of the line just input to |buffer|}
1008 @!max_buf_stack:0..buf_size; {largest index used in |buffer|}
1009
1010 @ The |input_ln| function brings the next line of input from the specified
1011 file into available positions of the buffer array and returns the value
1012 |true|, unless the file has already been entirely read, in which case it
1013 returns |false| and sets |last:=first|. In general, the |ASCII_code|
1014 numbers that represent the next line of the file are input into
1015 |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
1016 global variable |last| is set equal to |first| plus the length of the
1017 line. Trailing blanks are removed from the line; thus, either |last=first|
1018 (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
1019
1020 An overflow error is given, however, if the normal actions of |input_ln|
1021 would make |last>=buf_size|; this is done so that other parts of \TeX\
1022 can safely look at the contents of |buffer[last+1]| without overstepping
1023 the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
1024 |first<buf_size| will always hold, so that there is always room for an
1025 ``empty'' line.
1026
1027 The variable |max_buf_stack|, which is used to keep track of how large
1028 the |buf_size| parameter must be to accommodate the present job, is
1029 also kept up to date by |input_ln|.
1030
1031 If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
1032 before looking at the first character of the line; this skips over
1033 an |eoln| that was in |f^|. The procedure does not do a |get| when it
1034 reaches the end of the line; therefore it can be used to acquire input
1035 from the user's terminal as well as from ordinary text files.
1036
1037 Standard \PASCAL\ says that a file should have |eoln| immediately
1038 before |eof|, but \TeX\ needs only a weaker restriction: If |eof|
1039 occurs in the middle of a line, the system function |eoln| should return
1040 a |true| result (even though |f^| will be undefined).
1041
1042 Since the inner loop of |input_ln| is part of \TeX's ``inner loop''---each
1043 character of input comes in at this place---it is wise to reduce system
1044 overhead by making use of special routines that read in an entire array
1045 of characters at once, if such routines are available. The following
1046 code uses standard \PASCAL\ to illustrate what needs to be done, but
1047 finer tuning is often possible at well-developed \PASCAL\ sites.
1048 @^inner loop@>
1049
1050 @p function input_ln(var f:alpha_file;@!bypass_eoln:boolean):boolean;
1051 {inputs the next line or returns |false|}
1052 var last_nonblank:0..buf_size; {|last| with trailing blanks removed}
1053 begin if bypass_eoln then if not eof(f) then get(f);
1054 {input the first character of the line into |f^|}
1055 last:=first; {cf.\ Matthew 19\thinspace:\thinspace30}
1056 if eof(f) then input_ln:=false
1057 else begin last_nonblank:=first;
1058 while not eoln(f) do
1059 begin if last>=max_buf_stack then
1060 begin max_buf_stack:=last+1;
1061 if max_buf_stack=buf_size then
1062 @<Report overflow of the input buffer, and abort@>;
1063 end;
1064 buffer[last]:=xord[f^]; get(f); incr(last);
1065 if buffer[last-1]<>" " then last_nonblank:=last;
1066 end;
1067 last:=last_nonblank; input_ln:=true;
1068 end;
1069 end;
1070
1071 @ The user's terminal acts essentially like other files of text, except
1072 that it is used both for input and for output. When the terminal is
1073 considered an input file, the file variable is called |term_in|, and when it
1074 is considered an output file the file variable is |term_out|.
1075 @^system dependencies@>
1076
1077 @<Glob...@>=
1078 @!term_in:alpha_file; {the terminal as an input file}
1079 @!term_out:alpha_file; {the terminal as an output file}
1080
1081 @ Here is how to open the terminal files
1082 in \ph. The `\.{/I}' switch suppresses the first |get|.
1083 @:PASCAL H}{\ph@>
1084 @^system dependencies@>
1085
1086 @d t_open_in==reset(term_in,'TTY:','/O/I') {open the terminal for text input}
1087 @d t_open_out==rewrite(term_out,'TTY:','/O') {open the terminal for text output}
1088
1089 @ Sometimes it is necessary to synchronize the input/output mixture that
1090 happens on the user's terminal, and three system-dependent
1091 procedures are used for this
1092 purpose. The first of these, |update_terminal|, is called when we want
1093 to make sure that everything we have output to the terminal so far has
1094 actually left the computer's internal buffers and been sent.
1095 The second, |clear_terminal|, is called when we wish to cancel any
1096 input that the user may have typed ahead (since we are about to
1097 issue an unexpected error message). The third, |wake_up_terminal|,
1098 is supposed to revive the terminal if the user has disabled it by
1099 some instruction to the operating system. The following macros show how
1100 these operations can be specified in \ph:
1101 @:PASCAL H}{\ph@>
1102 @^system dependencies@>
1103
1104 @d update_terminal == break(term_out) {empty the terminal output buffer}
1105 @d clear_terminal == break_in(term_in,true) {clear the terminal input buffer}
1106 @d wake_up_terminal == do_nothing {cancel the user's cancellation of output}
1107
1108 @ We need a special routine to read the first line of \TeX\ input from
1109 the user's terminal. This line is different because it is read before we
1110 have opened the transcript file; there is sort of a ``chicken and
1111 egg'' problem here. If the user types `\.{\\input paper}' on the first
1112 line, or if some macro invoked by that line does such an \.{\\input},
1113 the transcript file will be named `\.{paper.log}'; but if no \.{\\input}
1114 commands are performed during the first line of terminal input, the transcript
1115 file will acquire its default name `\.{texput.log}'. (The transcript file
1116 will not contain error messages generated by the first line before the
1117 first \.{\\input} command.)
1118 @.texput@>
1119
1120 The first line is even more special if we are lucky enough to have an operating
1121 system that treats \TeX\ differently from a run-of-the-mill \PASCAL\ object
1122 program. It's nice to let the user start running a \TeX\ job by typing
1123 a command line like `\.{tex paper}'; in such a case, \TeX\ will operate
1124 as if the first line of input were `\.{paper}', i.e., the first line will
1125 consist of the remainder of the command line, after the part that invoked
1126 \TeX.
1127
1128 The first line is special also because it may be read before \TeX\ has
1129 input a format file. In such cases, normal error messages cannot yet
1130 be given. The following code uses concepts that will be explained later.
1131 (If the \PASCAL\ compiler does not support non-local |@!goto|\unskip, the
1132 @^system dependencies@>
1133 statement `|goto final_end|' should be replaced by something that
1134 quietly terminates the program.)
1135
1136 @<Report overflow of the input buffer, and abort@>=
1137 if format_ident=0 then
1138 begin write_ln(term_out,'Buffer size exceeded!'); goto final_end;
1139 @.Buffer size exceeded@>
1140 end
1141 else begin cur_input.loc_field:=first; cur_input.limit_field:=last-1;
1142 overflow("buffer size",buf_size);
1143 @:TeX capacity exceeded buffer size}{\quad buffer size@>
1144 end
1145
1146 @ Different systems have different ways to get started. But regardless of
1147 what conventions are adopted, the routine that initializes the terminal
1148 should satisfy the following specifications:
1149
1150 \yskip\textindent{1)}It should open file |term_in| for input from the
1151 terminal. (The file |term_out| will already be open for output to the
1152 terminal.)
1153
1154 \textindent{2)}If the user has given a command line, this line should be
1155 considered the first line of terminal input. Otherwise the
1156 user should be prompted with `\.{**}', and the first line of input
1157 should be whatever is typed in response.
1158
1159 \textindent{3)}The first line of input, which might or might not be a
1160 command line, should appear in locations |first| to |last-1| of the
1161 |buffer| array.
1162
1163 \textindent{4)}The global variable |loc| should be set so that the
1164 character to be read next by \TeX\ is in |buffer[loc]|. This
1165 character should not be blank, and we should have |loc<last|.
1166
1167 \yskip\noindent(It may be necessary to prompt the user several times
1168 before a non-blank line comes in. The prompt is `\.{**}' instead of the
1169 later `\.*' because the meaning is slightly different: `\.{\\input}' need
1170 not be typed immediately after~`\.{**}'.)
1171
1172 @d loc==cur_input.loc_field {location of first unread character in |buffer|}
1173
1174 @ The following program does the required initialization
1175 without retrieving a possible command line.
1176 It should be clear how to modify this routine to deal with command lines,
1177 if the system permits them.
1178 @^system dependencies@>
1179
1180 @p function init_terminal:boolean; {gets the terminal input started}
1181 label exit;
1182 begin t_open_in;
1183 loop@+begin wake_up_terminal; write(term_out,'**'); update_terminal;
1184 @.**@>
1185 if not input_ln(term_in,true) then {this shouldn't happen}
1186 begin write_ln(term_out);
1187 write(term_out,'! End of file on the terminal... why?');
1188 @.End of file on the terminal@>
1189 init_terminal:=false; return;
1190 end;
1191 loc:=first;
1192 while (loc<last)and(buffer[loc]=" ") do incr(loc);
1193 if loc<last then
1194 begin init_terminal:=true;
1195 return; {return unless the line was all blank}
1196 end;
1197 write_ln(term_out,'Please type the name of your input file.');
1198 end;
1199 exit:end;
1200
1201 @* \[4] String handling.
1202 Control sequence names and diagnostic messages are variable-length strings
1203 of eight-bit characters. Since \PASCAL\ does not have a well-developed string
1204 mechanism, \TeX\ does all of its string processing by homegrown methods.
1205
1206 Elaborate facilities for dynamic strings are not needed, so all of the
1207 necessary operations can be handled with a simple data structure.
1208 The array |str_pool| contains all of the (eight-bit) ASCII codes in all
1209 of the strings, and the array |str_start| contains indices of the starting
1210 points of each string. Strings are referred to by integer numbers, so that
1211 string number |s| comprises the characters |str_pool[j]| for
1212 |str_start_macro[s]<=j<str_start_macro[s+1]|. Additional integer variables
1213 |pool_ptr| and |str_ptr| indicate the number of entries used so far
1214 in |str_pool| and |str_start|, respectively; locations
1215 |str_pool[pool_ptr]| and |str_start_macro[str_ptr]| are
1216 ready for the next string to be allocated.
1217
1218 String numbers 0 to 255 are reserved for strings that correspond to single
1219 ASCII characters. This is in accordance with the conventions of \.{WEB},
1220 @.WEB@>
1221 which converts single-character strings into the ASCII code number of the
1222 single character involved, while it converts other strings into integers
1223 and builds a string pool file. Thus, when the string constant \.{"."} appears
1224 in the program below, \.{WEB} converts it into the integer 46, which is the
1225 ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
1226 into some integer greater than~255. String number 46 will presumably be the
1227 single character `\..'; but some ASCII codes have no standard visible
1228 representation, and \TeX\ sometimes needs to be able to print an arbitrary
1229 ASCII character, so the first 256 strings are used to specify exactly what
1230 should be printed for each of the 256 possibilities.
1231
1232 Elements of the |str_pool| array must be ASCII codes that can actually
1233 be printed; i.e., they must have an |xchr| equivalent in the local
1234 character set. (This restriction applies only to preloaded strings,
1235 not to those generated dynamically by the user.)
1236
1237 Some \PASCAL\ compilers won't pack integers into a single byte unless the
1238 integers lie in the range |-128..127|. To accommodate such systems
1239 we access the string pool only via macros that can easily be redefined.
1240 @^system dependencies@>
1241
1242 @d si(#) == # {convert from |ASCII_code| to |packed_ASCII_code|}
1243 @d so(#) == # {convert from |packed_ASCII_code| to |ASCII_code|}
1244 @d str_start_macro(#) == str_start[(#) - too_big_char]
1245
1246 @<Types...@>=
1247 @!pool_pointer = 0..pool_size; {for variables that point into |str_pool|}
1248 @!str_number = 0..max_strings; {for variables that point into |str_start|}
1249 @!packed_ASCII_code = 0..biggest_char; {elements of |str_pool| array}
1250
1251 @ @<Glob...@>=
1252 @!str_pool:packed array[pool_pointer] of packed_ASCII_code; {the characters}
1253 @!str_start : array[str_number] of pool_pointer; {the starting pointers}
1254 @!pool_ptr : pool_pointer; {first unused position in |str_pool|}
1255 @!str_ptr : str_number; {number of the current string being created}
1256 @!init_pool_ptr : pool_pointer; {the starting value of |pool_ptr|}
1257 @!init_str_ptr : str_number; {the starting value of |str_ptr|}
1258
1259 @ Several of the elementary string operations are performed using \.{WEB}
1260 macros instead of \PASCAL\ procedures, because many of the
1261 operations are done quite frequently and we want to avoid the
1262 overhead of procedure calls. For example, here is
1263 a simple macro that computes the length of a string.
1264 @.WEB@>
1265
1266 @p function length(s:str_number):integer;
1267 {the number of characters in string number |s|}
1268 begin if (s>=@"10000) then length:=str_start_macro(s+1)-str_start_macro(s)
1269 else if (s>=@"20) and (s<@"7F) then length:=1
1270 else if (s<=@"7F) then length:=3
1271 else if (s<@"100) then length:=4
1272 else length:=8
1273 end;
1274
1275 @ The length of the current string is called |cur_length|:
1276
1277 @d cur_length == (pool_ptr - str_start_macro(str_ptr))
1278
1279 @ Strings are created by appending character codes to |str_pool|.
1280 The |append_char| macro, defined here, does not check to see if the
1281 value of |pool_ptr| has gotten too high; this test is supposed to be
1282 made before |append_char| is used. There is also a |flush_char|
1283 macro, which erases the last character appended.
1284
1285 To test if there is room to append |l| more characters to |str_pool|,
1286 we shall write |str_room(l)|, which aborts \TeX\ and gives an
1287 apologetic error message if there isn't enough room.
1288
1289 @d append_char(#) == {put |ASCII_code| \# at the end of |str_pool|}
1290 begin
1291 if (si(#)>@"FFFF) then begin
1292 str_pool[pool_ptr]:=si((# - @"10000) div @"400 + @"D800); incr(pool_ptr);
1293 str_pool[pool_ptr]:=si((# ) mod @"400 + @"DC00); incr(pool_ptr);
1294 end else begin
1295 str_pool[pool_ptr]:=si(#); incr(pool_ptr);
1296 end;
1297 end
1298 @d flush_char == decr(pool_ptr) {forget the last character in the pool}
1299 @d str_room(#) == {make sure that the pool hasn't overflowed}
1300 begin if pool_ptr+# > pool_size then
1301 overflow("pool size",pool_size-init_pool_ptr);
1302 @:TeX capacity exceeded pool size}{\quad pool size@>
1303 end
1304
1305 @ Once a sequence of characters has been appended to |str_pool|, it
1306 officially becomes a string when the function |make_string| is called.
1307 This function returns the identification number of the new string as its
1308 value.
1309
1310 @p function make_string : str_number; {current string enters the pool}
1311 begin if str_ptr=max_strings then
1312 overflow("number of strings",max_strings-init_str_ptr);
1313 @:TeX capacity exceeded number of strings}{\quad number of strings@>
1314 incr(str_ptr); str_start_macro(str_ptr):=pool_ptr;
1315 make_string:=str_ptr-1;
1316 end;
1317
1318 @ To destroy the most recently made string, we say |flush_string|.
1319
1320 @d flush_string==begin decr(str_ptr); pool_ptr:=str_start_macro(str_ptr);
1321 end
1322
1323 @p procedure append_str(@!s:str_number); { append an existing string to the current string }
1324 var i: integer;
1325 j: pool_pointer;
1326 begin
1327 i:=length(s);
1328 str_room(i);
1329 j:=str_start_macro(s);
1330 while (i > 0) do begin
1331 append_char(str_pool[j]);
1332 incr(j); decr(i);
1333 end;
1334 end;
1335
1336 @ The following subroutine compares string |s| with another string of the
1337 same length that appears in |buffer| starting at position |k|;
1338 the result is |true| if and only if the strings are equal.
1339 Empirical tests indicate that |str_eq_buf| is used in such a way that
1340 it tends to return |true| about 80 percent of the time.
1341
1342 @p function str_eq_buf(@!s:str_number;@!k:integer):boolean;
1343 {test equality of strings}
1344 label not_found; {loop exit}
1345 var j: pool_pointer; {running index}
1346 @!result: boolean; {result of comparison}
1347 begin j:=str_start_macro(s);
1348 while j<str_start_macro(s+1) do
1349 begin
1350 if buffer[k]>=@"10000 then
1351 if so(str_pool[j])<>@"D800+(buffer[k]-@"10000)div@"400 then
1352 begin result:=false; goto not_found;
1353 end
1354 else if so(str_pool[j+1])<>@"DC00+(buffer[k]-@"10000)mod@"400 then
1355 begin result:=false; goto not_found;
1356 end
1357 else incr(j)
1358 else if so(str_pool[j])<>buffer[k] then
1359 begin result:=false; goto not_found;
1360 end;
1361 incr(j); incr(k);
1362 end;
1363 result:=true;
1364 not_found: str_eq_buf:=result;
1365 end;
1366
1367 @ Here is a similar routine, but it compares two strings in the string pool,
1368 and it does not assume that they have the same length.
1369
1370 @p function str_eq_str(@!s,@!t:str_number):boolean;
1371 {test equality of strings}
1372 label not_found; {loop exit}
1373 var j,@!k: pool_pointer; {running indices}
1374 @!result: boolean; {result of comparison}
1375 begin result:=false;
1376 if length(s)<>length(t) then goto not_found;
1377 if (length(s)=1) then begin
1378 if s<65536 then begin
1379 if t<65536 then begin
1380 if s<>t then goto not_found;
1381 end
1382 else begin
1383 if s<>str_pool[str_start_macro(t)] then goto not_found;
1384 end;
1385 end
1386 else begin
1387 if t<65536 then begin
1388 if str_pool[str_start_macro(s)]<>t then goto not_found;
1389 end
1390 else begin
1391 if str_pool[str_start_macro(s)]<>str_pool[str_start_macro(t)] then
1392 goto not_found;
1393 end;
1394 end;
1395 end
1396 else begin
1397 j:=str_start_macro(s); k:=str_start_macro(t);
1398 while j<str_start_macro(s+1) do
1399 begin if str_pool[j]<>str_pool[k] then goto not_found;
1400 incr(j); incr(k);
1401 end;
1402 end;
1403 result:=true;
1404 not_found: str_eq_str:=result;
1405 end;
1406
1407 @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
1408 and |str_ptr| are computed by the \.{INITEX} program, based in part
1409 on the information that \.{WEB} has output while processing \TeX.
1410 @.INITEX@>
1411 @^string pool@>
1412
1413 @p @!init function get_strings_started:boolean; {initializes the string pool,
1414 but returns |false| if something goes wrong}
1415 label done,exit;
1416 var
1417 @!m,@!n:text_char; {characters input from |pool_file|}
1418 @!g:str_number; {garbage}
1419 @!a:integer; {accumulator for check sum}
1420 @!c:boolean; {check sum has been checked}
1421 begin pool_ptr:=0; str_ptr:=0; str_start[0]:=0;
1422 @<Make the first 256 strings@>;
1423 @<Read the other strings from the \.{TEX.POOL} file and return |true|,
1424 or give an error message and return |false|@>;
1425 exit:end;
1426 tini
1427
1428 @ The first 65536 strings will consist of a single character only.
1429 But we don't actually make them; they're simulated on the fly.
1430
1431 @<Make the first 256...@>=
1432 begin
1433 str_ptr:=too_big_char;
1434 str_start_macro(str_ptr):=pool_ptr;
1435 end
1436
1437 @ The first 128 strings will contain 95 standard ASCII characters, and the
1438 other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
1439 unless a system-dependent change is made here. Installations that have
1440 an extended character set, where for example |xchr[@'32]=@t\.{\'^^Z\'}@>|,
1441 would like string @'32 to be the single character @'32 instead of the
1442 three characters @'136, @'136, @'132 (\.{\^\^Z}). On the other hand,
1443 even people with an extended character set will want to represent string
1444 @'15 by \.{\^\^M}, since @'15 is |carriage_return|; the idea is to
1445 produce visible strings instead of tabs or line-feeds or carriage-returns
1446 or bell-rings or characters that are treated anomalously in text files.
1447
1448 Unprintable characters of codes 128--255 are, similarly, rendered
1449 \.{\^\^80}--\.{\^\^ff}.
1450
1451 The boolean expression defined here should be |true| unless \TeX\
1452 internal code number~|k| corresponds to a non-troublesome visible
1453 symbol in the local character set. An appropriate formula for the
1454 extended character set recommended in {\sl The \TeX book\/} would, for
1455 example, be `|k in [0,@'10..@'12,@'14,@'15,@'33,@'177..@'377]|'.
1456 If character |k| cannot be printed, and |k<@'200|, then character |k+@'100| or
1457 |k-@'100| must be printable; moreover, ASCII codes |[@'41..@'46,
1458 @'60..@'71, @'136, @'141..@'146, @'160..@'171]| must be printable.
1459 Thus, at least 80 printable characters are needed.
1460 @:TeXbook}{\sl The \TeX book@>
1461 @^character set dependencies@>
1462 @^system dependencies@>
1463
1464 @ When the \.{WEB} system program called \.{TANGLE} processes the \.{TEX.WEB}
1465 description that you are now reading, it outputs the \PASCAL\ program
1466 \.{TEX.PAS} and also a string pool file called \.{TEX.POOL}. The \.{INITEX}
1467 @.WEB@>@.INITEX@>
1468 program reads the latter file, where each string appears as a two-digit decimal
1469 length followed by the string itself, and the information is recorded in
1470 \TeX's string memory.
1471
1472 @<Glob...@>=
1473 @!init @!pool_file:alpha_file; {the string-pool file output by \.{TANGLE}}
1474 tini
1475
1476 @ @d bad_pool(#)==begin wake_up_terminal; write_ln(term_out,#);
1477 a_close(pool_file); get_strings_started:=false; return;
1478 end
1479 @<Read the other strings...@>=
1480 name_of_file:=pool_name; {we needn't set |name_length|}
1481 if a_open_in(pool_file) then
1482 begin c:=false;
1483 repeat @<Read one string, but return |false| if the
1484 string memory space is getting too tight for comfort@>;
1485 until c;
1486 a_close(pool_file); get_strings_started:=true;
1487 end
1488 else bad_pool('! I can''t read TEX.POOL.')
1489 @.I can't read TEX.POOL@>
1490
1491 @ @<Read one string...@>=
1492 begin if eof(pool_file) then bad_pool('! TEX.POOL has no check sum.');
1493 @.TEX.POOL has no check sum@>
1494 read(pool_file,m,n); {read two digits of string length}
1495 if m='*' then @<Check the pool check sum@>
1496 else begin if (xord[m]<"0")or(xord[m]>"9")or@|
1497 (xord[n]<"0")or(xord[n]>"9") then
1498 bad_pool('! TEX.POOL line doesn''t begin with two digits.');
1499 @.TEX.POOL line doesn't...@>
1500 l:=xord[m]*10+xord[n]-"0"*11; {compute the length}
1501 if pool_ptr+l+string_vacancies>pool_size then
1502 bad_pool('! You have to increase POOLSIZE.');
1503 @.You have to increase POOLSIZE@>
1504 for k:=1 to l do
1505 begin if eoln(pool_file) then m:=' '@+else read(pool_file,m);
1506 append_char(xord[m]);
1507 end;
1508 read_ln(pool_file); g:=make_string;
1509 end;
1510 end
1511
1512 @ The \.{WEB} operation \.{@@\$} denotes the value that should be at the
1513 end of this \.{TEX.POOL} file; any other value means that the wrong pool
1514 file has been loaded.
1515 @^check sum@>
1516
1517 @<Check the pool check sum@>=
1518 begin a:=0; k:=1;
1519 loop@+ begin if (xord[n]<"0")or(xord[n]>"9") then
1520 bad_pool('! TEX.POOL check sum doesn''t have nine digits.');
1521 @.TEX.POOL check sum...@>
1522 a:=10*a+xord[n]-"0";
1523 if k=9 then goto done;
1524 incr(k); read(pool_file,n);
1525 end;
1526 done: if a<>@$ then bad_pool('! TEX.POOL doesn''t match; TANGLE me again.');
1527 @.TEX.POOL doesn't match@>
1528 c:=true;
1529 end
1530
1531 @* \[5] On-line and off-line printing.
1532 Messages that are sent to a user's terminal and to the transcript-log file
1533 are produced by several `|print|' procedures. These procedures will
1534 direct their output to a variety of places, based on the setting of
1535 the global variable |selector|, which has the following possible
1536 values:
1537
1538 \yskip
1539 \hang |term_and_log|, the normal setting, prints on the terminal and on the
1540 transcript file.
1541
1542 \hang |log_only|, prints only on the transcript file.
1543
1544 \hang |term_only|, prints only on the terminal.
1545
1546 \hang |no_print|, doesn't print at all. This is used only in rare cases
1547 before the transcript file is open.
1548
1549 \hang |pseudo|, puts output into a cyclic buffer that is used
1550 by the |show_context| routine; when we get to that routine we shall discuss
1551 the reasoning behind this curious mode.
1552
1553 \hang |new_string|, appends the output to the current string in the
1554 string pool.
1555
1556 \hang 0 to 15, prints on one of the sixteen files for \.{\\write} output.
1557
1558 \yskip
1559 \noindent The symbolic names `|term_and_log|', etc., have been assigned
1560 numeric codes that satisfy the convenient relations |no_print+1=term_only|,
1561 |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.
1562
1563 Three additional global variables, |tally| and |term_offset| and
1564 |file_offset|, record the number of characters that have been printed
1565 since they were most recently cleared to zero. We use |tally| to record
1566 the length of (possibly very long) stretches of printing; |term_offset|
1567 and |file_offset|, on the other hand, keep track of how many characters
1568 have appeared so far on the current line that has been output to the
1569 terminal or to the transcript file, respectively.
1570
1571 @d no_print=16 {|selector| setting that makes data disappear}
1572 @d term_only=17 {printing is destined for the terminal only}
1573 @d log_only=18 {printing is destined for the transcript file only}
1574 @d term_and_log=19 {normal |selector| setting}
1575 @d pseudo=20 {special |selector| setting for |show_context|}
1576 @d new_string=21 {printing is deflected to the string pool}
1577 @d max_selector=21 {highest selector setting}
1578
1579 @<Glob...@>=
1580 @!log_file : alpha_file; {transcript of \TeX\ session}
1581 @!selector : 0..max_selector; {where to print a message}
1582 @!dig : array[0..22] of 0..15; {digits in a number being output}
1583 @!tally : integer; {the number of characters recently printed}
1584 @!term_offset : 0..max_print_line;
1585 {the number of characters on the current terminal line}
1586 @!file_offset : 0..max_print_line;
1587 {the number of characters on the current file line}
1588 @!trick_buf:array[0..error_line] of ASCII_code; {circular buffer for
1589 pseudoprinting}
1590 @!trick_count: integer; {threshold for pseudoprinting, explained later}
1591 @!first_count: integer; {another variable for pseudoprinting}
1592
1593 @ @<Initialize the output routines@>=
1594 selector:=term_only; tally:=0; term_offset:=0; file_offset:=0;
1595
1596 @ Macro abbreviations for output to the terminal and to the log file are
1597 defined here for convenience. Some systems need special conventions
1598 for terminal output, and it is possible to adhere to those conventions
1599 by changing |wterm|, |wterm_ln|, and |wterm_cr| in this section.
1600 @^system dependencies@>
1601
1602 @d wterm(#)==write(term_out,#)
1603 @d wterm_ln(#)==write_ln(term_out,#)
1604 @d wterm_cr==write_ln(term_out)
1605 @d wlog(#)==write(log_file,#)
1606 @d wlog_ln(#)==write_ln(log_file,#)
1607 @d wlog_cr==write_ln(log_file)
1608
1609 @ To end a line of text output, we call |print_ln|.
1610
1611 @<Basic print...@>=
1612 procedure print_ln; {prints an end-of-line}
1613 begin case selector of
1614 term_and_log: begin wterm_cr; wlog_cr;
1615 term_offset:=0; file_offset:=0;
1616 end;
1617 log_only: begin wlog_cr; file_offset:=0;
1618 end;
1619 term_only: begin wterm_cr; term_offset:=0;
1620 end;
1621 no_print,pseudo,new_string: do_nothing;
1622 othercases write_ln(write_file[selector])
1623 endcases;@/
1624 end; {|tally| is not affected}
1625
1626 @ The |print_raw_char| procedure sends one character to the desired destination,
1627 using the |xchr| array to map it into an external character compatible with
1628 |input_ln|. All printing comes through |print_ln|, |print_char| or
1629 |print_visible_char|. When printing a multi-byte character, the boolean
1630 parameter |incr_offset| is set |false| except for the very last byte, to avoid
1631 calling |print_ln| in the middle of such character.
1632
1633 @<Basic printing...@>=
1634 procedure print_raw_char(@!s:UnicodeScalar;@!incr_offset:boolean); {prints a single character}
1635 label exit; {label is not used but nonetheless kept (for other changes?)}
1636 begin
1637 case selector of
1638 term_and_log: begin wterm(xchr[s]); wlog(xchr[s]);
1639 if incr_offset then
1640 begin incr(term_offset); incr(file_offset);
1641 end;
1642 if term_offset=max_print_line then
1643 begin wterm_cr; term_offset:=0;
1644 end;
1645 if file_offset=max_print_line then
1646 begin wlog_cr; file_offset:=0;
1647 end;
1648 end;
1649 log_only: begin wlog(xchr[s]);
1650 if incr_offset then incr(file_offset);
1651 if file_offset=max_print_line then print_ln;
1652 end;
1653 term_only: begin wterm(xchr[s]);
1654 if incr_offset then incr(term_offset);
1655 if term_offset=max_print_line then print_ln;
1656 end;
1657 no_print: do_nothing;
1658 pseudo: if tally<trick_count then trick_buf[tally mod error_line]:=s;
1659 new_string: begin if pool_ptr<pool_size then append_char(s);
1660 end; {we drop characters if the string space is full}
1661 othercases write(write_file[selector],xchr[s])
1662 endcases;@/
1663 incr(tally);
1664 exit:end;
1665
1666 @ The |print_char| procedure sends one character to the desired destination.
1667 Control sequence names, file names and string constructed with
1668 \.{\\string} might contain |ASCII_code| values that can't
1669 be printed using |print_raw_char|. These characters will be printed
1670 in three- or four-symbol form like `\.{\^\^A}' or `\.{\^\^e4}',
1671 unless the -8bit option is enabled.
1672 Output that goes to the terminal and/or log file is treated differently
1673 when it comes to determining whether a character is printable.
1674
1675 @d print_visible_char(#)==print_raw_char(#, true)
1676 @d print_lc_hex(#)==l:=#;
1677 if l<10 then print_visible_char(l+"0")@+else print_visible_char(l-10+"a")
1678
1679 @<Basic printing...@>=
1680 procedure print_char(@!s:integer); {prints a single character}
1681 label exit;
1682 var l: small_number;
1683 begin if (selector>pseudo) and (not doing_special) then
1684 {``printing'' to a new string, encode as UTF-16 rather than UTF-8}
1685 begin if s>=@"10000 then
1686 begin print_visible_char(@"D800 + (s - @"10000) div @"400);
1687 print_visible_char(@"DC00 + (s - @"10000) mod @"400);
1688 end else print_visible_char(s);
1689 return;
1690 end;
1691 if @<Character |s| is the current new-line character@> then
1692 if selector<pseudo then
1693 begin print_ln; return;
1694 end;
1695 if (s < 32) and (eight_bit_p = 0) and (not doing_special) then {control char: \.{\^\^X}}
1696 begin print_visible_char("^"); print_visible_char("^"); print_visible_char(s+64);
1697 end
1698 else if s < 127 then { printable ASCII }
1699 print_visible_char(s)
1700 else if (s = 127) then { DEL }
1701 begin if (eight_bit_p = 0) and (not doing_special) then
1702 begin print_visible_char("^"); print_visible_char("^"); print_visible_char("?")
1703 end else
1704 print_visible_char(s)
1705 end
1706 else if (s < @"A0) and (eight_bit_p = 0) and (not doing_special) then {C1 controls: \.{\^\^xx}}
1707 begin print_visible_char("^"); print_visible_char("^");
1708 print_lc_hex((s mod @"100) div @"10); print_lc_hex(s mod @"10);
1709 end
1710 else if selector=pseudo then
1711 print_visible_char(s) { Don't UTF8-encode text in |trick_buf|,
1712 we'll handle that when printing error context. }
1713 else begin
1714 { |char >= 128|: encode as UTF8 }
1715 if s<@"800 then begin
1716 print_raw_char(@"C0 + s div @"40, false);
1717 print_raw_char(@"80 + s mod @"40, true);
1718 end
1719 else if s<@"10000 then begin
1720 print_raw_char(@"E0 + (s div @"1000), false);
1721 print_raw_char(@"80 + (s mod @"1000) div @"40, false);
1722 print_raw_char(@"80 + (s mod @"40), true);
1723 end
1724 else begin
1725 print_raw_char(@"F0 + (s div @"40000), false);
1726 print_raw_char(@"80 + (s mod @"40000) div @"1000, false);
1727 print_raw_char(@"80 + (s mod @"1000) div @"40, false);
1728 print_raw_char(@"80 + (s mod @"40), true);
1729 end
1730 end;
1731 exit:end;
1732
1733 @ @d native_room(#)==while native_text_size <= native_len+# do begin
1734 native_text_size:=native_text_size+128;
1735 native_text:=xrealloc(native_text, native_text_size * sizeof(UTF16_code));
1736 end
1737 @d append_native(#)==begin native_text[native_len]:=#; incr(native_len); end
1738
1739 @ @<Glob...@>=
1740 @!doing_special: boolean;
1741 @!native_text: ^UTF16_code; { buffer for collecting native-font strings }
1742 @!native_text_size: integer; { size of buffer }
1743 @!native_len: integer;
1744 @!save_native_len: integer;
1745
1746 @ @<Set init...@>=
1747 doing_special:=false;
1748 native_text_size:=128;
1749 native_text:=xmalloc(native_text_size * sizeof(UTF16_code));
1750
1751 @ An entire string is output by calling |print|. Note that if we are outputting
1752 the single standard ASCII character \.c, we could call |print("c")|, since
1753 |"c"=99| is the number of a single-character string, as explained above. But
1754 |print_char("c")| is quicker, so \TeX\ goes directly to the |print_char|
1755 routine when it knows that this is safe. (The present implementation
1756 assumes that it is always safe to print a visible ASCII character.)
1757 @^system dependencies@>
1758
1759 @<Basic print...@>=
1760 procedure print(@!s:integer); {prints string |s|}
1761 label exit;
1762 var j:pool_pointer; {current character code position}
1763 @!nl:integer; {new-line character to restore}
1764 begin if s>=str_ptr then s:="???" {this can't happen}
1765 @.???@>
1766 else if s<biggest_char then
1767 if s<0 then s:="???" {can't happen}
1768 else begin if selector>pseudo then
1769 begin print_char(s); return; {internal strings are not expanded}
1770 end;
1771 if (@<Character |s| is the current new-line character@>) then
1772 if selector<pseudo then
1773 begin print_ln; return;
1774 end;
1775 nl:=new_line_char;
1776 new_line_char:=-1;
1777 print_char(s);
1778 new_line_char:=nl;
1779 return;
1780 end;
1781 j:=str_start_macro(s);
1782 while j<str_start_macro(s+1) do begin
1783 if (so(str_pool[j])>=@"D800) and (so(str_pool[j])<=@"DBFF)
1784 and (j+1<str_start_macro(s+1))
1785 and (so(str_pool[j+1])>=@"DC00) and (so(str_pool[j+1])<=@"DFFF) then
1786 begin print_char(@"10000 + (so(str_pool[j])-@"D800) * @"400
1787 + so(str_pool[j+1])-@"DC00); j:=j+2;
1788 end
1789 else begin print_char(so(str_pool[j])); incr(j);
1790 end;
1791 end;
1792 exit:end;
1793
1794 @ Old versions of \TeX\ needed a procedure called |slow_print| whose function
1795 is now subsumed by |print| and the new functionality of |print_char| and
1796 |print_visible_char|. We retain the old name |slow_print| here as a
1797 possible aid to future software arch\ae ologists.
1798
1799 @d slow_print == print
1800
1801 @ Here is the very first thing that \TeX\ prints: a headline that identifies
1802 the version number and format package. The |term_offset| variable is temporarily
1803 incorrect, but the discrepancy is not serious since we assume that this
1804 part of the program is system dependent.
1805 @^system dependencies@>
1806
1807 @<Initialize the output...@>=
1808 wterm(banner);
1809 if format_ident=0 then wterm_ln(' (no format preloaded)')
1810 else begin slow_print(format_ident); print_ln;
1811 end;
1812 update_terminal;
1813
1814 @ The procedure |print_nl| is like |print|, but it makes sure that the
1815 string appears at the beginning of a new line.
1816
1817 @<Basic print...@>=
1818 procedure print_nl(@!s:str_number); {prints string |s| at beginning of line}
1819 begin if ((term_offset>0)and(odd(selector)))or@|
1820 ((file_offset>0)and(selector>=log_only)) then print_ln;
1821 print(s);
1822 end;
1823
1824 @ The procedure |print_esc| prints a string that is preceded by
1825 the user's escape character (which is usually a backslash).
1826
1827 @<Basic print...@>=
1828 procedure print_esc(@!s:str_number); {prints escape character, then |s|}
1829 var c:integer; {the escape character code}
1830 begin @<Set variable |c| to the current escape character@>;
1831 if c>=0 then if c<=biggest_usv then print_char(c);
1832 slow_print(s);
1833 end;
1834
1835 @ An array of digits in the range |0..15| is printed by |print_the_digs|.
1836
1837 @<Basic print...@>=
1838 procedure print_the_digs(@!k:eight_bits);
1839 {prints |dig[k-1]|$\,\ldots\,$|dig[0]|}
1840 begin while k>0 do
1841 begin decr(k);
1842 if dig[k]<10 then print_char("0"+dig[k])
1843 else print_char("A"-10+dig[k]);
1844 end;
1845 end;
1846
1847 @ The following procedure, which prints out the decimal representation of a
1848 given integer |n|, has been written carefully so that it works properly
1849 if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
1850 to negative arguments, since such operations are not implemented consistently
1851 by all \PASCAL\ compilers.
1852
1853 @<Basic print...@>=
1854 procedure print_int(@!n:integer); {prints an integer in decimal form}
1855 var k:0..23; {index to current digit; we assume that $\vert n\vert<10^{23}$}
1856 @!m:integer; {used to negate |n| in possibly dangerous cases}
1857 begin k:=0;
1858 if n<0 then
1859 begin print_char("-");
1860 if n>-100000000 then negate(n)
1861 else begin m:=-1-n; n:=m div 10; m:=(m mod 10)+1; k:=1;
1862 if m<10 then dig[0]:=m
1863 else begin dig[0]:=0; incr(n);
1864 end;
1865 end;
1866 end;
1867 repeat dig[k]:=n mod 10; n:=n div 10; incr(k);
1868 until n=0;
1869 print_the_digs(k);
1870 end;
1871
1872 @ Here is a trivial procedure to print two digits; it is usually called with
1873 a parameter in the range |0<=n<=99|.
1874
1875 @p procedure print_two(@!n:integer); {prints two least significant digits}
1876 begin n:=abs(n) mod 100; print_char("0"+(n div 10));
1877 print_char("0"+(n mod 10));
1878 end;
1879
1880 @ Hexadecimal printing of nonnegative integers is accomplished by |print_hex|.
1881
1882 @p procedure print_hex(@!n:integer);
1883 {prints a positive integer in hexadecimal form}
1884 var k:0..22; {index to current digit; we assume that $0\L n<16^{22}$}
1885 begin k:=0; print_char("""");
1886 repeat dig[k]:=n mod 16; n:=n div 16; incr(k);
1887 until n=0;
1888 print_the_digs(k);
1889 end;
1890
1891 @ Old versions of \TeX\ needed a procedure called |print_ASCII| whose function
1892 is now subsumed by |print|. We retain the old name here as a possible aid to
1893 future software arch\ae ologists.
1894
1895 @d print_ASCII == print
1896
1897 @ Roman numerals are produced by the |print_roman_int| routine. Readers
1898 who like puzzles might enjoy trying to figure out how this tricky code
1899 works; therefore no explanation will be given. Notice that 1990 yields
1900 \.{mcmxc}, not \.{mxm}.
1901
1902 @p procedure print_roman_int(@!n:integer);
1903 label exit;
1904 var j,@!k: pool_pointer; {mysterious indices into |str_pool|}
1905 @!u,@!v: nonnegative_integer; {mysterious numbers}
1906 begin j:=str_start_macro("m2d5c2l5x2v5i"); v:=1000;
1907 loop@+ begin while n>=v do
1908 begin print_char(so(str_pool[j])); n:=n-v;
1909 end;
1910 if n<=0 then return; {nonpositive input produces no output}
1911 k:=j+2; u:=v div (so(str_pool[k-1])-"0");
1912 if str_pool[k-1]=si("2") then
1913 begin k:=k+2; u:=u div (so(str_pool[k-1])-"0");
1914 end;
1915 if n+u>=v then
1916 begin print_char(so(str_pool[k])); n:=n+u;
1917 end
1918 else begin j:=j+2; v:=v div (so(str_pool[j-1])-"0");
1919 end;
1920 end;
1921 exit:end;
1922
1923 @ The |print| subroutine will not print a string that is still being
1924 created. The following procedure will.
1925
1926 @p procedure print_current_string; {prints a yet-unmade string}
1927 var j:pool_pointer; {points to current character code}
1928 begin j:=str_start_macro(str_ptr);
1929 while j<pool_ptr do
1930 begin print_char(so(str_pool[j])); incr(j);
1931 end;
1932 end;
1933
1934 @ Here is a procedure that asks the user to type a line of input,
1935 assuming that the |selector| setting is either |term_only| or |term_and_log|.
1936 The input is placed into locations |first| through |last-1| of the
1937 |buffer| array, and echoed on the transcript file if appropriate.
1938
1939 This procedure is never called when |interaction<scroll_mode|.
1940
1941 @d prompt_input(#)==begin wake_up_terminal; print(#); term_input;
1942 end {prints a string and gets a line of input}
1943
1944 @p procedure term_input; {gets a line from the terminal}
1945 var k:0..buf_size; {index into |buffer|}
1946 begin update_terminal; {now the user sees the prompt for sure}
1947 if not input_ln(term_in,true) then fatal_error("End of file on the terminal!");
1948 @.End of file on the terminal@>
1949 term_offset:=0; {the user's line ended with \<\rm return>}
1950 decr(selector); {prepare to echo the input}
1951 if last<>first then for k:=first to last-1 do print(buffer[k]);
1952 print_ln; incr(selector); {restore previous status}
1953 end;
1954
1955 @* \[6] Reporting errors.
1956 When something anomalous is detected, \TeX\ typically does something like this:
1957 $$\vbox{\halign{#\hfil\cr
1958 |print_err("Something anomalous has been detected");|\cr
1959 |help3("This is the first line of my offer to help.")|\cr
1960 |("This is the second line. I'm trying to")|\cr
1961 |("explain the best way for you to proceed.");|\cr
1962 |error;|\cr}}$$
1963 A two-line help message would be given using |help2|, etc.; these informal
1964 helps should use simple vocabulary that complements the words used in the
1965 official error message that was printed. (Outside the U.S.A., the help
1966 messages should preferably be translated into the local vernacular. Each
1967 line of help is at most 60 characters long, in the present implementation,
1968 so that |max_print_line| will not be exceeded.)
1969
1970 The |print_err| procedure supplies a `\.!' before the official message,
1971 and makes sure that the terminal is awake if a stop is going to occur.
1972 The |error| procedure supplies a `\..' after the official message, then it
1973 shows the location of the error; and if |interaction=error_stop_mode|,
1974 it also enters into a dialog with the user, during which time the help
1975 message may be printed.
1976 @^system dependencies@>
1977
1978 @ The global variable |interaction| has four settings, representing increasing
1979 amounts of user interaction:
1980
1981 @d batch_mode=0 {omits all stops and omits terminal output}
1982 @d nonstop_mode=1 {omits all stops}
1983 @d scroll_mode=2 {omits error stops}
1984 @d error_stop_mode=3 {stops at every opportunity to interact}
1985 @d print_err(#)==begin if interaction=error_stop_mode then wake_up_terminal;
1986 print_nl("! "); print(#);
1987 end
1988 @d print_ignored_err(#)==begin
1989 {An error in original \TeX, but we want to send it only to the log in
1990 other engines.}
1991 old_selector_ignored_err := selector;
1992 selector := log_only;
1993 wlog_cr; wlog('ignored: '); print(#);
1994 selector := old_selector_ignored_err;
1995 end
1996
1997 @<Glob...@>=
1998 @!interaction:batch_mode..error_stop_mode; {current level of interaction}
1999
2000 @ @<Set init...@>=interaction:=error_stop_mode;
2001
2002 @ \TeX\ is careful not to call |error| when the print |selector| setting
2003 might be unusual. The only possible values of |selector| at the time of
2004 error messages are
2005
2006 \yskip\hang|no_print| (when |interaction=batch_mode|
2007 and |log_file| not yet open);
2008
2009 \hang|term_only| (when |interaction>batch_mode| and |log_file| not yet open);
2010
2011 \hang|log_only| (when |interaction=batch_mode| and |log_file| is open);
2012
2013 \hang|term_and_log| (when |interaction>batch_mode| and |log_file| is open).
2014
2015 @<Initialize the print |selector| based on |interaction|@>=
2016 if interaction=batch_mode then selector:=no_print@+else selector:=term_only
2017
2018 @ A global variable |deletions_allowed| is set |false| if the |get_next|
2019 routine is active when |error| is called; this ensures that |get_next|
2020 and related routines like |get_token| will never be called recursively.
2021 A similar interlock is provided by |set_box_allowed|.
2022 @^recursion@>
2023
2024 The global variable |history| records the worst level of error that
2025 has been detected. It has four possible values: |spotless|, |warning_issued|,
2026 |error_message_issued|, and |fatal_error_stop|.
2027
2028 Another global variable, |error_count|, is increased by one when an
2029 |error| occurs without an interactive dialog, and it is reset to zero at
2030 the end of every paragraph. If |error_count| reaches 100, \TeX\ decides
2031 that there is no point in continuing further.
2032
2033 @d spotless=0 {|history| value when nothing has been amiss yet}
2034 @d warning_issued=1 {|history| value when |begin_diagnostic| has been called}
2035 @d error_message_issued=2 {|history| value when |error| has been called}
2036 @d fatal_error_stop=3 {|history| value when termination was premature}
2037
2038 @<Glob...@>=
2039 @!deletions_allowed:boolean; {is it safe for |error| to call |get_token|?}
2040 @!set_box_allowed:boolean; {is it safe to do a \.{\\setbox} assignment?}
2041 @!history:spotless..fatal_error_stop; {has the source input been clean so far?}
2042 @!error_count:-1..100; {the number of scrolled errors since the
2043 last paragraph ended}
2044
2045 @ The value of |history| is initially |fatal_error_stop|, but it will
2046 be changed to |spotless| if \TeX\ survives the initialization process.
2047
2048 @<Set init...@>=
2049 deletions_allowed:=true; set_box_allowed:=true;
2050 error_count:=0; {|history| is initialized elsewhere}
2051
2052 @ Since errors can be detected almost anywhere in \TeX, we want to declare the
2053 error procedures near the beginning of the program. But the error procedures
2054 in turn use some other procedures, which need to be declared |forward|
2055 before we get to |error| itself.
2056
2057 It is possible for |error| to be called recursively if some error arises
2058 when |get_token| is being used to delete a token, and/or if some fatal error
2059 occurs while \TeX\ is trying to fix a non-fatal one. But such recursion
2060 @^recursion@>
2061 is never more than two levels deep.
2062
2063 @<Error handling...@>=
2064 procedure@?normalize_selector; forward;@t\2@>@/
2065 procedure@?get_token; forward;@t\2@>@/
2066 procedure@?term_input; forward;@t\2@>@/
2067 procedure@?show_context; forward;@t\2@>@/
2068 procedure@?begin_file_reading; forward;@t\2@>@/
2069 procedure@?open_log_file; forward;@t\2@>@/
2070 procedure@?close_files_and_terminate; forward;@t\2@>@/
2071 procedure@?clear_for_error_prompt; forward;@t\2@>@/
2072 procedure@?give_err_help; forward;@t\2@>@/
2073 @t\4\hskip-\fontdimen2\font@>@;@+@!debug@+procedure@?debug_help;
2074 forward;@;@+gubed
2075
2076 @ Individual lines of help are recorded in the array |help_line|, which
2077 contains entries in positions |0..(help_ptr-1)|. They should be printed
2078 in reverse order, i.e., with |help_line[0]| appearing last.
2079
2080 @d hlp1(#)==help_line[0]:=#;@+end
2081 @d hlp2(#)==help_line[1]:=#; hlp1
2082 @d hlp3(#)==help_line[2]:=#; hlp2
2083 @d hlp4(#)==help_line[3]:=#; hlp3
2084 @d hlp5(#)==help_line[4]:=#; hlp4
2085 @d hlp6(#)==help_line[5]:=#; hlp5
2086 @d help0==help_ptr:=0 {sometimes there might be no help}
2087 @d help1==@+begin help_ptr:=1; hlp1 {use this with one help line}
2088 @d help2==@+begin help_ptr:=2; hlp2 {use this with two help lines}
2089 @d help3==@+begin help_ptr:=3; hlp3 {use this with three help lines}
2090 @d help4==@+begin help_ptr:=4; hlp4 {use this with four help lines}
2091 @d help5==@+begin help_ptr:=5; hlp5 {use this with five help lines}
2092 @d help6==@+begin help_ptr:=6; hlp6 {use this with six help lines}
2093
2094 @<Glob...@>=
2095 @!help_line:array[0..5] of str_number; {helps for the next |error|}
2096 @!help_ptr:0..6; {the number of help lines present}
2097 @!use_err_help:boolean; {should the |err_help| list be shown?}
2098
2099 @ @<Set init...@>=
2100 help_ptr:=0; use_err_help:=false;
2101
2102 @ The |jump_out| procedure just cuts across all active procedure levels and
2103 goes to |end_of_TEX|. This is the only nontrivial |@!goto| statement in the
2104 whole program. It is used when there is no recovery from a particular error.
2105
2106 Some \PASCAL\ compilers do not implement non-local |goto| statements.
2107 @^system dependencies@>
2108 In such cases the body of |jump_out| should simply be
2109 `|close_files_and_terminate|;\thinspace' followed by a call on some system
2110 procedure that quietly terminates the program.
2111
2112 @<Error hand...@>=
2113 procedure jump_out;
2114 begin goto end_of_TEX;
2115 end;
2116
2117 @ Here now is the general |error| routine.
2118
2119 @<Error hand...@>=
2120 procedure error; {completes the job of error reporting}
2121 label continue,exit;
2122 var c:UnicodeScalar; {what the user types}
2123 @!s1,@!s2,@!s3,@!s4:integer;
2124 {used to save global variables when deleting tokens}
2125 begin if history<error_message_issued then history:=error_message_issued;
2126 print_char("."); show_context;
2127 if interaction=error_stop_mode then
2128 @<Get user's advice and |return|@>;
2129 incr(error_count);
2130 if error_count=100 then
2131 begin print_nl("(That makes 100 errors; please try again.)");
2132 @.That makes 100 errors...@>
2133 history:=fatal_error_stop; jump_out;
2134 end;
2135 @<Put help message on the transcript file@>;
2136 exit:end;
2137
2138 @ @<Get user's advice...@>=
2139 loop@+begin continue: if interaction<>error_stop_mode then return;
2140 clear_for_error_prompt; prompt_input("? ");
2141 @.?\relax@>
2142 if last=first then return;
2143 c:=buffer[first];
2144 if c>="a" then c:=c+"A"-"a"; {convert to uppercase}
2145 @<Interpret code |c| and |return| if done@>;
2146 end
2147
2148 @ It is desirable to provide an `\.E' option here that gives the user
2149 an easy way to return from \TeX\ to the system editor, with the offending
2150 line ready to be edited. But such an extension requires some system
2151 wizardry, so the present implementation simply types out the name of the
2152 file that should be
2153 edited and the relevant line number.
2154 @^system dependencies@>
2155
2156 There is a secret `\.D' option available when the debugging routines haven't
2157 been commented~out.
2158 @^debugging@>
2159
2160 @<Interpret code |c| and |return| if done@>=
2161 case c of
2162 "0","1","2","3","4","5","6","7","8","9": if deletions_allowed then
2163 @<Delete \(c)|c-"0"| tokens and |goto continue|@>;
2164 @t\4\4@>@;@+@!debug "D": begin debug_help; goto continue;@+end;@+gubed@/
2165 "E": if base_ptr>0 then if input_stack[base_ptr].name_field>=256 then
2166 begin print_nl("You want to edit file ");
2167 @.You want to edit file x@>
2168 slow_print(input_stack[base_ptr].name_field);
2169 print(" at line "); print_int(line);
2170 interaction:=scroll_mode; jump_out;
2171 end;
2172 "H": @<Print the help information and |goto continue|@>;
2173 "I":@<Introduce new material from the terminal and |return|@>;
2174 "Q","R","S":@<Change the interaction level and |return|@>;
2175 "X":begin interaction:=scroll_mode; jump_out;
2176 end;
2177 othercases do_nothing
2178 endcases;@/
2179 @<Print the menu of available options@>
2180
2181 @ @<Print the menu...@>=
2182 begin print("Type <return> to proceed, S to scroll future error messages,");@/
2183 @.Type <return> to proceed...@>
2184 print_nl("R to run without stopping, Q to run quietly,");@/
2185 print_nl("I to insert something, ");
2186 if base_ptr>0 then if input_stack[base_ptr].name_field>=256 then
2187 print("E to edit your file,");
2188 if deletions_allowed then
2189 print_nl("1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
2190 print_nl("H for help, X to quit.");
2191 end
2192
2193 @ Here the author of \TeX\ apologizes for making use of the numerical
2194 relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
2195 |batch_mode|, |nonstop_mode|, |scroll_mode|.
2196 @^Knuth, Donald Ervin@>
2197
2198 @<Change the interaction...@>=
2199 begin error_count:=0; interaction:=batch_mode+c-"Q";
2200 print("OK, entering ");
2201 case c of
2202 "Q":begin print_esc("batchmode"); decr(selector);
2203 end;
2204 "R":print_esc("nonstopmode");
2205 "S":print_esc("scrollmode");
2206 end; {there are no other cases}
2207 print("..."); print_ln; update_terminal; return;
2208 end
2209
2210 @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
2211 contain the material inserted by the user; otherwise another prompt will
2212 be given. In order to understand this part of the program fully, you need
2213 to be familiar with \TeX's input stacks.
2214
2215 @<Introduce new material...@>=
2216 begin begin_file_reading; {enter a new syntactic level for terminal input}
2217 {now |state=mid_line|, so an initial blank space will count as a blank}
2218 if last>first+1 then
2219 begin loc:=first+1; buffer[first]:=" ";
2220 end
2221 else begin prompt_input("insert>"); loc:=first;
2222 @.insert>@>
2223 end;
2224 first:=last;
2225 cur_input.limit_field:=last-1; {no |end_line_char| ends this line}
2226 return;
2227 end
2228
2229 @ We allow deletion of up to 99 tokens at a time.
2230
2231 @<Delete \(c)|c-"0"| tokens...@>=
2232 begin s1:=cur_tok; s2:=cur_cmd; s3:=cur_chr; s4:=align_state;
2233 align_state:=1000000; OK_to_interrupt:=false;
2234 if (last>first+1) and (buffer[first+1]>="0")and(buffer[first+1]<="9") then
2235 c:=c*10+buffer[first+1]-"0"*11
2236 else c:=c-"0";
2237 while c>0 do
2238 begin get_token; {one-level recursive call of |error| is possible}
2239 decr(c);
2240 end;
2241 cur_tok:=s1; cur_cmd:=s2; cur_chr:=s3; align_state:=s4; OK_to_interrupt:=true;
2242 help2("I have just deleted some text, as you asked.")@/
2243 ("You can now delete more, or insert, or whatever.");
2244 show_context; goto continue;
2245 end
2246
2247 @ @<Print the help info...@>=
2248 begin if use_err_help then
2249 begin give_err_help; use_err_help:=false;
2250 end
2251 else begin if help_ptr=0 then
2252 help2("Sorry, I don't know how to help in this situation.")@/
2253 @t\kern1em@>("Maybe you should try asking a human?");
2254 repeat decr(help_ptr); print(help_line[help_ptr]); print_ln;
2255 until help_ptr=0;
2256 end;
2257 help4("Sorry, I already gave what help I could...")@/
2258 ("Maybe you should try asking a human?")@/
2259 ("An error might have occurred before I noticed any problems.")@/
2260 ("``If all else fails, read the instructions.''");@/
2261 goto continue;
2262 end
2263
2264 @ @<Put help message on the transcript file@>=
2265 if interaction>batch_mode then decr(selector); {avoid terminal output}
2266 if use_err_help then
2267 begin print_ln; give_err_help;
2268 end
2269 else while help_ptr>0 do
2270 begin decr(help_ptr); print_nl(help_line[help_ptr]);
2271 end;
2272 print_ln;
2273 if interaction>batch_mode then incr(selector); {re-enable terminal output}
2274 print_ln
2275
2276 @ A dozen or so error messages end with a parenthesized integer, so we
2277 save a teeny bit of program space by declaring the following procedure:
2278
2279 @p procedure int_error(@!n:integer);
2280 begin print(" ("); print_int(n); print_char(")"); error;
2281 end;
2282
2283 @ In anomalous cases, the print selector might be in an unknown state;
2284 the following subroutine is called to fix things just enough to keep
2285 running a bit longer.
2286
2287 @p procedure normalize_selector;
2288 begin if log_opened then selector:=term_and_log
2289 else selector:=term_only;
2290 if job_name=0 then open_log_file;
2291 if interaction=batch_mode then decr(selector);
2292 end;
2293
2294 @ The following procedure prints \TeX's last words before dying.
2295
2296 @d succumb==begin if interaction=error_stop_mode then
2297 interaction:=scroll_mode; {no more interaction}
2298 if log_opened then error;
2299 @!debug if interaction>batch_mode then debug_help;@+gubed@;@/
2300 history:=fatal_error_stop; jump_out; {irrecoverable error}
2301 end
2302
2303 @<Error hand...@>=
2304 procedure fatal_error(@!s:str_number); {prints |s|, and that's it}
2305 begin normalize_selector;@/
2306 print_err("Emergency stop"); help1(s); succumb;
2307 @.Emergency stop@>
2308 end;
2309
2310 @ Here is the most dreaded error message.
2311
2312 @<Error hand...@>=
2313 procedure overflow(@!s:str_number;@!n:integer); {stop due to finiteness}
2314 begin normalize_selector;
2315 print_err("TeX capacity exceeded, sorry [");
2316 @.TeX capacity exceeded ...@>
2317 print(s); print_char("="); print_int(n); print_char("]");
2318 help2("If you really absolutely need more capacity,")@/
2319 ("you can ask a wizard to enlarge me.");
2320 succumb;
2321 end;
2322
2323 @ The program might sometime run completely amok, at which point there is
2324 no choice but to stop. If no previous error has been detected, that's bad
2325 news; a message is printed that is really intended for the \TeX\
2326 maintenance person instead of the user (unless the user has been
2327 particularly diabolical). The index entries for `this can't happen' may
2328 help to pinpoint the problem.
2329 @^dry rot@>
2330
2331 @<Error hand...@>=
2332 procedure confusion(@!s:str_number);
2333 {consistency check violated; |s| tells where}
2334 begin normalize_selector;
2335 if history<error_message_issued then
2336 begin print_err("This can't happen ("); print(s); print_char(")");
2337 @.This can't happen@>
2338 help1("I'm broken. Please show this to someone who can fix can fix");
2339 end
2340 else begin print_err("I can't go on meeting you like this");
2341 @.I can't go on...@>
2342 help2("One of your faux pas seems to have wounded me deeply...")@/
2343 ("in fact, I'm barely conscious. Please fix it and try again.");
2344 end;
2345 succumb;
2346 end;
2347
2348 @ Users occasionally want to interrupt \TeX\ while it's running.
2349 If the \PASCAL\ runtime system allows this, one can implement
2350 a routine that sets the global variable |interrupt| to some nonzero value
2351 when such an interrupt is signalled. Otherwise there is probably at least
2352 a way to make |interrupt| nonzero using the \PASCAL\ debugger.
2353 @^system dependencies@>
2354 @^debugging@>
2355
2356 @d check_interrupt==begin if interrupt<>0 then pause_for_instructions;
2357 end
2358
2359 @<Global...@>=
2360 @!interrupt:integer; {should \TeX\ pause for instructions?}
2361 @!OK_to_interrupt:boolean; {should interrupts be observed?}
2362
2363 @ @<Set init...@>=
2364 interrupt:=0; OK_to_interrupt:=true;
2365
2366 @ When an interrupt has been detected, the program goes into its
2367 highest interaction level and lets the user have nearly the full flexibility of
2368 the |error| routine. \TeX\ checks for interrupts only at times when it is
2369 safe to do this.
2370
2371 @p procedure pause_for_instructions;
2372 begin if OK_to_interrupt then
2373 begin interaction:=error_stop_mode;
2374 if (selector=log_only)or(selector=no_print) then
2375 incr(selector);
2376 print_err("Interruption");
2377 @.Interruption@>
2378 help3("You rang?")@/
2379 ("Try to insert an instruction for me (e.g., `I\showlists'),")@/
2380 ("unless you just want to quit by typing `X'.");
2381 deletions_allowed:=false; error; deletions_allowed:=true;
2382 interrupt:=0;
2383 end;
2384 end;
2385
2386 @* \[7] Arithmetic with scaled dimensions.
2387 The principal computations performed by \TeX\ are done entirely in terms of
2388 integers less than $2^{31}$ in magnitude; and divisions are done only when both
2389 dividend and divisor are nonnegative. Thus, the arithmetic specified in this
2390 program can be carried out in exactly the same way on a wide variety of
2391 computers, including some small ones. Why? Because the arithmetic
2392 calculations need to be spelled out precisely in order to guarantee that
2393 \TeX\ will produce identical output on different machines. If some
2394 quantities were rounded differently in different implementations, we would
2395 find that line breaks and even page breaks might occur in different places.
2396 Hence the arithmetic of \TeX\ has been designed with care, and systems that
2397 claim to be implementations of \TeX82 should follow precisely the
2398 @:TeX82}{\TeX82@>
2399 calculations as they appear in the present program.
2400
2401 (Actually there are three places where \TeX\ uses |div| with a possibly negative
2402 numerator. These are harmless; see |div| in the index. Also if the user
2403 sets the \.{\\time} or the \.{\\year} to a negative value, some diagnostic
2404 information will involve negative-numerator division. The same remarks
2405 apply for |mod| as well as for |div|.)
2406
2407 @ Here is a routine that calculates half of an integer, using an
2408 unambiguous convention with respect to signed odd numbers.
2409
2410 @p function half(@!x:integer):integer;
2411 begin if odd(x) then half:=(x+1) div 2
2412 else half:=x @!div 2;
2413 end;
2414
2415 @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
2416 of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
2417 positions from the right end of a binary computer word.
2418
2419 @d unity == @'200000 {$2^{16}$, represents 1.00000}
2420 @d two == @'400000 {$2^{17}$, represents 2.00000}
2421
2422 @<Types...@>=
2423 @!scaled = integer; {this type is used for scaled integers}
2424 @!nonnegative_integer=0..@'17777777777; {$0\L x<2^{31}$}
2425 @!small_number=0..hyphenatable_length_limit; {this type is self-explanatory}
2426
2427 @ The following function is used to create a scaled integer from a given decimal
2428 fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
2429 given in |dig[i]|, and the calculation produces a correctly rounded result.
2430
2431 @p function round_decimals(@!k:small_number) : scaled;
2432 {converts a decimal fraction}
2433 var a:integer; {the accumulator}
2434 begin a:=0;
2435 while k>0 do
2436 begin decr(k); a:=(a+dig[k]*two) div 10;
2437 end;
2438 round_decimals:=(a+1) div 2;
2439 end;
2440
2441 @ Conversely, here is a procedure analogous to |print_int|. If the output
2442 of this procedure is subsequently read by \TeX\ and converted by the
2443 |round_decimals| routine above, it turns out that the original value will
2444 be reproduced exactly; the ``simplest'' such decimal number is output,
2445 but there is always at least one digit following the decimal point.
2446
2447 The invariant relation in the \&{repeat} loop is that a sequence of
2448 decimal digits yet to be printed will yield the original number if and only if
2449 they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
2450 We can stop if and only if $f=0$ satisfies this condition; the loop will
2451 terminate before $s$ can possibly become zero.
2452
2453 @p procedure print_scaled(@!s:scaled); {prints scaled real, rounded to five
2454 digits}
2455 var delta:scaled; {amount of allowable inaccuracy}
2456 begin if s<0 then
2457 begin print_char("-"); negate(s); {print the sign, if negative}
2458 end;
2459 print_int(s div unity); {print the integer part}
2460 print_char(".");
2461 s:=10*(s mod unity)+5; delta:=10;
2462 repeat if delta>unity then s:=s+@'100000-50000; {round the last digit}
2463 print_char("0"+(s div unity)); s:=10*(s mod unity); delta:=delta*10;
2464 until s<=delta;
2465 end;
2466
2467 @ Physical sizes that a \TeX\ user specifies for portions of documents are
2468 represented internally as scaled points. Thus, if we define an `sp' (scaled
2469 @^sp@>
2470 point) as a unit equal to $2^{-16}$ printer's points, every dimension
2471 inside of \TeX\ is an integer number of sp. There are exactly
2472 4,736,286.72 sp per inch. Users are not allowed to specify dimensions
2473 larger than $2^{30}-1$ sp, which is a distance of about 18.892 feet (5.7583
2474 meters); two such quantities can be added without overflow on a 32-bit
2475 computer.
2476
2477 The present implementation of \TeX\ does not check for overflow when
2478 @^overflow in arithmetic@>
2479 dimensions are added or subtracted. This could be done by inserting a
2480 few dozen tests of the form `\ignorespaces|if x>=@'10000000000 then
2481 @t\\{report\_overflow}@>|', but the chance of overflow is so remote that
2482 such tests do not seem worthwhile.
2483
2484 \TeX\ needs to do only a few arithmetic operations on scaled quantities,
2485 other than addition and subtraction, and the following subroutines do most of
2486 the work. A single computation might use several subroutine calls, and it is
2487 desirable to avoid producing multiple error messages in case of arithmetic
2488 overflow; so the routines set the global variable |arith_error| to |true|
2489 instead of reporting errors directly to the user. Another global variable,
2490 |remainder|, holds the remainder after a division.
2491
2492 @<Glob...@>=
2493 @!arith_error:boolean; {has arithmetic overflow occurred recently?}
2494 @!remainder:scaled; {amount subtracted to get an exact division}
2495
2496 @ The first arithmetical subroutine we need computes $nx+y$, where |x|
2497 and~|y| are |scaled| and |n| is an integer. We will also use it to
2498 multiply integers.
2499
2500 @d nx_plus_y(#)==mult_and_add(#,@'7777777777)
2501 @d mult_integers(#)==mult_and_add(#,0,@'17777777777)
2502
2503 @p function mult_and_add(@!n:integer;@!x,@!y,@!max_answer:scaled):scaled;
2504 begin if n<0 then
2505 begin negate(x); negate(n);
2506 end;
2507 if n=0 then mult_and_add:=y
2508 else if ((x<=(max_answer-y) div n)and(-x<=(max_answer+y) div n)) then
2509 mult_and_add:=n*x+y
2510 else begin arith_error:=true; mult_and_add:=0;
2511 end;
2512 end;
2513
2514 @ We also need to divide scaled dimensions by integers.
2515
2516 @p function x_over_n(@!x:scaled;@!n:integer):scaled;
2517 var negative:boolean; {should |remainder| be negated?}
2518 begin negative:=false;
2519 if n=0 then
2520 begin arith_error:=true; x_over_n:=0; remainder:=x;
2521 end
2522 else begin if n<0 then
2523 begin negate(x); negate(n); negative:=true;
2524 end;
2525 if x>=0 then
2526 begin x_over_n:=x div n; remainder:=x mod n;
2527 end
2528 else begin x_over_n:=-((-x) div n); remainder:=-((-x) mod n);
2529 end;
2530 end;
2531 if negative then negate(remainder);
2532 end;
2533
2534 @ Then comes the multiplication of a scaled number by a fraction |n/d|,
2535 where |n| and |d| are nonnegative integers |<=@t$2^{16}$@>| and |d| is
2536 positive. It would be too dangerous to multiply by~|n| and then divide
2537 by~|d|, in separate operations, since overflow might well occur; and it
2538 would be too inaccurate to divide by |d| and then multiply by |n|. Hence
2539 this subroutine simulates 1.5-precision arithmetic.
2540
2541 @p function xn_over_d(@!x:scaled; @!n,@!d:integer):scaled;
2542 var positive:boolean; {was |x>=0|?}
2543 @!t,@!u,@!v:nonnegative_integer; {intermediate quantities}
2544 begin if x>=0 then positive:=true
2545 else begin negate(x); positive:=false;
2546 end;
2547 t:=(x mod @'100000)*n;
2548 u:=(x div @'100000)*n+(t div @'100000);
2549 v:=(u mod d)*@'100000 + (t mod @'100000);
2550 if u div d>=@'100000 then arith_error:=true
2551 else u:=@'100000*(u div d) + (v div d);
2552 if positive then
2553 begin xn_over_d:=u; remainder:=v mod d;
2554 end
2555 else begin xn_over_d:=-u; remainder:=-(v mod d);
2556 end;
2557 end;
2558
2559 @ The next subroutine is used to compute the ``badness'' of glue, when a
2560 total~|t| is supposed to be made from amounts that sum to~|s|. According
2561 to {\sl The \TeX book}, the badness of this situation is $100(t/s)^3$;
2562 however, badness is simply a heuristic, so we need not squeeze out the
2563 last drop of accuracy when computing it. All we really want is an
2564 approximation that has similar properties.
2565 @:TeXbook}{\sl The \TeX book@>
2566
2567 The actual method used to compute the badness is easier to read from the
2568 program than to describe in words. It produces an integer value that is a
2569 reasonably close approximation to $100(t/s)^3$, and all implementations
2570 of \TeX\ should use precisely this method. Any badness of $2^{13}$ or more is
2571 treated as infinitely bad, and represented by 10000.
2572
2573 It is not difficult to prove that $$\hbox{|badness(t+1,s)>=badness(t,s)
2574 >=badness(t,s+1)|}.$$ The badness function defined here is capable of
2575 computing at most 1095 distinct values, but that is plenty.
2576
2577 @d inf_bad = 10000 {infinitely bad value}
2578
2579 @p function badness(@!t,@!s:scaled):halfword; {compute badness, given |t>=0|}
2580 var r:integer; {approximation to $\alpha t/s$, where $\alpha^3\approx
2581 100\cdot2^{18}$}
2582 begin if t=0 then badness:=0
2583 else if s<=0 then badness:=inf_bad
2584 else begin if t<=7230584 then r:=(t*297) div s {$297^3=99.94\times2^{18}$}
2585 else if s>=1663497 then r:=t div (s div 297)
2586 else r:=t;
2587 if r>1290 then badness:=inf_bad {$1290^3<2^{31}<1291^3$}
2588 else badness:=(r*r*r+@'400000) div @'1000000;
2589 end; {that was $r^3/2^{18}$, rounded to the nearest integer}
2590 end;
2591
2592 @ When \TeX\ ``packages'' a list into a box, it needs to calculate the
2593 proportionality ratio by which the glue inside the box should stretch
2594 or shrink. This calculation does not affect \TeX's decision making,
2595 so the precise details of rounding, etc., in the glue calculation are not
2596 of critical importance for the consistency of results on different computers.
2597
2598 We shall use the type |glue_ratio| for such proportionality ratios.
2599 A glue ratio should take the same amount of memory as an
2600 |integer| (usually 32 bits) if it is to blend smoothly with \TeX's
2601 other data structures. Thus |glue_ratio| should be equivalent to
2602 |short_real| in some implementations of \PASCAL. Alternatively,
2603 it is possible to deal with glue ratios using nothing but fixed-point
2604 arithmetic; see {\sl TUGboat \bf3},1 (March 1982), 10--27. (But the
2605 routines cited there must be modified to allow negative glue ratios.)
2606 @^system dependencies@>
2607
2608 @d set_glue_ratio_zero(#) == #:=0.0 {store the representation of zero ratio}
2609 @d set_glue_ratio_one(#) == #:=1.0 {store the representation of unit ratio}
2610 @d float(#) == # {convert from |glue_ratio| to type |real|}
2611 @d unfloat(#) == # {convert from |real| to type |glue_ratio|}
2612 @d float_constant(#) == #.0 {convert |integer| constant to |real|}
2613
2614 @<Types...@>=
2615 @!glue_ratio=real; {one-word representation of a glue expansion factor}
2616
2617 @* \[7b] Random numbers.
2618
2619 \font\tenlogo=logo10 % font used for the METAFONT logo
2620 \def\MP{{\tenlogo META}\-{\tenlogo POST}}
2621 \def\pdfTeX{pdf\TeX}
2622
2623 This section is (almost) straight from MetaPost. I had to change
2624 the types (use |integer| instead of |fraction|), but that should
2625 not have any influence on the actual calculations (the original
2626 comments refer to quantities like |fraction_four| ($2^{30}$), and
2627 that is the same as the numeric representation of |maxdimen|).
2628
2629 I've copied the low-level variables and routines that are needed, but
2630 only those (e.g. |m_log|), not the accompanying ones like |m_exp|. Most
2631 of the following low-level numeric routines are only needed within the
2632 calculation of |norm_rand|. I've been forced to rename |make_fraction|
2633 to |make_frac| because TeX already has a routine by that name with
2634 a wholly different function (it creates a |fraction_noad| for math
2635 typesetting) -- Taco
2636
2637 And now let's complete our collection of numeric utility routines
2638 by considering random number generation.
2639 \MP\ generates pseudo-random numbers with the additive scheme recommended
2640 in Section 3.6 of {\sl The Art of Computer Programming}; however, the
2641 results are random fractions between 0 and |fraction_one-1|, inclusive.
2642
2643 There's an auxiliary array |randoms| that contains 55 pseudo-random
2644 fractions. Using the recurrence $x_n=(x_{n-55}-x_{n-31})\bmod 2^{28}$,
2645 we generate batches of 55 new $x_n$'s at a time by calling |new_randoms|.
2646 The global variable |j_random| tells which element has most recently
2647 been consumed.
2648
2649 @<Glob...@>=
2650 @!randoms:array[0..54] of integer; {the last 55 random values generated}
2651 @!j_random:0..54; {the number of unused |randoms|}
2652 @!random_seed:scaled; {the default random seed}
2653
2654 @ A small bit of metafont is needed.
2655
2656 @d fraction_half==@'1000000000 {$2^{27}$, represents 0.50000000}
2657 @d fraction_one==@'2000000000 {$2^{28}$, represents 1.00000000}
2658 @d fraction_four==@'10000000000 {$2^{30}$, represents 4.00000000}
2659 @d el_gordo == @'17777777777 {$2^{31}-1$, the largest value that \MP\ likes}
2660 @d halfp(#)==(#) div 2
2661 @d double(#) == #:=#+# {multiply a variable by two}
2662
2663 @ The |make_frac| routine produces the |fraction| equivalent of
2664 |p/q|, given integers |p| and~|q|; it computes the integer
2665 $f=\lfloor2^{28}p/q+{1\over2}\rfloor$, when $p$ and $q$ are
2666 positive. If |p| and |q| are both of the same scaled type |t|,
2667 the ``type relation'' |make_frac(t,t)=fraction| is valid;
2668 and it's also possible to use the subroutine ``backwards,'' using
2669 the relation |make_frac(t,fraction)=t| between scaled types.
2670
2671 If the result would have magnitude $2^{31}$ or more, |make_frac|
2672 sets |arith_error:=true|. Most of \MP's internal computations have
2673 been designed to avoid this sort of error.
2674
2675 If this subroutine were programmed in assembly language on a typical
2676 machine, we could simply compute |(@t$2^{28}$@>*p)div q|, since a
2677 double-precision product can often be input to a fixed-point division
2678 instruction. But when we are restricted to \PASCAL\ arithmetic it
2679 is necessary either to resort to multiple-precision maneuvering
2680 or to use a simple but slow iteration. The multiple-precision technique
2681 would be about three times faster than the code adopted here, but it
2682 would be comparatively long and tricky, involving about sixteen
2683 additional multiplications and divisions.
2684
2685 This operation is part of \MP's ``inner loop''; indeed, it will
2686 consume nearly 10\pct! of the running time (exclusive of input and output)
2687 if the code below is left unchanged. A machine-dependent recoding
2688 will therefore make \MP\ run faster. The present implementation
2689 is highly portable, but slow; it avoids multiplication and division
2690 except in the initial stage. System wizards should be careful to
2691 replace it with a routine that is guaranteed to produce identical
2692 results in all cases.
2693 @^system dependencies@>
2694
2695 As noted below, a few more routines should also be replaced by machine-dependent
2696 code, for efficiency. But when a procedure is not part of the ``inner loop,''
2697 such changes aren't advisable; simplicity and robustness are
2698 preferable to trickery, unless the cost is too high.
2699 @^inner loop@>
2700
2701 @p function make_frac(@!p,@!q:integer):integer;
2702 var @!f:integer; {the fraction bits, with a leading 1 bit}
2703 @!n:integer; {the integer part of $\vert p/q\vert$}
2704 @!negative:boolean; {should the result be negated?}
2705 @!be_careful:integer; {disables certain compiler optimizations}
2706 begin if p>=0 then negative:=false
2707 else begin negate(p); negative:=true;
2708 end;
2709 if q<=0 then
2710 begin debug if q=0 then confusion("/");@;@+gubed@;@/
2711 @:this can't happen /}{\quad \./@>
2712 negate(q); negative:=not negative;
2713 end;
2714 n:=p div q; p:=p mod q;
2715 if n>=8 then
2716 begin arith_error:=true;
2717 if negative then make_frac:=-el_gordo@+else make_frac:=el_gordo;
2718 end
2719 else begin n:=(n-1)*fraction_one;
2720 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>;
2721 if negative then make_frac:=-(f+n)@+else make_frac:=f+n;
2722 end;
2723 end;
2724
2725 @ The |repeat| loop here preserves the following invariant relations
2726 between |f|, |p|, and~|q|:
2727 (i)~|0<=p<q|; (ii)~$fq+p=2^k(q+p_0)$, where $k$ is an integer and
2728 $p_0$ is the original value of~$p$.
2729
2730 Notice that the computation specifies
2731 |(p-q)+p| instead of |(p+p)-q|, because the latter could overflow.
2732 Let us hope that optimizing compilers do not miss this point; a
2733 special variable |be_careful| is used to emphasize the necessary
2734 order of computation. Optimizing compilers should keep |be_careful|
2735 in a register, not store it in memory.
2736 @^inner loop@>
2737
2738 @<Compute $f=\lfloor 2^{28}(1+p/q)+{1\over2}\rfloor$@>=
2739 f:=1;
2740 repeat be_careful:=p-q; p:=be_careful+p;
2741 if p>=0 then f:=f+f+1
2742 else begin double(f); p:=p+q;
2743 end;
2744 until f>=fraction_one;
2745 be_careful:=p-q;
2746 if be_careful+p>=0 then incr(f)
2747
2748 @
2749
2750 @p function take_frac(@!q:integer;@!f:integer):integer;
2751 var @!p:integer; {the fraction so far}
2752 @!negative:boolean; {should the result be negated?}
2753 @!n:integer; {additional multiple of $q$}
2754 @!be_careful:integer; {disables certain compiler optimizations}
2755 begin @<Reduce to the case that |f>=0| and |q>0|@>;
2756 if f<fraction_one then n:=0
2757 else begin n:=f div fraction_one; f:=f mod fraction_one;
2758 if q<=el_gordo div n then n:=n*q
2759 else begin arith_error:=true; n:=el_gordo;
2760 end;
2761 end;
2762 f:=f+fraction_one;
2763 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>;
2764 be_careful:=n-el_gordo;
2765 if be_careful+p>0 then
2766 begin arith_error:=true; n:=el_gordo-p;
2767 end;
2768 if negative then take_frac:=-(n+p)
2769 else take_frac:=n+p;
2770 end;
2771
2772 @ @<Reduce to the case that |f>=0| and |q>0|@>=
2773 if f>=0 then negative:=false
2774 else begin negate(f); negative:=true;
2775 end;
2776 if q<0 then
2777 begin negate(q); negative:=not negative;
2778 end;
2779
2780 @ The invariant relations in this case are (i)~$\lfloor(qf+p)/2^k\rfloor
2781 =\lfloor qf_0/2^{28}+{1\over2}\rfloor$, where $k$ is an integer and
2782 $f_0$ is the original value of~$f$; (ii)~$2^k\L f<2^{k+1}$.
2783 @^inner loop@>
2784
2785 @<Compute $p=\lfloor qf/2^{28}+{1\over2}\rfloor-q$@>=
2786 p:=fraction_half; {that's $2^{27}$; the invariants hold now with $k=28$}
2787 if q<fraction_four then
2788 repeat if odd(f) then p:=halfp(p+q)@+else p:=halfp(p);
2789 f:=halfp(f);
2790 until f=1
2791 else repeat if odd(f) then p:=p+halfp(q-p)@+else p:=halfp(p);
2792 f:=halfp(f);
2793 until f=1
2794
2795 @ The subroutines for logarithm and exponential involve two tables.
2796 The first is simple: |two_to_the[k]| equals $2^k$. The second involves
2797 a bit more calculation, which the author claims to have done correctly:
2798 |spec_log[k]| is $2^{27}$ times $\ln\bigl(1/(1-2^{-k})\bigr)=
2799 2^{-k}+{1\over2}2^{-2k}+{1\over3}2^{-3k}+\cdots\,$, rounded to the
2800 nearest integer.
2801
2802 @<Glob...@>=
2803 @!two_to_the:array[0..30] of integer; {powers of two}
2804 @!spec_log:array[1..28] of integer; {special logarithms}
2805
2806
2807 @ @<Set init...@>=
2808 two_to_the[0]:=1;
2809 for k:=1 to 30 do two_to_the[k]:=2*two_to_the[k-1];
2810 spec_log[1]:=93032640;
2811 spec_log[2]:=38612034;
2812 spec_log[3]:=17922280;
2813 spec_log[4]:=8662214;
2814 spec_log[5]:=4261238;
2815 spec_log[6]:=2113709;
2816 spec_log[7]:=1052693;
2817 spec_log[8]:=525315;
2818 spec_log[9]:=262400;
2819 spec_log[10]:=131136;
2820 spec_log[11]:=65552;
2821 spec_log[12]:=32772;
2822 spec_log[13]:=16385;
2823 for k:=14 to 27 do spec_log[k]:=two_to_the[27-k];
2824 spec_log[28]:=1;
2825
2826 @
2827
2828 @p function m_log(@!x:integer):integer;
2829 var @!y,@!z:integer; {auxiliary registers}
2830 @!k:integer; {iteration counter}
2831 begin if x<=0 then @<Handle non-positive logarithm@>
2832 else begin y:=1302456956+4-100; {$14\times2^{27}\ln2\approx1302456956.421063$}
2833 z:=27595+6553600; {and $2^{16}\times .421063\approx 27595$}
2834 while x<fraction_four do
2835 begin double(x); y:=y-93032639; z:=z-48782;
2836 end; {$2^{27}\ln2\approx 93032639.74436163$
2837 and $2^{16}\times.74436163\approx 48782$}
2838 y:=y+(z div unity); k:=2;
2839 while x>fraction_four+4 do
2840 @<Increase |k| until |x| can be multiplied by a
2841 factor of $2^{-k}$, and adjust $y$ accordingly@>;
2842 m_log:=y div 8;
2843 end;
2844 end;
2845
2846 @ @<Increase |k| until |x| can...@>=
2847 begin z:=((x-1) div two_to_the[k])+1; {$z=\lceil x/2^k\rceil$}
2848 while x<fraction_four+z do
2849 begin z:=halfp(z+1); k:=k+1;
2850 end;
2851 y:=y+spec_log[k]; x:=x-z;
2852 end
2853
2854 @ @<Handle non-positive logarithm@>=
2855 begin print_err("Logarithm of ");
2856 @.Logarithm...replaced by 0@>
2857 print_scaled(x); print(" has been replaced by 0");
2858 help2("Since I don't take logs of non-positive numbers,")@/
2859 ("I'm zeroing this one. Proceed, with fingers crossed.");
2860 error; m_log:=0;
2861 end
2862
2863 @ The following somewhat different subroutine tests rigorously if $ab$ is
2864 greater than, equal to, or less than~$cd$,
2865 given integers $(a,b,c,d)$. In most cases a quick decision is reached.
2866 The result is $+1$, 0, or~$-1$ in the three respective cases.
2867
2868 @d return_sign(#)==begin ab_vs_cd:=#; return;
2869 end
2870
2871 @p function ab_vs_cd(@!a,b,c,d:integer):integer;
2872 label exit;
2873 var @!q,@!r:integer; {temporary registers}
2874 begin @<Reduce to the case that |a,c>=0|, |b,d>0|@>;
2875 loop@+ begin q := a div d; r := c div b;
2876 if q<>r then
2877 if q>r then return_sign(1)@+else return_sign(-1);
2878 q := a mod d; r := c mod b;
2879 if r=0 then
2880 if q=0 then return_sign(0)@+else return_sign(1);
2881 if q=0 then return_sign(-1);
2882 a:=b; b:=q; c:=d; d:=r;
2883 end; {now |a>d>0| and |c>b>0|}
2884 exit:end;
2885
2886 @ @<Reduce to the case that |a...@>=
2887 if a<0 then
2888 begin negate(a); negate(b);
2889 end;
2890 if c<0 then
2891 begin negate(c); negate(d);
2892 end;
2893 if d<=0 then
2894 begin if b>=0 then
2895 if ((a=0)or(b=0))and((c=0)or(d=0)) then return_sign(0)
2896 else return_sign(1);
2897 if d=0 then
2898 if a=0 then return_sign(0)@+else return_sign(-1);
2899 q:=a; a:=c; c:=q; q:=-b; b:=-d; d:=q;
2900 end
2901 else if b<=0 then
2902 begin if b<0 then if a>0 then return_sign(-1);
2903 if c=0 then return_sign(0) else return_sign(-1);
2904 end
2905
2906 @ To consume a random integer, the program below will say `|next_random|'
2907 and then it will fetch |randoms[j_random]|.
2908
2909 @d next_random==if j_random=0 then new_randoms
2910 else decr(j_random)
2911
2912 @p procedure new_randoms;
2913 var @!k:0..54; {index into |randoms|}
2914 @!x:integer; {accumulator}
2915 begin for k:=0 to 23 do
2916 begin x:=randoms[k]-randoms[k+31];
2917 if x<0 then x:=x+fraction_one;
2918 randoms[k]:=x;
2919 end;
2920 for k:=24 to 54 do
2921 begin x:=randoms[k]-randoms[k-24];
2922 if x<0 then x:=x+fraction_one;
2923 randoms[k]:=x;
2924 end;
2925 j_random:=54;
2926 end;
2927
2928 @ To initialize the |randoms| table, we call the following routine.
2929
2930 @p procedure init_randoms(@!seed:integer);
2931 var @!j,@!jj,@!k:integer; {more or less random integers}
2932 @!i:0..54; {index into |randoms|}
2933 begin j:=abs(seed);
2934 while j>=fraction_one do j:=halfp(j);
2935 k:=1;
2936 for i:=0 to 54 do
2937 begin jj:=k; k:=j-k; j:=jj;
2938 if k<0 then k:=k+fraction_one;
2939 randoms[(i*21)mod 55]:=j;
2940 end;
2941 new_randoms; new_randoms; new_randoms; {``warm up'' the array}
2942 end;
2943
2944 @ To produce a uniform random number in the range |0<=u<x| or |0>=u>x|
2945 or |0=u=x|, given a |scaled| value~|x|, we proceed as shown here.
2946
2947 Note that the call of |take_frac| will produce the values 0 and~|x|
2948 with about half the probability that it will produce any other particular
2949 values between 0 and~|x|, because it rounds its answers.
2950
2951 @p function unif_rand(@!x:integer):integer;
2952 var @!y:integer; {trial value}
2953 begin next_random; y:=take_frac(abs(x),randoms[j_random]);
2954 if y=abs(x) then unif_rand:=0
2955 else if x>0 then unif_rand:=y
2956 else unif_rand:=-y;
2957 end;
2958
2959 @ Finally, a normal deviate with mean zero and unit standard deviation
2960 can readily be obtained with the ratio method (Algorithm 3.4.1R in
2961 {\sl The Art of Computer Programming\/}).
2962
2963 @p function norm_rand:integer;
2964 var @!x,@!u,@!l:integer; {what the book would call $2^{16}X$, $2^{28}U$,
2965 and $-2^{24}\ln U$}
2966 begin repeat
2967 repeat next_random;
2968 x:=take_frac(112429,randoms[j_random]-fraction_half);
2969 {$2^{16}\sqrt{8/e}\approx 112428.82793$}
2970 next_random; u:=randoms[j_random];
2971 until abs(x)<u;
2972 x:=make_frac(x,u);
2973 l:=139548960-m_log(u); {$2^{24}\cdot12\ln2\approx139548959.6165$}
2974 until ab_vs_cd(1024,l,x,x)>=0;
2975 norm_rand:=x;
2976 end;
2977
2978 @* \[8] Packed data.
2979 In order to make efficient use of storage space, \TeX\ bases its major data
2980 structures on a |memory_word|, which contains either a (signed) integer,
2981 possibly scaled, or a (signed) |glue_ratio|, or a small number of
2982 fields that are one half or one quarter of the size used for storing
2983 integers.
2984
2985 If |x| is a variable of type |memory_word|, it contains up to four
2986 fields that can be referred to as follows:
2987 $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
2988 |x|&.|int|&(an |integer|)\cr
2989 |x|&.|sc|\qquad&(a |scaled| integer)\cr
2990 |x|&.|gr|&(a |glue_ratio|)\cr
2991 |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
2992 |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
2993 field)\cr
2994 |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
2995 &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
2996 This is somewhat cumbersome to write, and not very readable either, but
2997 macros will be used to make the notation shorter and more transparent.
2998 The \PASCAL\ code below gives a formal definition of |memory_word| and
2999 its subsidiary types, using packed variant records. \TeX\ makes no
3000 assumptions about the relative positions of the fields within a word.
3001
3002 Since we are assuming 32-bit integers, a halfword must contain at least
3003 16 bits, and a quarterword must contain at least 8 bits.
3004 @^system dependencies@>
3005 But it doesn't hurt to have more bits; for example, with enough 36-bit
3006 words you might be able to have |mem_max| as large as 262142, which is
3007 eight times as much memory as anybody had during the first four years of
3008 \TeX's existence.
3009
3010 N.B.: Valuable memory space will be dreadfully wasted unless \TeX\ is compiled
3011 by a \PASCAL\ that packs all of the |memory_word| variants into
3012 the space of a single integer. This means, for example, that |glue_ratio|
3013 words should be |short_real| instead of |real| on some computers. Some
3014 \PASCAL\ compilers will pack an integer whose subrange is `|0..255|' into
3015 an eight-bit field, but others insist on allocating space for an additional
3016 sign bit; on such systems you can get 256 values into a quarterword only
3017 if the subrange is `|-128..127|'.
3018
3019 The present implementation tries to accommodate as many variations as possible,
3020 so it makes few assumptions. If integers having the subrange
3021 `|min_quarterword..max_quarterword|' can be packed into a quarterword,
3022 and if integers having the subrange `|min_halfword..max_halfword|'
3023 can be packed into a halfword, everything should work satisfactorily.
3024
3025 It is usually most efficient to have |min_quarterword=min_halfword=0|,
3026 so one should try to achieve this unless it causes a severe problem.
3027 The values defined here are recommended for most 32-bit computers.
3028
3029 @d min_quarterword=0 {smallest allowable value in a |quarterword|}
3030 @d max_quarterword=@"FFFF {largest allowable value in a |quarterword|}
3031 @d min_halfword==-@"FFFFFFF {smallest allowable value in a |halfword|}
3032 @d max_halfword==@"3FFFFFFF {largest allowable value in a |halfword|}
3033
3034 @ Here are the inequalities that the quarterword and halfword values
3035 must satisfy (or rather, the inequalities that they mustn't satisfy):
3036
3037 @<Check the ``constant''...@>=
3038 init if (mem_min<>mem_bot)or(mem_max<>mem_top) then bad:=10;@+tini@;@/
3039 if (mem_min>mem_bot)or(mem_max<mem_top) then bad:=10;
3040 if (min_quarterword>0)or(max_quarterword<@"7FFF) then bad:=11;
3041 if (min_halfword>0)or(max_halfword<@"3FFFFFFF) then bad:=12;
3042 if (min_quarterword<min_halfword)or@|
3043 (max_quarterword>max_halfword) then bad:=13;
3044 if (mem_min<min_halfword)or(mem_max>=max_halfword)or@|
3045 (mem_bot-mem_min>max_halfword+1) then bad:=14;
3046 if (font_base<min_quarterword)or(font_max>max_quarterword) then bad:=15;
3047 if font_max>font_base+256 then bad:=16;
3048 if (save_size>max_halfword)or(max_strings>max_halfword) then bad:=17;
3049 if buf_size>max_halfword then bad:=18;
3050 if max_quarterword-min_quarterword<@"FFFF then bad:=19;
3051
3052 @ The operation of adding or subtracting |min_quarterword| occurs quite
3053 frequently in \TeX, so it is convenient to abbreviate this operation
3054 by using the macros |qi| and |qo| for input and output to and from
3055 quarterword format.
3056
3057 The inner loop of \TeX\ will run faster with respect to compilers
3058 that don't optimize expressions like `|x+0|' and `|x-0|', if these
3059 macros are simplified in the obvious way when |min_quarterword=0|.
3060 @^inner loop@>@^system dependencies@>
3061
3062 @d qi(#)==#+min_quarterword
3063 {to put an |eight_bits| item into a quarterword}
3064 @d qo(#)==#-min_quarterword
3065 {to take an |eight_bits| item out of a quarterword}
3066 @d hi(#)==#+min_halfword
3067 {to put a sixteen-bit item into a halfword}
3068 @d ho(#)==#-min_halfword
3069 {to take a sixteen-bit item from a halfword}
3070
3071 @ The reader should study the following definitions closely:
3072 @^system dependencies@>
3073
3074 @d sc==int {|scaled| data is equivalent to |integer|}
3075
3076 @<Types...@>=
3077 @!quarterword = min_quarterword..max_quarterword; {1/4 of a word}
3078 @!halfword=min_halfword..max_halfword; {1/2 of a word}
3079 @!two_choices = 1..2; {used when there are two variants in a record}
3080 @!four_choices = 1..4; {used when there are four variants in a record}
3081 @!two_halves = packed record@;@/
3082 @!rh:halfword;
3083 case two_choices of
3084 1: (@!lh:halfword);
3085 2: (@!b0:quarterword; @!b1:quarterword);
3086 end;
3087 @!four_quarters = packed record@;@/
3088 @!b0:quarterword;
3089 @!b1:quarterword;
3090 @!b2:quarterword;
3091 @!b3:quarterword;
3092 end;
3093 @!memory_word = record@;@/
3094 case four_choices of
3095 1: (@!int:integer);
3096 2: (@!gr:glue_ratio);
3097 3: (@!hh:two_halves);
3098 4: (@!qqqq:four_quarters);
3099 end;
3100 @!word_file = gzFile;
3101
3102 @ When debugging, we may want to print a |memory_word| without knowing
3103 what type it is; so we print it in all modes.
3104 @^dirty \PASCAL@>@^debugging@>
3105
3106 @p @!debug procedure print_word(@!w:memory_word);
3107 {prints |w| in all ways}
3108 begin print_int(w.int); print_char(" ");@/
3109 print_scaled(w.sc); print_char(" ");@/
3110 print_scaled(round(unity*float(w.gr))); print_ln;@/
3111 @^real multiplication@>
3112 print_int(w.hh.lh); print_char("="); print_int(w.hh.b0); print_char(":");
3113 print_int(w.hh.b1); print_char(";"); print_int(w.hh.rh); print_char(" ");@/
3114 print_int(w.qqqq.b0); print_char(":"); print_int(w.qqqq.b1); print_char(":");
3115 print_int(w.qqqq.b2); print_char(":"); print_int(w.qqqq.b3);
3116 end;
3117 gubed
3118
3119 @* \[9] Dynamic memory allocation.
3120 The \TeX\ system does nearly all of its own memory allocation, so that it
3121 can readily be transported into environments that do not have automatic
3122 facilities for strings, garbage collection, etc., and so that it can be in
3123 control of what error messages the user receives. The dynamic storage
3124 requirements of \TeX\ are handled by providing a large array |mem| in
3125 which consecutive blocks of words are used as nodes by the \TeX\ routines.
3126
3127 Pointer variables are indices into this array, or into another array
3128 called |eqtb| that will be explained later. A pointer variable might
3129 also be a special flag that lies outside the bounds of |mem|, so we
3130 allow pointers to assume any |halfword| value. The minimum halfword
3131 value represents a null pointer. \TeX\ does not assume that |mem[null]| exists.
3132
3133 @d pointer==halfword {a flag or a location in |mem| or |eqtb|}
3134 @d null==min_halfword {the null pointer}
3135
3136 @<Glob...@>=
3137 @!temp_ptr:pointer; {a pointer variable for occasional emergency use}
3138
3139 @ The |mem| array is divided into two regions that are allocated separately,
3140 but the dividing line between these two regions is not fixed; they grow
3141 together until finding their ``natural'' size in a particular job.
3142 Locations less than or equal to |lo_mem_max| are used for storing
3143 variable-length records consisting of two or more words each. This region
3144 is maintained using an algorithm similar to the one described in exercise
3145 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
3146 appears in the allocated nodes; the program is responsible for knowing the
3147 relevant size when a node is freed. Locations greater than or equal to
3148 |hi_mem_min| are used for storing one-word records; a conventional
3149 \.{AVAIL} stack is used for allocation in this region.
3150
3151 Locations of |mem| between |mem_bot| and |mem_top| may be dumped as part
3152 of preloaded format files, by the \.{INITEX} preprocessor.
3153 @.INITEX@>
3154 Production versions of \TeX\ may extend the memory at both ends in order to
3155 provide more space; locations between |mem_min| and |mem_bot| are always
3156 used for variable-size nodes, and locations between |mem_top| and |mem_max|
3157 are always used for single-word nodes.
3158
3159 The key pointers that govern |mem| allocation have a prescribed order:
3160 $$\advance\thickmuskip-2mu
3161 \hbox{|null<=mem_min<=mem_bot<lo_mem_max<
3162 hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
3163
3164 Empirical tests show that the present implementation of \TeX\ tends to
3165 spend about 9\pct! of its running time allocating nodes, and about 6\pct!
3166 deallocating them after their use.
3167
3168 @<Glob...@>=
3169 @!mem : array[mem_min..mem_max] of memory_word; {the big dynamic storage area}
3170 @!lo_mem_max : pointer; {the largest location of variable-size memory in use}
3171 @!hi_mem_min : pointer; {the smallest location of one-word memory in use}
3172
3173 @ In order to study the memory requirements of particular applications, it
3174 is possible to prepare a version of \TeX\ that keeps track of current and
3175 maximum memory usage. When code between the delimiters |@!stat| $\ldots$
3176 |tats| is not ``commented out,'' \TeX\ will run a bit slower but it will
3177 report these statistics when |tracing_stats| is sufficiently large.
3178
3179 @<Glob...@>=
3180 @!var_used, @!dyn_used : integer; {how much memory is in use}
3181
3182 @ Let's consider the one-word memory region first, since it's the
3183 simplest. The pointer variable |mem_end| holds the highest-numbered location
3184 of |mem| that has ever been used. The free locations of |mem| that
3185 occur between |hi_mem_min| and |mem_end|, inclusive, are of type
3186 |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
3187 and |rh| fields of |mem[p]| when it is of this type. The single-word
3188 free locations form a linked list
3189 $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
3190 terminated by |null|.
3191
3192 @d link(#) == mem[#].hh.rh {the |link| field of a memory word}
3193 @d info(#) == mem[#].hh.lh {the |info| field of a memory word}
3194
3195 @<Glob...@>=
3196 @!avail : pointer; {head of the list of available one-word nodes}
3197 @!mem_end : pointer; {the last one-word node used in |mem|}
3198
3199 @ If memory is exhausted, it might mean that the user has forgotten
3200 a right brace. We will define some procedures later that try to help
3201 pinpoint the trouble.
3202
3203 @p @<Declare the procedure called |show_token_list|@>@/
3204 @<Declare the procedure called |runaway|@>
3205
3206 @ The function |get_avail| returns a pointer to a new one-word node whose
3207 |link| field is null. However, \TeX\ will halt if there is no more room left.
3208 @^inner loop@>
3209
3210 If the available-space list is empty, i.e., if |avail=null|,
3211 we try first to increase |mem_end|. If that cannot be done, i.e., if
3212 |mem_end=mem_max|, we try to decrease |hi_mem_min|. If that cannot be
3213 done, i.e., if |hi_mem_min=lo_mem_max+1|, we have to quit.
3214
3215 @p function get_avail : pointer; {single-word node allocation}
3216 var p:pointer; {the new node being got}
3217 begin p:=avail; {get top location in the |avail| stack}
3218 if p<>null then avail:=link(avail) {and pop it off}
3219 else if mem_end<mem_max then {or go into virgin territory}
3220 begin incr(mem_end); p:=mem_end;
3221 end
3222 else begin decr(hi_mem_min); p:=hi_mem_min;
3223 if hi_mem_min<=lo_mem_max then
3224 begin runaway; {if memory is exhausted, display possible runaway text}
3225 overflow("main memory size",mem_max+1-mem_min);
3226 {quit; all one-word nodes are busy}
3227 @:TeX capacity exceeded main memory size}{\quad main memory size@>
3228 end;
3229 end;
3230 link(p):=null; {provide an oft-desired initialization of the new node}
3231 @!stat incr(dyn_used);@+tats@;{maintain statistics}
3232 get_avail:=p;
3233 end;
3234
3235 @ Conversely, a one-word node is recycled by calling |free_avail|.
3236 This routine is part of \TeX's ``inner loop,'' so we want it to be fast.
3237 @^inner loop@>
3238
3239 @d free_avail(#)== {single-word node liberation}
3240 begin link(#):=avail; avail:=#;
3241 @!stat decr(dyn_used);@+tats@/
3242 end
3243
3244 @ There's also a |fast_get_avail| routine, which saves the procedure-call
3245 overhead at the expense of extra programming. This routine is used in
3246 the places that would otherwise account for the most calls of |get_avail|.
3247 @^inner loop@>
3248
3249 @d fast_get_avail(#)==@t@>@;@/
3250 begin #:=avail; {avoid |get_avail| if possible, to save time}
3251 if #=null then #:=get_avail
3252 else begin avail:=link(#); link(#):=null;
3253 @!stat incr(dyn_used);@+tats@/
3254 end;
3255 end
3256
3257 @ The procedure |flush_list(p)| frees an entire linked list of
3258 one-word nodes that starts at position |p|.
3259 @^inner loop@>
3260
3261 @p procedure flush_list(@!p:pointer); {makes list of single-word nodes
3262 available}
3263 var @!q,@!r:pointer; {list traversers}
3264 begin if p<>null then
3265 begin r:=p;
3266 repeat q:=r; r:=link(r); @!stat decr(dyn_used);@+tats@/
3267 until r=null; {now |q| is the last node on the list}
3268 link(q):=avail; avail:=p;
3269 end;
3270 end;
3271
3272 @ The available-space list that keeps track of the variable-size portion
3273 of |mem| is a nonempty, doubly-linked circular list of empty nodes,
3274 pointed to by the roving pointer |rover|.
3275
3276 Each empty node has size 2 or more; the first word contains the special
3277 value |max_halfword| in its |link| field and the size in its |info| field;
3278 the second word contains the two pointers for double linking.
3279
3280 Each nonempty node also has size 2 or more. Its first word is of type
3281 |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
3282 Otherwise there is complete flexibility with respect to the contents
3283 of its other fields and its other words.
3284
3285 (We require |mem_max<max_halfword| because terrible things can happen
3286 when |max_halfword| appears in the |link| field of a nonempty node.)
3287
3288 @d empty_flag == max_halfword {the |link| of an empty variable-size node}
3289 @d is_empty(#) == (link(#)=empty_flag) {tests for empty node}
3290 @d node_size == info {the size field in empty variable-size nodes}
3291 @d llink(#) == info(#+1) {left link in doubly-linked list of empty nodes}
3292 @d rlink(#) == link(#+1) {right link in doubly-linked list of empty nodes}
3293
3294 @<Glob...@>=
3295 @!rover : pointer; {points to some node in the list of empties}
3296
3297 @ A call to |get_node| with argument |s| returns a pointer to a new node
3298 of size~|s|, which must be 2~or more. The |link| field of the first word
3299 of this new node is set to null. An overflow stop occurs if no suitable
3300 space exists.
3301
3302 If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
3303 areas and returns the value |max_halfword|.
3304
3305 @p function get_node(@!s:integer):pointer; {variable-size node allocation}
3306 label found,exit,restart;
3307 var p:pointer; {the node currently under inspection}
3308 @!q:pointer; {the node physically after node |p|}
3309 @!r:integer; {the newly allocated node, or a candidate for this honor}
3310 @!t:integer; {temporary register}
3311 begin restart: p:=rover; {start at some free node in the ring}
3312 repeat @<Try to allocate within node |p| and its physical successors,
3313 and |goto found| if allocation was possible@>;
3314 @^inner loop@>
3315 p:=rlink(p); {move to the next node in the ring}
3316 until p=rover; {repeat until the whole list has been traversed}
3317 if s=@'10000000000 then
3318 begin get_node:=max_halfword; return;
3319 end;
3320 if lo_mem_max+2<hi_mem_min then if lo_mem_max+2<=mem_bot+max_halfword then
3321 @<Grow more variable-size memory and |goto restart|@>;
3322 overflow("main memory size",mem_max+1-mem_min);
3323 {sorry, nothing satisfactory is left}
3324 @:TeX capacity exceeded main memory size}{\quad main memory size@>
3325 found: link(r):=null; {this node is now nonempty}
3326 @!stat var_used:=var_used+s; {maintain usage statistics}
3327 tats@;@/
3328 get_node:=r;
3329 exit:end;
3330
3331 @ The lower part of |mem| grows by 1000 words at a time, unless
3332 we are very close to going under. When it grows, we simply link
3333 a new node into the available-space list. This method of controlled
3334 growth helps to keep the |mem| usage consecutive when \TeX\ is
3335 implemented on ``virtual memory'' systems.
3336 @^virtual memory@>
3337
3338 @<Grow more variable-size memory and |goto restart|@>=
3339 begin if hi_mem_min-lo_mem_max>=1998 then t:=lo_mem_max+1000
3340 else t:=lo_mem_max+1+(hi_mem_min-lo_mem_max) div 2;
3341 {|lo_mem_max+2<=t<hi_mem_min|}
3342 p:=llink(rover); q:=lo_mem_max; rlink(p):=q; llink(rover):=q;@/
3343 if t>mem_bot+max_halfword then t:=mem_bot+max_halfword;
3344 rlink(q):=rover; llink(q):=p; link(q):=empty_flag; node_size(q):=t-lo_mem_max;@/
3345 lo_mem_max:=t; link(lo_mem_max):=null; info(lo_mem_max):=null;
3346 rover:=q; goto restart;
3347 end
3348
3349 @ Empirical tests show that the routine in this section performs a
3350 node-merging operation about 0.75 times per allocation, on the average,
3351 after which it finds that |r>p+1| about 95\pct! of the time.
3352
3353 @<Try to allocate...@>=
3354 q:=p+node_size(p); {find the physical successor}
3355 @^inner loop@>
3356 while is_empty(q) do {merge node |p| with node |q|}
3357 begin t:=rlink(q);
3358 if q=rover then rover:=t;
3359 llink(t):=llink(q); rlink(llink(q)):=t;@/
3360 q:=q+node_size(q);
3361 end;
3362 r:=q-s;
3363 if r>p+1 then @<Allocate from the top of node |p| and |goto found|@>;
3364 if r=p then if rlink(p)<>p then
3365 @<Allocate entire node |p| and |goto found|@>;
3366 node_size(p):=q-p {reset the size in case it grew}
3367
3368 @ @<Allocate from the top...@>=
3369 begin node_size(p):=r-p; {store the remaining size}
3370 @^inner loop@>
3371 rover:=p; {start searching here next time}
3372 goto found;
3373 end
3374
3375 @ Here we delete node |p| from the ring, and let |rover| rove around.
3376
3377 @<Allocate entire...@>=
3378 begin rover:=rlink(p); t:=llink(p);
3379 llink(rover):=t; rlink(t):=rover;
3380 goto found;
3381 end
3382
3383 @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
3384 the operation |free_node(p,s)| will make its words available, by inserting
3385 |p| as a new empty node just before where |rover| now points.
3386 @^inner loop@>
3387
3388 @p procedure free_node(@!p:pointer; @!s:halfword); {variable-size node
3389 liberation}
3390 var q:pointer; {|llink(rover)|}
3391 begin node_size(p):=s; link(p):=empty_flag;
3392 q:=llink(rover); llink(p):=q; rlink(p):=rover; {set both links}
3393 llink(rover):=p; rlink(q):=p; {insert |p| into the ring}
3394 @!stat var_used:=var_used-s;@+tats@;{maintain statistics}
3395 end;
3396
3397 @ Just before \.{INITEX} writes out the memory, it sorts the doubly linked
3398 available space list. The list is probably very short at such times, so a
3399 simple insertion sort is used. The smallest available location will be
3400 pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
3401
3402 @p @!init procedure sort_avail; {sorts the available variable-size nodes
3403 by location}
3404 var p,@!q,@!r: pointer; {indices into |mem|}
3405 @!old_rover:pointer; {initial |rover| setting}
3406 begin p:=get_node(@'10000000000); {merge adjacent free areas}
3407 p:=rlink(rover); rlink(rover):=max_halfword; old_rover:=rover;
3408 while p<>old_rover do @<Sort \(p)|p| into the list starting at |rover|
3409 and advance |p| to |rlink(p)|@>;
3410 p:=rover;
3411 while rlink(p)<>max_halfword do
3412 begin llink(rlink(p)):=p; p:=rlink(p);
3413 end;
3414 rlink(p):=rover; llink(rover):=p;
3415 end;
3416 tini
3417
3418 @ The following |while| loop is guaranteed to
3419 terminate, since the list that starts at
3420 |rover| ends with |max_halfword| during the sorting procedure.
3421
3422 @<Sort \(p)|p|...@>=
3423 if p<rover then
3424 begin q:=p; p:=rlink(q); rlink(q):=rover; rover:=q;
3425 end
3426 else begin q:=rover;
3427 while rlink(q)<p do q:=rlink(q);
3428 r:=rlink(p); rlink(p):=rlink(q); rlink(q):=p; p:=r;
3429 end
3430
3431 @* \[10] Data structures for boxes and their friends.
3432 From the computer's standpoint, \TeX's chief mission is to create
3433 horizontal and vertical lists. We shall now investigate how the elements
3434 of these lists are represented internally as nodes in the dynamic memory.
3435
3436 A horizontal or vertical list is linked together by |link| fields in
3437 the first word of each node. Individual nodes represent boxes, glue,
3438 penalties, or special things like discretionary hyphens; because of this
3439 variety, some nodes are longer than others, and we must distinguish different
3440 kinds of nodes. We do this by putting a `|type|' field in the first word,
3441 together with the link and an optional `|subtype|'.
3442
3443 @d type(#) == mem[#].hh.b0 {identifies what kind of node this is}
3444 @d subtype(#) == mem[#].hh.b1 {secondary identification in some cases}
3445
3446 @ A |@!char_node|, which represents a single character, is the most important
3447 kind of node because it accounts for the vast majority of all boxes.
3448 Special precautions are therefore taken to ensure that a |char_node| does
3449 not take up much memory space. Every such node is one word long, and in fact
3450 it is identifiable by this property, since other kinds of nodes have at least
3451 two words, and they appear in |mem| locations less than |hi_mem_min|.
3452 This makes it possible to omit the |type| field in a |char_node|, leaving
3453 us room for two bytes that identify a |font| and a |character| within
3454 that font.
3455
3456 Note that the format of a |char_node| allows for up to 256 different
3457 fonts and up to 256 characters per font; but most implementations will
3458 probably limit the total number of fonts to fewer than 75 per job,
3459 and most fonts will stick to characters whose codes are
3460 less than 128 (since higher codes
3461 are more difficult to access on most keyboards).
3462
3463 Extensions of \TeX\ intended for oriental languages will need even more
3464 than $256\times256$ possible characters, when we consider different sizes
3465 @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
3466 and styles of type. It is suggested that Chinese and Japanese fonts be
3467 handled by representing such characters in two consecutive |char_node|
3468 entries: The first of these has |font=font_base|, and its |link| points
3469 to the second;
3470 the second identifies the font and the character dimensions.
3471 The saving feature about oriental characters is that most of them have
3472 the same box dimensions. The |character| field of the first |char_node|
3473 is a ``\\{charext}'' that distinguishes between graphic symbols whose
3474 dimensions are identical for typesetting purposes. (See the \MF\ manual.)
3475 Such an extension of \TeX\ would not be difficult; further details are
3476 left to the reader.
3477
3478 In order to make sure that the |character| code fits in a quarterword,
3479 \TeX\ adds the quantity |min_quarterword| to the actual code.
3480
3481 Character nodes appear only in horizontal lists, never in vertical lists.
3482
3483 @d is_char_node(#) == (#>=hi_mem_min)
3484 {does the argument point to a |char_node|?}
3485 @d font == type {the font code in a |char_node|}
3486 @d character == subtype {the character code in a |char_node|}
3487
3488 @ An |hlist_node| stands for a box that was made from a horizontal list.
3489 Each |hlist_node| is seven words long, and contains the following fields
3490 (in addition to the mandatory |type| and |link|, which we shall not
3491 mention explicitly when discussing the other node types): The |height| and
3492 |width| and |depth| are scaled integers denoting the dimensions of the
3493 box. There is also a |shift_amount| field, a scaled integer indicating
3494 how much this box should be lowered (if it appears in a horizontal list),
3495 or how much it should be moved to the right (if it appears in a vertical
3496 list). There is a |list_ptr| field, which points to the beginning of the
3497 list from which this box was fabricated; if |list_ptr| is |null|, the box
3498 is empty. Finally, there are three fields that represent the setting of
3499 the glue: |glue_set(p)| is a word of type |glue_ratio| that represents
3500 the proportionality constant for glue setting; |glue_sign(p)| is
3501 |stretching| or |shrinking| or |normal| depending on whether or not the
3502 glue should stretch or shrink or remain rigid; and |glue_order(p)|
3503 specifies the order of infinity to which glue setting applies (|normal|,
3504 |fil|, |fill|, or |filll|). The |subtype| field is not used in \TeX.
3505 In \eTeX\ the |subtype| field records the box direction mode |box_lr|.
3506
3507 @d hlist_node=0 {|type| of hlist nodes}
3508 @d box_node_size=7 {number of words to allocate for a box node}
3509 @d width_offset=1 {position of |width| field in a box node}
3510 @d depth_offset=2 {position of |depth| field in a box node}
3511 @d height_offset=3 {position of |height| field in a box node}
3512 @d width(#) == mem[#+width_offset].sc {width of the box, in sp}
3513 @d depth(#) == mem[#+depth_offset].sc {depth of the box, in sp}
3514 @d height(#) == mem[#+height_offset].sc {height of the box, in sp}
3515 @d shift_amount(#) == mem[#+4].sc {repositioning distance, in sp}
3516 @d list_offset=5 {position of |list_ptr| field in a box node}
3517 @d list_ptr(#) == link(#+list_offset) {beginning of the list inside the box}
3518 @d glue_order(#) == subtype(#+list_offset) {applicable order of infinity}
3519 @d glue_sign(#) == type(#+list_offset) {stretching or shrinking}
3520 @d normal=0 {the most common case when several cases are named}
3521 @d stretching = 1 {glue setting applies to the stretch components}
3522 @d shrinking = 2 {glue setting applies to the shrink components}
3523 @d glue_offset = 6 {position of |glue_set| in a box node}
3524 @d glue_set(#) == mem[#+glue_offset].gr
3525 {a word of type |glue_ratio| for glue setting}
3526
3527 @ The |new_null_box| function returns a pointer to an |hlist_node| in
3528 which all subfields have the values corresponding to `\.{\\hbox\{\}}'.
3529 (The |subtype| field is set to |min_quarterword|, for historic reasons
3530 that are no longer relevant.)
3531
3532 @p function new_null_box:pointer; {creates a new box node}
3533 var p:pointer; {the new node}
3534 begin p:=get_node(box_node_size); type(p):=hlist_node;
3535 subtype(p):=min_quarterword;
3536 width(p):=0; depth(p):=0; height(p):=0; shift_amount(p):=0; list_ptr(p):=null;
3537 glue_sign(p):=normal; glue_order(p):=normal; set_glue_ratio_zero(glue_set(p));
3538 new_null_box:=p;
3539 end;
3540
3541 @ A |vlist_node| is like an |hlist_node| in all respects except that it
3542 contains a vertical list.
3543
3544 @d vlist_node=1 {|type| of vlist nodes}
3545
3546 @ A |rule_node| stands for a solid black rectangle; it has |width|,
3547 |depth|, and |height| fields just as in an |hlist_node|. However, if
3548 any of these dimensions is $-2^{30}$, the actual value will be determined
3549 by running the rule up to the boundary of the innermost enclosing box.
3550 This is called a ``running dimension.'' The |width| is never running in
3551 an hlist; the |height| and |depth| are never running in a~vlist.
3552
3553 @d rule_node=2 {|type| of rule nodes}
3554 @d rule_node_size=4 {number of words to allocate for a rule node}
3555 @d null_flag==-@'10000000000 {$-2^{30}$, signifies a missing item}
3556 @d is_running(#) == (#=null_flag) {tests for a running dimension}
3557
3558 @ A new rule node is delivered by the |new_rule| function. It
3559 makes all the dimensions ``running,'' so you have to change the
3560 ones that are not allowed to run.
3561
3562 @p function new_rule:pointer;
3563 var p:pointer; {the new node}
3564 begin p:=get_node(rule_node_size); type(p):=rule_node;
3565 subtype(p):=0; {the |subtype| is not used}
3566 width(p):=null_flag; depth(p):=null_flag; height(p):=null_flag;
3567 new_rule:=p;
3568 end;
3569
3570 @ Insertions are represented by |ins_node| records, where the |subtype|
3571 indicates the corresponding box number. For example, `\.{\\insert 250}'
3572 leads to an |ins_node| whose |subtype| is |250+min_quarterword|.
3573 The |height| field of an |ins_node| is slightly misnamed; it actually holds
3574 the natural height plus depth of the vertical list being inserted.
3575 The |depth| field holds the |split_max_depth| to be used in case this
3576 insertion is split, and the |split_top_ptr| points to the corresponding
3577 |split_top_skip|. The |float_cost| field holds the |floating_penalty| that
3578 will be used if this insertion floats to a subsequent page after a
3579 split insertion of the same class. There is one more field, the
3580 |ins_ptr|, which points to the beginning of the vlist for the insertion.
3581
3582 @d ins_node=3 {|type| of insertion nodes}
3583 @d ins_node_size=5 {number of words to allocate for an insertion}
3584 @d float_cost(#)==mem[#+1].int {the |floating_penalty| to be used}
3585 @d ins_ptr(#)==info(#+4) {the vertical list to be inserted}
3586 @d split_top_ptr(#)==link(#+4) {the |split_top_skip| to be used}
3587
3588 @ A |mark_node| has a |mark_ptr| field that points to the reference count
3589 of a token list that contains the user's \.{\\mark} text.
3590 In addition there is a |mark_class| field that contains the mark class.
3591
3592 @d mark_node=4 {|type| of a mark node}
3593 @d small_node_size=2 {number of words to allocate for most node types}
3594 @d mark_ptr(#)==link(#+1) {head of the token list for a mark}
3595 @d mark_class(#)==info(#+1) {the mark class}
3596
3597 @ An |adjust_node|, which occurs only in horizontal lists,
3598 specifies material that will be moved out into the surrounding
3599 vertical list; i.e., it is used to implement \TeX's `\.{\\vadjust}'
3600 operation. The |adjust_ptr| field points to the vlist containing this
3601 material.
3602
3603 @d adjust_node=5 {|type| of an adjust node}
3604 @d adjust_pre == subtype {|if subtype <>0| it is pre-adjustment}
3605 @#{|append_list| is used to append a list to |tail|}
3606 @d append_list(#) == begin link(tail):=link(#); append_list_end
3607 @d append_list_end(#) == tail:=#; end
3608 @d adjust_ptr(#)==mem[#+1].int
3609 {vertical list to be moved out of horizontal list}
3610
3611 @ A |ligature_node|, which occurs only in horizontal lists, specifies
3612 a character that was fabricated from the interaction of two or more
3613 actual characters. The second word of the node, which is called the
3614 |lig_char| word, contains |font| and |character| fields just as in a
3615 |char_node|. The characters that generated the ligature have not been
3616 forgotten, since they are needed for diagnostic messages and for
3617 hyphenation; the |lig_ptr| field points to a linked list of character
3618 nodes for all original characters that have been deleted. (This list
3619 might be empty if the characters that generated the ligature were
3620 retained in other nodes.)
3621
3622 The |subtype| field is 0, plus 2 and/or 1 if the original source of the
3623 ligature included implicit left and/or right boundaries.
3624
3625 @d ligature_node=6 {|type| of a ligature node}
3626 @d lig_char(#)==#+1 {the word where the ligature is to be found}
3627 @d lig_ptr(#)==link(lig_char(#)) {the list of characters}
3628
3629 @ The |new_ligature| function creates a ligature node having given
3630 contents of the |font|, |character|, and |lig_ptr| fields. We also have
3631 a |new_lig_item| function, which returns a two-word node having a given
3632 |character| field. Such nodes are used for temporary processing as ligatures
3633 are being created.
3634
3635 @p function new_ligature(@!f,@!c:quarterword; @!q:pointer):pointer;
3636 var p:pointer; {the new node}
3637 begin p:=get_node(small_node_size); type(p):=ligature_node;
3638 font(lig_char(p)):=f; character(lig_char(p)):=c; lig_ptr(p):=q;
3639 subtype(p):=0; new_ligature:=p;
3640 end;
3641 @#
3642 function new_lig_item(@!c:quarterword):pointer;
3643 var p:pointer; {the new node}
3644 begin p:=get_node(small_node_size); character(p):=c; lig_ptr(p):=null;
3645 new_lig_item:=p;
3646 end;
3647
3648 @ A |disc_node|, which occurs only in horizontal lists, specifies a
3649 ``dis\-cretion\-ary'' line break. If such a break occurs at node |p|, the text
3650 that starts at |pre_break(p)| will precede the break, the text that starts at
3651 |post_break(p)| will follow the break, and text that appears in the next
3652 |replace_count(p)| nodes will be ignored. For example, an ordinary
3653 discretionary hyphen, indicated by `\.{\\-}', yields a |disc_node| with
3654 |pre_break| pointing to a |char_node| containing a hyphen, |post_break=null|,
3655 and |replace_count=0|. All three of the discretionary texts must be
3656 lists that consist entirely of character, kern, box, rule, and ligature nodes.
3657
3658 If |pre_break(p)=null|, the |ex_hyphen_penalty| will be charged for this
3659 break. Otherwise the |hyphen_penalty| will be charged. The texts will
3660 actually be substituted into the list by the line-breaking algorithm if it
3661 decides to make the break, and the discretionary node will disappear at
3662 that time; thus, the output routine sees only discretionaries that were
3663 not chosen.
3664
3665 @d disc_node=7 {|type| of a discretionary node}
3666 @d replace_count==subtype {how many subsequent nodes to replace}
3667 @d pre_break==llink {text that precedes a discretionary break}
3668 @d post_break==rlink {text that follows a discretionary break}
3669
3670 @p function new_disc:pointer; {creates an empty |disc_node|}
3671 var p:pointer; {the new node}
3672 begin p:=get_node(small_node_size); type(p):=disc_node;
3673 replace_count(p):=0; pre_break(p):=null; post_break(p):=null;
3674 new_disc:=p;
3675 end;
3676
3677 @ A |whatsit_node| is a wild card reserved for extensions to \TeX. The
3678 |subtype| field in its first word says what `\\{whatsit}' it is, and
3679 implicitly determines the node size (which must be 2 or more) and the
3680 format of the remaining words. When a |whatsit_node| is encountered
3681 in a list, special actions are invoked; knowledgeable people who are
3682 careful not to mess up the rest of \TeX\ are able to make \TeX\ do new
3683 things by adding code at the end of the program. For example, there
3684 might be a `\TeX nicolor' extension to specify different colors of ink,
3685 @^extensions to \TeX@>
3686 and the whatsit node might contain the desired parameters.
3687
3688 The present implementation of \TeX\ treats the features associated with
3689 `\.{\\write}' and `\.{\\special}' as if they were extensions, in order to
3690 illustrate how such routines might be coded. We shall defer further
3691 discussion of extensions until the end of this program.
3692
3693 @d whatsit_node=8 {|type| of special extension nodes}
3694
3695 @ To support ``native'' fonts, we build |native_word_node|s, which are variable
3696 size whatsits. These have the same |width|, |depth|, and |height| fields as a
3697 |box_node|, at offsets 1-3, and then a word containing a size field for the
3698 node, a font number, a length, and a glyph count. Then there is a field
3699 containing a C pointer to a glyph info array; this and the glyph count are set
3700 by |set_native_metrics|. Copying and freeing of these nodes needs to take
3701 account of this! This is followed by |2*length| bytes, for the actual
3702 characters of the string (in UTF-16).
3703
3704 So |native_node_size|, which does not include any space for the actual text, is
3705 6.
3706
3707 0-3 whatsits subtypes are used for open, write, close, special; 4 is language;
3708 pdf\TeX\ uses up through 30-something, so we use subtypes starting from 40.
3709
3710 There are also |glyph_node|s; these are like |native_word_node|s in having
3711 |width|, |depth|, and |height| fields, but then they contain a glyph ID rather
3712 than size and length fields, and there's no subsidiary C pointer.
3713
3714 @d native_word_node=40 {|subtype| of whatsits that hold |native_font| words}
3715 @d native_word_node_AT=41 {a |native_word_node| that should output ActualText}
3716 @d is_native_word_subtype(#)==((subtype(#)>=native_word_node) and (subtype(#)<=native_word_node_AT))
3717
3718 @d glyph_node=42 {|subtype| in whatsits that hold glyph numbers}
3719
3720 @d native_node_size=6 {size of a |native_word| node (plus the actual chars) -- see also \.{xetex.h}}
3721 @d glyph_node_size=5
3722 @d native_size(#)==mem[#+4].qqqq.b0
3723 @d native_font(#)==mem[#+4].qqqq.b1
3724 @d native_length(#)==mem[#+4].qqqq.b2
3725 @d native_glyph_count(#)==mem[#+4].qqqq.b3
3726 @d native_glyph_info_ptr(#)==mem[#+5].ptr
3727 @d native_glyph_info_size=10 {number of bytes of info per glyph: 16-bit glyph ID, 32-bit x and y coords}
3728 @d native_glyph==native_length {in |glyph_node|s, we store the glyph number here}
3729
3730 @d free_native_glyph_info(#) ==
3731 begin
3732 if native_glyph_info_ptr(#) <> null_ptr then begin
3733 libc_free(native_glyph_info_ptr(#));
3734 native_glyph_info_ptr(#):=null_ptr;
3735 native_glyph_count(#):=0;
3736 end
3737 end
3738
3739 @p procedure copy_native_glyph_info(src:pointer; dest:pointer);
3740 var glyph_count:integer;
3741 begin
3742 if native_glyph_info_ptr(src) <> null_ptr then begin
3743 glyph_count:=native_glyph_count(src);
3744 native_glyph_info_ptr(dest):=xmalloc_array(char, glyph_count * native_glyph_info_size);
3745 memcpy(native_glyph_info_ptr(dest), native_glyph_info_ptr(src), glyph_count * native_glyph_info_size);
3746 native_glyph_count(dest):=glyph_count;
3747 end
3748 end;
3749
3750 @ Picture files are handled with nodes that include fields for the transform associated
3751 with the picture, and a pathname for the picture file itself.
3752 They also have
3753 the |width|, |depth|, and |height| fields of a |box_node| at offsets 1-3. (|depth| will
3754 always be zero, as it happens.)
3755
3756 So |pic_node_size|, which does not include any space for the picture file pathname, is 7.
3757
3758 A |pdf_node| is just like |pic_node|, but generate a different \.{XDV} file code.
3759
3760 @d pic_node=43 {|subtype| in whatsits that hold picture file references}
3761 @d pdf_node=44 {|subtype| in whatsits that hold PDF page references}
3762 @#
3763 @d pic_node_size=9 {must sync with \.{xetex.h}}
3764 @d pic_path_length(#)==mem[#+4].hh.b0
3765 @d pic_page(#)==mem[#+4].hh.b1
3766 @d pic_transform1(#)==mem[#+5].hh.lh
3767 @d pic_transform2(#)==mem[#+5].hh.rh
3768 @d pic_transform3(#)==mem[#+6].hh.lh
3769 @d pic_transform4(#)==mem[#+6].hh.rh
3770 @d pic_transform5(#)==mem[#+7].hh.lh
3771 @d pic_transform6(#)==mem[#+7].hh.rh
3772 @d pic_pdf_box(#)==mem[#+8].hh.b0
3773
3774 @ A |math_node|, which occurs only in horizontal lists, appears before and
3775 after mathematical formulas. The |subtype| field is |before| before the
3776 formula and |after| after it. There is a |width| field, which represents
3777 the amount of surrounding space inserted by \.{\\mathsurround}.
3778
3779 In addition a |math_node| with |subtype>after| and |width=0| will be
3780 (ab)used to record a regular |math_node| reinserted after being
3781 discarded at a line break or one of the text direction primitives (
3782 \.{\\beginL}, \.{\\endL}, \.{\\beginR}, and \.{\\endR} ).
3783
3784 @d math_node=9 {|type| of a math node}
3785 @d before=0 {|subtype| for math node that introduces a formula}
3786 @d after=1 {|subtype| for math node that winds up a formula}
3787 @#
3788 @d M_code=2
3789 @d begin_M_code=M_code+before {|subtype| for \.{\\beginM} node}
3790 @d end_M_code=M_code+after {|subtype| for \.{\\endM} node}
3791 @d L_code=4
3792 @d begin_L_code=L_code+begin_M_code {|subtype| for \.{\\beginL} node}
3793 @d end_L_code=L_code+end_M_code {|subtype| for \.{\\endL} node}
3794 @d R_code=L_code+L_code
3795 @d begin_R_code=R_code+begin_M_code {|subtype| for \.{\\beginR} node}
3796 @d end_R_code=R_code+end_M_code {|subtype| for \.{\\endR} node}
3797 @#
3798 @d end_LR(#)==odd(subtype(#))
3799 @d end_LR_type(#)==(L_code*(subtype(#) div L_code)+end_M_code)
3800 @d begin_LR_type(#)==(#-after+before)
3801
3802 @p function new_math(@!w:scaled;@!s:small_number):pointer;
3803 var p:pointer; {the new node}
3804 begin p:=get_node(small_node_size); type(p):=math_node;
3805 subtype(p):=s; width(p):=w; new_math:=p;
3806 end;
3807
3808 @ \TeX\ makes use of the fact that |hlist_node|, |vlist_node|,
3809 |rule_node|, |ins_node|, |mark_node|, |adjust_node|, |ligature_node|,
3810 |disc_node|, |whatsit_node|, and |math_node| are at the low end of the
3811 type codes, by permitting a break at glue in a list if and only if the
3812 |type| of the previous node is less than |math_node|. Furthermore, a
3813 node is discarded after a break if its type is |math_node| or~more.
3814
3815 @d precedes_break(#)==(type(#)<math_node)
3816 @d non_discardable(#)==(type(#)<math_node)
3817
3818 @ A |glue_node| represents glue in a list. However, it is really only
3819 a pointer to a separate glue specification, since \TeX\ makes use of the
3820 fact that many essentially identical nodes of glue are usually present.
3821 If |p| points to a |glue_node|, |glue_ptr(p)| points to
3822 another packet of words that specify the stretch and shrink components, etc.
3823
3824 Glue nodes also serve to represent leaders; the |subtype| is used to
3825 distinguish between ordinary glue (which is called |normal|) and the three
3826 kinds of leaders (which are called |a_leaders|, |c_leaders|, and |x_leaders|).
3827 The |leader_ptr| field points to a rule node or to a box node containing the
3828 leaders; it is set to |null| in ordinary glue nodes.
3829
3830 Many kinds of glue are computed from \TeX's ``skip'' parameters, and
3831 it is helpful to know which parameter has led to a particular glue node.
3832 Therefore the |subtype| is set to indicate the source of glue, whenever
3833 it originated as a parameter. We will be defining symbolic names for the
3834 parameter numbers later (e.g., |line_skip_code=0|, |baseline_skip_code=1|,
3835 etc.); it suffices for now to say that the |subtype| of parametric glue
3836 will be the same as the parameter number, plus~one.
3837
3838 In math formulas there are two more possibilities for the |subtype| in a
3839 glue node: |mu_glue| denotes an \.{\\mskip} (where the units are scaled \.{mu}
3840 instead of scaled \.{pt}); and |cond_math_glue| denotes the `\.{\\nonscript}'
3841 feature that cancels the glue node immediately following if it appears
3842 in a subscript.
3843
3844 @d glue_node=10 {|type| of node that points to a glue specification}
3845 @d cond_math_glue=98 {special |subtype| to suppress glue in the next node}
3846 @d mu_glue=99 {|subtype| for math glue}
3847 @d a_leaders=100 {|subtype| for aligned leaders}
3848 @d c_leaders=101 {|subtype| for centered leaders}
3849 @d x_leaders=102 {|subtype| for expanded leaders}
3850 @d glue_ptr==llink {pointer to a glue specification}
3851 @d leader_ptr==rlink {pointer to box or rule node for leaders}
3852
3853 @ A glue specification has a halfword reference count in its first word,
3854 @^reference counts@>
3855 representing |null| plus the number of glue nodes that point to it (less one).
3856 Note that the reference count appears in the same position as
3857 the |link| field in list nodes; this is the field that is initialized
3858 to |null| when a node is allocated, and it is also the field that is flagged
3859 by |empty_flag| in empty nodes.
3860
3861 Glue specifications also contain three |scaled| fields, for the |width|,
3862 |stretch|, and |shrink| dimensions. Finally, there are two one-byte
3863 fields called |stretch_order| and |shrink_order|; these contain the
3864 orders of infinity (|normal|, |fil|, |fill|, or |filll|)
3865 corresponding to the stretch and shrink values.
3866
3867 @d glue_spec_size=4 {number of words to allocate for a glue specification}
3868 @d glue_ref_count(#) == link(#) {reference count of a glue specification}
3869 @d stretch(#) == mem[#+2].sc {the stretchability of this glob of glue}
3870 @d shrink(#) == mem[#+3].sc {the shrinkability of this glob of glue}
3871 @d stretch_order == type {order of infinity for stretching}
3872 @d shrink_order == subtype {order of infinity for shrinking}
3873 @d fil=1 {first-order infinity}
3874 @d fill=2 {second-order infinity}
3875 @d filll=3 {third-order infinity}
3876
3877 @<Types...@>=
3878 @!glue_ord=normal..filll; {infinity to the 0, 1, 2, or 3 power}
3879
3880 @ Here is a function that returns a pointer to a copy of a glue spec.
3881 The reference count in the copy is |null|, because there is assumed
3882 to be exactly one reference to the new specification.
3883
3884 @p function new_spec(@!p:pointer):pointer; {duplicates a glue specification}
3885 var q:pointer; {the new spec}
3886 begin q:=get_node(glue_spec_size);@/
3887 mem[q]:=mem[p]; glue_ref_count(q):=null;@/
3888 width(q):=width(p); stretch(q):=stretch(p); shrink(q):=shrink(p);
3889 new_spec:=q;
3890 end;
3891
3892 @ And here's a function that creates a glue node for a given parameter
3893 identified by its code number; for example,
3894 |new_param_glue(line_skip_code)| returns a pointer to a glue node for the
3895 current \.{\\lineskip}.
3896
3897 @p function new_param_glue(@!n:small_number):pointer;
3898 var p:pointer; {the new node}
3899 @!q:pointer; {the glue specification}
3900 begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=n+1;
3901 leader_ptr(p):=null;@/
3902 q:=@<Current |mem| equivalent of glue parameter number |n|@>@t@>;
3903 glue_ptr(p):=q; incr(glue_ref_count(q));
3904 new_param_glue:=p;
3905 end;
3906
3907 @ Glue nodes that are more or less anonymous are created by |new_glue|,
3908 whose argument points to a glue specification.
3909
3910 @p function new_glue(@!q:pointer):pointer;
3911 var p:pointer; {the new node}
3912 begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=normal;
3913 leader_ptr(p):=null; glue_ptr(p):=q; incr(glue_ref_count(q));
3914 new_glue:=p;
3915 end;
3916
3917 @ Still another subroutine is needed: This one is sort of a combination
3918 of |new_param_glue| and |new_glue|. It creates a glue node for one of
3919 the current glue parameters, but it makes a fresh copy of the glue
3920 specification, since that specification will probably be subject to change,
3921 while the parameter will stay put. The global variable |temp_ptr| is
3922 set to the address of the new spec.
3923
3924 @p function new_skip_param(@!n:small_number):pointer;
3925 var p:pointer; {the new node}
3926 begin temp_ptr:=new_spec(@<Current |mem| equivalent of glue parameter...@>);
3927 p:=new_glue(temp_ptr); glue_ref_count(temp_ptr):=null; subtype(p):=n+1;
3928 new_skip_param:=p;
3929 end;
3930
3931 @ A |kern_node| has a |width| field to specify a (normally negative)
3932 amount of spacing. This spacing correction appears in horizontal lists
3933 between letters like A and V when the font designer said that it looks
3934 better to move them closer together or further apart. A kern node can
3935 also appear in a vertical list, when its `|width|' denotes additional
3936 spacing in the vertical direction. The |subtype| is either |normal| (for
3937 kerns inserted from font information or math mode calculations) or |explicit|
3938 (for kerns inserted from \.{\\kern} and \.{\\/} commands) or |acc_kern|
3939 (for kerns inserted from non-math accents) or |mu_glue| (for kerns
3940 inserted from \.{\\mkern} specifications in math formulas).
3941
3942 @d kern_node=11 {|type| of a kern node}
3943 @d explicit=1 {|subtype| of kern nodes from \.{\\kern} and \.{\\/}}
3944 @d acc_kern=2 {|subtype| of kern nodes from accents}
3945 @d space_adjustment=3 {|subtype| of kern nodes from \.{\\XeTeXinterwordspaceshaping} adjustment}
3946
3947 @# {memory structure for marginal kerns}
3948 @d margin_kern_node = 40
3949 @d margin_kern_node_size = 3
3950 @d margin_char(#) == info(# + 2) {unused for now; relevant for font expansion}
3951
3952 @# {|subtype| of marginal kerns}
3953 @d left_side == 0
3954 @d right_side == 1
3955
3956 @# {base for lp/rp codes starts from 2:
3957 0 for |hyphen_char|,
3958 1 for |skew_char|}
3959 @d lp_code_base == 2
3960 @d rp_code_base == 3
3961
3962 @d max_hlist_stack = 512 {maximum fill level for |hlist_stack|}
3963 {maybe good if larger than |2 * max_quarterword|, so that box nesting level would overflow first}
3964
3965 @ The |new_kern| function creates a kern node having a given width.
3966
3967 @p function new_kern(@!w:scaled):pointer;
3968 var p:pointer; {the new node}
3969 begin p:=get_node(small_node_size); type(p):=kern_node;
3970 subtype(p):=normal;
3971 width(p):=w;
3972 new_kern:=p;
3973 end;
3974
3975 @ @<Glob...@>=
3976 @!last_leftmost_char: pointer;
3977 @!last_rightmost_char: pointer;
3978 @!hlist_stack:array[0..max_hlist_stack] of pointer; {stack for |find_protchar_left()| and |find_protchar_right()|}
3979 @!hlist_stack_level:0..max_hlist_stack; {fill level for |hlist_stack|}
3980 @!first_p: pointer; {to access the first node of the paragraph}
3981 @!global_prev_p: pointer; {to access |prev_p| in |line_break|; should be kept in sync with |prev_p| by |update_prev_p|}
3982
3983 @ A |penalty_node| specifies the penalty associated with line or page
3984 breaking, in its |penalty| field. This field is a fullword integer, but
3985 the full range of integer values is not used: Any penalty |>=10000| is
3986 treated as infinity, and no break will be allowed for such high values.
3987 Similarly, any penalty |<=-10000| is treated as negative infinity, and a
3988 break will be forced.
3989
3990 @d penalty_node=12 {|type| of a penalty node}
3991 @d inf_penalty=inf_bad {``infinite'' penalty value}
3992 @d eject_penalty=-inf_penalty {``negatively infinite'' penalty value}
3993 @d penalty(#) == mem[#+1].int {the added cost of breaking a list here}
3994
3995 @ Anyone who has been reading the last few sections of the program will
3996 be able to guess what comes next.
3997
3998 @p function new_penalty(@!m:integer):pointer;
3999 var p:pointer; {the new node}
4000 begin p:=get_node(small_node_size); type(p):=penalty_node;
4001 subtype(p):=0; {the |subtype| is not used}
4002 penalty(p):=m; new_penalty:=p;
4003 end;
4004
4005 @ You might think that we have introduced enough node types by now. Well,
4006 almost, but there is one more: An |unset_node| has nearly the same format
4007 as an |hlist_node| or |vlist_node|; it is used for entries in \.{\\halign}
4008 or \.{\\valign} that are not yet in their final form, since the box
4009 dimensions are their ``natural'' sizes before any glue adjustment has been
4010 made. The |glue_set| word is not present; instead, we have a |glue_stretch|
4011 field, which contains the total stretch of order |glue_order| that is
4012 present in the hlist or vlist being boxed.
4013 Similarly, the |shift_amount| field is replaced by a |glue_shrink| field,
4014 containing the total shrink of order |glue_sign| that is present.
4015 The |subtype| field is called |span_count|; an unset box typically
4016 contains the data for |qo(span_count)+1| columns.
4017 Unset nodes will be changed to box nodes when alignment is completed.
4018
4019 @d unset_node=13 {|type| for an unset node}
4020 @d glue_stretch(#)==mem[#+glue_offset].sc {total stretch in an unset node}
4021 @d glue_shrink==shift_amount {total shrink in an unset node}
4022 @d span_count==subtype {indicates the number of spanned columns}
4023
4024 @ In fact, there are still more types coming. When we get to math formula
4025 processing we will see that a |style_node| has |type=14|; and a number
4026 of larger type codes will also be defined, for use in math mode only.
4027
4028 @ Warning: If any changes are made to these data structure layouts, such as
4029 changing any of the node sizes or even reordering the words of nodes,
4030 the |copy_node_list| procedure and the memory initialization code
4031 below may have to be changed. Such potentially dangerous parts of the
4032 program are listed in the index under `data structure assumptions'.
4033 @!@^data structure assumptions@>
4034 However, other references to the nodes are made symbolically in terms of
4035 the \.{WEB} macro definitions above, so that format changes will leave
4036 \TeX's other algorithms intact.
4037 @^system dependencies@>
4038
4039 @* \[11] Memory layout.
4040 Some areas of |mem| are dedicated to fixed usage, since static allocation is
4041 more efficient than dynamic allocation when we can get away with it. For
4042 example, locations |mem_bot| to |mem_bot+3| are always used to store the
4043 specification for glue that is `\.{0pt plus 0pt minus 0pt}'. The
4044 following macro definitions accomplish the static allocation by giving
4045 symbolic names to the fixed positions. Static variable-size nodes appear
4046 in locations |mem_bot| through |lo_mem_stat_max|, and static single-word nodes
4047 appear in locations |hi_mem_stat_min| through |mem_top|, inclusive. It is
4048 harmless to let |lig_trick| and |garbage| share the same location of |mem|.
4049
4050 @d zero_glue==mem_bot {specification for \.{0pt plus 0pt minus 0pt}}
4051 @d fil_glue==zero_glue+glue_spec_size {\.{0pt plus 1fil minus 0pt}}
4052 @d fill_glue==fil_glue+glue_spec_size {\.{0pt plus 1fill minus 0pt}}
4053 @d ss_glue==fill_glue+glue_spec_size {\.{0pt plus 1fil minus 1fil}}
4054 @d fil_neg_glue==ss_glue+glue_spec_size {\.{0pt plus -1fil minus 0pt}}
4055 @d lo_mem_stat_max==fil_neg_glue+glue_spec_size-1 {largest statically
4056 allocated word in the variable-size |mem|}
4057 @#
4058 @d page_ins_head==mem_top {list of insertion data for current page}
4059 @d contrib_head==mem_top-1 {vlist of items not yet on current page}
4060 @d page_head==mem_top-2 {vlist for current page}
4061 @d temp_head==mem_top-3 {head of a temporary list of some kind}
4062 @d hold_head==mem_top-4 {head of a temporary list of another kind}
4063 @d adjust_head==mem_top-5 {head of adjustment list returned by |hpack|}
4064 @d active==mem_top-7 {head of active list in |line_break|, needs two words}
4065 @d align_head==mem_top-8 {head of preamble list for alignments}
4066 @d end_span==mem_top-9 {tail of spanned-width lists}
4067 @d omit_template==mem_top-10 {a constant token list}
4068 @d null_list==mem_top-11 {permanently empty list}
4069 @d lig_trick==mem_top-12 {a ligature masquerading as a |char_node|}
4070 @d garbage==mem_top-12 {used for scrap information}
4071 @d backup_head==mem_top-13 {head of token list built by |scan_keyword|}
4072 @d pre_adjust_head==mem_top-14 {head of pre-adjustment list returned by |hpack|}
4073 @d hi_mem_stat_min==mem_top-14 {smallest statically allocated word in
4074 the one-word |mem|}
4075 @d hi_mem_stat_usage=15 {the number of one-word nodes always present}
4076
4077 @ The following code gets |mem| off to a good start, when \TeX\ is
4078 initializing itself the slow~way.
4079
4080 @<Local variables for init...@>=
4081 @!k:integer; {index into |mem|, |eqtb|, etc.}
4082
4083 @ @<Initialize table entries...@>=
4084 for k:=mem_bot+1 to lo_mem_stat_max do mem[k].sc:=0;
4085 {all glue dimensions are zeroed}
4086 @^data structure assumptions@>
4087 k:=mem_bot;@+while k<=lo_mem_stat_max do
4088 {set first words of glue specifications}
4089 begin glue_ref_count(k):=null+1;
4090 stretch_order(k):=normal; shrink_order(k):=normal;
4091 k:=k+glue_spec_size;
4092 end;
4093 stretch(fil_glue):=unity; stretch_order(fil_glue):=fil;@/
4094 stretch(fill_glue):=unity; stretch_order(fill_glue):=fill;@/
4095 stretch(ss_glue):=unity; stretch_order(ss_glue):=fil;@/
4096 shrink(ss_glue):=unity; shrink_order(ss_glue):=fil;@/
4097 stretch(fil_neg_glue):=-unity; stretch_order(fil_neg_glue):=fil;@/
4098 rover:=lo_mem_stat_max+1;
4099 link(rover):=empty_flag; {now initialize the dynamic memory}
4100 node_size(rover):=1000; {which is a 1000-word available node}
4101 llink(rover):=rover; rlink(rover):=rover;@/
4102 lo_mem_max:=rover+1000; link(lo_mem_max):=null; info(lo_mem_max):=null;@/
4103 for k:=hi_mem_stat_min to mem_top do
4104 mem[k]:=mem[lo_mem_max]; {clear list heads}
4105 @<Initialize the special list heads and constant nodes@>;
4106 avail:=null; mem_end:=mem_top;
4107 hi_mem_min:=hi_mem_stat_min; {initialize the one-word memory}
4108 var_used:=lo_mem_stat_max+1-mem_bot; dyn_used:=hi_mem_stat_usage;
4109 {initialize statistics}
4110
4111 @ If \TeX\ is extended improperly, the |mem| array might get screwed up.
4112 For example, some pointers might be wrong, or some ``dead'' nodes might not
4113 have been freed when the last reference to them disappeared. Procedures
4114 |check_mem| and |search_mem| are available to help diagnose such
4115 problems. These procedures make use of two arrays called |free| and
4116 |was_free| that are present only if \TeX's debugging routines have
4117 been included. (You may want to decrease the size of |mem| while you
4118 @^debugging@>
4119 are debugging.)
4120
4121 @<Glob...@>=
4122 @!debug @!free: packed array [mem_min..mem_max] of boolean; {free cells}
4123 @t\hskip10pt@>@!was_free: packed array [mem_min..mem_max] of boolean;
4124 {previously free cells}
4125 @t\hskip10pt@>@!was_mem_end,@!was_lo_max,@!was_hi_min: pointer;
4126 {previous |mem_end|, |lo_mem_max|, and |hi_mem_min|}
4127 @t\hskip10pt@>@!panicking:boolean; {do we want to check memory constantly?}
4128 gubed
4129
4130 @ @<Set initial...@>=
4131 @!debug was_mem_end:=mem_min; {indicate that everything was previously free}
4132 was_lo_max:=mem_min; was_hi_min:=mem_max;
4133 panicking:=false;
4134 gubed
4135
4136 @ Procedure |check_mem| makes sure that the available space lists of
4137 |mem| are well formed, and it optionally prints out all locations
4138 that are reserved now but were free the last time this procedure was called.
4139
4140 @p @!debug procedure check_mem(@!print_locs : boolean);
4141 label done1,done2; {loop exits}
4142 var p,@!q:pointer; {current locations of interest in |mem|}
4143 @!clobbered:boolean; {is something amiss?}
4144 begin for p:=mem_min to lo_mem_max do free[p]:=false; {you can probably
4145 do this faster}
4146 for p:=hi_mem_min to mem_end do free[p]:=false; {ditto}
4147 @<Check single-word |avail| list@>;
4148 @<Check variable-size |avail| list@>;
4149 @<Check flags of unavailable nodes@>;
4150 if print_locs then @<Print newly busy locations@>;
4151 for p:=mem_min to lo_mem_max do was_free[p]:=free[p];
4152 for p:=hi_mem_min to mem_end do was_free[p]:=free[p];
4153 {|was_free:=free| might be faster}
4154 was_mem_end:=mem_end; was_lo_max:=lo_mem_max; was_hi_min:=hi_mem_min;
4155 end;
4156 gubed
4157
4158 @ @<Check single-word...@>=
4159 p:=avail; q:=null; clobbered:=false;
4160 while p<>null do
4161 begin if (p>mem_end)or(p<hi_mem_min) then clobbered:=true
4162 else if free[p] then clobbered:=true;
4163 if clobbered then
4164 begin print_nl("AVAIL list clobbered at ");
4165 @.AVAIL list clobbered...@>
4166 print_int(q); goto done1;
4167 end;
4168 free[p]:=true; q:=p; p:=link(q);
4169 end;
4170 done1:
4171
4172 @ @<Check variable-size...@>=
4173 p:=rover; q:=null; clobbered:=false;
4174 repeat if (p>=lo_mem_max)or(p<mem_min) then clobbered:=true
4175 else if (rlink(p)>=lo_mem_max)or(rlink(p)<mem_min) then clobbered:=true
4176 else if not(is_empty(p))or(node_size(p)<2)or@|
4177 (p+node_size(p)>lo_mem_max)or@| (llink(rlink(p))<>p) then clobbered:=true;
4178 if clobbered then
4179 begin print_nl("Double-AVAIL list clobbered at ");
4180 print_int(q); goto done2;
4181 end;
4182 for q:=p to p+node_size(p)-1 do {mark all locations free}
4183 begin if free[q] then
4184 begin print_nl("Doubly free location at ");
4185 @.Doubly free location...@>
4186 print_int(q); goto done2;
4187 end;
4188 free[q]:=true;
4189 end;
4190 q:=p; p:=rlink(p);
4191 until p=rover;
4192 done2:
4193
4194 @ @<Check flags...@>=
4195 p:=mem_min;
4196 while p<=lo_mem_max do {node |p| should not be empty}
4197 begin if is_empty(p) then
4198 begin print_nl("Bad flag at "); print_int(p);
4199 @.Bad flag...@>
4200 end;
4201 while (p<=lo_mem_max) and not free[p] do incr(p);
4202 while (p<=lo_mem_max) and free[p] do incr(p);
4203 end
4204
4205 @ @<Print newly busy...@>=
4206 begin print_nl("New busy locs:");
4207 for p:=mem_min to lo_mem_max do
4208 if not free[p] and ((p>was_lo_max) or was_free[p]) then
4209 begin print_char(" "); print_int(p);
4210 end;
4211 for p:=hi_mem_min to mem_end do
4212 if not free[p] and
4213 ((p<was_hi_min) or (p>was_mem_end) or was_free[p]) then
4214 begin print_char(" "); print_int(p);
4215 end;
4216 end
4217
4218 @ The |search_mem| procedure attempts to answer the question ``Who points
4219 to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
4220 that might not be of type |two_halves|. Strictly speaking, this is
4221 @^dirty \PASCAL@>
4222 undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
4223 point to |p| purely by coincidence). But for debugging purposes, we want
4224 to rule out the places that do {\sl not\/} point to |p|, so a few false
4225 drops are tolerable.
4226
4227 @p @!debug procedure search_mem(@!p:pointer); {look for pointers to |p|}
4228 var q:integer; {current position being searched}
4229 begin for q:=mem_min to lo_mem_max do
4230 begin if link(q)=p then
4231 begin print_nl("LINK("); print_int(q); print_char(")");
4232 end;
4233 if info(q)=p then
4234 begin print_nl("INFO("); print_int(q); print_char(")");
4235 end;
4236 end;
4237 for q:=hi_mem_min to mem_end do
4238 begin if link(q)=p then
4239 begin print_nl("LINK("); print_int(q); print_char(")");
4240 end;
4241 if info(q)=p then
4242 begin print_nl("INFO("); print_int(q); print_char(")");
4243 end;
4244 end;
4245 @<Search |eqtb| for equivalents equal to |p|@>;
4246 @<Search |save_stack| for equivalents that point to |p|@>;
4247 @<Search |hyph_list| for pointers to |p|@>;
4248 end;
4249 gubed
4250
4251 @ Some stuff for character protrusion, etc.
4252
4253 @p
4254 procedure pdf_error(t, p: str_number);
4255 begin
4256 normalize_selector;
4257 print_err("Error");
4258 if t <> 0 then begin
4259 print(" (");
4260 print(t);
4261 print(")");
4262 end;
4263 print(": "); print(p);
4264 succumb;
4265 end;
4266
4267 function prev_rightmost(s, e: pointer): pointer;
4268 {finds the node preceding the rightmost node |e|; |s| is some node
4269 before |e|}
4270 var p: pointer;
4271 begin
4272 prev_rightmost:=null;
4273 p:=s;
4274 if p = null then
4275 return;
4276 while link(p) <> e do begin
4277 p:=link(p);
4278 if p = null then
4279 return;
4280 end;
4281 prev_rightmost:=p;
4282 end;
4283
4284 function round_xn_over_d(@!x:scaled; @!n,@!d:integer):scaled;
4285 var positive:boolean; {was |x>=0|?}
4286 @!t,@!u,@!v:nonnegative_integer; {intermediate quantities}
4287 begin if x>=0 then positive:=true
4288 else begin negate(x); positive:=false;
4289 end;
4290 t:=(x mod @'100000)*n;
4291 u:=(x div @'100000)*n+(t div @'100000);
4292 v:=(u mod d)*@'100000 + (t mod @'100000);
4293 if u div d>=@'100000 then arith_error:=true
4294 else u:=@'100000*(u div d) + (v div d);
4295 v:=v mod d;
4296 if 2*v >= d then
4297 incr(u);
4298 if positive then
4299 round_xn_over_d:=u
4300 else
4301 round_xn_over_d:=-u;
4302 end;
4303
4304 function is_bit_set(n: integer; s: small_number): boolean;
4305 {check if $s$-th bit (one-based) of $n$ is set}
4306 var m, i: integer;
4307 begin
4308 m := 1;
4309 for i := 1 to s - 1 do
4310 m := m * 2;
4311 is_bit_set := (n div m) mod 2;
4312 end;
4313
4314 @<Declare procedures that need to be declared forward for \pdfTeX@>@;
4315
4316 @* \[12] Displaying boxes.
4317 We can reinforce our knowledge of the data structures just introduced
4318 by considering two procedures that display a list in symbolic form.
4319 The first of these, called |short_display|, is used in ``overfull box''
4320 messages to give the top-level description of a list. The other one,
4321 called |show_node_list|, prints a detailed description of exactly what
4322 is in the data structure.
4323
4324 The philosophy of |short_display| is to ignore the fine points about exactly
4325 what is inside boxes, except that ligatures and discretionary breaks are
4326 expanded. As a result, |short_display| is a recursive procedure, but the
4327 recursion is never more than one level deep.
4328 @^recursion@>
4329
4330 A global variable |font_in_short_display| keeps track of the font code that
4331 is assumed to be present when |short_display| begins; deviations from this
4332 font will be printed.
4333
4334 @<Glob...@>=
4335 @!font_in_short_display:integer; {an internal font number}
4336
4337 @ Boxes, rules, inserts, whatsits, marks, and things in general that are
4338 sort of ``complicated'' are indicated only by printing `\.{[]}'.
4339
4340 @p procedure short_display(@!p:integer); {prints highlights of list |p|}
4341 var n:integer; {for replacement counts}
4342 begin while p>mem_min do
4343 begin if is_char_node(p) then
4344 begin if p<=mem_end then
4345 begin if font(p)<>font_in_short_display then
4346 begin if (font(p)<font_base)or(font(p)>font_max) then
4347 print_char("*")
4348 @.*\relax@>
4349 else @<Print the font identifier for |font(p)|@>;
4350 print_char(" "); font_in_short_display:=font(p);
4351 end;
4352 print_ASCII(qo(character(p)));
4353 end;
4354 end
4355 else @<Print a short indication of the contents of node |p|@>;
4356 p:=link(p);
4357 end;
4358 end;
4359
4360 @ @<Print a short indication of the contents of node |p|@>=
4361 case type(p) of
4362 hlist_node,vlist_node,ins_node,mark_node,adjust_node,
4363 unset_node: print("[]");
4364 whatsit_node:
4365 case subtype(p) of
4366 native_word_node, native_word_node_AT: begin
4367 if native_font(p)<>font_in_short_display then begin
4368 print_esc(font_id_text(native_font(p)));
4369 print_char(" ");
4370 font_in_short_display:=native_font(p);
4371 end;
4372 print_native_word(p);
4373 end;
4374 othercases print("[]")
4375 endcases;
4376 rule_node: print_char("|");
4377 glue_node: if glue_ptr(p)<>zero_glue then print_char(" ");
4378 math_node: if subtype(p)>=L_code then print("[]")
4379 else print_char("$");
4380 ligature_node: short_display(lig_ptr(p));
4381 disc_node: begin short_display(pre_break(p));
4382 short_display(post_break(p));@/
4383 n:=replace_count(p);
4384 while n>0 do
4385 begin if link(p)<>null then p:=link(p);
4386 decr(n);
4387 end;
4388 end;
4389 othercases do_nothing
4390 endcases
4391
4392 @ The |show_node_list| routine requires some auxiliary subroutines: one to
4393 print a font-and-character combination, one to print a token list without
4394 its reference count, and one to print a rule dimension.
4395
4396 @p procedure print_font_and_char(@!p:integer); {prints |char_node| data}
4397 begin if p>mem_end then print_esc("CLOBBERED.")
4398 else begin if (font(p)<font_base)or(font(p)>font_max) then print_char("*")
4399 @.*\relax@>
4400 else @<Print the font identifier for |font(p)|@>;
4401 print_char(" "); print_ASCII(qo(character(p)));
4402 end;
4403 end;
4404 @#
4405 procedure print_mark(@!p:integer); {prints token list data in braces}
4406 begin print_char("{");
4407 if (p<hi_mem_min)or(p>mem_end) then print_esc("CLOBBERED.")
4408 else show_token_list(link(p),null,max_print_line-10);
4409 print_char("}");
4410 end;
4411 @#
4412 procedure print_rule_dimen(@!d:scaled); {prints dimension in rule node}
4413 begin if is_running(d) then print_char("*") else print_scaled(d);
4414 @.*\relax@>
4415 end;
4416
4417 @ Then there is a subroutine that prints glue stretch and shrink, possibly
4418 followed by the name of finite units:
4419
4420 @p procedure print_glue(@!d:scaled;@!order:integer;@!s:str_number);
4421 {prints a glue component}
4422 begin print_scaled(d);
4423 if (order<normal)or(order>filll) then print("foul")
4424 else if order>normal then
4425 begin print("fil");
4426 while order>fil do
4427 begin print_char("l"); decr(order);
4428 end;
4429 end
4430 else if s<>0 then print(s);
4431 end;
4432
4433 @ The next subroutine prints a whole glue specification.
4434
4435 @p procedure print_spec(@!p:integer;@!s:str_number);
4436 {prints a glue specification}
4437 begin if (p<mem_min)or(p>=lo_mem_max) then print_char("*")
4438 @.*\relax@>
4439 else begin print_scaled(width(p));
4440 if s<>0 then print(s);
4441 if stretch(p)<>0 then
4442 begin print(" plus "); print_glue(stretch(p),stretch_order(p),s);
4443 end;
4444 if shrink(p)<>0 then
4445 begin print(" minus "); print_glue(shrink(p),shrink_order(p),s);
4446 end;
4447 end;
4448 end;
4449
4450 @ We also need to declare some procedures that appear later in this
4451 documentation.
4452
4453 @p @<Declare procedures needed for displaying the elements of mlists@>@;
4454 @<Declare the procedure called |print_skip_param|@>
4455
4456 @ Since boxes can be inside of boxes, |show_node_list| is inherently recursive,
4457 @^recursion@>
4458 up to a given maximum number of levels. The history of nesting is indicated
4459 by the current string, which will be printed at the beginning of each line;
4460 the length of this string, namely |cur_length|, is the depth of nesting.
4461
4462 Recursive calls on |show_node_list| therefore use the following pattern:
4463
4464 @d node_list_display(#)==
4465 begin append_char("."); show_node_list(#); flush_char;
4466 end {|str_room| need not be checked; see |show_box| below}
4467
4468 @ A global variable called |depth_threshold| is used to record the maximum
4469 depth of nesting for which |show_node_list| will show information. If we
4470 have |depth_threshold=0|, for example, only the top level information will
4471 be given and no sublists will be traversed. Another global variable, called
4472 |breadth_max|, tells the maximum number of items to show at each level;
4473 |breadth_max| had better be positive, or you won't see anything.
4474
4475 @<Glob...@>=
4476 @!depth_threshold : integer; {maximum nesting depth in box displays}
4477 @!breadth_max : integer; {maximum number of items shown at the same list level}
4478
4479 @ Now we are ready for |show_node_list| itself. This procedure has been
4480 written to be ``extra robust'' in the sense that it should not crash or get
4481 into a loop even if the data structures have been messed up by bugs in
4482 the rest of the program. You can safely call its parent routine
4483 |show_box(p)| for arbitrary values of |p| when you are debugging \TeX.
4484 However, in the presence of bad data, the procedure may
4485 @^dirty \PASCAL@>@^debugging@>
4486 fetch a |memory_word| whose variant is different from the way it was stored;
4487 for example, it might try to read |mem[p].hh| when |mem[p]|
4488 contains a scaled integer, if |p| is a pointer that has been
4489 clobbered or chosen at random.
4490
4491 @p procedure show_node_list(@!p:integer); {prints a node list symbolically}
4492 label exit;
4493 var n:integer; {the number of items already printed at this level}
4494 i:integer; {temp index for printing chars of picfile paths}
4495 @!g:real; {a glue ratio, as a floating point number}
4496 begin if cur_length>depth_threshold then
4497 begin if p>null then print(" []");
4498 {indicate that there's been some truncation}
4499 return;
4500 end;
4501 n:=0;
4502 while p>mem_min do
4503 begin print_ln; print_current_string; {display the nesting history}
4504 if p>mem_end then {pointer out of range}
4505 begin print("Bad link, display aborted."); return;
4506 @.Bad link...@>
4507 end;
4508 incr(n); if n>breadth_max then {time to stop}
4509 begin print("etc."); return;
4510 @.etc@>
4511 end;
4512 @<Display node |p|@>;
4513 p:=link(p);
4514 end;
4515 exit:
4516 end;
4517
4518 @ @<Display node |p|@>=
4519 if is_char_node(p) then print_font_and_char(p)
4520 else case type(p) of
4521 hlist_node,vlist_node,unset_node: @<Display box |p|@>;
4522 rule_node: @<Display rule |p|@>;
4523 ins_node: @<Display insertion |p|@>;
4524 whatsit_node: @<Display the whatsit node |p|@>;
4525 glue_node: @<Display glue |p|@>;
4526 kern_node: @<Display kern |p|@>;
4527 margin_kern_node: begin
4528 print_esc("kern");
4529 print_scaled(width(p));
4530 if subtype(p) = left_side then
4531 print(" (left margin)")
4532 else
4533 print(" (right margin)");
4534 end;
4535 math_node: @<Display math node |p|@>;
4536 ligature_node: @<Display ligature |p|@>;
4537 penalty_node: @<Display penalty |p|@>;
4538 disc_node: @<Display discretionary |p|@>;
4539 mark_node: @<Display mark |p|@>;
4540 adjust_node: @<Display adjustment |p|@>;
4541 @t\4@>@<Cases of |show_node_list| that arise in mlists only@>@;
4542 othercases print("Unknown node type!")
4543 endcases
4544
4545 @ @<Display box |p|@>=
4546 begin if type(p)=hlist_node then print_esc("h")
4547 else if type(p)=vlist_node then print_esc("v")
4548 else print_esc("unset");
4549 print("box("); print_scaled(height(p)); print_char("+");
4550 print_scaled(depth(p)); print(")x"); print_scaled(width(p));
4551 if type(p)=unset_node then
4552 @<Display special fields of the unset node |p|@>
4553 else begin @<Display the value of |glue_set(p)|@>;
4554 if shift_amount(p)<>0 then
4555 begin print(", shifted "); print_scaled(shift_amount(p));
4556 end;
4557 if eTeX_ex then @<Display if this box is never to be reversed@>;
4558 end;
4559 node_list_display(list_ptr(p)); {recursive call}
4560 end
4561
4562 @ @<Display special fields of the unset node |p|@>=
4563 begin if span_count(p)<>min_quarterword then
4564 begin print(" ("); print_int(qo(span_count(p))+1);
4565 print(" columns)");
4566 end;
4567 if glue_stretch(p)<>0 then
4568 begin print(", stretch "); print_glue(glue_stretch(p),glue_order(p),0);
4569 end;
4570 if glue_shrink(p)<>0 then
4571 begin print(", shrink "); print_glue(glue_shrink(p),glue_sign(p),0);
4572 end;
4573 end
4574
4575 @ The code will have to change in this place if |glue_ratio| is
4576 a structured type instead of an ordinary |real|. Note that this routine
4577 should avoid arithmetic errors even if the |glue_set| field holds an
4578 arbitrary random value. The following code assumes that a properly
4579 formed nonzero |real| number has absolute value $2^{20}$ or more when
4580 it is regarded as an integer; this precaution was adequate to prevent
4581 floating point underflow on the author's computer.
4582 @^system dependencies@>
4583 @^dirty \PASCAL@>
4584
4585 @<Display the value of |glue_set(p)|@>=
4586 g:=float(glue_set(p));
4587 if (g<>float_constant(0))and(glue_sign(p)<>normal) then
4588 begin print(", glue set ");
4589 if glue_sign(p)=shrinking then print("- ");
4590 if abs(mem[p+glue_offset].int)<@'4000000 then print("?.?")
4591 else if abs(g)>float_constant(20000) then
4592 begin if g>float_constant(0) then print_char(">")
4593 else print("< -");
4594 print_glue(20000*unity,glue_order(p),0);
4595 end
4596 else print_glue(round(unity*g),glue_order(p),0);
4597 @^real multiplication@>
4598 end
4599
4600 @ @<Display rule |p|@>=
4601 begin print_esc("rule("); print_rule_dimen(height(p)); print_char("+");
4602 print_rule_dimen(depth(p)); print(")x"); print_rule_dimen(width(p));
4603 end
4604
4605 @ @<Display insertion |p|@>=
4606 begin print_esc("insert"); print_int(qo(subtype(p)));
4607 print(", natural size "); print_scaled(height(p));
4608 print("; split("); print_spec(split_top_ptr(p),0);
4609 print_char(","); print_scaled(depth(p));
4610 print("); float cost "); print_int(float_cost(p));
4611 node_list_display(ins_ptr(p)); {recursive call}
4612 end
4613
4614 @ @<Display glue |p|@>=
4615 if subtype(p)>=a_leaders then @<Display leaders |p|@>
4616 else begin print_esc("glue");
4617 if subtype(p)<>normal then
4618 begin print_char("(");
4619 if subtype(p)<cond_math_glue then
4620 print_skip_param(subtype(p)-1)
4621 else if subtype(p)=cond_math_glue then print_esc("nonscript")
4622 else print_esc("mskip");
4623 print_char(")");
4624 end;
4625 if subtype(p)<>cond_math_glue then
4626 begin print_char(" ");
4627 if subtype(p)<cond_math_glue then print_spec(glue_ptr(p),0)
4628 else print_spec(glue_ptr(p),"mu");
4629 end;
4630 end
4631
4632 @ @<Display leaders |p|@>=
4633 begin print_esc("");
4634 if subtype(p)=c_leaders then print_char("c")
4635 else if subtype(p)=x_leaders then print_char("x");
4636 print("leaders "); print_spec(glue_ptr(p),0);
4637 node_list_display(leader_ptr(p)); {recursive call}
4638 end
4639
4640 @ An ``explicit'' kern value is indicated implicitly by an explicit space.
4641
4642 @<Display kern |p|@>=
4643 if subtype(p)<>mu_glue then
4644 begin print_esc("kern");
4645 if subtype(p)<>normal then print_char(" ");
4646 print_scaled(width(p));
4647 if subtype(p)=acc_kern then print(" (for accent)")
4648 @.for accent@>
4649 else if subtype(p)=space_adjustment then print(" (space adjustment)");
4650 end
4651 else begin print_esc("mkern"); print_scaled(width(p)); print("mu");
4652 end
4653
4654 @ @<Display math node |p|@>=
4655 if subtype(p)>after then
4656 begin if end_LR(p) then print_esc("end")
4657 else print_esc("begin");
4658 if subtype(p)>R_code then print_char("R")
4659 else if subtype(p)>L_code then print_char("L")
4660 else print_char("M");
4661 end else
4662 begin print_esc("math");
4663 if subtype(p)=before then print("on")
4664 else print("off");
4665 if width(p)<>0 then
4666 begin print(", surrounded "); print_scaled(width(p));
4667 end;
4668 end
4669
4670 @ @<Display ligature |p|@>=
4671 begin print_font_and_char(lig_char(p)); print(" (ligature ");
4672 if subtype(p)>1 then print_char("|");
4673 font_in_short_display:=font(lig_char(p)); short_display(lig_ptr(p));
4674 if odd(subtype(p)) then print_char("|");
4675 print_char(")");
4676 end
4677
4678 @ @<Display penalty |p|@>=
4679 begin print_esc("penalty "); print_int(penalty(p));
4680 end
4681
4682 @ The |post_break| list of a discretionary node is indicated by a prefixed
4683 `\.{\char'174}' instead of the `\..' before the |pre_break| list.
4684
4685 @<Display discretionary |p|@>=
4686 begin print_esc("discretionary");
4687 if replace_count(p)>0 then
4688 begin print(" replacing "); print_int(replace_count(p));
4689 end;
4690 node_list_display(pre_break(p)); {recursive call}
4691 append_char("|"); show_node_list(post_break(p)); flush_char; {recursive call}
4692 end
4693
4694 @ @<Display mark |p|@>=
4695 begin print_esc("mark");
4696 if mark_class(p)<>0 then
4697 begin print_char("s"); print_int(mark_class(p));
4698 end;
4699 print_mark(mark_ptr(p));
4700 end
4701
4702 @ @<Display adjustment |p|@>=
4703 begin print_esc("vadjust"); if adjust_pre(p) <> 0 then print(" pre ");
4704 node_list_display(adjust_ptr(p)); {recursive call}
4705 end
4706
4707 @ The recursive machinery is started by calling |show_box|.
4708 @^recursion@>
4709
4710 @p procedure show_box(@!p:pointer);
4711 begin @<Assign the values |depth_threshold:=show_box_depth| and
4712 |breadth_max:=show_box_breadth|@>;
4713 if breadth_max<=0 then breadth_max:=5;
4714 if pool_ptr+depth_threshold>=pool_size then
4715 depth_threshold:=pool_size-pool_ptr-1;
4716 {now there's enough room for prefix string}
4717 show_node_list(p); {the show starts at |p|}
4718 print_ln;
4719 end;
4720
4721 procedure short_display_n(@!p, m:integer); {prints highlights of list |p|}
4722 begin
4723 breadth_max:=m;
4724 depth_threshold:=pool_size-pool_ptr-1;
4725 show_node_list(p); {the show starts at |p|}
4726 end;
4727
4728 @* \[13] Destroying boxes.
4729 When we are done with a node list, we are obliged to return it to free
4730 storage, including all of its sublists. The recursive procedure
4731 |flush_node_list| does this for us.
4732
4733 @ First, however, we shall consider two non-recursive procedures that do
4734 simpler tasks. The first of these, |delete_token_ref|, is called when
4735 a pointer to a token list's reference count is being removed. This means
4736 that the token list should disappear if the reference count was |null|,
4737 otherwise the count should be decreased by one.
4738 @^reference counts@>
4739
4740 @d token_ref_count(#) == info(#) {reference count preceding a token list}
4741
4742 @p procedure delete_token_ref(@!p:pointer); {|p| points to the reference count
4743 of a token list that is losing one reference}
4744 begin if token_ref_count(p)=null then flush_list(p)
4745 else decr(token_ref_count(p));
4746 end;
4747
4748 @ Similarly, |delete_glue_ref| is called when a pointer to a glue
4749 specification is being withdrawn.
4750 @^reference counts@>
4751 @d fast_delete_glue_ref(#)==@t@>@;@/
4752 begin if glue_ref_count(#)=null then free_node(#,glue_spec_size)
4753 else decr(glue_ref_count(#));
4754 end
4755
4756 @p procedure delete_glue_ref(@!p:pointer); {|p| points to a glue specification}
4757 fast_delete_glue_ref(p);
4758
4759 @ Now we are ready to delete any node list, recursively.
4760 In practice, the nodes deleted are usually charnodes (about 2/3 of the time),
4761 and they are glue nodes in about half of the remaining cases.
4762 @^recursion@>
4763
4764 @p procedure flush_node_list(@!p:pointer); {erase list of nodes starting at |p|}
4765 label done; {go here when node |p| has been freed}
4766 var q:pointer; {successor to node |p|}
4767 begin while p<>null do
4768 @^inner loop@>
4769 begin q:=link(p);
4770 if is_char_node(p) then free_avail(p)
4771 else begin case type(p) of
4772 hlist_node,vlist_node,unset_node: begin flush_node_list(list_ptr(p));
4773 free_node(p,box_node_size); goto done;
4774 end;
4775 rule_node: begin free_node(p,rule_node_size); goto done;
4776 end;
4777 ins_node: begin flush_node_list(ins_ptr(p));
4778 delete_glue_ref(split_top_ptr(p));
4779 free_node(p,ins_node_size); goto done;
4780 end;
4781 whatsit_node: @<Wipe out the whatsit node |p| and |goto done|@>;
4782 glue_node: begin fast_delete_glue_ref(glue_ptr(p));
4783 if leader_ptr(p)<>null then flush_node_list(leader_ptr(p));
4784 end;
4785 kern_node,math_node,penalty_node: do_nothing;
4786 margin_kern_node: begin
4787 free_node(p, margin_kern_node_size);
4788 goto done;
4789 end;
4790 ligature_node: flush_node_list(lig_ptr(p));
4791 mark_node: delete_token_ref(mark_ptr(p));
4792 disc_node: begin flush_node_list(pre_break(p));
4793 flush_node_list(post_break(p));
4794 end;
4795 adjust_node: flush_node_list(adjust_ptr(p));
4796 @t\4@>@<Cases of |flush_node_list| that arise in mlists only@>@;
4797 othercases confusion("flushing")
4798 @:this can't happen flushing}{\quad flushing@>
4799 endcases;@/
4800 free_node(p,small_node_size);
4801 done:end;
4802 p:=q;
4803 end;
4804 end;
4805
4806 @* \[14] Copying boxes.
4807 Another recursive operation that acts on boxes is sometimes needed: The
4808 procedure |copy_node_list| returns a pointer to another node list that has
4809 the same structure and meaning as the original. Note that since glue
4810 specifications and token lists have reference counts, we need not make
4811 copies of them. Reference counts can never get too large to fit in a
4812 halfword, since each pointer to a node is in a different memory address,
4813 and the total number of memory addresses fits in a halfword.
4814 @^recursion@>
4815 @^reference counts@>
4816
4817 (Well, there actually are also references from outside |mem|; if the
4818 |save_stack| is made arbitrarily large, it would theoretically be possible
4819 to break \TeX\ by overflowing a reference count. But who would want to do that?)
4820
4821 @d add_token_ref(#)==incr(token_ref_count(#)) {new reference to a token list}
4822 @d add_glue_ref(#)==incr(glue_ref_count(#)) {new reference to a glue spec}
4823
4824 @ The copying procedure copies words en masse without bothering
4825 to look at their individual fields. If the node format changes---for
4826 example, if the size is altered, or if some link field is moved to another
4827 relative position---then this code may need to be changed too.
4828 @^data structure assumptions@>
4829
4830 @p function copy_node_list(@!p:pointer):pointer; {makes a duplicate of the
4831 node list that starts at |p| and returns a pointer to the new list}
4832 var h:pointer; {temporary head of copied list}
4833 @!q:pointer; {previous position in new list}
4834 @!r:pointer; {current node being fabricated for new list}
4835 @!words:0..5; {number of words remaining to be copied}
4836 begin h:=get_avail; q:=h;
4837 while p<>null do
4838 begin @<Make a copy of node |p| in node |r|@>;
4839 link(q):=r; q:=r; p:=link(p);
4840 end;
4841 link(q):=null; q:=link(h); free_avail(h);
4842 copy_node_list:=q;
4843 end;
4844
4845 @ @<Make a copy of node |p|...@>=
4846 words:=1; {this setting occurs in more branches than any other}
4847 if is_char_node(p) then r:=get_avail
4848 else @<Case statement to copy different types and set |words| to the number
4849 of initial words not yet copied@>;
4850 while words>0 do
4851 begin decr(words); mem[r+words]:=mem[p+words];
4852 end
4853
4854 @ @<Case statement to copy...@>=
4855 case type(p) of
4856 hlist_node,vlist_node,unset_node: begin r:=get_node(box_node_size);
4857 mem[r+6]:=mem[p+6]; mem[r+5]:=mem[p+5]; {copy the last two words}
4858 list_ptr(r):=copy_node_list(list_ptr(p)); {this affects |mem[r+5]|}
4859 words:=5;
4860 end;
4861 rule_node: begin r:=get_node(rule_node_size); words:=rule_node_size;
4862 end;
4863 ins_node: begin r:=get_node(ins_node_size); mem[r+4]:=mem[p+4];
4864 add_glue_ref(split_top_ptr(p));
4865 ins_ptr(r):=copy_node_list(ins_ptr(p)); {this affects |mem[r+4]|}
4866 words:=ins_node_size-1;
4867 end;
4868 whatsit_node:@<Make a partial copy of the whatsit node |p| and make |r|
4869 point to it; set |words| to the number of initial words not yet copied@>;
4870 glue_node: begin r:=get_node(small_node_size); add_glue_ref(glue_ptr(p));
4871 glue_ptr(r):=glue_ptr(p); leader_ptr(r):=copy_node_list(leader_ptr(p));
4872 end;
4873 kern_node,math_node,penalty_node: begin r:=get_node(small_node_size);
4874 words:=small_node_size;
4875 end;
4876 margin_kern_node: begin
4877 r:=get_node(margin_kern_node_size);
4878 words:=margin_kern_node_size;
4879 end;
4880 ligature_node: begin r:=get_node(small_node_size);
4881 mem[lig_char(r)]:=mem[lig_char(p)]; {copy |font| and |character|}
4882 lig_ptr(r):=copy_node_list(lig_ptr(p));
4883 end;
4884 disc_node: begin r:=get_node(small_node_size);
4885 pre_break(r):=copy_node_list(pre_break(p));
4886 post_break(r):=copy_node_list(post_break(p));
4887 end;
4888 mark_node: begin r:=get_node(small_node_size); add_token_ref(mark_ptr(p));
4889 words:=small_node_size;
4890 end;
4891 adjust_node: begin r:=get_node(small_node_size);
4892 adjust_ptr(r):=copy_node_list(adjust_ptr(p));
4893 end; {|words=1=small_node_size-1|}
4894 othercases confusion("copying")
4895 @:this can't happen copying}{\quad copying@>
4896 endcases
4897
4898 @* \[15] The command codes.
4899 Before we can go any further, we need to define symbolic names for the internal
4900 code numbers that represent the various commands obeyed by \TeX. These codes
4901 are somewhat arbitrary, but not completely so. For example, the command
4902 codes for character types are fixed by the language, since a user says,
4903 e.g., `\.{\\catcode \`\\\${} = 3}' to make \.{\char'44} a math delimiter,
4904 and the command code |math_shift| is equal to~3. Some other codes have
4905 been made adjacent so that |case| statements in the program need not consider
4906 cases that are widely spaced, or so that |case| statements can be replaced
4907 by |if| statements.
4908
4909 At any rate, here is the list, for future reference. First come the
4910 ``catcode'' commands, several of which share their numeric codes with
4911 ordinary commands when the catcode cannot emerge from \TeX's scanning routine.
4912
4913 @d escape=0 {escape delimiter (called \.\\ in {\sl The \TeX book\/})}
4914 @:TeXbook}{\sl The \TeX book@>
4915 @d relax=0 {do nothing ( \.{\\relax} )}
4916 @d left_brace=1 {beginning of a group ( \.\{ )}
4917 @d right_brace=2 {ending of a group ( \.\} )}
4918 @d math_shift=3 {mathematics shift character ( \.\$ )}
4919 @d tab_mark=4 {alignment delimiter ( \.\&, \.{\\span} )}
4920 @d car_ret=5 {end of line ( |carriage_return|, \.{\\cr}, \.{\\crcr} )}
4921 @d out_param=5 {output a macro parameter}
4922 @d mac_param=6 {macro parameter symbol ( \.\# )}
4923 @d sup_mark=7 {superscript ( \.{\char'136} )}
4924 @d sub_mark=8 {subscript ( \.{\char'137} )}
4925 @d ignore=9 {characters to ignore ( \.{\^\^@@} )}
4926 @d endv=9 {end of \<v_j> list in alignment template}
4927 @d spacer=10 {characters equivalent to blank space ( \.{\ } )}
4928 @d letter=11 {characters regarded as letters ( \.{A..Z}, \.{a..z} )}
4929 @d other_char=12 {none of the special character types}
4930 @d active_char=13 {characters that invoke macros ( \.{\char`\~} )}
4931 @d par_end=13 {end of paragraph ( \.{\\par} )}
4932 @d match=13 {match a macro parameter}
4933 @d comment=14 {characters that introduce comments ( \.\% )}
4934 @d end_match=14 {end of parameters to macro}
4935 @d stop=14 {end of job ( \.{\\end}, \.{\\dump} )}
4936 @d invalid_char=15 {characters that shouldn't appear ( \.{\^\^?} )}
4937 @d delim_num=15 {specify delimiter numerically ( \.{\\delimiter} )}
4938 @d max_char_code=15 {largest catcode for individual characters}
4939
4940 @ Next are the ordinary run-of-the-mill command codes. Codes that are
4941 |min_internal| or more represent internal quantities that might be
4942 expanded by `\.{\\the}'.
4943
4944 @d char_num=16 {character specified numerically ( \.{\\char} )}
4945 @d math_char_num=17 {explicit math code ( \.{\\mathchar} )}
4946 @d mark=18 {mark definition ( \.{\\mark} )}
4947 @d xray=19 {peek inside of \TeX\ ( \.{\\show}, \.{\\showbox}, etc.~)}
4948 @d make_box=20 {make a box ( \.{\\box}, \.{\\copy}, \.{\\hbox}, etc.~)}
4949 @d hmove=21 {horizontal motion ( \.{\\moveleft}, \.{\\moveright} )}
4950 @d vmove=22 {vertical motion ( \.{\\raise}, \.{\\lower} )}
4951 @d un_hbox=23 {unglue a box ( \.{\\unhbox}, \.{\\unhcopy} )}
4952 @d un_vbox=24 {unglue a box ( \.{\\unvbox}, \.{\\unvcopy} )}
4953 {( or \.{\\pagediscards}, \.{\\splitdiscards} )}
4954 @d remove_item=25 {nullify last item ( \.{\\unpenalty},
4955 \.{\\unkern}, \.{\\unskip} )}
4956 @d hskip=26 {horizontal glue ( \.{\\hskip}, \.{\\hfil}, etc.~)}
4957 @d vskip=27 {vertical glue ( \.{\\vskip}, \.{\\vfil}, etc.~)}
4958 @d mskip=28 {math glue ( \.{\\mskip} )}
4959 @d kern=29 {fixed space ( \.{\\kern} )}
4960 @d mkern=30 {math kern ( \.{\\mkern} )}
4961 @d leader_ship=31 {use a box ( \.{\\shipout}, \.{\\leaders}, etc.~)}
4962 @d halign=32 {horizontal table alignment ( \.{\\halign} )}
4963 @d valign=33 {vertical table alignment ( \.{\\valign} )}
4964 {or text direction directives ( \.{\\beginL}, etc.~)}
4965 @d no_align=34 {temporary escape from alignment ( \.{\\noalign} )}
4966 @d vrule=35 {vertical rule ( \.{\\vrule} )}
4967 @d hrule=36 {horizontal rule ( \.{\\hrule} )}
4968 @d insert=37 {vlist inserted in box ( \.{\\insert} )}
4969 @d vadjust=38 {vlist inserted in enclosing paragraph ( \.{\\vadjust} )}
4970 @d ignore_spaces=39 {gobble |spacer| tokens ( \.{\\ignorespaces} )}
4971 @d after_assignment=40 {save till assignment is done ( \.{\\afterassignment} )}
4972 @d after_group=41 {save till group is done ( \.{\\aftergroup} )}
4973 @d break_penalty=42 {additional badness ( \.{\\penalty} )}
4974 @d start_par=43 {begin paragraph ( \.{\\indent}, \.{\\noindent} )}
4975 @d ital_corr=44 {italic correction ( \.{\\/} )}
4976 @d accent=45 {attach accent in text ( \.{\\accent} )}
4977 @d math_accent=46 {attach accent in math ( \.{\\mathaccent} )}
4978 @d discretionary=47 {discretionary texts ( \.{\\-}, \.{\\discretionary} )}
4979 @d eq_no=48 {equation number ( \.{\\eqno}, \.{\\leqno} )}
4980 @d left_right=49 {variable delimiter ( \.{\\left}, \.{\\right} )}
4981 {( or \.{\\middle} )}
4982 @d math_comp=50 {component of formula ( \.{\\mathbin}, etc.~)}
4983 @d limit_switch=51 {diddle limit conventions ( \.{\\displaylimits}, etc.~)}
4984 @d above=52 {generalized fraction ( \.{\\above}, \.{\\atop}, etc.~)}
4985 @d math_style=53 {style specification ( \.{\\displaystyle}, etc.~)}
4986 @d math_choice=54 {choice specification ( \.{\\mathchoice} )}
4987 @d non_script=55 {conditional math glue ( \.{\\nonscript} )}
4988 @d vcenter=56 {vertically center a vbox ( \.{\\vcenter} )}
4989 @d case_shift=57 {force specific case ( \.{\\lowercase}, \.{\\uppercase}~)}
4990 @d message=58 {send to user ( \.{\\message}, \.{\\errmessage} )}
4991 @d extension=59 {extensions to \TeX\ ( \.{\\write}, \.{\\special}, etc.~)}
4992 @d in_stream=60 {files for reading ( \.{\\openin}, \.{\\closein} )}
4993 @d begin_group=61 {begin local grouping ( \.{\\begingroup} )}
4994 @d end_group=62 {end local grouping ( \.{\\endgroup} )}
4995 @d omit=63 {omit alignment template ( \.{\\omit} )}
4996 @d ex_space=64 {explicit space ( \.{\\\ } )}
4997 @d no_boundary=65 {suppress boundary ligatures ( \.{\\noboundary} )}
4998 @d radical=66 {square root and similar signs ( \.{\\radical} )}
4999 @d end_cs_name=67 {end control sequence ( \.{\\endcsname} )}
5000 @d min_internal=68 {the smallest code that can follow \.{\\the}}
5001 @d char_given=68 {character code defined by \.{\\chardef}}
5002 @d math_given=69 {math code defined by \.{\\mathchardef}}
5003 @d XeTeX_math_given=70 {extended math code defined by \.{\\Umathchardef}}
5004 @d last_item=71 {most recent item ( \.{\\lastpenalty},
5005 \.{\\lastkern}, \.{\\lastskip} )}
5006 @d max_non_prefixed_command=71 {largest command code that can't be \.{\\global}}
5007
5008 @ The next codes are special; they all relate to mode-independent
5009 assignment of values to \TeX's internal registers or tables.
5010 Codes that are |max_internal| or less represent internal quantities
5011 that might be expanded by `\.{\\the}'.
5012
5013 @d toks_register=72 {token list register ( \.{\\toks} )}
5014 @d assign_toks=73 {special token list ( \.{\\output}, \.{\\everypar}, etc.~)}
5015 @d assign_int=74 {user-defined integer ( \.{\\tolerance}, \.{\\day}, etc.~)}
5016 @d assign_dimen=75 {user-defined length ( \.{\\hsize}, etc.~)}
5017 @d assign_glue=76 {user-defined glue ( \.{\\baselineskip}, etc.~)}
5018 @d assign_mu_glue=77 {user-defined muglue ( \.{\\thinmuskip}, etc.~)}
5019 @d assign_font_dimen=78 {user-defined font dimension ( \.{\\fontdimen} )}
5020 @d assign_font_int=79 {user-defined font integer ( \.{\\hyphenchar},
5021 \.{\\skewchar} )}
5022 @d set_aux=80 {specify state info ( \.{\\spacefactor}, \.{\\prevdepth} )}
5023 @d set_prev_graf=81 {specify state info ( \.{\\prevgraf} )}
5024 @d set_page_dimen=82 {specify state info ( \.{\\pagegoal}, etc.~)}
5025 @d set_page_int=83 {specify state info ( \.{\\deadcycles},
5026 \.{\\insertpenalties} )}
5027 {( or \.{\\interactionmode} )}
5028 @d set_box_dimen=84 {change dimension of box ( \.{\\wd}, \.{\\ht}, \.{\\dp} )}
5029 @d set_shape=85 {specify fancy paragraph shape ( \.{\\parshape} )}
5030 {(or \.{\\interlinepenalties}, etc.~)}
5031 @d def_code=86 {define a character code ( \.{\\catcode}, etc.~)}
5032 @d XeTeX_def_code=87 {\.{\\Umathcode}, \.{\\Udelcode}}
5033 @d def_family=88 {declare math fonts ( \.{\\textfont}, etc.~)}
5034 @d set_font=89 {set current font ( font identifiers )}
5035 @d def_font=90 {define a font file ( \.{\\font} )}
5036 @d register=91 {internal register ( \.{\\count}, \.{\\dimen}, etc.~)}
5037 @d max_internal=91 {the largest code that can follow \.{\\the}}
5038 @d advance=92 {advance a register or parameter ( \.{\\advance} )}
5039 @d multiply=93 {multiply a register or parameter ( \.{\\multiply} )}
5040 @d divide=94 {divide a register or parameter ( \.{\\divide} )}
5041 @d prefix=95 {qualify a definition ( \.{\\global}, \.{\\long}, \.{\\outer} )}
5042 {( or \.{\\protected} )}
5043 @d let=96 {assign a command code ( \.{\\let}, \.{\\futurelet} )}
5044 @d shorthand_def=97 {code definition ( \.{\\chardef}, \.{\\countdef}, etc.~)}
5045 @d read_to_cs=98 {read into a control sequence ( \.{\\read} )}
5046 {( or \.{\\readline} )}
5047 @d def=99 {macro definition ( \.{\\def}, \.{\\gdef}, \.{\\xdef}, \.{\\edef} )}
5048 @d set_box=100 {set a box ( \.{\\setbox} )}
5049 @d hyph_data=101 {hyphenation data ( \.{\\hyphenation}, \.{\\patterns} )}
5050 @d set_interaction=102 {define level of interaction ( \.{\\batchmode}, etc.~)}
5051 @d max_command=102 {the largest command code seen at |big_switch|}
5052
5053 @ The remaining command codes are extra special, since they cannot get through
5054 \TeX's scanner to the main control routine. They have been given values higher
5055 than |max_command| so that their special nature is easily discernible.
5056 The ``expandable'' commands come first.
5057
5058 @d undefined_cs=max_command+1 {initial state of most |eq_type| fields}
5059 @d expand_after=max_command+2 {special expansion ( \.{\\expandafter} )}
5060 @d no_expand=max_command+3 {special nonexpansion ( \.{\\noexpand} )}
5061 @d input=max_command+4 {input a source file ( \.{\\input}, \.{\\endinput} )}
5062 {( or \.{\\scantokens} )}
5063 @d if_test=max_command+5 {conditional text ( \.{\\if}, \.{\\ifcase}, etc.~)}
5064 @d fi_or_else=max_command+6 {delimiters for conditionals ( \.{\\else}, etc.~)}
5065 @d cs_name=max_command+7 {make a control sequence from tokens ( \.{\\csname} )}
5066 @d convert=max_command+8 {convert to text ( \.{\\number}, \.{\\string}, etc.~)}
5067 @d the=max_command+9 {expand an internal quantity ( \.{\\the} )}
5068 {( or \.{\\unexpanded}, \.{\\detokenize} )}
5069 @d top_bot_mark=max_command+10 {inserted mark ( \.{\\topmark}, etc.~)}
5070 @d call=max_command+11 {non-long, non-outer control sequence}
5071 @d long_call=max_command+12 {long, non-outer control sequence}
5072 @d outer_call=max_command+13 {non-long, outer control sequence}
5073 @d long_outer_call=max_command+14 {long, outer control sequence}
5074 @d end_template=max_command+15 {end of an alignment template}
5075 @d dont_expand=max_command+16 {the following token was marked by \.{\\noexpand}}
5076 @d glue_ref=max_command+17 {the equivalent points to a glue specification}
5077 @d shape_ref=max_command+18 {the equivalent points to a parshape specification}
5078 @d box_ref=max_command+19 {the equivalent points to a box node, or is |null|}
5079 @d data=max_command+20 {the equivalent is simply a halfword number}
5080
5081 @* \[16] The semantic nest.
5082 \TeX\ is typically in the midst of building many lists at once. For example,
5083 when a math formula is being processed, \TeX\ is in math mode and
5084 working on an mlist; this formula has temporarily interrupted \TeX\ from
5085 being in horizontal mode and building the hlist of a paragraph; and this
5086 paragraph has temporarily interrupted \TeX\ from being in vertical mode
5087 and building the vlist for the next page of a document. Similarly, when a
5088 \.{\\vbox} occurs inside of an \.{\\hbox}, \TeX\ is temporarily
5089 interrupted from working in restricted horizontal mode, and it enters
5090 internal vertical mode. The ``semantic nest'' is a stack that
5091 keeps track of what lists and modes are currently suspended.
5092
5093 At each level of processing we are in one of six modes:
5094
5095 \yskip\hang|vmode| stands for vertical mode (the page builder);
5096
5097 \hang|hmode| stands for horizontal mode (the paragraph builder);
5098
5099 \hang|mmode| stands for displayed formula mode;
5100
5101 \hang|-vmode| stands for internal vertical mode (e.g., in a \.{\\vbox});
5102
5103 \hang|-hmode| stands for restricted horizontal mode (e.g., in an \.{\\hbox});
5104
5105 \hang|-mmode| stands for math formula mode (not displayed).
5106
5107 \yskip\noindent The mode is temporarily set to zero while processing \.{\\write}
5108 texts.
5109
5110 Numeric values are assigned to |vmode|, |hmode|, and |mmode| so that
5111 \TeX's ``big semantic switch'' can select the appropriate thing to
5112 do by computing the value |abs(mode)+cur_cmd|, where |mode| is the current
5113 mode and |cur_cmd| is the current command code.
5114
5115 @d vmode=1 {vertical mode}
5116 @d hmode=vmode+max_command+1 {horizontal mode}
5117 @d mmode=hmode+max_command+1 {math mode}
5118
5119 @p procedure print_mode(@!m:integer); {prints the mode represented by |m|}
5120 begin if m>0 then
5121 case m div (max_command+1) of
5122 0:print("vertical");
5123 1:print("horizontal");
5124 2:print("display math");
5125 end
5126 else if m=0 then print("no")
5127 else case (-m) div (max_command+1) of
5128 0:print("internal vertical");
5129 1:print("restricted horizontal");
5130 2:print("math");
5131 end;
5132 print(" mode");
5133 end;
5134
5135 @ The state of affairs at any semantic level can be represented by
5136 five values:
5137
5138 \yskip\hang|mode| is the number representing the semantic mode, as
5139 just explained.
5140
5141 \yskip\hang|head| is a |pointer| to a list head for the list being built;
5142 |link(head)| therefore points to the first element of the list, or
5143 to |null| if the list is empty.
5144
5145 \yskip\hang|tail| is a |pointer| to the final node of the list being
5146 built; thus, |tail=head| if and only if the list is empty.
5147
5148 \yskip\hang|prev_graf| is the number of lines of the current paragraph that
5149 have already been put into the present vertical list.
5150
5151 \yskip\hang|aux| is an auxiliary |memory_word| that gives further information
5152 that is needed to characterize the situation.
5153
5154 \yskip\noindent
5155 In vertical mode, |aux| is also known as |prev_depth|; it is the scaled
5156 value representing the depth of the previous box, for use in baseline
5157 calculations, or it is |<=-1000|pt if the next box on the vertical list is to
5158 be exempt from baseline calculations. In horizontal mode, |aux| is also
5159 known as |space_factor| and |clang|; it holds the current space factor used in
5160 spacing calculations, and the current language used for hyphenation.
5161 (The value of |clang| is undefined in restricted horizontal mode.)
5162 In math mode, |aux| is also known as |incompleat_noad|; if
5163 not |null|, it points to a record that represents the numerator of a
5164 generalized fraction for which the denominator is currently being formed
5165 in the current list.
5166
5167 There is also a sixth quantity, |mode_line|, which correlates
5168 the semantic nest with the user's input; |mode_line| contains the source
5169 line number at which the current level of nesting was entered. The negative
5170 of this line number is the |mode_line| at the level of the
5171 user's output routine.
5172
5173 A seventh quantity, |eTeX_aux|, is used by the extended features \eTeX.
5174 In vertical modes it is known as |LR_save| and holds the LR stack when a
5175 paragraph is interrupted by a displayed formula. In display math mode
5176 it is known as |LR_box| and holds a pointer to a prototype box for the
5177 display. In math mode it is known as |delim_ptr| and points to the most
5178 recent |left_noad| or |middle_noad| of a |math_left_group|.
5179
5180 In horizontal mode, the |prev_graf| field is used for initial language data.
5181
5182 The semantic nest is an array called |nest| that holds the |mode|, |head|,
5183 |tail|, |prev_graf|, |aux|, and |mode_line| values for all semantic levels
5184 below the currently active one. Information about the currently active
5185 level is kept in the global quantities |mode|, |head|, |tail|, |prev_graf|,
5186 |aux|, and |mode_line|, which live in a \PASCAL\ record that is ready to
5187 be pushed onto |nest| if necessary.
5188
5189 @d ignore_depth==-65536000 {|prev_depth| value that is ignored}
5190
5191 @<Types...@>=
5192 @!list_state_record=record@!mode_field:-mmode..mmode;@+
5193 @!head_field,@!tail_field: pointer;
5194 @!eTeX_aux_field: pointer;
5195 @!pg_field,@!ml_field: integer;@+
5196 @!aux_field: memory_word;
5197 end;
5198
5199 @ @d mode==cur_list.mode_field {current mode}
5200 @d head==cur_list.head_field {header node of current list}
5201 @d tail==cur_list.tail_field {final node on current list}
5202 @d eTeX_aux==cur_list.eTeX_aux_field {auxiliary data for \eTeX}
5203 @d LR_save==eTeX_aux {LR stack when a paragraph is interrupted}
5204 @d LR_box==eTeX_aux {prototype box for display}
5205 @d delim_ptr==eTeX_aux {most recent left or right noad of a math left group}
5206 @d prev_graf==cur_list.pg_field {number of paragraph lines accumulated}
5207 @d aux==cur_list.aux_field {auxiliary data about the current list}
5208 @d prev_depth==aux.sc {the name of |aux| in vertical mode}
5209 @d space_factor==aux.hh.lh {part of |aux| in horizontal mode}
5210 @d clang==aux.hh.rh {the other part of |aux| in horizontal mode}
5211 @d incompleat_noad==aux.int {the name of |aux| in math mode}
5212 @d mode_line==cur_list.ml_field {source file line number at beginning of list}
5213
5214 @<Glob...@>=
5215 @!nest:array[0..nest_size] of list_state_record;
5216 @!nest_ptr:0..nest_size; {first unused location of |nest|}
5217 @!max_nest_stack:0..nest_size; {maximum of |nest_ptr| when pushing}
5218 @!cur_list:list_state_record; {the ``top'' semantic state}
5219 @!shown_mode:-mmode..mmode; {most recent mode shown by \.{\\tracingcommands}}
5220
5221 @ Here is a common way to make the current list grow:
5222
5223 @d tail_append(#)==begin link(tail):=#; tail:=link(tail);
5224 end
5225
5226 @ We will see later that the vertical list at the bottom semantic level is split
5227 into two parts; the ``current page'' runs from |page_head| to |page_tail|,
5228 and the ``contribution list'' runs from |contrib_head| to |tail| of
5229 semantic level zero. The idea is that contributions are first formed in
5230 vertical mode, then ``contributed'' to the current page (during which time
5231 the page-breaking decisions are made). For now, we don't need to know
5232 any more details about the page-building process.
5233
5234 @<Set init...@>=
5235 nest_ptr:=0; max_nest_stack:=0;
5236 mode:=vmode; head:=contrib_head; tail:=contrib_head;
5237 eTeX_aux:=null;
5238 prev_depth:=ignore_depth; mode_line:=0;
5239 prev_graf:=0; shown_mode:=0;
5240 @<Start a new current page@>;
5241
5242 @ When \TeX's work on one level is interrupted, the state is saved by
5243 calling |push_nest|. This routine changes |head| and |tail| so that
5244 a new (empty) list is begun; it does not change |mode| or |aux|.
5245
5246 @p procedure push_nest; {enter a new semantic level, save the old}
5247 begin if nest_ptr>max_nest_stack then
5248 begin max_nest_stack:=nest_ptr;
5249 if nest_ptr=nest_size then overflow("semantic nest size",nest_size);
5250 @:TeX capacity exceeded semantic nest size}{\quad semantic nest size@>
5251 end;
5252 nest[nest_ptr]:=cur_list; {stack the record}
5253 incr(nest_ptr); head:=get_avail; tail:=head; prev_graf:=0; mode_line:=line;
5254 eTeX_aux:=null;
5255 end;
5256
5257 @ Conversely, when \TeX\ is finished on the current level, the former
5258 state is restored by calling |pop_nest|. This routine will never be
5259 called at the lowest semantic level, nor will it be called unless |head|
5260 is a node that should be returned to free memory.
5261
5262 @p procedure pop_nest; {leave a semantic level, re-enter the old}
5263 begin free_avail(head); decr(nest_ptr); cur_list:=nest[nest_ptr];
5264 end;
5265
5266 @ Here is a procedure that displays what \TeX\ is working on, at all levels.
5267
5268 @p procedure@?print_totals; forward;@t\2@>
5269 procedure show_activities;
5270 var p:0..nest_size; {index into |nest|}
5271 @!m:-mmode..mmode; {mode}
5272 @!a:memory_word; {auxiliary}
5273 @!q,@!r:pointer; {for showing the current page}
5274 @!t:integer; {ditto}
5275 begin nest[nest_ptr]:=cur_list; {put the top level into the array}
5276 print_nl(""); print_ln;
5277 for p:=nest_ptr downto 0 do
5278 begin m:=nest[p].mode_field; a:=nest[p].aux_field;
5279 print_nl("### "); print_mode(m);
5280 print(" entered at line "); print_int(abs(nest[p].ml_field));
5281 if m=hmode then if nest[p].pg_field <> @'40600000 then
5282 begin print(" (language"); print_int(nest[p].pg_field mod @'200000);
5283 print(":hyphenmin"); print_int(nest[p].pg_field div @'20000000);
5284 print_char(","); print_int((nest[p].pg_field div @'200000) mod @'100);
5285 print_char(")");
5286 end;
5287 if nest[p].ml_field<0 then print(" (\output routine)");
5288 if p=0 then
5289 begin @<Show the status of the current page@>;
5290 if link(contrib_head)<>null then
5291 print_nl("### recent contributions:");
5292 end;
5293 show_box(link(nest[p].head_field));
5294 @<Show the auxiliary field, |a|@>;
5295 end;
5296 end;
5297
5298 @ @<Show the auxiliary...@>=
5299 case abs(m) div (max_command+1) of
5300 0: begin print_nl("prevdepth ");
5301 if a.sc<=ignore_depth then print("ignored")
5302 else print_scaled(a.sc);
5303 if nest[p].pg_field<>0 then
5304 begin print(", prevgraf ");
5305 print_int(nest[p].pg_field); print(" line");
5306 if nest[p].pg_field<>1 then print_char("s");
5307 end;
5308 end;
5309 1: begin print_nl("spacefactor "); print_int(a.hh.lh);
5310 if m>0 then@+ if a.hh.rh>0 then
5311 begin print(", current language "); print_int(a.hh.rh);@+
5312 end;
5313 end;
5314 2: if a.int<>null then
5315 begin print("this will begin denominator of:"); show_box(a.int);@+
5316 end;
5317 end {there are no other cases}
5318
5319 @* \[17] The table of equivalents.
5320 Now that we have studied the data structures for \TeX's semantic routines,
5321 we ought to consider the data structures used by its syntactic routines. In
5322 other words, our next concern will be
5323 the tables that \TeX\ looks at when it is scanning
5324 what the user has written.
5325
5326 The biggest and most important such table is called |eqtb|. It holds the
5327 current ``equivalents'' of things; i.e., it explains what things mean
5328 or what their current values are, for all quantities that are subject to
5329 the nesting structure provided by \TeX's grouping mechanism. There are six
5330 parts to |eqtb|:
5331
5332 \yskip\hangg 1) |eqtb[active_base..(hash_base-1)]| holds the current
5333 equivalents of single-character control sequences.
5334
5335 \yskip\hangg 2) |eqtb[hash_base..(glue_base-1)]| holds the current
5336 equivalents of multiletter control sequences.
5337
5338 \yskip\hangg 3) |eqtb[glue_base..(local_base-1)]| holds the current
5339 equivalents of glue parameters like the current baselineskip.
5340
5341 \yskip\hangg 4) |eqtb[local_base..(int_base-1)]| holds the current
5342 equivalents of local halfword quantities like the current box registers,
5343 the current ``catcodes,'' the current font, and a pointer to the current
5344 paragraph shape.
5345
5346 \yskip\hangg 5) |eqtb[int_base..(dimen_base-1)]| holds the current
5347 equivalents of fullword integer parameters like the current hyphenation
5348 penalty.
5349
5350 \yskip\hangg 6) |eqtb[dimen_base..eqtb_size]| holds the current equivalents
5351 of fullword dimension parameters like the current hsize or amount of
5352 hanging indentation.
5353
5354 \yskip\noindent Note that, for example, the current amount of
5355 baselineskip glue is determined by the setting of a particular location
5356 in region~3 of |eqtb|, while the current meaning of the control sequence
5357 `\.{\\baselineskip}' (which might have been changed by \.{\\def} or
5358 \.{\\let}) appears in region~2.
5359
5360 @ Each entry in |eqtb| is a |memory_word|. Most of these words are of type
5361 |two_halves|, and subdivided into three fields:
5362
5363 \yskip\hangg 1) The |eq_level| (a quarterword) is the level of grouping at
5364 which this equivalent was defined. If the level is |level_zero|, the
5365 equivalent has never been defined; |level_one| refers to the outer level
5366 (outside of all groups), and this level is also used for global
5367 definitions that never go away. Higher levels are for equivalents that
5368 will disappear at the end of their group. @^global definitions@>
5369
5370 \yskip\hangg 2) The |eq_type| (another quarterword) specifies what kind of
5371 entry this is. There are many types, since each \TeX\ primitive like
5372 \.{\\hbox}, \.{\\def}, etc., has its own special code. The list of
5373 command codes above includes all possible settings of the |eq_type| field.
5374
5375 \yskip\hangg 3) The |equiv| (a halfword) is the current equivalent value.
5376 This may be a font number, a pointer into |mem|, or a variety of other
5377 things.
5378
5379 @d eq_level_field(#)==#.hh.b1
5380 @d eq_type_field(#)==#.hh.b0
5381 @d equiv_field(#)==#.hh.rh
5382 @d eq_level(#)==eq_level_field(eqtb[#]) {level of definition}
5383 @d eq_type(#)==eq_type_field(eqtb[#]) {command code for equivalent}
5384 @d equiv(#)==equiv_field(eqtb[#]) {equivalent value}
5385 @d level_zero=min_quarterword {level for undefined quantities}
5386 @d level_one=level_zero+1 {outermost level for defined quantities}
5387
5388 @ Many locations in |eqtb| have symbolic names. The purpose of the next
5389 paragraphs is to define these names, and to set up the initial values of the
5390 equivalents.
5391
5392 In the first region we have |number_usvs| equivalents for ``active characters''
5393 that act as control sequences, followed by |too_big_char| equivalents for
5394 single-character control sequences.
5395
5396 Then comes region~2, which corresponds to the hash table that we will
5397 define later. The maximum address in this region is used for a dummy
5398 control sequence that is perpetually undefined. There also are several
5399 locations for control sequences that are perpetually defined
5400 (since they are used in error recovery).
5401
5402 @d active_base=1 {beginning of region 1, for active character equivalents}
5403 @d single_base=active_base+number_usvs
5404 {equivalents of one-character control sequences}
5405 {single-character sequence whose character code is ${}>|@"FFFF|$ are
5406 treated as a multiletter sequence, because UTF-16 is used in the string pool. }
5407 @d null_cs=single_base+too_big_char {equivalent of \.{\\csname\\endcsname}}
5408 @d hash_base=null_cs+1 {beginning of region 2, for the hash table}
5409 @d frozen_control_sequence=hash_base+hash_size {for error recovery}
5410 @d frozen_protection=frozen_control_sequence {inaccessible but definable}
5411 @d frozen_cr=frozen_control_sequence+1 {permanent `\.{\\cr}'}
5412 @d frozen_end_group=frozen_control_sequence+2 {permanent `\.{\\endgroup}'}
5413 @d frozen_right=frozen_control_sequence+3 {permanent `\.{\\right}'}
5414 @d frozen_fi=frozen_control_sequence+4 {permanent `\.{\\fi}'}
5415 @d frozen_end_template=frozen_control_sequence+5 {permanent `\.{\\endtemplate}'}
5416 @d frozen_endv=frozen_control_sequence+6 {second permanent `\.{\\endtemplate}'}
5417 @d frozen_relax=frozen_control_sequence+7 {permanent `\.{\\relax}'}
5418 @d end_write=frozen_control_sequence+8 {permanent `\.{\\endwrite}'}
5419 @d frozen_dont_expand=frozen_control_sequence+9
5420 {permanent `\.{\\notexpanded:}'}
5421 @d prim_size=2100 {maximum number of primitives }
5422 @d frozen_null_font=frozen_control_sequence+10
5423 {permanent `\.{\\nullfont}'}
5424 @d frozen_primitive=frozen_control_sequence+11
5425 {permanent `\.{\\pdfprimitive}'}
5426 @d prim_eqtb_base=frozen_primitive+1
5427 @d font_id_base=frozen_null_font-font_base
5428 {begins table of 257 permanent font identifiers}
5429 @d undefined_control_sequence=frozen_null_font+257 {dummy location}
5430 @d glue_base=undefined_control_sequence+1 {beginning of region 3}
5431
5432 @<Initialize table entries...@>=
5433 eq_type(undefined_control_sequence):=undefined_cs;
5434 equiv(undefined_control_sequence):=null;
5435 eq_level(undefined_control_sequence):=level_zero;
5436 for k:=active_base to undefined_control_sequence-1 do
5437 eqtb[k]:=eqtb[undefined_control_sequence];
5438
5439 @ Here is a routine that displays the current meaning of an |eqtb| entry
5440 in region 1 or~2. (Similar routines for the other regions will appear
5441 below.)
5442
5443 @<Show equivalent |n|, in region 1 or 2@>=
5444 begin sprint_cs(n); print_char("="); print_cmd_chr(eq_type(n),equiv(n));
5445 if eq_type(n)>=call then
5446 begin print_char(":"); show_token_list(link(equiv(n)),null,32);
5447 end;
5448 end
5449
5450 @ Region 3 of |eqtb| contains the |number_regs| \.{\\skip} registers,
5451 as well as the glue parameters defined here. It is important that the
5452 ``muskip'' parameters have larger numbers than the others.
5453
5454 @d line_skip_code=0 {interline glue if |baseline_skip| is infeasible}
5455 @d baseline_skip_code=1 {desired glue between baselines}
5456 @d par_skip_code=2 {extra glue just above a paragraph}
5457 @d above_display_skip_code=3 {extra glue just above displayed math}
5458 @d below_display_skip_code=4 {extra glue just below displayed math}
5459 @d above_display_short_skip_code=5
5460 {glue above displayed math following short lines}
5461 @d below_display_short_skip_code=6
5462 {glue below displayed math following short lines}
5463 @d left_skip_code=7 {glue at left of justified lines}
5464 @d right_skip_code=8 {glue at right of justified lines}
5465 @d top_skip_code=9 {glue at top of main pages}
5466 @d split_top_skip_code=10 {glue at top of split pages}
5467 @d tab_skip_code=11 {glue between aligned entries}
5468 @d space_skip_code=12 {glue between words (if not |zero_glue|)}
5469 @d xspace_skip_code=13 {glue after sentences (if not |zero_glue|)}
5470 @d par_fill_skip_code=14 {glue on last line of paragraph}
5471 @d XeTeX_linebreak_skip_code=15 {glue introduced at potential linebreak location}
5472 @d thin_mu_skip_code=16 {thin space in math formula}
5473 @d med_mu_skip_code=17 {medium space in math formula}
5474 @d thick_mu_skip_code=18 {thick space in math formula}
5475 @d glue_pars=19 {total number of glue parameters}
5476 @d skip_base=glue_base+glue_pars {table of |number_regs| ``skip'' registers}
5477 @d mu_skip_base=skip_base+number_regs
5478 {table of |number_regs| ``muskip'' registers}
5479 @d local_base=mu_skip_base+number_regs {beginning of region 4}
5480 @#
5481 @d skip(#)==equiv(skip_base+#) {|mem| location of glue specification}
5482 @d mu_skip(#)==equiv(mu_skip_base+#) {|mem| location of math glue spec}
5483 @d glue_par(#)==equiv(glue_base+#) {|mem| location of glue specification}
5484 @d line_skip==glue_par(line_skip_code)
5485 @d baseline_skip==glue_par(baseline_skip_code)
5486 @d par_skip==glue_par(par_skip_code)
5487 @d above_display_skip==glue_par(above_display_skip_code)
5488 @d below_display_skip==glue_par(below_display_skip_code)
5489 @d above_display_short_skip==glue_par(above_display_short_skip_code)
5490 @d below_display_short_skip==glue_par(below_display_short_skip_code)
5491 @d left_skip==glue_par(left_skip_code)
5492 @d right_skip==glue_par(right_skip_code)
5493 @d top_skip==glue_par(top_skip_code)
5494 @d split_top_skip==glue_par(split_top_skip_code)
5495 @d tab_skip==glue_par(tab_skip_code)
5496 @d space_skip==glue_par(space_skip_code)
5497 @d xspace_skip==glue_par(xspace_skip_code)
5498 @d par_fill_skip==glue_par(par_fill_skip_code)
5499 @d XeTeX_linebreak_skip==glue_par(XeTeX_linebreak_skip_code)
5500 @d thin_mu_skip==glue_par(thin_mu_skip_code)
5501 @d med_mu_skip==glue_par(med_mu_skip_code)
5502 @d thick_mu_skip==glue_par(thick_mu_skip_code)
5503
5504 @<Current |mem| equivalent of glue parameter number |n|@>=glue_par(n)
5505
5506 @ Sometimes we need to convert \TeX's internal code numbers into symbolic
5507 form. The |print_skip_param| routine gives the symbolic name of a glue
5508 parameter.
5509
5510 @<Declare the procedure called |print_skip_param|@>=
5511 procedure print_skip_param(@!n:integer);
5512 begin case n of
5513 line_skip_code: print_esc("lineskip");
5514 baseline_skip_code: print_esc("baselineskip");
5515 par_skip_code: print_esc("parskip");
5516 above_display_skip_code: print_esc("abovedisplayskip");
5517 below_display_skip_code: print_esc("belowdisplayskip");
5518 above_display_short_skip_code: print_esc("abovedisplayshortskip");
5519 below_display_short_skip_code: print_esc("belowdisplayshortskip");
5520 left_skip_code: print_esc("leftskip");
5521 right_skip_code: print_esc("rightskip");
5522 top_skip_code: print_esc("topskip");
5523 split_top_skip_code: print_esc("splittopskip");
5524 tab_skip_code: print_esc("tabskip");
5525 space_skip_code: print_esc("spaceskip");
5526 xspace_skip_code: print_esc("xspaceskip");
5527 par_fill_skip_code: print_esc("parfillskip");
5528 XeTeX_linebreak_skip_code: print_esc("XeTeXlinebreakskip");
5529 thin_mu_skip_code: print_esc("thinmuskip");
5530 med_mu_skip_code: print_esc("medmuskip");
5531 thick_mu_skip_code: print_esc("thickmuskip");
5532 othercases print("[unknown glue parameter!]")
5533 endcases;
5534 end;
5535
5536 @ The symbolic names for glue parameters are put into \TeX's hash table
5537 by using the routine called |primitive|, defined below. Let us enter them
5538 now, so that we don't have to list all those parameter names anywhere else.
5539
5540 @<Put each of \TeX's primitives into the hash table@>=
5541 primitive("lineskip",assign_glue,glue_base+line_skip_code);@/
5542 @!@:line_skip_}{\.{\\lineskip} primitive@>
5543 primitive("baselineskip",assign_glue,glue_base+baseline_skip_code);@/
5544 @!@:baseline_skip_}{\.{\\baselineskip} primitive@>
5545 primitive("parskip",assign_glue,glue_base+par_skip_code);@/
5546 @!@:par_skip_}{\.{\\parskip} primitive@>
5547 primitive("abovedisplayskip",assign_glue,glue_base+above_display_skip_code);@/
5548 @!@:above_display_skip_}{\.{\\abovedisplayskip} primitive@>
5549 primitive("belowdisplayskip",assign_glue,glue_base+below_display_skip_code);@/
5550 @!@:below_display_skip_}{\.{\\belowdisplayskip} primitive@>
5551 primitive("abovedisplayshortskip",
5552 assign_glue,glue_base+above_display_short_skip_code);@/
5553 @!@:above_display_short_skip_}{\.{\\abovedisplayshortskip} primitive@>
5554 primitive("belowdisplayshortskip",
5555 assign_glue,glue_base+below_display_short_skip_code);@/
5556 @!@:below_display_short_skip_}{\.{\\belowdisplayshortskip} primitive@>
5557 primitive("leftskip",assign_glue,glue_base+left_skip_code);@/
5558 @!@:left_skip_}{\.{\\leftskip} primitive@>
5559 primitive("rightskip",assign_glue,glue_base+right_skip_code);@/
5560 @!@:right_skip_}{\.{\\rightskip} primitive@>
5561 primitive("topskip",assign_glue,glue_base+top_skip_code);@/
5562 @!@:top_skip_}{\.{\\topskip} primitive@>
5563 primitive("splittopskip",assign_glue,glue_base+split_top_skip_code);@/
5564 @!@:split_top_skip_}{\.{\\splittopskip} primitive@>
5565 primitive("tabskip",assign_glue,glue_base+tab_skip_code);@/
5566 @!@:tab_skip_}{\.{\\tabskip} primitive@>
5567 primitive("spaceskip",assign_glue,glue_base+space_skip_code);@/
5568 @!@:space_skip_}{\.{\\spaceskip} primitive@>
5569 primitive("xspaceskip",assign_glue,glue_base+xspace_skip_code);@/
5570 @!@:xspace_skip_}{\.{\\xspaceskip} primitive@>
5571 primitive("parfillskip",assign_glue,glue_base+par_fill_skip_code);@/
5572 @!@:par_fill_skip_}{\.{\\parfillskip} primitive@>
5573 primitive("XeTeXlinebreakskip",assign_glue,glue_base+XeTeX_linebreak_skip_code);@/
5574 @!@:XeTeX_linebreak_skip_}{\.{\\XeTeXlinebreakskip} primitive@>
5575 primitive("thinmuskip",assign_mu_glue,glue_base+thin_mu_skip_code);@/
5576 @!@:thin_mu_skip_}{\.{\\thinmuskip} primitive@>
5577 primitive("medmuskip",assign_mu_glue,glue_base+med_mu_skip_code);@/
5578 @!@:med_mu_skip_}{\.{\\medmuskip} primitive@>
5579 primitive("thickmuskip",assign_mu_glue,glue_base+thick_mu_skip_code);@/
5580 @!@:thick_mu_skip_}{\.{\\thickmuskip} primitive@>
5581
5582 @ @<Cases of |print_cmd_chr| for symbolic printing of primitives@>=
5583 assign_glue,assign_mu_glue: if chr_code<skip_base then
5584 print_skip_param(chr_code-glue_base)
5585 else if chr_code<mu_skip_base then
5586 begin print_esc("skip"); print_int(chr_code-skip_base);
5587 end
5588 else begin print_esc("muskip"); print_int(chr_code-mu_skip_base);
5589 end;
5590
5591 @ All glue parameters and registers are initially `\.{0pt plus0pt minus0pt}'.
5592
5593 @<Initialize table entries...@>=
5594 equiv(glue_base):=zero_glue; eq_level(glue_base):=level_one;
5595 eq_type(glue_base):=glue_ref;
5596 for k:=glue_base+1 to local_base-1 do eqtb[k]:=eqtb[glue_base];
5597 glue_ref_count(zero_glue):=glue_ref_count(zero_glue)+local_base-glue_base;
5598
5599 @ @<Show equivalent |n|, in region 3@>=
5600 if n<skip_base then
5601 begin print_skip_param(n-glue_base); print_char("=");
5602 if n<glue_base+thin_mu_skip_code then print_spec(equiv(n),"pt")
5603 else print_spec(equiv(n),"mu");
5604 end
5605 else if n<mu_skip_base then
5606 begin print_esc("skip"); print_int(n-skip_base); print_char("=");
5607 print_spec(equiv(n),"pt");
5608 end
5609 else begin print_esc("muskip"); print_int(n-mu_skip_base); print_char("=");
5610 print_spec(equiv(n),"mu");
5611 end
5612
5613 @ Region 4 of |eqtb| contains the local quantities defined here. The
5614 bulk of this region is taken up by five tables that are indexed by eight-bit
5615 characters; these tables are important to both the syntactic and semantic
5616 portions of \TeX. There are also a bunch of special things like font and
5617 token parameters, as well as the tables of \.{\\toks} and \.{\\box}
5618 registers.
5619
5620 @d par_shape_loc=local_base {specifies paragraph shape}
5621 @d output_routine_loc=local_base+1 {points to token list for \.{\\output}}
5622 @d every_par_loc=local_base+2 {points to token list for \.{\\everypar}}
5623 @d every_math_loc=local_base+3 {points to token list for \.{\\everymath}}
5624 @d every_display_loc=local_base+4 {points to token list for \.{\\everydisplay}}
5625 @d every_hbox_loc=local_base+5 {points to token list for \.{\\everyhbox}}
5626 @d every_vbox_loc=local_base+6 {points to token list for \.{\\everyvbox}}
5627 @d every_job_loc=local_base+7 {points to token list for \.{\\everyjob}}
5628 @d every_cr_loc=local_base+8 {points to token list for \.{\\everycr}}
5629 @d err_help_loc=local_base+9 {points to token list for \.{\\errhelp}}
5630 @d tex_toks=local_base+10 {end of \TeX's token list parameters}
5631 @#
5632 @d etex_toks_base=tex_toks {base for \eTeX's token list parameters}
5633 @d every_eof_loc=etex_toks_base {points to token list for \.{\\everyeof}}
5634 @d XeTeX_inter_char_loc=every_eof_loc+1 {not really used, but serves as a flag}
5635 @d etex_toks=XeTeX_inter_char_loc+1 {end of \eTeX's token list parameters}
5636 @#
5637 @d toks_base=etex_toks {table of |number_regs| token list registers}
5638 @#
5639 @d etex_pen_base=toks_base+number_regs {start of table of \eTeX's penalties}
5640 @d inter_line_penalties_loc=etex_pen_base {additional penalties between lines}
5641 @d club_penalties_loc=etex_pen_base+1 {penalties for creating club lines}
5642 @d widow_penalties_loc=etex_pen_base+2 {penalties for creating widow lines}
5643 @d display_widow_penalties_loc=etex_pen_base+3 {ditto, just before a display}
5644 @d etex_pens=etex_pen_base+4 {end of table of \eTeX's penalties}
5645 @#
5646 @d box_base=etex_pens {table of |number_regs| box registers}
5647 @d cur_font_loc=box_base+number_regs {internal font number outside math mode}
5648 @d math_font_base=cur_font_loc+1 {table of |number_math_fonts| math font numbers}
5649 @d cat_code_base=math_font_base+number_math_fonts
5650 {table of |number_usvs| command codes (the ``catcodes'')}
5651 @d lc_code_base=cat_code_base+number_usvs {table of |number_usvs| lowercase mappings}
5652 @d uc_code_base=lc_code_base+number_usvs {table of |number_usvs| uppercase mappings}
5653 @d sf_code_base=uc_code_base+number_usvs {table of |number_usvs| spacefactor mappings}
5654 @d math_code_base=sf_code_base+number_usvs {table of |number_usvs| math mode mappings}
5655 @d int_base=math_code_base+number_usvs {beginning of region 5}
5656 @#
5657 @d par_shape_ptr==equiv(par_shape_loc)
5658 @d output_routine==equiv(output_routine_loc)
5659 @d every_par==equiv(every_par_loc)
5660 @d every_math==equiv(every_math_loc)
5661 @d every_display==equiv(every_display_loc)
5662 @d every_hbox==equiv(every_hbox_loc)
5663 @d every_vbox==equiv(every_vbox_loc)
5664 @d every_job==equiv(every_job_loc)
5665 @d every_cr==equiv(every_cr_loc)
5666 @d err_help==equiv(err_help_loc)
5667 @d toks(#)==equiv(toks_base+#)
5668 @d box(#)==equiv(box_base+#)
5669 @d cur_font==equiv(cur_font_loc)
5670 @d fam_fnt(#)==equiv(math_font_base+#)
5671 @d cat_code(#)==equiv(cat_code_base+#)
5672 @d lc_code(#)==equiv(lc_code_base+#)
5673 @d uc_code(#)==equiv(uc_code_base+#)
5674 @d sf_code(#)==equiv(sf_code_base+#)
5675 @d math_code(#)==equiv(math_code_base+#)
5676 {Note: |math_code(c)| is the true math code plus |min_halfword|}
5677
5678 @<Put each...@>=
5679 primitive("output",assign_toks,output_routine_loc);
5680 @!@:output_}{\.{\\output} primitive@>
5681 primitive("everypar",assign_toks,every_par_loc);
5682 @!@:every_par_}{\.{\\everypar} primitive@>
5683 primitive("everymath",assign_toks,every_math_loc);
5684 @!@:every_math_}{\.{\\everymath} primitive@>
5685 primitive("everydisplay",assign_toks,every_display_loc);
5686 @!@:every_display_}{\.{\\everydisplay} primitive@>
5687 primitive("everyhbox",assign_toks,every_hbox_loc);
5688 @!@:every_hbox_}{\.{\\everyhbox} primitive@>
5689 primitive("everyvbox",assign_toks,every_vbox_loc);
5690 @!@:every_vbox_}{\.{\\everyvbox} primitive@>
5691 primitive("everyjob",assign_toks,every_job_loc);
5692 @!@:every_job_}{\.{\\everyjob} primitive@>
5693 primitive("everycr",assign_toks,every_cr_loc);
5694 @!@:every_cr_}{\.{\\everycr} primitive@>
5695 primitive("errhelp",assign_toks,err_help_loc);
5696 @!@:err_help_}{\.{\\errhelp} primitive@>
5697
5698 @ @<Cases of |print_cmd_chr|...@>=
5699 assign_toks: if chr_code>=toks_base then
5700 begin print_esc("toks"); print_int(chr_code-toks_base);
5701 end
5702 else case chr_code of
5703 output_routine_loc: print_esc("output");
5704 every_par_loc: print_esc("everypar");
5705 every_math_loc: print_esc("everymath");
5706 every_display_loc: print_esc("everydisplay");
5707 every_hbox_loc: print_esc("everyhbox");
5708 every_vbox_loc: print_esc("everyvbox");
5709 every_job_loc: print_esc("everyjob");
5710 every_cr_loc: print_esc("everycr");
5711 @/@<Cases of |assign_toks| for |print_cmd_chr|@>@/
5712 othercases print_esc("errhelp")
5713 endcases;
5714
5715 @ We initialize most things to null or undefined values. An undefined font
5716 is represented by the internal code |font_base|.
5717
5718 However, the character code tables are given initial values based on the
5719 conventional interpretation of ASCII code. These initial values should
5720 not be changed when \TeX\ is adapted for use with non-English languages;
5721 all changes to the initialization conventions should be made in format
5722 packages, not in \TeX\ itself, so that global interchange of formats is
5723 possible.
5724
5725 @d null_font==font_base
5726 @d var_fam_class = 7
5727 @d active_math_char = @"1FFFFF
5728 @d is_active_math_char(#) == math_char_field(#) = active_math_char
5729 @d is_var_family(#) == math_class_field(#) = 7
5730
5731 @<Initialize table entries...@>=
5732 par_shape_ptr:=null; eq_type(par_shape_loc):=shape_ref;
5733 eq_level(par_shape_loc):=level_one;@/
5734 for k:=etex_pen_base to etex_pens-1 do
5735 eqtb[k]:=eqtb[par_shape_loc];
5736 for k:=output_routine_loc to toks_base+number_regs-1 do
5737 eqtb[k]:=eqtb[undefined_control_sequence];
5738 box(0):=null; eq_type(box_base):=box_ref; eq_level(box_base):=level_one;
5739 for k:=box_base+1 to box_base+number_regs-1 do eqtb[k]:=eqtb[box_base];
5740 cur_font:=null_font; eq_type(cur_font_loc):=data;
5741 eq_level(cur_font_loc):=level_one;@/
5742 for k:=math_font_base to math_font_base+number_math_fonts-1 do eqtb[k]:=eqtb[cur_font_loc];
5743 equiv(cat_code_base):=0; eq_type(cat_code_base):=data;
5744 eq_level(cat_code_base):=level_one;@/
5745 for k:=cat_code_base+1 to int_base-1 do eqtb[k]:=eqtb[cat_code_base];
5746 for k:=0 to number_usvs-1 do
5747 begin cat_code(k):=other_char; math_code(k):=hi(k); sf_code(k):=1000;
5748 end;
5749 cat_code(carriage_return):=car_ret; cat_code(" "):=spacer;
5750 cat_code("\"):=escape; cat_code("%"):=comment;
5751 cat_code(invalid_code):=invalid_char; cat_code(null_code):=ignore;
5752 for k:="0" to "9" do math_code(k):=hi(k + set_class_field(var_fam_class));
5753 for k:="A" to "Z" do
5754 begin cat_code(k):=letter; cat_code(k+"a"-"A"):=letter;@/
5755 math_code(k):=hi(k + set_family_field(1) + set_class_field(var_fam_class));
5756 math_code(k+"a"-"A"):=hi(k+"a"-"A" + set_family_field(1) + set_class_field(var_fam_class));@/
5757 lc_code(k):=k+"a"-"A"; lc_code(k+"a"-"A"):=k+"a"-"A";@/
5758 uc_code(k):=k; uc_code(k+"a"-"A"):=k;@/
5759 sf_code(k):=999;
5760 end;
5761
5762 @ @<Show equivalent |n|, in region 4@>=
5763 if (n=par_shape_loc) or ((n>=etex_pen_base) and (n<etex_pens)) then
5764 begin print_cmd_chr(set_shape,n); print_char("=");
5765 if equiv(n)=null then print_char("0")
5766 else if n>par_shape_loc then
5767 begin print_int(penalty(equiv(n))); print_char(" ");
5768 print_int(penalty(equiv(n)+1));
5769 if penalty(equiv(n))>1 then print_esc("ETC.");
5770 end
5771 else print_int(info(par_shape_ptr));
5772 end
5773 else if n<toks_base then
5774 begin print_cmd_chr(assign_toks,n); print_char("=");
5775 if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
5776 end
5777 else if n<box_base then
5778 begin print_esc("toks"); print_int(n-toks_base); print_char("=");
5779 if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
5780 end
5781 else if n<cur_font_loc then
5782 begin print_esc("box"); print_int(n-box_base); print_char("=");
5783 if equiv(n)=null then print("void")
5784 else begin depth_threshold:=0; breadth_max:=1; show_node_list(equiv(n));
5785 end;
5786 end
5787 else if n<cat_code_base then @<Show the font identifier in |eqtb[n]|@>
5788 else @<Show the halfword code in |eqtb[n]|@>
5789
5790 @ @<Show the font identifier in |eqtb[n]|@>=
5791 begin if n=cur_font_loc then print("current font")
5792 else if n<math_font_base+script_size then
5793 begin print_esc("textfont"); print_int(n-math_font_base);
5794 end
5795 else if n<math_font_base+script_script_size then
5796 begin print_esc("scriptfont"); print_int(n-math_font_base-script_size);
5797 end
5798 else begin print_esc("scriptscriptfont");
5799 print_int(n-math_font_base-script_script_size);
5800 end;
5801 print_char("=");@/
5802 print_esc(hash[font_id_base+equiv(n)].rh);
5803 {that's |font_id_text(equiv(n))|}
5804 end
5805
5806 @ @<Show the halfword code in |eqtb[n]|@>=
5807 if n<math_code_base then
5808 begin if n<lc_code_base then
5809 begin print_esc("catcode"); print_int(n-cat_code_base);
5810 end
5811 else if n<uc_code_base then
5812 begin print_esc("lccode"); print_int(n-lc_code_base);
5813 end
5814 else if n<sf_code_base then
5815 begin print_esc("uccode"); print_int(n-uc_code_base);
5816 end
5817 else begin print_esc("sfcode"); print_int(n-sf_code_base);
5818 end;
5819 print_char("="); print_int(equiv(n));
5820 end
5821 else begin print_esc("mathcode"); print_int(n-math_code_base);
5822 print_char("="); print_int(ho(equiv(n)));
5823 end
5824
5825 @ Region 5 of |eqtb| contains the integer parameters and registers defined
5826 here, as well as the |del_code| table. The latter table differs from the
5827 |cat_code..math_code| tables that precede it, since delimiter codes are
5828 fullword integers while the other kinds of codes occupy at most a
5829 halfword. This is what makes region~5 different from region~4. We will
5830 store the |eq_level| information in an auxiliary array of quarterwords
5831 that will be defined later.
5832
5833 @d pretolerance_code=0 {badness tolerance before hyphenation}
5834 @d tolerance_code=1 {badness tolerance after hyphenation}
5835 @d line_penalty_code=2 {added to the badness of every line}
5836 @d hyphen_penalty_code=3 {penalty for break after discretionary hyphen}
5837 @d ex_hyphen_penalty_code=4 {penalty for break after explicit hyphen}
5838 @d club_penalty_code=5 {penalty for creating a club line}
5839 @d widow_penalty_code=6 {penalty for creating a widow line}
5840 @d display_widow_penalty_code=7 {ditto, just before a display}
5841 @d broken_penalty_code=8 {penalty for breaking a page at a broken line}
5842 @d bin_op_penalty_code=9 {penalty for breaking after a binary operation}
5843 @d rel_penalty_code=10 {penalty for breaking after a relation}
5844 @d pre_display_penalty_code=11
5845 {penalty for breaking just before a displayed formula}
5846 @d post_display_penalty_code=12
5847 {penalty for breaking just after a displayed formula}
5848 @d inter_line_penalty_code=13 {additional penalty between lines}
5849 @d double_hyphen_demerits_code=14 {demerits for double hyphen break}
5850 @d final_hyphen_demerits_code=15 {demerits for final hyphen break}
5851 @d adj_demerits_code=16 {demerits for adjacent incompatible lines}
5852 @d mag_code=17 {magnification ratio}
5853 @d delimiter_factor_code=18 {ratio for variable-size delimiters}
5854 @d looseness_code=19 {change in number of lines for a paragraph}
5855 @d time_code=20 {current time of day}
5856 @d day_code=21 {current day of the month}
5857 @d month_code=22 {current month of the year}
5858 @d year_code=23 {current year of our Lord}
5859 @d show_box_breadth_code=24 {nodes per level in |show_box|}
5860 @d show_box_depth_code=25 {maximum level in |show_box|}
5861 @d hbadness_code=26 {hboxes exceeding this badness will be shown by |hpack|}
5862 @d vbadness_code=27 {vboxes exceeding this badness will be shown by |vpack|}
5863 @d pausing_code=28 {pause after each line is read from a file}
5864 @d tracing_online_code=29 {show diagnostic output on terminal}
5865 @d tracing_macros_code=30 {show macros as they are being expanded}
5866 @d tracing_stats_code=31 {show memory usage if \TeX\ knows it}
5867 @d tracing_paragraphs_code=32 {show line-break calculations}
5868 @d tracing_pages_code=33 {show page-break calculations}
5869 @d tracing_output_code=34 {show boxes when they are shipped out}
5870 @d tracing_lost_chars_code=35 {show characters that aren't in the font}
5871 @d tracing_commands_code=36 {show command codes at |big_switch|}
5872 @d tracing_restores_code=37 {show equivalents when they are restored}
5873 @d uc_hyph_code=38 {hyphenate words beginning with a capital letter}
5874 @d output_penalty_code=39 {penalty found at current page break}
5875 @d max_dead_cycles_code=40 {bound on consecutive dead cycles of output}
5876 @d hang_after_code=41 {hanging indentation changes after this many lines}
5877 @d floating_penalty_code=42 {penalty for insertions held over after a split}
5878 @d global_defs_code=43 {override \.{\\global} specifications}
5879 @d cur_fam_code=44 {current family}
5880 @d escape_char_code=45 {escape character for token output}
5881 @d default_hyphen_char_code=46 {value of \.{\\hyphenchar} when a font is loaded}
5882 @d default_skew_char_code=47 {value of \.{\\skewchar} when a font is loaded}
5883 @d end_line_char_code=48 {character placed at the right end of the buffer}
5884 @d new_line_char_code=49 {character that prints as |print_ln|}
5885 @d language_code=50 {current hyphenation table}
5886 @d left_hyphen_min_code=51 {minimum left hyphenation fragment size}
5887 @d right_hyphen_min_code=52 {minimum right hyphenation fragment size}
5888 @d holding_inserts_code=53 {do not remove insertion nodes from \.{\\box255}}
5889 @d error_context_lines_code=54 {maximum intermediate line pairs shown}
5890 @d tex_int_pars=55 {total number of \TeX's integer parameters}
5891 @#
5892 @d etex_int_base=tex_int_pars {base for \eTeX's integer parameters}
5893 @d tracing_assigns_code=etex_int_base {show assignments}
5894 @d tracing_groups_code=etex_int_base+1 {show save/restore groups}
5895 @d tracing_ifs_code=etex_int_base+2 {show conditionals}
5896 @d tracing_scan_tokens_code=etex_int_base+3 {show pseudo file open and close}
5897 @d tracing_nesting_code=etex_int_base+4 {show incomplete groups and ifs within files}
5898 @d pre_display_direction_code=etex_int_base+5 {text direction preceding a display}
5899 @d last_line_fit_code=etex_int_base+6 {adjustment for last line of paragraph}
5900 @d saving_vdiscards_code=etex_int_base+7 {save items discarded from vlists}
5901 @d saving_hyph_codes_code=etex_int_base+8 {save hyphenation codes for languages}
5902 @d suppress_fontnotfound_error_code=etex_int_base+9 {suppress errors for missing fonts}
5903 @d ignore_primitive_error_code=etex_int_base+10 {ignore some primitive/engine errors}
5904 @d XeTeX_linebreak_locale_code=etex_int_base+11 {string number of locale to use for linebreak locations}
5905 @d XeTeX_linebreak_penalty_code=etex_int_base+12 {penalty to use at locale-dependent linebreak locations}
5906 @d XeTeX_protrude_chars_code=etex_int_base+13 {protrude chars at left/right edge of paragraphs}
5907 @d eTeX_state_code=etex_int_base+14 {\eTeX\ state variables}
5908 @d etex_int_pars=eTeX_state_code+eTeX_states {total number of \eTeX's integer parameters}
5909 @#
5910 @d int_pars=etex_int_pars {total number of integer parameters}
5911 @d count_base=int_base+int_pars {|number_regs| user \.{\\count} registers}
5912 @d del_code_base=count_base+number_regs {|number_usvs| delimiter code mappings}
5913 @d dimen_base=del_code_base+number_usvs {beginning of region 6}
5914 @#
5915 @d del_code(#)==eqtb[del_code_base+#].int
5916 @d count(#)==eqtb[count_base+#].int
5917 @d int_par(#)==eqtb[int_base+#].int {an integer parameter}
5918 @d pretolerance==int_par(pretolerance_code)
5919 @d tolerance==int_par(tolerance_code)
5920 @d line_penalty==int_par(line_penalty_code)
5921 @d hyphen_penalty==int_par(hyphen_penalty_code)
5922 @d ex_hyphen_penalty==int_par(ex_hyphen_penalty_code)
5923 @d club_penalty==int_par(club_penalty_code)
5924 @d widow_penalty==int_par(widow_penalty_code)
5925 @d display_widow_penalty==int_par(display_widow_penalty_code)
5926 @d broken_penalty==int_par(broken_penalty_code)
5927 @d bin_op_penalty==int_par(bin_op_penalty_code)
5928 @d rel_penalty==int_par(rel_penalty_code)
5929 @d pre_display_penalty==int_par(pre_display_penalty_code)
5930 @d post_display_penalty==int_par(post_display_penalty_code)
5931 @d inter_line_penalty==int_par(inter_line_penalty_code)
5932 @d double_hyphen_demerits==int_par(double_hyphen_demerits_code)
5933 @d final_hyphen_demerits==int_par(final_hyphen_demerits_code)
5934 @d adj_demerits==int_par(adj_demerits_code)
5935 @d mag==int_par(mag_code)
5936 @d delimiter_factor==int_par(delimiter_factor_code)
5937 @d looseness==int_par(looseness_code)
5938 @d time==int_par(time_code)
5939 @d day==int_par(day_code)
5940 @d month==int_par(month_code)
5941 @d year==int_par(year_code)
5942 @d show_box_breadth==int_par(show_box_breadth_code)
5943 @d show_box_depth==int_par(show_box_depth_code)
5944 @d hbadness==int_par(hbadness_code)
5945 @d vbadness==int_par(vbadness_code)
5946 @d pausing==int_par(pausing_code)
5947 @d tracing_online==int_par(tracing_online_code)
5948 @d tracing_macros==int_par(tracing_macros_code)
5949 @d tracing_stats==int_par(tracing_stats_code)
5950 @d tracing_paragraphs==int_par(tracing_paragraphs_code)
5951 @d tracing_pages==int_par(tracing_pages_code)
5952 @d tracing_output==int_par(tracing_output_code)
5953 @d tracing_lost_chars==int_par(tracing_lost_chars_code)
5954 @d tracing_commands==int_par(tracing_commands_code)
5955 @d tracing_restores==int_par(tracing_restores_code)
5956 @d uc_hyph==int_par(uc_hyph_code)
5957 @d output_penalty==int_par(output_penalty_code)
5958 @d max_dead_cycles==int_par(max_dead_cycles_code)
5959 @d hang_after==int_par(hang_after_code)
5960 @d floating_penalty==int_par(floating_penalty_code)
5961 @d global_defs==int_par(global_defs_code)
5962 @d cur_fam==int_par(cur_fam_code)
5963 @d escape_char==int_par(escape_char_code)
5964 @d default_hyphen_char==int_par(default_hyphen_char_code)
5965 @d default_skew_char==int_par(default_skew_char_code)
5966 @d end_line_char==int_par(end_line_char_code)
5967 @d new_line_char==int_par(new_line_char_code)
5968 @d language==int_par(language_code)
5969 @d left_hyphen_min==int_par(left_hyphen_min_code)
5970 @d right_hyphen_min==int_par(right_hyphen_min_code)
5971 @d holding_inserts==int_par(holding_inserts_code)
5972 @d error_context_lines==int_par(error_context_lines_code)
5973 @#
5974 @d tracing_assigns==int_par(tracing_assigns_code)
5975 @d tracing_groups==int_par(tracing_groups_code)
5976 @d tracing_ifs==int_par(tracing_ifs_code)
5977 @d tracing_scan_tokens==int_par(tracing_scan_tokens_code)
5978 @d tracing_nesting==int_par(tracing_nesting_code)
5979 @d pre_display_direction==int_par(pre_display_direction_code)
5980 @d last_line_fit==int_par(last_line_fit_code)
5981 @d saving_vdiscards==int_par(saving_vdiscards_code)
5982 @d saving_hyph_codes==int_par(saving_hyph_codes_code)
5983 @d suppress_fontnotfound_error==int_par(suppress_fontnotfound_error_code)
5984 @d ignore_primitive_error==int_par(ignore_primitive_error_code)
5985 @d XeTeX_linebreak_locale==int_par(XeTeX_linebreak_locale_code)
5986 @d XeTeX_linebreak_penalty==int_par(XeTeX_linebreak_penalty_code)
5987 @d XeTeX_protrude_chars==int_par(XeTeX_protrude_chars_code)
5988
5989 @<Assign the values |depth_threshold:=show_box_depth|...@>=
5990 depth_threshold:=show_box_depth;
5991 breadth_max:=show_box_breadth
5992
5993 @ We can print the symbolic name of an integer parameter as follows.
5994
5995 @p procedure print_param(@!n:integer);
5996 begin case n of
5997 pretolerance_code:print_esc("pretolerance");
5998 tolerance_code:print_esc("tolerance");
5999 line_penalty_code:print_esc("linepenalty");
6000 hyphen_penalty_code:print_esc("hyphenpenalty");
6001 ex_hyphen_penalty_code:print_esc("exhyphenpenalty");
6002 club_penalty_code:print_esc("clubpenalty");
6003 widow_penalty_code:print_esc("widowpenalty");
6004 display_widow_penalty_code:print_esc("displaywidowpenalty");
6005 broken_penalty_code:print_esc("brokenpenalty");
6006 bin_op_penalty_code:print_esc("binoppenalty");
6007 rel_penalty_code:print_esc("relpenalty");
6008 pre_display_penalty_code:print_esc("predisplaypenalty");
6009 post_display_penalty_code:print_esc("postdisplaypenalty");
6010 inter_line_penalty_code:print_esc("interlinepenalty");
6011 double_hyphen_demerits_code:print_esc("doublehyphendemerits");
6012 final_hyphen_demerits_code:print_esc("finalhyphendemerits");
6013 adj_demerits_code:print_esc("adjdemerits");
6014 mag_code:print_esc("mag");
6015 delimiter_factor_code:print_esc("delimiterfactor");
6016 looseness_code:print_esc("looseness");
6017 time_code:print_esc("time");
6018 day_code:print_esc("day");
6019 month_code:print_esc("month");
6020 year_code:print_esc("year");
6021 show_box_breadth_code:print_esc("showboxbreadth");
6022 show_box_depth_code:print_esc("showboxdepth");
6023 hbadness_code:print_esc("hbadness");
6024 vbadness_code:print_esc("vbadness");
6025 pausing_code:print_esc("pausing");
6026 tracing_online_code:print_esc("tracingonline");
6027 tracing_macros_code:print_esc("tracingmacros");
6028 tracing_stats_code:print_esc("tracingstats");
6029 tracing_paragraphs_code:print_esc("tracingparagraphs");
6030 tracing_pages_code:print_esc("tracingpages");
6031 tracing_output_code:print_esc("tracingoutput");
6032 tracing_lost_chars_code:print_esc("tracinglostchars");
6033 tracing_commands_code:print_esc("tracingcommands");
6034 tracing_restores_code:print_esc("tracingrestores");
6035 uc_hyph_code:print_esc("uchyph");
6036 output_penalty_code:print_esc("outputpenalty");
6037 max_dead_cycles_code:print_esc("maxdeadcycles");
6038 hang_after_code:print_esc("hangafter");
6039 floating_penalty_code:print_esc("floatingpenalty");
6040 global_defs_code:print_esc("globaldefs");
6041 cur_fam_code:print_esc("fam");
6042 escape_char_code:print_esc("escapechar");
6043 default_hyphen_char_code:print_esc("defaulthyphenchar");
6044 default_skew_char_code:print_esc("defaultskewchar");
6045 end_line_char_code:print_esc("endlinechar");
6046 new_line_char_code:print_esc("newlinechar");
6047 language_code:print_esc("language");
6048 left_hyphen_min_code:print_esc("lefthyphenmin");
6049 right_hyphen_min_code:print_esc("righthyphenmin");
6050 holding_inserts_code:print_esc("holdinginserts");
6051 error_context_lines_code:print_esc("errorcontextlines");
6052 XeTeX_linebreak_penalty_code:print_esc("XeTeXlinebreakpenalty");
6053 XeTeX_protrude_chars_code:print_esc("XeTeXprotrudechars");
6054 @/@<Cases for |print_param|@>@/
6055 othercases print("[unknown integer parameter!]")
6056 endcases;
6057 end;
6058
6059 @ The integer parameter names must be entered into the hash table.
6060
6061 @<Put each...@>=
6062 primitive("pretolerance",assign_int,int_base+pretolerance_code);@/
6063 @!@:pretolerance_}{\.{\\pretolerance} primitive@>
6064 primitive("tolerance",assign_int,int_base+tolerance_code);@/
6065 @!@:tolerance_}{\.{\\tolerance} primitive@>
6066 primitive("linepenalty",assign_int,int_base+line_penalty_code);@/
6067 @!@:line_penalty_}{\.{\\linepenalty} primitive@>
6068 primitive("hyphenpenalty",assign_int,int_base+hyphen_penalty_code);@/
6069 @!@:hyphen_penalty_}{\.{\\hyphenpenalty} primitive@>
6070 primitive("exhyphenpenalty",assign_int,int_base+ex_hyphen_penalty_code);@/
6071 @!@:ex_hyphen_penalty_}{\.{\\exhyphenpenalty} primitive@>
6072 primitive("clubpenalty",assign_int,int_base+club_penalty_code);@/
6073 @!@:club_penalty_}{\.{\\clubpenalty} primitive@>
6074 primitive("widowpenalty",assign_int,int_base+widow_penalty_code);@/
6075 @!@:widow_penalty_}{\.{\\widowpenalty} primitive@>
6076 primitive("displaywidowpenalty",
6077 assign_int,int_base+display_widow_penalty_code);@/
6078 @!@:display_widow_penalty_}{\.{\\displaywidowpenalty} primitive@>
6079 primitive("brokenpenalty",assign_int,int_base+broken_penalty_code);@/
6080 @!@:broken_penalty_}{\.{\\brokenpenalty} primitive@>
6081 primitive("binoppenalty",assign_int,int_base+bin_op_penalty_code);@/
6082 @!@:bin_op_penalty_}{\.{\\binoppenalty} primitive@>
6083 primitive("relpenalty",assign_int,int_base+rel_penalty_code);@/
6084 @!@:rel_penalty_}{\.{\\relpenalty} primitive@>
6085 primitive("predisplaypenalty",assign_int,int_base+pre_display_penalty_code);@/
6086 @!@:pre_display_penalty_}{\.{\\predisplaypenalty} primitive@>
6087 primitive("postdisplaypenalty",assign_int,int_base+post_display_penalty_code);@/
6088 @!@:post_display_penalty_}{\.{\\postdisplaypenalty} primitive@>
6089 primitive("interlinepenalty",assign_int,int_base+inter_line_penalty_code);@/
6090 @!@:inter_line_penalty_}{\.{\\interlinepenalty} primitive@>
6091 primitive("doublehyphendemerits",
6092 assign_int,int_base+double_hyphen_demerits_code);@/
6093 @!@:double_hyphen_demerits_}{\.{\\doublehyphendemerits} primitive@>
6094 primitive("finalhyphendemerits",
6095 assign_int,int_base+final_hyphen_demerits_code);@/
6096 @!@:final_hyphen_demerits_}{\.{\\finalhyphendemerits} primitive@>
6097 primitive("adjdemerits",assign_int,int_base+adj_demerits_code);@/
6098 @!@:adj_demerits_}{\.{\\adjdemerits} primitive@>
6099 primitive("mag",assign_int,int_base+mag_code);@/
6100 @!@:mag_}{\.{\\mag} primitive@>
6101 primitive("delimiterfactor",assign_int,int_base+delimiter_factor_code);@/
6102 @!@:delimiter_factor_}{\.{\\delimiterfactor} primitive@>
6103 primitive("looseness",assign_int,int_base+looseness_code);@/
6104 @!@:looseness_}{\.{\\looseness} primitive@>
6105 primitive("time",assign_int,int_base+time_code);@/
6106 @!@:time_}{\.{\\time} primitive@>
6107 primitive("day",assign_int,int_base+day_code);@/
6108 @!@:day_}{\.{\\day} primitive@>
6109 primitive("month",assign_int,int_base+month_code);@/
6110 @!@:month_}{\.{\\month} primitive@>
6111 primitive("year",assign_int,int_base+year_code);@/
6112 @!@:year_}{\.{\\year} primitive@>
6113 primitive("showboxbreadth",assign_int,int_base+show_box_breadth_code);@/
6114 @!@:show_box_breadth_}{\.{\\showboxbreadth} primitive@>
6115 primitive("showboxdepth",assign_int,int_base+show_box_depth_code);@/
6116 @!@:show_box_depth_}{\.{\\showboxdepth} primitive@>
6117 primitive("hbadness",assign_int,int_base+hbadness_code);@/
6118 @!@:hbadness_}{\.{\\hbadness} primitive@>
6119 primitive("vbadness",assign_int,int_base+vbadness_code);@/
6120 @!@:vbadness_}{\.{\\vbadness} primitive@>
6121 primitive("pausing",assign_int,int_base+pausing_code);@/
6122 @!@:pausing_}{\.{\\pausing} primitive@>
6123 primitive("tracingonline",assign_int,int_base+tracing_online_code);@/
6124 @!@:tracing_online_}{\.{\\tracingonline} primitive@>
6125 primitive("tracingmacros",assign_int,int_base+tracing_macros_code);@/
6126 @!@:tracing_macros_}{\.{\\tracingmacros} primitive@>
6127 primitive("tracingstats",assign_int,int_base+tracing_stats_code);@/
6128 @!@:tracing_stats_}{\.{\\tracingstats} primitive@>
6129 primitive("tracingparagraphs",assign_int,int_base+tracing_paragraphs_code);@/
6130 @!@:tracing_paragraphs_}{\.{\\tracingparagraphs} primitive@>
6131 primitive("tracingpages",assign_int,int_base+tracing_pages_code);@/
6132 @!@:tracing_pages_}{\.{\\tracingpages} primitive@>
6133 primitive("tracingoutput",assign_int,int_base+tracing_output_code);@/
6134 @!@:tracing_output_}{\.{\\tracingoutput} primitive@>
6135 primitive("tracinglostchars",assign_int,int_base+tracing_lost_chars_code);@/
6136 @!@:tracing_lost_chars_}{\.{\\tracinglostchars} primitive@>
6137 primitive("tracingcommands",assign_int,int_base+tracing_commands_code);@/
6138 @!@:tracing_commands_}{\.{\\tracingcommands} primitive@>
6139 primitive("tracingrestores",assign_int,int_base+tracing_restores_code);@/
6140 @!@:tracing_restores_}{\.{\\tracingrestores} primitive@>
6141 primitive("uchyph",assign_int,int_base+uc_hyph_code);@/
6142 @!@:uc_hyph_}{\.{\\uchyph} primitive@>
6143 primitive("outputpenalty",assign_int,int_base+output_penalty_code);@/
6144 @!@:output_penalty_}{\.{\\outputpenalty} primitive@>
6145 primitive("maxdeadcycles",assign_int,int_base+max_dead_cycles_code);@/
6146 @!@:max_dead_cycles_}{\.{\\maxdeadcycles} primitive@>
6147 primitive("hangafter",assign_int,int_base+hang_after_code);@/
6148 @!@:hang_after_}{\.{\\hangafter} primitive@>
6149 primitive("floatingpenalty",assign_int,int_base+floating_penalty_code);@/
6150 @!@:floating_penalty_}{\.{\\floatingpenalty} primitive@>
6151 primitive("globaldefs",assign_int,int_base+global_defs_code);@/
6152 @!@:global_defs_}{\.{\\globaldefs} primitive@>
6153 primitive("fam",assign_int,int_base+cur_fam_code);@/
6154 @!@:fam_}{\.{\\fam} primitive@>
6155 primitive("escapechar",assign_int,int_base+escape_char_code);@/
6156 @!@:escape_char_}{\.{\\escapechar} primitive@>
6157 primitive("defaulthyphenchar",assign_int,int_base+default_hyphen_char_code);@/
6158 @!@:default_hyphen_char_}{\.{\\defaulthyphenchar} primitive@>
6159 primitive("defaultskewchar",assign_int,int_base+default_skew_char_code);@/
6160 @!@:default_skew_char_}{\.{\\defaultskewchar} primitive@>
6161 primitive("endlinechar",assign_int,int_base+end_line_char_code);@/
6162 @!@:end_line_char_}{\.{\\endlinechar} primitive@>
6163 primitive("newlinechar",assign_int,int_base+new_line_char_code);@/
6164 @!@:new_line_char_}{\.{\\newlinechar} primitive@>
6165 primitive("language",assign_int,int_base+language_code);@/
6166 @!@:language_}{\.{\\language} primitive@>
6167 primitive("lefthyphenmin",assign_int,int_base+left_hyphen_min_code);@/
6168 @!@:left_hyphen_min_}{\.{\\lefthyphenmin} primitive@>
6169 primitive("righthyphenmin",assign_int,int_base+right_hyphen_min_code);@/
6170 @!@:right_hyphen_min_}{\.{\\righthyphenmin} primitive@>
6171 primitive("holdinginserts",assign_int,int_base+holding_inserts_code);@/
6172 @!@:holding_inserts_}{\.{\\holdinginserts} primitive@>
6173 primitive("errorcontextlines",assign_int,int_base+error_context_lines_code);@/
6174 @!@:error_context_lines_}{\.{\\errorcontextlines} primitive@>
6175 primitive("XeTeXlinebreakpenalty",assign_int,int_base+XeTeX_linebreak_penalty_code);@/
6176 @!@:XeTeX_linebreak_penalty_}{\.{\\XeTeXlinebreakpenalty} primitive@>
6177 primitive("XeTeXprotrudechars",assign_int,int_base+XeTeX_protrude_chars_code);@/
6178 @!@:XeTeX_protrude_chars_}{\.{\\XeTeXprotrudechars} primitive@>
6179
6180 @ @<Cases of |print_cmd_chr|...@>=
6181 assign_int: if chr_code<count_base then print_param(chr_code-int_base)
6182 else begin print_esc("count"); print_int(chr_code-count_base);
6183 end;
6184
6185 @ The integer parameters should really be initialized by a macro package;
6186 the following initialization does the minimum to keep \TeX\ from
6187 complete failure.
6188 @^null delimiter@>
6189
6190 @<Initialize table entries...@>=
6191 for k:=int_base to del_code_base-1 do eqtb[k].int:=0;
6192 mag:=1000; tolerance:=10000; hang_after:=1; max_dead_cycles:=25;
6193 escape_char:="\"; end_line_char:=carriage_return;
6194 for k:=0 to number_usvs-1 do del_code(k):=-1;
6195 del_code("."):=0; {this null delimiter is used in error recovery}
6196
6197 @ The following procedure, which is called just before \TeX\ initializes its
6198 input and output, establishes the initial values of the date and time.
6199 @^system dependencies@>
6200 Since standard \PASCAL\ cannot provide such information, something special
6201 is needed. The program here simply assumes that suitable values appear in
6202 the global variables \\{sys\_time}, \\{sys\_day}, \\{sys\_month}, and
6203 \\{sys\_year} (which are initialized to noon on 4 July 1776,
6204 in case the implementor is careless).
6205
6206 @p procedure fix_date_and_time;
6207 begin sys_time:=12*60;
6208 sys_day:=4; sys_month:=7; sys_year:=1776; {self-evident truths}
6209 time:=sys_time; {minutes since midnight}
6210 day:=sys_day; {day of the month}
6211 month:=sys_month; {month of the year}
6212 year:=sys_year; {Anno Domini}
6213 end;
6214
6215 @ @<Show equivalent |n|, in region 5@>=
6216 begin if n<count_base then print_param(n-int_base)
6217 else if n<del_code_base then
6218 begin print_esc("count"); print_int(n-count_base);
6219 end
6220 else begin print_esc("delcode"); print_int(n-del_code_base);
6221 end;
6222 print_char("="); print_int(eqtb[n].int);
6223 end
6224
6225 @ @<Set variable |c| to the current escape character@>=c:=escape_char
6226
6227 @ @<Character |s| is the current new-line character@>=s=new_line_char
6228
6229 @ \TeX\ is occasionally supposed to print diagnostic information that
6230 goes only into the transcript file, unless |tracing_online| is positive.
6231 Here are two routines that adjust the destination of print commands:
6232
6233 @p procedure begin_diagnostic; {prepare to do some tracing}
6234 begin old_setting:=selector;
6235 if (tracing_online<=0)and(selector=term_and_log) then
6236 begin decr(selector);
6237 if history=spotless then history:=warning_issued;
6238 end;
6239 end;
6240 @#
6241 procedure end_diagnostic(@!blank_line:boolean);
6242 {restore proper conditions after tracing}
6243 begin print_nl("");
6244 if blank_line then print_ln;
6245 selector:=old_setting;
6246 end;
6247
6248 @ Of course we had better declare a few more global variables, if the previous
6249 routines are going to work.
6250
6251 @<Glob...@>=
6252 @!old_setting:0..max_selector;
6253 @!old_selector_ignored_err:0..max_selector; { for |print_ignored_err|}
6254 @!sys_time,@!sys_day,@!sys_month,@!sys_year:integer;
6255 {date and time supplied by external system}
6256
6257 @ The final region of |eqtb| contains the dimension parameters defined
6258 here, and the |number_regs| \.{\\dimen} registers.
6259
6260 @d par_indent_code=0 {indentation of paragraphs}
6261 @d math_surround_code=1 {space around math in text}
6262 @d line_skip_limit_code=2 {threshold for |line_skip| instead of |baseline_skip|}
6263 @d hsize_code=3 {line width in horizontal mode}
6264 @d vsize_code=4 {page height in vertical mode}
6265 @d max_depth_code=5 {maximum depth of boxes on main pages}
6266 @d split_max_depth_code=6 {maximum depth of boxes on split pages}
6267 @d box_max_depth_code=7 {maximum depth of explicit vboxes}
6268 @d hfuzz_code=8 {tolerance for overfull hbox messages}
6269 @d vfuzz_code=9 {tolerance for overfull vbox messages}
6270 @d delimiter_shortfall_code=10 {maximum amount uncovered by variable delimiters}
6271 @d null_delimiter_space_code=11 {blank space in null delimiters}
6272 @d script_space_code=12 {extra space after subscript or superscript}
6273 @d pre_display_size_code=13 {length of text preceding a display}
6274 @d display_width_code=14 {length of line for displayed equation}
6275 @d display_indent_code=15 {indentation of line for displayed equation}
6276 @d overfull_rule_code=16 {width of rule that identifies overfull hboxes}
6277 @d hang_indent_code=17 {amount of hanging indentation}
6278 @d h_offset_code=18 {amount of horizontal offset when shipping pages out}
6279 @d v_offset_code=19 {amount of vertical offset when shipping pages out}
6280 @d emergency_stretch_code=20 {reduces badnesses on final pass of line-breaking}
6281 @d pdf_page_width_code=21 {page width of the PDF output}
6282 @d pdf_page_height_code=22 {page height of the PDF output}
6283 @d dimen_pars=23 {total number of dimension parameters}
6284 @d scaled_base=dimen_base+dimen_pars
6285 {table of |number_regs| user-defined \.{\\dimen} registers}
6286 @d eqtb_size=scaled_base+biggest_reg {largest subscript of |eqtb|}
6287 @#
6288 @d dimen(#)==eqtb[scaled_base+#].sc
6289 @d dimen_par(#)==eqtb[dimen_base+#].sc {a scaled quantity}
6290 @d par_indent==dimen_par(par_indent_code)
6291 @d math_surround==dimen_par(math_surround_code)
6292 @d line_skip_limit==dimen_par(line_skip_limit_code)
6293 @d hsize==dimen_par(hsize_code)
6294 @d vsize==dimen_par(vsize_code)
6295 @d max_depth==dimen_par(max_depth_code)
6296 @d split_max_depth==dimen_par(split_max_depth_code)
6297 @d box_max_depth==dimen_par(box_max_depth_code)
6298 @d hfuzz==dimen_par(hfuzz_code)
6299 @d vfuzz==dimen_par(vfuzz_code)
6300 @d delimiter_shortfall==dimen_par(delimiter_shortfall_code)
6301 @d null_delimiter_space==dimen_par(null_delimiter_space_code)
6302 @d script_space==dimen_par(script_space_code)
6303 @d pre_display_size==dimen_par(pre_display_size_code)
6304 @d display_width==dimen_par(display_width_code)
6305 @d display_indent==dimen_par(display_indent_code)
6306 @d overfull_rule==dimen_par(overfull_rule_code)
6307 @d hang_indent==dimen_par(hang_indent_code)
6308 @d h_offset==dimen_par(h_offset_code)
6309 @d v_offset==dimen_par(v_offset_code)
6310 @d emergency_stretch==dimen_par(emergency_stretch_code)
6311 @d pdf_page_width == dimen_par(pdf_page_width_code)
6312 @d pdf_page_height == dimen_par(pdf_page_height_code)
6313
6314 @p procedure print_length_param(@!n:integer);
6315 begin case n of
6316 par_indent_code:print_esc("parindent");
6317 math_surround_code:print_esc("mathsurround");
6318 line_skip_limit_code:print_esc("lineskiplimit");
6319 hsize_code:print_esc("hsize");
6320 vsize_code:print_esc("vsize");
6321 max_depth_code:print_esc("maxdepth");
6322 split_max_depth_code:print_esc("splitmaxdepth");
6323 box_max_depth_code:print_esc("boxmaxdepth");
6324 hfuzz_code:print_esc("hfuzz");
6325 vfuzz_code:print_esc("vfuzz");
6326 delimiter_shortfall_code:print_esc("delimitershortfall");
6327 null_delimiter_space_code:print_esc("nulldelimiterspace");
6328 script_space_code:print_esc("scriptspace");
6329 pre_display_size_code:print_esc("predisplaysize");
6330 display_width_code:print_esc("displaywidth");
6331 display_indent_code:print_esc("displayindent");
6332 overfull_rule_code:print_esc("overfullrule");
6333 hang_indent_code:print_esc("hangindent");
6334 h_offset_code:print_esc("hoffset");
6335 v_offset_code:print_esc("voffset");
6336 emergency_stretch_code:print_esc("emergencystretch");
6337 pdf_page_width_code: print_esc("pdfpagewidth");
6338 pdf_page_height_code: print_esc("pdfpageheight");
6339 othercases print("[unknown dimen parameter!]")
6340 endcases;
6341 end;
6342
6343 @ @<Put each...@>=
6344 primitive("parindent",assign_dimen,dimen_base+par_indent_code);@/
6345 @!@:par_indent_}{\.{\\parindent} primitive@>
6346 primitive("mathsurround",assign_dimen,dimen_base+math_surround_code);@/
6347 @!@:math_surround_}{\.{\\mathsurround} primitive@>
6348 primitive("lineskiplimit",assign_dimen,dimen_base+line_skip_limit_code);@/
6349 @!@:line_skip_limit_}{\.{\\lineskiplimit} primitive@>
6350 primitive("hsize",assign_dimen,dimen_base+hsize_code);@/
6351 @!@:hsize_}{\.{\\hsize} primitive@>
6352 primitive("vsize",assign_dimen,dimen_base+vsize_code);@/
6353 @!@:vsize_}{\.{\\vsize} primitive@>
6354 primitive("maxdepth",assign_dimen,dimen_base+max_depth_code);@/
6355 @!@:max_depth_}{\.{\\maxdepth} primitive@>
6356 primitive("splitmaxdepth",assign_dimen,dimen_base+split_max_depth_code);@/
6357 @!@:split_max_depth_}{\.{\\splitmaxdepth} primitive@>
6358 primitive("boxmaxdepth",assign_dimen,dimen_base+box_max_depth_code);@/
6359 @!@:box_max_depth_}{\.{\\boxmaxdepth} primitive@>
6360 primitive("hfuzz",assign_dimen,dimen_base+hfuzz_code);@/
6361 @!@:hfuzz_}{\.{\\hfuzz} primitive@>
6362 primitive("vfuzz",assign_dimen,dimen_base+vfuzz_code);@/
6363 @!@:vfuzz_}{\.{\\vfuzz} primitive@>
6364 primitive("delimitershortfall",
6365 assign_dimen,dimen_base+delimiter_shortfall_code);@/
6366 @!@:delimiter_shortfall_}{\.{\\delimitershortfall} primitive@>
6367 primitive("nulldelimiterspace",
6368 assign_dimen,dimen_base+null_delimiter_space_code);@/
6369 @!@:null_delimiter_space_}{\.{\\nulldelimiterspace} primitive@>
6370 primitive("scriptspace",assign_dimen,dimen_base+script_space_code);@/
6371 @!@:script_space_}{\.{\\scriptspace} primitive@>
6372 primitive("predisplaysize",assign_dimen,dimen_base+pre_display_size_code);@/
6373 @!@:pre_display_size_}{\.{\\predisplaysize} primitive@>
6374 primitive("displaywidth",assign_dimen,dimen_base+display_width_code);@/
6375 @!@:display_width_}{\.{\\displaywidth} primitive@>
6376 primitive("displayindent",assign_dimen,dimen_base+display_indent_code);@/
6377 @!@:display_indent_}{\.{\\displayindent} primitive@>
6378 primitive("overfullrule",assign_dimen,dimen_base+overfull_rule_code);@/
6379 @!@:overfull_rule_}{\.{\\overfullrule} primitive@>
6380 primitive("hangindent",assign_dimen,dimen_base+hang_indent_code);@/
6381 @!@:hang_indent_}{\.{\\hangindent} primitive@>
6382 primitive("hoffset",assign_dimen,dimen_base+h_offset_code);@/
6383 @!@:h_offset_}{\.{\\hoffset} primitive@>
6384 primitive("voffset",assign_dimen,dimen_base+v_offset_code);@/
6385 @!@:v_offset_}{\.{\\voffset} primitive@>
6386 primitive("emergencystretch",assign_dimen,dimen_base+emergency_stretch_code);@/
6387 @!@:emergency_stretch_}{\.{\\emergencystretch} primitive@>
6388
6389 primitive("pdfpagewidth",assign_dimen,dimen_base+pdf_page_width_code);@/
6390 @!@:pdf_page_width_}{\.{\\pdfpagewidth} primitive@>
6391 primitive("pdfpageheight",assign_dimen,dimen_base+pdf_page_height_code);@/
6392 @!@:pdf_page_height_}{\.{\\pdfpageheight} primitive@>
6393
6394 @ @<Cases of |print_cmd_chr|...@>=
6395 assign_dimen: if chr_code<scaled_base then
6396 print_length_param(chr_code-dimen_base)
6397 else begin print_esc("dimen"); print_int(chr_code-scaled_base);
6398 end;
6399
6400 @ @<Initialize table entries...@>=
6401 for k:=dimen_base to eqtb_size do eqtb[k].sc:=0;
6402
6403 @ @<Show equivalent |n|, in region 6@>=
6404 begin if n<scaled_base then print_length_param(n-dimen_base)
6405 else begin print_esc("dimen"); print_int(n-scaled_base);
6406 end;
6407 print_char("="); print_scaled(eqtb[n].sc); print("pt");
6408 end
6409
6410 @ Here is a procedure that displays the contents of |eqtb[n]|
6411 symbolically.
6412
6413 @p@t\4@>@<Declare the procedure called |print_cmd_chr|@>@;@/
6414 @!stat procedure show_eqtb(@!n:pointer);
6415 begin if n<active_base then print_char("?") {this can't happen}
6416 else if n<glue_base then @<Show equivalent |n|, in region 1 or 2@>
6417 else if n<local_base then @<Show equivalent |n|, in region 3@>
6418 else if n<int_base then @<Show equivalent |n|, in region 4@>
6419 else if n<dimen_base then @<Show equivalent |n|, in region 5@>
6420 else if n<=eqtb_size then @<Show equivalent |n|, in region 6@>
6421 else print_char("?"); {this can't happen either}
6422 end;
6423 tats
6424
6425 @ The last two regions of |eqtb| have fullword values instead of the
6426 three fields |eq_level|, |eq_type|, and |equiv|. An |eq_type| is unnecessary,
6427 but \TeX\ needs to store the |eq_level| information in another array
6428 called |xeq_level|.
6429
6430 @<Glob...@>=
6431 @!eqtb:array[active_base..eqtb_size] of memory_word;
6432 @!xeq_level:array[int_base..eqtb_size] of quarterword;
6433
6434 @ @<Set init...@>=
6435 for k:=int_base to eqtb_size do xeq_level[k]:=level_one;
6436
6437 @ When the debugging routine |search_mem| is looking for pointers having a
6438 given value, it is interested only in regions 1 to~3 of~|eqtb|, and in the
6439 first part of region~4.
6440
6441 @<Search |eqtb| for equivalents equal to |p|@>=
6442 for q:=active_base to box_base+biggest_reg do
6443 begin if equiv(q)=p then
6444 begin print_nl("EQUIV("); print_int(q); print_char(")");
6445 end;
6446 end
6447
6448 @* \[18] The hash table.
6449 Control sequences are stored and retrieved by means of a fairly standard hash
6450 table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
6451 in {\sl The Art of Computer Programming\/}). Once a control sequence enters the
6452 table, it is never removed, because there are complicated situations
6453 involving \.{\\gdef} where the removal of a control sequence at the end of
6454 a group would be a mistake preventable only by the introduction of a
6455 complicated reference-count mechanism.
6456
6457 The actual sequence of letters forming a control sequence identifier is
6458 stored in the |str_pool| array together with all the other strings. An
6459 auxiliary array |hash| consists of items with two halfword fields per
6460 word. The first of these, called |next(p)|, points to the next identifier
6461 belonging to the same coalesced list as the identifier corresponding to~|p|;
6462 and the other, called |text(p)|, points to the |str_start| entry for
6463 |p|'s identifier. If position~|p| of the hash table is empty, we have
6464 |text(p)=0|; if position |p| is either empty or the end of a coalesced
6465 hash list, we have |next(p)=0|. An auxiliary pointer variable called
6466 |hash_used| is maintained in such a way that all locations |p>=hash_used|
6467 are nonempty. The global variable |cs_count| tells how many multiletter
6468 control sequences have been defined, if statistics are being kept.
6469
6470 A global boolean variable called |no_new_control_sequence| is set to
6471 |true| during the time that new hash table entries are forbidden.
6472
6473 @d next(#) == hash[#].lh {link for coalesced lists}
6474 @d text(#) == hash[#].rh {string number for control sequence name}
6475 @d hash_is_full == (hash_used=hash_base) {test if all positions are occupied}
6476 @d font_id_text(#) == text(font_id_base+#) {a frozen font identifier's name}
6477
6478 @<Glob...@>=
6479 @!hash: array[hash_base..undefined_control_sequence-1] of two_halves;
6480 {the hash table}
6481 @!hash_used:pointer; {allocation pointer for |hash|}
6482 @!no_new_control_sequence:boolean; {are new identifiers legal?}
6483 @!cs_count:integer; {total number of known identifiers}
6484
6485 @ Primitive support needs a few extra variables and definitions
6486
6487 @d prim_prime=1777 {about 85\pct! of |primitive_size|}
6488 @d prim_base=1
6489 @d prim_next(#) == prim[#].lh {link for coalesced lists}
6490 @d prim_text(#) == prim[#].rh {string number for control sequence name, plus one}
6491 @d prim_is_full == (prim_used=prim_base) {test if all positions are occupied}
6492 @d prim_eq_level_field(#)==#.hh.b1
6493 @d prim_eq_type_field(#)==#.hh.b0
6494 @d prim_equiv_field(#)==#.hh.rh
6495 @d prim_eq_level(#)==prim_eq_level_field(eqtb[prim_eqtb_base+#]) {level of definition}
6496 @d prim_eq_type(#)==prim_eq_type_field(eqtb[prim_eqtb_base+#]) {command code for equivalent}
6497 @d prim_equiv(#)==prim_equiv_field(eqtb[prim_eqtb_base+#]) {equivalent value}
6498 @d undefined_primitive=0
6499
6500 @<Glob...@>=
6501 @!prim: array [0..prim_size] of two_halves; {the primitives table}
6502 @!prim_used:pointer; {allocation pointer for |prim|}
6503
6504 @ @<Set init...@>=
6505 no_new_control_sequence:=true; {new identifiers are usually forbidden}
6506 prim_next(0):=0; prim_text(0):=0;
6507 for k:=1 to prim_size do prim[k]:=prim[0];
6508 next(hash_base):=0; text(hash_base):=0;
6509 for k:=hash_base+1 to undefined_control_sequence-1 do hash[k]:=hash[hash_base];
6510
6511 @ @<Initialize table entries...@>=
6512 prim_used:=prim_size; {nothing is used}
6513 hash_used:=frozen_control_sequence; {nothing is used}
6514 cs_count:=0;
6515 eq_type(frozen_dont_expand):=dont_expand;
6516 text(frozen_dont_expand):="notexpanded:";
6517 @.notexpanded:@>
6518
6519 eq_type(frozen_primitive):=ignore_spaces;
6520 equiv(frozen_primitive):=1;
6521 eq_level(frozen_primitive):=level_one;
6522 text(frozen_primitive):="primitive";
6523
6524 @ Here is the subroutine that searches the hash table for an identifier
6525 that matches a given string of length |l>0| appearing in |buffer[j..
6526 (j+l-1)]|. If the identifier is found, the corresponding hash table address
6527 is returned. Otherwise, if the global variable |no_new_control_sequence|
6528 is |true|, the dummy address |undefined_control_sequence| is returned.
6529 Otherwise the identifier is inserted into the hash table and its location
6530 is returned.
6531
6532 @p function id_lookup(@!j,@!l:integer):pointer; {search the hash table}
6533 label found; {go here if you found it}
6534 var h:integer; {hash code}
6535 @!d:integer; {number of characters in incomplete current string}
6536 @!p:pointer; {index in |hash| array}
6537 @!k:pointer; {index in |buffer| array}
6538 @!ll:integer; {length in UTF16 code units}
6539 begin @<Compute the hash code |h|@>;
6540 p:=h+hash_base; {we start searching here; note that |0<=h<hash_prime|}
6541 ll:=l; for d:=0 to l-1 do if buffer[j+d]>=@"10000 then incr(ll);
6542 loop@+begin if text(p)>0 then if length(text(p))=ll then
6543 if str_eq_buf(text(p),j) then goto found;
6544 if next(p)=0 then
6545 begin if no_new_control_sequence then
6546 p:=undefined_control_sequence
6547 else @<Insert a new control sequence after |p|, then make
6548 |p| point to it@>;
6549 goto found;
6550 end;
6551 p:=next(p);
6552 end;
6553 found: id_lookup:=p;
6554 end;
6555
6556 @ @<Insert a new control...@>=
6557 begin if text(p)>0 then
6558 begin repeat if hash_is_full then overflow("hash size",hash_size);
6559 @:TeX capacity exceeded hash size}{\quad hash size@>
6560 decr(hash_used);
6561 until text(hash_used)=0; {search for an empty location in |hash|}
6562 next(p):=hash_used; p:=hash_used;
6563 end;
6564 str_room(ll); d:=cur_length;
6565 while pool_ptr>str_start_macro(str_ptr) do
6566 begin decr(pool_ptr); str_pool[pool_ptr+l]:=str_pool[pool_ptr];
6567 end; {move current string up to make room for another}
6568 for k:=j to j+l-1 do begin
6569 if buffer[k]<@"10000 then append_char(buffer[k])
6570 else begin
6571 append_char(@"D800+(buffer[k]-@"10000)div@"400);
6572 append_char(@"DC00+(buffer[k]-@"10000)mod@"400);
6573 end
6574 end;
6575 text(p):=make_string; pool_ptr:=pool_ptr+d;
6576 @!stat incr(cs_count);@+tats@;@/
6577 end
6578
6579 @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
6580 should be a prime number. The theory of hashing tells us to expect fewer
6581 than two table probes, on the average, when the search is successful.
6582 [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
6583 @^Vitter, Jeffrey Scott@>
6584
6585 @<Compute the hash code |h|@>=
6586 h:=0;
6587 for k:=j to j+l-1 do
6588 begin h:=h+h+buffer[k];
6589 while h>=hash_prime do h:=h-hash_prime;
6590 end
6591
6592 @ Here is the subroutine that searches the primitive table for an identifier
6593
6594 @p function prim_lookup(@!s:str_number):pointer; {search the primitives table}
6595 label found; {go here if you found it}
6596 var h:integer; {hash code}
6597 @!p:pointer; {index in |hash| array}
6598 @!k:pointer; {index in string pool}
6599 @!j,@!l:integer;
6600 begin
6601 if s<=biggest_char then begin
6602 if s<0 then begin p:=undefined_primitive; goto found; end
6603 else p:=(s mod prim_prime)+prim_base; {we start searching here}
6604 end
6605 else begin
6606 j:=str_start_macro(s);
6607 if s = str_ptr then l:=cur_length else l:=length(s);
6608 @<Compute the primitive code |h|@>;
6609 p:=h+prim_base; {we start searching here; note that |0<=h<prim_prime|}
6610 end;
6611 loop@+begin
6612 if prim_text(p)>1+biggest_char then { |p| points a multi-letter primitive }
6613 begin if length(prim_text(p)-1)=l then
6614 if str_eq_str(prim_text(p)-1,s) then goto found;
6615 end
6616 else if prim_text(p)=1+s then goto found; { |p| points a single-letter primitive }
6617 if prim_next(p)=0 then
6618 begin if no_new_control_sequence then
6619 p:=undefined_primitive
6620 else @<Insert a new primitive after |p|, then make
6621 |p| point to it@>;
6622 goto found;
6623 end;
6624 p:=prim_next(p);
6625 end;
6626 found: prim_lookup:=p;
6627 end;
6628
6629 @ @<Insert a new primitive...@>=
6630 begin if prim_text(p)>0 then
6631 begin repeat if prim_is_full then overflow("primitive size",prim_size);
6632 @:TeX capacity exceeded primitive size}{\quad primitive size@>
6633 decr(prim_used);
6634 until prim_text(prim_used)=0; {search for an empty location in |prim|}
6635 prim_next(p):=prim_used; p:=prim_used;
6636 end;
6637 prim_text(p):=s+1;
6638 end
6639
6640 @ The value of |prim_prime| should be roughly 85\pct! of
6641 |prim_size|, and it should be a prime number.
6642
6643 @<Compute the primitive code |h|@>=
6644 h:=str_pool[j];
6645 for k:=j+1 to j+l-1 do
6646 begin h:=h+h+str_pool[k];
6647 while h>=prim_prime do h:=h-prim_prime;
6648 end
6649
6650 @ Single-character control sequences do not need to be looked up in a hash
6651 table, since we can use the character code itself as a direct address.
6652 The procedure |print_cs| prints the name of a control sequence, given
6653 a pointer to its address in |eqtb|. A space is printed after the name
6654 unless it is a single nonletter or an active character. This procedure
6655 might be invoked with invalid data, so it is ``extra robust.'' The
6656 individual characters must be printed one at a time using |print|, since
6657 they may be unprintable.
6658
6659 @<Basic printing...@>=
6660 procedure print_cs(@!p:integer); {prints a purported control sequence}
6661 begin if p<hash_base then {single character}
6662 if p>=single_base then
6663 if p=null_cs then
6664 begin print_esc("csname"); print_esc("endcsname"); print_char(" ");
6665 end
6666 else begin print_esc(p-single_base);
6667 if cat_code(p-single_base)=letter then print_char(" ");
6668 end
6669 else if p<active_base then print_esc("IMPOSSIBLE.")
6670 @.IMPOSSIBLE@>
6671 else print_char(p-active_base)
6672 else if p>=undefined_control_sequence then print_esc("IMPOSSIBLE.")
6673 else if (text(p)<0)or(text(p)>=str_ptr) then print_esc("NONEXISTENT.")
6674 @.NONEXISTENT@>
6675 else begin
6676 if (p>=prim_eqtb_base)and(p<frozen_null_font) then
6677 print_esc(prim_text(p-prim_eqtb_base)-1) else print_esc(text(p));
6678 print_char(" ");
6679 end;
6680 end;
6681
6682 @ Here is a similar procedure; it avoids the error checks, and it never
6683 prints a space after the control sequence.
6684
6685 @<Basic printing procedures@>=
6686 procedure sprint_cs(@!p:pointer); {prints a control sequence}
6687 begin if p<hash_base then
6688 if p<single_base then print_char(p-active_base)
6689 else if p<null_cs then print_esc(p-single_base)
6690 else begin print_esc("csname"); print_esc("endcsname");
6691 end
6692 else if (p>=prim_eqtb_base)and(p<frozen_null_font) then
6693 print_esc(prim_text(p-prim_eqtb_base)-1)
6694 else print_esc(text(p));
6695 end;
6696
6697 @ We need to put \TeX's ``primitive'' control sequences into the hash
6698 table, together with their command code (which will be the |eq_type|)
6699 and an operand (which will be the |equiv|). The |primitive| procedure
6700 does this, in a way that no \TeX\ user can. The global value |cur_val|
6701 contains the new |eqtb| pointer after |primitive| has acted.
6702
6703 @p @!init procedure primitive(@!s:str_number;@!c:quarterword;@!o:halfword);
6704 var k:pool_pointer; {index into |str_pool|}
6705 @!j:0..buf_size; {index into |buffer|}
6706 @!l:small_number; {length of the string}
6707 @!prim_val:integer; {needed to fill |prim_eqtb|}
6708 begin if s<256 then begin
6709 cur_val:=s+single_base;
6710 prim_val:=prim_lookup(s);
6711 end
6712 else begin k:=str_start_macro(s); l:=str_start_macro(s+1)-k;
6713 {we will move |s| into the (possibly non-empty) |buffer|}
6714 if first+l>buf_size+1 then
6715 overflow("buffer size",buf_size);
6716 @:TeX capacity exceeded buffer size}{\quad buffer size@>
6717 for j:=0 to l-1 do buffer[first+j]:=so(str_pool[k+j]);
6718 cur_val:=id_lookup(first,l); {|no_new_control_sequence| is |false|}
6719 flush_string; text(cur_val):=s; {we don't want to have the string twice}
6720 prim_val:=prim_lookup(s);
6721 end;
6722 eq_level(cur_val):=level_one; eq_type(cur_val):=c; equiv(cur_val):=o;
6723 prim_eq_level(prim_val):=level_one;
6724 prim_eq_type(prim_val):=c;
6725 prim_equiv(prim_val):=o;
6726 end;
6727 tini
6728
6729 @ Many of \TeX's primitives need no |equiv|, since they are identifiable
6730 by their |eq_type| alone. These primitives are loaded into the hash table
6731 as follows:
6732
6733 @<Put each of \TeX's primitives into the hash table@>=
6734 primitive(" ",ex_space,0);@/
6735 @!@:Single-character primitives /}{\quad\.{\\\ }@>
6736 primitive("/",ital_corr,0);@/
6737 @!@:Single-character primitives /}{\quad\.{\\/}@>
6738 primitive("accent",accent,0);@/
6739 @!@:accent_}{\.{\\accent} primitive@>
6740 primitive("advance",advance,0);@/
6741 @!@:advance_}{\.{\\advance} primitive@>
6742 primitive("afterassignment",after_assignment,0);@/
6743 @!@:after_assignment_}{\.{\\afterassignment} primitive@>
6744 primitive("aftergroup",after_group,0);@/
6745 @!@:after_group_}{\.{\\aftergroup} primitive@>
6746 primitive("begingroup",begin_group,0);@/
6747 @!@:begin_group_}{\.{\\begingroup} primitive@>
6748 primitive("char",char_num,0);@/
6749 @!@:char_}{\.{\\char} primitive@>
6750 primitive("csname",cs_name,0);@/
6751 @!@:cs_name_}{\.{\\csname} primitive@>
6752 primitive("delimiter",delim_num,0);@/
6753 @!@:delimiter_}{\.{\\delimiter} primitive@>
6754 primitive("XeTeXdelimiter",delim_num,1);@/
6755 primitive("Udelimiter",delim_num,1);@/
6756 @!@:U_delimiter_}{\.{\\Udelimiter} primitive@>
6757 primitive("divide",divide,0);@/
6758 @!@:divide_}{\.{\\divide} primitive@>
6759 primitive("endcsname",end_cs_name,0);@/
6760 @!@:end_cs_name_}{\.{\\endcsname} primitive@>
6761 primitive("endgroup",end_group,0);
6762 @!@:end_group_}{\.{\\endgroup} primitive@>
6763 text(frozen_end_group):="endgroup"; eqtb[frozen_end_group]:=eqtb[cur_val];@/
6764 primitive("expandafter",expand_after,0);@/
6765 @!@:expand_after_}{\.{\\expandafter} primitive@>
6766 primitive("font",def_font,0);@/
6767 @!@:font_}{\.{\\font} primitive@>
6768 primitive("fontdimen",assign_font_dimen,0);@/
6769 @!@:font_dimen_}{\.{\\fontdimen} primitive@>
6770 primitive("halign",halign,0);@/
6771 @!@:halign_}{\.{\\halign} primitive@>
6772 primitive("hrule",hrule,0);@/
6773 @!@:hrule_}{\.{\\hrule} primitive@>
6774 primitive("ignorespaces",ignore_spaces,0);@/
6775 @!@:ignore_spaces_}{\.{\\ignorespaces} primitive@>
6776 primitive("insert",insert,0);@/
6777 @!@:insert_}{\.{\\insert} primitive@>
6778 primitive("mark",mark,0);@/
6779 @!@:mark_}{\.{\\mark} primitive@>
6780 primitive("mathaccent",math_accent,0);@/
6781 @!@:math_accent_}{\.{\\mathaccent} primitive@>
6782 primitive("XeTeXmathaccent",math_accent,1);@/
6783 primitive("Umathaccent",math_accent,1);@/
6784 @!@:U_math_accent_}{\.{\\Umathaccent} primitive@>
6785 primitive("mathchar",math_char_num,0);@/
6786 @!@:math_char_}{\.{\\mathchar} primitive@>
6787 primitive("XeTeXmathcharnum",math_char_num,1);@/
6788 primitive("Umathcharnum",math_char_num,1);@/
6789 @!@:U_math_char_num_}{\.{\\Umathcharnum} primitive@>
6790 primitive("XeTeXmathchar",math_char_num,2);@/
6791 primitive("Umathchar",math_char_num,2);@/
6792 @!@:U_math_char_}{\.{\\Umathchar} primitive@>
6793 primitive("mathchoice",math_choice,0);@/
6794 @!@:math_choice_}{\.{\\mathchoice} primitive@>
6795 primitive("multiply",multiply,0);@/
6796 @!@:multiply_}{\.{\\multiply} primitive@>
6797 primitive("noalign",no_align,0);@/
6798 @!@:no_align_}{\.{\\noalign} primitive@>
6799 primitive("noboundary",no_boundary,0);@/
6800 @!@:no_boundary_}{\.{\\noboundary} primitive@>
6801 primitive("noexpand",no_expand,0);@/
6802 @!@:no_expand_}{\.{\\noexpand} primitive@>
6803 primitive("primitive",no_expand,1);@/
6804 @!@:primitive_}{\.{\\primitive} primitive@>
6805 primitive("nonscript",non_script,0);@/
6806 @!@:non_script_}{\.{\\nonscript} primitive@>
6807 primitive("omit",omit,0);@/
6808 @!@:omit_}{\.{\\omit} primitive@>
6809 primitive("parshape",set_shape,par_shape_loc);@/
6810 @!@:par_shape_}{\.{\\parshape} primitive@>
6811 primitive("penalty",break_penalty,0);@/
6812 @!@:penalty_}{\.{\\penalty} primitive@>
6813 primitive("prevgraf",set_prev_graf,0);@/
6814 @!@:prev_graf_}{\.{\\prevgraf} primitive@>
6815 primitive("radical",radical,0);@/
6816 @!@:radical_}{\.{\\radical} primitive@>
6817 primitive("XeTeXradical",radical,1);@/
6818 primitive("Uradical",radical,1);@/
6819 @!@:U_radical_}{\.{\\Uradical} primitive@>
6820 primitive("read",read_to_cs,0);@/
6821 @!@:read_}{\.{\\read} primitive@>
6822 primitive("relax",relax,too_big_usv); {cf.\ |scan_file_name|}
6823 @!@:relax_}{\.{\\relax} primitive@>
6824 text(frozen_relax):="relax"; eqtb[frozen_relax]:=eqtb[cur_val];@/
6825 primitive("setbox",set_box,0);@/
6826 @!@:set_box_}{\.{\\setbox} primitive@>
6827 primitive("the",the,0);@/
6828 @!@:the_}{\.{\\the} primitive@>
6829 primitive("toks",toks_register,mem_bot);@/
6830 @!@:toks_}{\.{\\toks} primitive@>
6831 primitive("vadjust",vadjust,0);@/
6832 @!@:vadjust_}{\.{\\vadjust} primitive@>
6833 primitive("valign",valign,0);@/
6834 @!@:valign_}{\.{\\valign} primitive@>
6835 primitive("vcenter",vcenter,0);@/
6836 @!@:vcenter_}{\.{\\vcenter} primitive@>
6837 primitive("vrule",vrule,0);@/
6838 @!@:vrule_}{\.{\\vrule} primitive@>
6839
6840 @ Each primitive has a corresponding inverse, so that it is possible to
6841 display the cryptic numeric contents of |eqtb| in symbolic form.
6842 Every call of |primitive| in this program is therefore accompanied by some
6843 straightforward code that forms part of the |print_cmd_chr| routine
6844 below.
6845
6846 @<Cases of |print_cmd_chr|...@>=
6847 accent: print_esc("accent");
6848 advance: print_esc("advance");
6849 after_assignment: print_esc("afterassignment");
6850 after_group: print_esc("aftergroup");
6851 assign_font_dimen: print_esc("fontdimen");
6852 begin_group: print_esc("begingroup");
6853 break_penalty: print_esc("penalty");
6854 char_num: print_esc("char");
6855 cs_name: print_esc("csname");
6856 def_font: print_esc("font");
6857 delim_num: if chr_code=1 then print_esc("Udelimiter")
6858 else print_esc("delimiter");
6859 divide: print_esc("divide");
6860 end_cs_name: print_esc("endcsname");
6861 end_group: print_esc("endgroup");
6862 ex_space: print_esc(" ");
6863 expand_after: if chr_code=0 then print_esc("expandafter")
6864 @<Cases of |expandafter| for |print_cmd_chr|@>;
6865 halign: print_esc("halign");
6866 hrule: print_esc("hrule");
6867 ignore_spaces: if chr_code=0 then print_esc("ignorespaces") else print_esc("primitive");
6868 insert: print_esc("insert");
6869 ital_corr: print_esc("/");
6870 mark: begin print_esc("mark");
6871 if chr_code>0 then print_char("s");
6872 end;
6873 math_accent: if chr_code=1 then print_esc("Umathaccent")
6874 else print_esc("mathaccent");
6875 math_char_num: if chr_code=2 then print_esc("Umathchar")
6876 else if chr_code=1 then print_esc("Umathcharnum")
6877 else print_esc("mathchar");
6878 math_choice: print_esc("mathchoice");
6879 multiply: print_esc("multiply");
6880 no_align: print_esc("noalign");
6881 no_boundary:print_esc("noboundary");
6882 no_expand: if chr_code=0 then print_esc("noexpand")
6883 else print_esc("primitive");
6884 non_script: print_esc("nonscript");
6885 omit: print_esc("omit");
6886 radical: if chr_code=1 then print_esc("Uradical") else print_esc("radical");
6887 read_to_cs: if chr_code=0 then print_esc("read")
6888 @<Cases of |read| for |print_cmd_chr|@>;
6889 relax: print_esc("relax");
6890 set_box: print_esc("setbox");
6891 set_prev_graf: print_esc("prevgraf");
6892 set_shape: case chr_code of
6893 par_shape_loc: print_esc("parshape");
6894 @<Cases of |set_shape| for |print_cmd_chr|@>@;@/
6895 end; {there are no other cases}
6896 the: if chr_code=0 then print_esc("the")
6897 @<Cases of |the| for |print_cmd_chr|@>;
6898 toks_register: @<Cases of |toks_register| for |print_cmd_chr|@>;
6899 vadjust: print_esc("vadjust");
6900 valign: if chr_code=0 then print_esc("valign")@/
6901 @<Cases of |valign| for |print_cmd_chr|@>;
6902 vcenter: print_esc("vcenter");
6903 vrule: print_esc("vrule");
6904
6905 @ We will deal with the other primitives later, at some point in the program
6906 where their |eq_type| and |equiv| values are more meaningful. For example,
6907 the primitives for math mode will be loaded when we consider the routines
6908 that deal with formulas. It is easy to find where each particular
6909 primitive was treated by looking in the index at the end; for example, the
6910 section where |"radical"| entered |eqtb| is listed under `\.{\\radical}
6911 primitive'. (Primitives consisting of a single nonalphabetic character,
6912 @!like `\.{\\/}', are listed under `Single-character primitives'.)
6913 @!@^Single-character primitives@>
6914
6915 Meanwhile, this is a convenient place to catch up on something we were unable
6916 to do before the hash table was defined:
6917
6918 @<Print the font identifier for |font(p)|@>=
6919 print_esc(font_id_text(font(p)))
6920
6921 @* \[19] Saving and restoring equivalents.
6922 The nested structure provided by `$\.{\char'173}\ldots\.{\char'175}$' groups
6923 in \TeX\ means that |eqtb| entries valid in outer groups should be saved
6924 and restored later if they are overridden inside the braces. When a new |eqtb|
6925 value is being assigned, the program therefore checks to see if the previous
6926 entry belongs to an outer level. In such a case, the old value is placed
6927 on the |save_stack| just before the new value enters |eqtb|. At the
6928 end of a grouping level, i.e., when the right brace is sensed, the
6929 |save_stack| is used to restore the outer values, and the inner ones are
6930 destroyed.
6931
6932 Entries on the |save_stack| are of type |memory_word|. The top item on
6933 this stack is |save_stack[p]|, where |p=save_ptr-1|; it contains three
6934 fields called |save_type|, |save_level|, and |save_index|, and it is
6935 interpreted in one of five ways:
6936
6937 \yskip\hangg 1) If |save_type(p)=restore_old_value|, then
6938 |save_index(p)| is a location in |eqtb| whose current value should
6939 be destroyed at the end of the current group and replaced by |save_stack[p-1]|.
6940 Furthermore if |save_index(p)>=int_base|, then |save_level(p)|
6941 should replace the corresponding entry in |xeq_level|.
6942
6943 \yskip\hangg 2) If |save_type(p)=restore_zero|, then |save_index(p)|
6944 is a location in |eqtb| whose current value should be destroyed at the end
6945 of the current group, when it should be
6946 replaced by the value of |eqtb[undefined_control_sequence]|.
6947
6948 \yskip\hangg 3) If |save_type(p)=insert_token|, then |save_index(p)|
6949 is a token that should be inserted into \TeX's input when the current
6950 group ends.
6951
6952 \yskip\hangg 4) If |save_type(p)=level_boundary|, then |save_level(p)|
6953 is a code explaining what kind of group we were previously in, and
6954 |save_index(p)| points to the level boundary word at the bottom of
6955 the entries for that group.
6956 Furthermore, in extended \eTeX\ mode, |save_stack[p-1]| contains the
6957 source line number at which the current level of grouping was entered.
6958
6959 \yskip\hang 5) If |save_type(p)=restore_sa|, then |sa_chain| points to a
6960 chain of sparse array entries to be restored at the end of the current
6961 group. Furthermore |save_index(p)| and |save_level(p)| should replace
6962 the values of |sa_chain| and |sa_level| respectively.
6963
6964 @d save_type(#)==save_stack[#].hh.b0 {classifies a |save_stack| entry}
6965 @d save_level(#)==save_stack[#].hh.b1
6966 {saved level for regions 5 and 6, or group code}
6967 @d save_index(#)==save_stack[#].hh.rh
6968 {|eqtb| location or token or |save_stack| location}
6969 @d restore_old_value=0 {|save_type| when a value should be restored later}
6970 @d restore_zero=1 {|save_type| when an undefined entry should be restored}
6971 @d insert_token=2 {|save_type| when a token is being saved for later use}
6972 @d level_boundary=3 {|save_type| corresponding to beginning of group}
6973 @d restore_sa=4 {|save_type| when sparse array entries should be restored}
6974
6975 @p@t\4@>@<Declare \eTeX\ procedures for tracing and input@>
6976
6977 @ Here are the group codes that are used to discriminate between different
6978 kinds of groups. They allow \TeX\ to decide what special actions, if any,
6979 should be performed when a group ends.
6980 \def\grp{\.{\char'173...\char'175}}
6981
6982 Some groups are not supposed to be ended by right braces. For example,
6983 the `\.\$' that begins a math formula causes a |math_shift_group| to
6984 be started, and this should be terminated by a matching `\.\$'. Similarly,
6985 a group that starts with \.{\\left} should end with \.{\\right}, and
6986 one that starts with \.{\\begingroup} should end with \.{\\endgroup}.
6987
6988 @d bottom_level=0 {group code for the outside world}
6989 @d simple_group=1 {group code for local structure only}
6990 @d hbox_group=2 {code for `\.{\\hbox}\grp'}
6991 @d adjusted_hbox_group=3 {code for `\.{\\hbox}\grp' in vertical mode}
6992 @d vbox_group=4 {code for `\.{\\vbox}\grp'}
6993 @d vtop_group=5 {code for `\.{\\vtop}\grp'}
6994 @d align_group=6 {code for `\.{\\halign}\grp', `\.{\\valign}\grp'}
6995 @d no_align_group=7 {code for `\.{\\noalign}\grp'}
6996 @d output_group=8 {code for output routine}
6997 @d math_group=9 {code for, e.g., `\.{\char'136}\grp'}
6998 @d disc_group=10 {code for `\.{\\discretionary}\grp\grp\grp'}
6999 @d insert_group=11 {code for `\.{\\insert}\grp', `\.{\\vadjust}\grp'}
7000 @d vcenter_group=12 {code for `\.{\\vcenter}\grp'}
7001 @d math_choice_group=13 {code for `\.{\\mathchoice}\grp\grp\grp\grp'}
7002 @d semi_simple_group=14 {code for `\.{\\begingroup...\\endgroup}'}
7003 @d math_shift_group=15 {code for `\.{\$...\$}'}
7004 @d math_left_group=16 {code for `\.{\\left...\\right}'}
7005 @d max_group_code=16
7006
7007 @<Types...@>=
7008 @!group_code=0..max_group_code; {|save_level| for a level boundary}
7009
7010 @ The global variable |cur_group| keeps track of what sort of group we are
7011 currently in. Another global variable, |cur_boundary|, points to the
7012 topmost |level_boundary| word. And |cur_level| is the current depth of
7013 nesting. The routines are designed to preserve the condition that no entry
7014 in the |save_stack| or in |eqtb| ever has a level greater than |cur_level|.
7015
7016 @ @<Glob...@>=
7017 @!save_stack : array[0..save_size] of memory_word;
7018 @!save_ptr : 0..save_size; {first unused entry on |save_stack|}
7019 @!max_save_stack:0..save_size; {maximum usage of save stack}
7020 @!cur_level: quarterword; {current nesting level for groups}
7021 @!cur_group: group_code; {current group type}
7022 @!cur_boundary: 0..save_size; {where the current level begins}
7023
7024 @ At this time it might be a good idea for the reader to review the introduction
7025 to |eqtb| that was given above just before the long lists of parameter names.
7026 Recall that the ``outer level'' of the program is |level_one|, since
7027 undefined control sequences are assumed to be ``defined'' at |level_zero|.
7028
7029 @<Set init...@>=
7030 save_ptr:=0; cur_level:=level_one; cur_group:=bottom_level; cur_boundary:=0;
7031 max_save_stack:=0;
7032
7033 @ The following macro is used to test if there is room for up to seven more
7034 entries on |save_stack|. By making a conservative test like this, we can
7035 get by with testing for overflow in only a few places.
7036
7037 @d check_full_save_stack==if save_ptr>max_save_stack then
7038 begin max_save_stack:=save_ptr;
7039 if max_save_stack>save_size-7 then overflow("save size",save_size);
7040 @:TeX capacity exceeded save size}{\quad save size@>
7041 end
7042
7043 @ Procedure |new_save_level| is called when a group begins. The
7044 argument is a group identification code like `|hbox_group|'. After
7045 calling this routine, it is safe to put five more entries on |save_stack|.
7046
7047 In some cases integer-valued items are placed onto the
7048 |save_stack| just below a |level_boundary| word, because this is a
7049 convenient place to keep information that is supposed to ``pop up'' just
7050 when the group has finished.
7051 For example, when `\.{\\hbox to 100pt}\grp' is being treated, the 100pt
7052 dimension is stored on |save_stack| just before |new_save_level| is
7053 called.
7054
7055 We use the notation |saved(k)| to stand for an integer item that
7056 appears in location |save_ptr+k| of the save stack.
7057
7058 @d saved(#)==save_stack[save_ptr+#].int
7059
7060 @p procedure new_save_level(@!c:group_code); {begin a new level of grouping}
7061 begin check_full_save_stack;
7062 if eTeX_ex then
7063 begin saved(0):=line; incr(save_ptr);
7064 end;
7065 save_type(save_ptr):=level_boundary; save_level(save_ptr):=cur_group;
7066 save_index(save_ptr):=cur_boundary;
7067 if cur_level=max_quarterword then overflow("grouping levels",
7068 @:TeX capacity exceeded grouping levels}{\quad grouping levels@>
7069 max_quarterword-min_quarterword);
7070 {quit if |(cur_level+1)| is too big to be stored in |eqtb|}
7071 cur_boundary:=save_ptr; cur_group:=c;
7072 @!stat if tracing_groups>0 then group_trace(false);@+tats@;@/
7073 incr(cur_level); incr(save_ptr);
7074 end;
7075
7076 @ Just before an entry of |eqtb| is changed, the following procedure should
7077 be called to update the other data structures properly. It is important
7078 to keep in mind that reference counts in |mem| include references from
7079 within |save_stack|, so these counts must be handled carefully.
7080 @^reference counts@>
7081
7082 @p procedure eq_destroy(@!w:memory_word); {gets ready to forget |w|}
7083 var q:pointer; {|equiv| field of |w|}
7084 begin case eq_type_field(w) of
7085 call,long_call,outer_call,long_outer_call: delete_token_ref(equiv_field(w));
7086 glue_ref: delete_glue_ref(equiv_field(w));
7087 shape_ref: begin q:=equiv_field(w); {we need to free a \.{\\parshape} block}
7088 if q<>null then free_node(q,info(q)+info(q)+1);
7089 end; {such a block is |2n+1| words long, where |n=info(q)|}
7090 box_ref: flush_node_list(equiv_field(w));
7091 @/@<Cases for |eq_destroy|@>@/
7092 othercases do_nothing
7093 endcases;
7094 end;
7095
7096 @ To save a value of |eqtb[p]| that was established at level |l|, we
7097 can use the following subroutine.
7098
7099 @p procedure eq_save(@!p:pointer;@!l:quarterword); {saves |eqtb[p]|}
7100 begin check_full_save_stack;
7101 if l=level_zero then save_type(save_ptr):=restore_zero
7102 else begin save_stack[save_ptr]:=eqtb[p]; incr(save_ptr);
7103 save_type(save_ptr):=restore_old_value;
7104 end;
7105 save_level(save_ptr):=l; save_index(save_ptr):=p; incr(save_ptr);
7106 end;
7107
7108 @ The procedure |eq_define| defines an |eqtb| entry having specified
7109 |eq_type| and |equiv| fields, and saves the former value if appropriate.
7110 This procedure is used only for entries in the first four regions of |eqtb|,
7111 i.e., only for entries that have |eq_type| and |equiv| fields.
7112 After calling this routine, it is safe to put four more entries on
7113 |save_stack|, provided that there was room for four more entries before
7114 the call, since |eq_save| makes the necessary test.
7115
7116 @d assign_trace(#)==@!stat if tracing_assigns>0 then restore_trace(#);
7117 tats
7118
7119 @p procedure eq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
7120 {new data for |eqtb|}
7121 label exit;
7122 begin if eTeX_ex and(eq_type(p)=t)and(equiv(p)=e) then
7123 begin assign_trace(p,"reassigning")@;@/
7124 eq_destroy(eqtb[p]); return;
7125 end;
7126 assign_trace(p,"changing")@;@/
7127 if eq_level(p)=cur_level then eq_destroy(eqtb[p])
7128 else if cur_level>level_one then eq_save(p,eq_level(p));
7129 eq_level(p):=cur_level; eq_type(p):=t; equiv(p):=e;
7130 assign_trace(p,"into")@;@/
7131 exit:end;
7132
7133 @ The counterpart of |eq_define| for the remaining (fullword) positions in
7134 |eqtb| is called |eq_word_define|. Since |xeq_level[p]>=level_one| for all
7135 |p|, a `|restore_zero|' will never be used in this case.
7136
7137 @p procedure eq_word_define(@!p:pointer;@!w:integer);
7138 label exit;
7139 begin if eTeX_ex and(eqtb[p].int=w) then
7140 begin assign_trace(p,"reassigning")@;@/
7141 return;
7142 end;
7143 assign_trace(p,"changing")@;@/
7144 if xeq_level[p]<>cur_level then
7145 begin eq_save(p,xeq_level[p]); xeq_level[p]:=cur_level;
7146 end;
7147 eqtb[p].int:=w;
7148 assign_trace(p,"into")@;@/
7149 exit:end;
7150
7151 @ The |eq_define| and |eq_word_define| routines take care of local definitions.
7152 @^global definitions@>
7153 Global definitions are done in almost the same way, but there is no need
7154 to save old values, and the new value is associated with |level_one|.
7155
7156 @p procedure geq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
7157 {global |eq_define|}
7158 begin assign_trace(p,"globally changing")@;@/
7159 begin eq_destroy(eqtb[p]);
7160 eq_level(p):=level_one; eq_type(p):=t; equiv(p):=e;
7161 end;
7162 assign_trace(p,"into")@;@/
7163 end;
7164 @#
7165 procedure geq_word_define(@!p:pointer;@!w:integer); {global |eq_word_define|}
7166 begin assign_trace(p,"globally changing")@;@/
7167 begin eqtb[p].int:=w; xeq_level[p]:=level_one;
7168 end;
7169 assign_trace(p,"into")@;@/
7170 end;
7171
7172 @ Subroutine |save_for_after| puts a token on the stack for save-keeping.
7173
7174 @p procedure save_for_after(@!t:halfword);
7175 begin if cur_level>level_one then
7176 begin check_full_save_stack;
7177 save_type(save_ptr):=insert_token; save_level(save_ptr):=level_zero;
7178 save_index(save_ptr):=t; incr(save_ptr);
7179 end;
7180 end;
7181
7182 @ The |unsave| routine goes the other way, taking items off of |save_stack|.
7183 This routine takes care of restoration when a level ends; everything
7184 belonging to the topmost group is cleared off of the save stack.
7185
7186 @p
7187 procedure@?back_input; forward; @t\2@>
7188 procedure unsave; {pops the top level off the save stack}
7189 label done;
7190 var p:pointer; {position to be restored}
7191 @!l:quarterword; {saved level, if in fullword regions of |eqtb|}
7192 @!t:halfword; {saved value of |cur_tok|}
7193 @!a:boolean; {have we already processed an \.{\\aftergroup} ?}
7194 begin a:=false;
7195 if cur_level>level_one then
7196 begin decr(cur_level);
7197 @<Clear off top level from |save_stack|@>;
7198 end
7199 else confusion("curlevel"); {|unsave| is not used when |cur_group=bottom_level|}
7200 @:this can't happen curlevel}{\quad curlevel@>
7201 end;
7202
7203 @ @<Clear off...@>=
7204 loop@+begin decr(save_ptr);
7205 if save_type(save_ptr)=level_boundary then goto done;
7206 p:=save_index(save_ptr);
7207 if save_type(save_ptr)=insert_token then
7208 @<Insert token |p| into \TeX's input@>
7209 else if save_type(save_ptr)=restore_sa then
7210 begin sa_restore; sa_chain:=p; sa_level:=save_level(save_ptr);
7211 end
7212 else begin if save_type(save_ptr)=restore_old_value then
7213 begin l:=save_level(save_ptr); decr(save_ptr);
7214 end
7215 else save_stack[save_ptr]:=eqtb[undefined_control_sequence];
7216 @<Store \(s)|save_stack[save_ptr]| in |eqtb[p]|, unless
7217 |eqtb[p]| holds a global value@>;
7218 end;
7219 end;
7220 done: @!stat if tracing_groups>0 then group_trace(true);@+tats@;@/
7221 if grp_stack[in_open]=cur_boundary then group_warning;
7222 {groups possibly not properly nested with files}
7223 cur_group:=save_level(save_ptr); cur_boundary:=save_index(save_ptr);
7224 if eTeX_ex then decr(save_ptr)
7225
7226 @ A global definition, which sets the level to |level_one|,
7227 @^global definitions@>
7228 will not be undone by |unsave|. If at least one global definition of
7229 |eqtb[p]| has been carried out within the group that just ended, the
7230 last such definition will therefore survive.
7231
7232 @<Store \(s)|save...@>=
7233 if p<int_base then
7234 if eq_level(p)=level_one then
7235 begin eq_destroy(save_stack[save_ptr]); {destroy the saved value}
7236 @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
7237 end
7238 else begin eq_destroy(eqtb[p]); {destroy the current value}
7239 eqtb[p]:=save_stack[save_ptr]; {restore the saved value}
7240 @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
7241 end
7242 else if xeq_level[p]<>level_one then
7243 begin eqtb[p]:=save_stack[save_ptr]; xeq_level[p]:=l;
7244 @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
7245 end
7246 else begin
7247 @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
7248 end
7249
7250 @ @<Declare \eTeX\ procedures for tr...@>=
7251 @!stat procedure restore_trace(@!p:pointer;@!s:str_number);
7252 {|eqtb[p]| has just been restored or retained}
7253 begin begin_diagnostic; print_char("{"); print(s); print_char(" ");
7254 show_eqtb(p); print_char("}");
7255 end_diagnostic(false);
7256 end;
7257 tats
7258
7259 @ When looking for possible pointers to a memory location, it is helpful
7260 to look for references from |eqtb| that might be waiting on the
7261 save stack. Of course, we might find spurious pointers too; but this
7262 routine is merely an aid when debugging, and at such times we are
7263 grateful for any scraps of information, even if they prove to be irrelevant.
7264 @^dirty \PASCAL@>
7265
7266 @<Search |save_stack| for equivalents that point to |p|@>=
7267 if save_ptr>0 then for q:=0 to save_ptr-1 do
7268 begin if equiv_field(save_stack[q])=p then
7269 begin print_nl("SAVE("); print_int(q); print_char(")");
7270 end;
7271 end
7272
7273 @ Most of the parameters kept in |eqtb| can be changed freely, but there's
7274 an exception: The magnification should not be used with two different
7275 values during any \TeX\ job, since a single magnification is applied to an
7276 entire run. The global variable |mag_set| is set to the current magnification
7277 whenever it becomes necessary to ``freeze'' it at a particular value.
7278
7279 @<Glob...@>=
7280 @!mag_set:integer; {if nonzero, this magnification should be used henceforth}
7281
7282 @ @<Set init...@>=
7283 mag_set:=0;
7284
7285 @ The |prepare_mag| subroutine is called whenever \TeX\ wants to use |mag|
7286 for magnification.
7287
7288 @p procedure prepare_mag;
7289 begin if (mag_set>0)and(mag<>mag_set) then
7290 begin print_err("Incompatible magnification ("); print_int(mag);
7291 @.Incompatible magnification@>
7292 print(");"); print_nl(" the previous value will be retained");
7293 help2("I can handle only one magnification ratio per job. So I've")@/
7294 ("reverted to the magnification you used earlier on this run.");@/
7295 int_error(mag_set);
7296 geq_word_define(int_base+mag_code,mag_set); {|mag:=mag_set|}
7297 end;
7298 if (mag<=0)or(mag>32768) then
7299 begin print_err("Illegal magnification has been changed to 1000");@/
7300 @.Illegal magnification...@>
7301 help1("The magnification ratio must be between 1 and 32768.");
7302 int_error(mag); geq_word_define(int_base+mag_code,1000);
7303 end;
7304 mag_set:=mag;
7305 end;
7306
7307 @* \[20] Token lists.
7308 A \TeX\ token is either a character or a control sequence, and it is
7309 @^token@>
7310 represented internally in one of two ways: (1)~A character whose ASCII
7311 code number is |c| and whose command code is |m| is represented as the
7312 number $2^{21}m+c$; the command code is in the range |1<=m<=14|. (2)~A control
7313 sequence whose |eqtb| address is |p| is represented as the number
7314 |cs_token_flag+p|. Here |cs_token_flag=@t$2^{25}-1$@>| is larger than
7315 $2^{21}m+c$, yet it is small enough that |cs_token_flag+p< max_halfword|;
7316 thus, a token fits comfortably in a halfword.
7317
7318 A token |t| represents a |left_brace| command if and only if
7319 |t<left_brace_limit|; it represents a |right_brace| command if and only if
7320 we have |left_brace_limit<=t<right_brace_limit|; and it represents a |match| or
7321 |end_match| command if and only if |match_token<=t<=end_match_token|.
7322 The following definitions take care of these token-oriented constants
7323 and a few others.
7324
7325 @d cs_token_flag=@"1FFFFFF {amount added to the |eqtb| location in a
7326 token that stands for a control sequence; is a multiple of~|@"10000|, less~1}
7327 @d max_char_val=@"200000 {to separate char and command code}
7328 @d left_brace_token=@"200000 {$2^{21}\cdot|left_brace|$}
7329 @d left_brace_limit=@"400000 {$2^{21}\cdot(|left_brace|+1)$}
7330 @d right_brace_token=@"400000 {$2^{21}\cdot|right_brace|$}
7331 @d right_brace_limit=@"600000 {$2^{21}\cdot(|right_brace|+1)$}
7332 @d math_shift_token=@"600000 {$2^{21}\cdot|math_shift|$}
7333 @d tab_token=@"800000 {$2^{21}\cdot|tab_mark|$}
7334 @d out_param_token=@"A00000 {$2^{21}\cdot|out_param|$}
7335 @d space_token=@"1400020 {$2^{21}\cdot|spacer|+|" "|$}
7336 @d letter_token=@"1600000 {$2^{21}\cdot|letter|$}
7337 @d other_token=@"1800000 {$2^{21}\cdot|other_char|$}
7338 @d match_token=@"1A00000 {$2^{21}\cdot|match|$}
7339 @d end_match_token=@"1C00000 {$2^{21}\cdot|end_match|$}
7340 @#
7341 @d protected_token=end_match_token+1 {$2^{21}\cdot|end_match|+1$}
7342
7343 @ @<Check the ``constant''...@>=
7344 if cs_token_flag+undefined_control_sequence>max_halfword then bad:=21;
7345
7346 @ A token list is a singly linked list of one-word nodes in |mem|, where
7347 each word contains a token and a link. Macro definitions, output-routine
7348 definitions, marks, \.{\\write} texts, and a few other things
7349 are remembered by \TeX\ in the form
7350 of token lists, usually preceded by a node with a reference count in its
7351 |token_ref_count| field. The token stored in location |p| is called
7352 |info(p)|.
7353
7354 Three special commands appear in the token lists of macro definitions.
7355 When |m=match|, it means that \TeX\ should scan a parameter
7356 for the current macro; when |m=end_match|, it means that parameter
7357 matching should end and \TeX\ should start reading the macro text; and
7358 when |m=out_param|, it means that \TeX\ should insert parameter
7359 number |c| into the text at this point.
7360
7361 The enclosing \.{\char'173} and \.{\char'175} characters of a macro
7362 definition are omitted, but an output routine
7363 will be enclosed in braces.
7364
7365 Here is an example macro definition that illustrates these conventions.
7366 After \TeX\ processes the text
7367 $$\.{\\def\\mac a\#1\#2 \\b \{\#1\\-a \#\#1\#2 \#2\}}$$
7368 the definition of \.{\\mac} is represented as a token list containing
7369 $$\def\,{\hskip2pt}
7370 \vbox{\halign{\hfil#\hfil\cr
7371 (reference count), |letter|\,\.a, |match|\,\#, |match|\,\#, |spacer|\,\.\ ,
7372 \.{\\b}, |end_match|,\cr
7373 |out_param|\,1, \.{\\-}, |letter|\,\.a, |spacer|\,\.\ , |mac_param|\,\#,
7374 |other_char|\,\.1,\cr
7375 |out_param|\,2, |spacer|\,\.\ , |out_param|\,2.\cr}}$$
7376 The procedure |scan_toks| builds such token lists, and |macro_call|
7377 does the parameter matching.
7378 @^reference counts@>
7379
7380 Examples such as
7381 $$\.{\\def\\m\{\\def\\m\{a\}\ b\}}$$
7382 explain why reference counts would be needed even if \TeX\ had no \.{\\let}
7383 operation: When the token list for \.{\\m} is being read, the redefinition of
7384 \.{\\m} changes the |eqtb| entry before the token list has been fully
7385 consumed, so we dare not simply destroy a token list when its
7386 control sequence is being redefined.
7387
7388 If the parameter-matching part of a definition ends with `\.{\#\{}',
7389 the corresponding token list will have `\.\{' just before the `|end_match|'
7390 and also at the very end. The first `\.\{' is used to delimit the parameter; the
7391 second one keeps the first from disappearing.
7392
7393 @ The procedure |show_token_list|, which prints a symbolic form of
7394 the token list that starts at a given node |p|, illustrates these
7395 conventions. The token list being displayed should not begin with a reference
7396 count. However, the procedure is intended to be robust, so that if the
7397 memory links are awry or if |p| is not really a pointer to a token list,
7398 nothing catastrophic will happen.
7399
7400 An additional parameter |q| is also given; this parameter is either null
7401 or it points to a node in the token list where a certain magic computation
7402 takes place that will be explained later. (Basically, |q| is non-null when
7403 we are printing the two-line context information at the time of an error
7404 message; |q| marks the place corresponding to where the second line
7405 should begin.)
7406
7407 For example, if |p| points to the node containing the first \.a in the
7408 token list above, then |show_token_list| will print the string
7409 $$\hbox{`\.{a\#1\#2\ \\b\ ->\#1\\-a\ \#\#1\#2\ \#2}';}$$
7410 and if |q| points to the node containing the second \.a,
7411 the magic computation will be performed just before the second \.a is printed.
7412
7413 The generation will stop, and `\.{\\ETC.}' will be printed, if the length
7414 of printing exceeds a given limit~|l|. Anomalous entries are printed in the
7415 form of control sequences that are not followed by a blank space, e.g.,
7416 `\.{\\BAD.}'; this cannot be confused with actual control sequences because
7417 a real control sequence named \.{BAD} would come out `\.{\\BAD\ }'.
7418
7419 @<Declare the procedure called |show_token_list|@>=
7420 procedure show_token_list(@!p,@!q:integer;@!l:integer);
7421 label exit;
7422 var m,@!c:integer; {pieces of a token}
7423 @!match_chr:integer; {character used in a `|match|'}
7424 @!n:ASCII_code; {the highest parameter number, as an ASCII digit}
7425 begin match_chr:="#"; n:="0"; tally:=0;
7426 while (p<>null) and (tally<l) do
7427 begin if p=q then @<Do magic computation@>;
7428 @<Display token |p|, and |return| if there are problems@>;
7429 p:=link(p);
7430 end;
7431 if p<>null then print_esc("ETC.");
7432 @.ETC@>
7433 exit:
7434 end;
7435
7436 @ @<Display token |p|...@>=
7437 if (p<hi_mem_min) or (p>mem_end) then
7438 begin print_esc("CLOBBERED."); return;
7439 @.CLOBBERED@>
7440 end;
7441 if info(p)>=cs_token_flag then print_cs(info(p)-cs_token_flag)
7442 else begin m:=info(p) div max_char_val; c:=info(p) mod max_char_val;
7443 if info(p)<0 then print_esc("BAD.")
7444 @.BAD@>
7445 else @<Display the token $(|m|,|c|)$@>;
7446 end
7447
7448 @ The procedure usually ``learns'' the character code used for macro
7449 parameters by seeing one in a |match| command before it runs into any
7450 |out_param| commands.
7451
7452 @<Display the token ...@>=
7453 case m of
7454 left_brace,right_brace,math_shift,tab_mark,sup_mark,sub_mark,spacer,
7455 letter,other_char: print_char(c);
7456 mac_param: begin print_char(c); print_char(c);
7457 end;
7458 out_param: begin print_char(match_chr);
7459 if c<=9 then print_char(c+"0")
7460 else begin print_char("!"); return;
7461 end;
7462 end;
7463 match: begin match_chr:=c; print_char(c); incr(n); print_char(n);
7464 if n>"9" then return;
7465 end;
7466 end_match: if c=0 then print("->");
7467 @.->@>
7468 othercases print_esc("BAD.")
7469 @.BAD@>
7470 endcases
7471
7472 @ Here's the way we sometimes want to display a token list, given a pointer
7473 to its reference count; the pointer may be null.
7474
7475 @p procedure token_show(@!p:pointer);
7476 begin if p<>null then show_token_list(link(p),null,10000000);
7477 end;
7478
7479 @ The |print_meaning| subroutine displays |cur_cmd| and |cur_chr| in
7480 symbolic form, including the expansion of a macro or mark.
7481
7482 @p procedure print_meaning;
7483 begin print_cmd_chr(cur_cmd,cur_chr);
7484 if cur_cmd>=call then
7485 begin print_char(":"); print_ln; token_show(cur_chr);
7486 end
7487 else if (cur_cmd=top_bot_mark)and(cur_chr<marks_code) then
7488 begin print_char(":"); print_ln;
7489 token_show(cur_mark[cur_chr]);
7490 end;
7491 end;
7492
7493 @* \[21] Introduction to the syntactic routines.
7494 Let's pause a moment now and try to look at the Big Picture.
7495 The \TeX\ program consists of three main parts: syntactic routines,
7496 semantic routines, and output routines. The chief purpose of the
7497 syntactic routines is to deliver the user's input to the semantic routines,
7498 one token at a time. The semantic routines act as an interpreter
7499 responding to these tokens, which may be regarded as commands. And the
7500 output routines are periodically called on to convert box-and-glue
7501 lists into a compact set of instructions that will be sent
7502 to a typesetter. We have discussed the basic data structures and utility
7503 routines of \TeX, so we are good and ready to plunge into the real activity by
7504 considering the syntactic routines.
7505
7506 Our current goal is to come to grips with the |get_next| procedure,
7507 which is the keystone of \TeX's input mechanism. Each call of |get_next|
7508 sets the value of three variables |cur_cmd|, |cur_chr|, and |cur_cs|,
7509 representing the next input token.
7510 $$\vbox{\halign{#\hfil\cr
7511 \hbox{|cur_cmd| denotes a command code from the long list of codes
7512 given above;}\cr
7513 \hbox{|cur_chr| denotes a character code or other modifier of the command
7514 code;}\cr
7515 \hbox{|cur_cs| is the |eqtb| location of the current control sequence,}\cr
7516 \hbox{\qquad if the current token was a control sequence,
7517 otherwise it's zero.}\cr}}$$
7518 Underlying this external behavior of |get_next| is all the machinery
7519 necessary to convert from character files to tokens. At a given time we
7520 may be only partially finished with the reading of several files (for
7521 which \.{\\input} was specified), and partially finished with the expansion
7522 of some user-defined macros and/or some macro parameters, and partially
7523 finished with the generation of some text in a template for \.{\\halign},
7524 and so on. When reading a character file, special characters must be
7525 classified as math delimiters, etc.; comments and extra blank spaces must
7526 be removed, paragraphs must be recognized, and control sequences must be
7527 found in the hash table. Furthermore there are occasions in which the
7528 scanning routines have looked ahead for a word like `\.{plus}' but only
7529 part of that word was found, hence a few characters must be put back
7530 into the input and scanned again.
7531
7532 To handle these situations, which might all be present simultaneously,
7533 \TeX\ uses various stacks that hold information about the incomplete
7534 activities, and there is a finite state control for each level of the
7535 input mechanism. These stacks record the current state of an implicitly
7536 recursive process, but the |get_next| procedure is not recursive.
7537 Therefore it will not be difficult to translate these algorithms into
7538 low-level languages that do not support recursion.
7539
7540 @<Glob...@>=
7541 @!cur_cmd: eight_bits; {current command set by |get_next|}
7542 @!cur_chr: halfword; {operand of current command}
7543 @!cur_cs: pointer; {control sequence found here, zero if none found}
7544 @!cur_tok: halfword; {packed representative of |cur_cmd| and |cur_chr|}
7545
7546 @ The |print_cmd_chr| routine prints a symbolic interpretation of a
7547 command code and its modifier. This is used in certain `\.{You can\'t}'
7548 error messages, and in the implementation of diagnostic routines like
7549 \.{\\show}.
7550
7551 The body of |print_cmd_chr| is a rather tedious listing of print
7552 commands, and most of it is essentially an inverse to the |primitive|
7553 routine that enters a \TeX\ primitive into |eqtb|. Therefore much of
7554 this procedure appears elsewhere in the program,
7555 together with the corresponding |primitive| calls.
7556
7557 @d chr_cmd(#)==begin print(#);
7558 if chr_code < @"10000 then print_ASCII(chr_code)
7559 else print_char(chr_code); {non-Plane 0 Unicodes can't be sent through |print_ASCII|}
7560 end
7561
7562 @<Declare the procedure called |print_cmd_chr|@>=
7563 procedure print_cmd_chr(@!cmd:quarterword;@!chr_code:halfword);
7564 var n:integer; {temp variable}
7565 @!font_name_str:str_number; {local vars for \.{\\fontname} quoting extension}
7566 @!quote_char:UTF16_code;
7567 begin case cmd of
7568 left_brace: chr_cmd("begin-group character ");
7569 right_brace: chr_cmd("end-group character ");
7570 math_shift: chr_cmd("math shift character ");
7571 mac_param: chr_cmd("macro parameter character ");
7572 sup_mark: chr_cmd("superscript character ");
7573 sub_mark: chr_cmd("subscript character ");
7574 endv: print("end of alignment template");
7575 spacer: chr_cmd("blank space ");
7576 letter: chr_cmd("the letter ");
7577 other_char: chr_cmd("the character ");
7578 @t\4@>@<Cases of |print_cmd_chr| for symbolic printing of primitives@>@/
7579 othercases print("[unknown command code!]")
7580 endcases;
7581 end;
7582
7583 @ Here is a procedure that displays the current command.
7584
7585 @p procedure show_cur_cmd_chr;
7586 var n:integer; {level of \.{\\if...\\fi} nesting}
7587 @!l:integer; {line where \.{\\if} started}
7588 @!p:pointer;
7589 begin begin_diagnostic; print_nl("{");
7590 if mode<>shown_mode then
7591 begin print_mode(mode); print(": "); shown_mode:=mode;
7592 end;
7593 print_cmd_chr(cur_cmd,cur_chr);
7594 if tracing_ifs>0 then
7595 if cur_cmd>=if_test then if cur_cmd<=fi_or_else then
7596 begin print(": ");
7597 if cur_cmd=fi_or_else then
7598 begin print_cmd_chr(if_test,cur_if); print_char(" ");
7599 n:=0; l:=if_line;
7600 end
7601 else begin n:=1; l:=line;
7602 end;
7603 p:=cond_ptr;
7604 while p<>null do
7605 begin incr(n); p:=link(p);
7606 end;
7607 print("(level "); print_int(n); print_char(")"); print_if_line(l);
7608 end;
7609 print_char("}");
7610 end_diagnostic(false);
7611 end;
7612
7613 @* \[22] Input stacks and states.
7614 This implementation of
7615 \TeX\ uses two different conventions for representing sequential stacks.
7616 @^stack conventions@>@^conventions for representing stacks@>
7617
7618 \yskip\hangg 1) If there is frequent access to the top entry, and if the
7619 stack is essentially never empty, then the top entry is kept in a global
7620 variable (even better would be a machine register), and the other entries
7621 appear in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the
7622 semantic stack described above is handled this way, and so is the input
7623 stack that we are about to study.
7624
7625 \yskip\hangg 2) If there is infrequent top access, the entire stack contents
7626 are in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the |save_stack|
7627 is treated this way, as we have seen.
7628
7629 \yskip\noindent
7630 The state of \TeX's input mechanism appears in the input stack, whose
7631 entries are records with six fields, called |state|, |index|, |start|, |loc|,
7632 |limit|, and |name|. This stack is maintained with
7633 convention~(1), so it is declared in the following way:
7634
7635 @<Types...@>=
7636 @!in_state_record = record
7637 @!state_field, @!index_field: quarterword;
7638 @!start_field,@!loc_field, @!limit_field, @!name_field: halfword;
7639 end;
7640
7641 @ @<Glob...@>=
7642 @!input_stack : array[0..stack_size] of in_state_record;
7643 @!input_ptr : 0..stack_size; {first unused location of |input_stack|}
7644 @!max_in_stack: 0..stack_size; {largest value of |input_ptr| when pushing}
7645 @!cur_input : in_state_record;
7646 {the ``top'' input state, according to convention (1)}
7647
7648 @ We've already defined the special variable |loc==cur_input.loc_field|
7649 in our discussion of basic input-output routines. The other components of
7650 |cur_input| are defined in the same way:
7651
7652 @d state==cur_input.state_field {current scanner state}
7653 @d index==cur_input.index_field {reference for buffer information}
7654 @d start==cur_input.start_field {starting position in |buffer|}
7655 @d limit==cur_input.limit_field {end of current line in |buffer|}
7656 @d name==cur_input.name_field {name of the current file}
7657
7658 @ Let's look more closely now at the control variables
7659 (|state|,~|index|,~|start|,~|loc|,~|limit|,~|name|),
7660 assuming that \TeX\ is reading a line of characters that have been input
7661 from some file or from the user's terminal. There is an array called
7662 |buffer| that acts as a stack of all lines of characters that are
7663 currently being read from files, including all lines on subsidiary
7664 levels of the input stack that are not yet completed. \TeX\ will return to
7665 the other lines when it is finished with the present input file.
7666
7667 (Incidentally, on a machine with byte-oriented addressing, it might be
7668 appropriate to combine |buffer| with the |str_pool| array,
7669 letting the buffer entries grow downward from the top of the string pool
7670 and checking that these two tables don't bump into each other.)
7671
7672 The line we are currently working on begins in position |start| of the
7673 buffer; the next character we are about to read is |buffer[loc]|; and
7674 |limit| is the location of the last character present. If |loc>limit|,
7675 the line has been completely read. Usually |buffer[limit]| is the
7676 |end_line_char|, denoting the end of a line, but this is not
7677 true if the current line is an insertion that was entered on the user's
7678 terminal in response to an error message.
7679
7680 The |name| variable is a string number that designates the name of
7681 the current file, if we are reading a text file. It is zero if we
7682 are reading from the terminal; it is |n+1| if we are reading from
7683 input stream |n|, where |0<=n<=16|. (Input stream 16 stands for
7684 an invalid stream number; in such cases the input is actually from
7685 the terminal, under control of the procedure |read_toks|.)
7686 Finally |18<=name<=19| indicates that we are reading a pseudo file
7687 created by the \.{\\scantokens} command.
7688
7689 The |state| variable has one of three values, when we are scanning such
7690 files:
7691 $$\baselineskip 15pt\vbox{\halign{#\hfil\cr
7692 1) |state=mid_line| is the normal state.\cr
7693 2) |state=skip_blanks| is like |mid_line|, but blanks are ignored.\cr
7694 3) |state=new_line| is the state at the beginning of a line.\cr}}$$
7695 These state values are assigned numeric codes so that if we add the state
7696 code to the next character's command code, we get distinct values. For
7697 example, `|mid_line+spacer|' stands for the case that a blank
7698 space character occurs in the middle of a line when it is not being
7699 ignored; after this case is processed, the next value of |state| will
7700 be |skip_blanks|.
7701
7702 @d mid_line=1 {|state| code when scanning a line of characters}
7703 @d skip_blanks=2+max_char_code {|state| code when ignoring blanks}
7704 @d new_line=3+max_char_code+max_char_code {|state| code at start of line}
7705
7706 @ Additional information about the current line is available via the
7707 |index| variable, which counts how many lines of characters are present
7708 in the buffer below the current level. We have |index=0| when reading
7709 from the terminal and prompting the user for each line; then if the user types,
7710 e.g., `\.{\\input paper}', we will have |index=1| while reading
7711 the file \.{paper.tex}. However, it does not follow that |index| is the
7712 same as the input stack pointer, since many of the levels on the input
7713 stack may come from token lists. For example, the instruction `\.{\\input
7714 paper}' might occur in a token list.
7715
7716 The global variable |in_open| is equal to the |index|
7717 value of the highest non-token-list level. Thus, the number of partially read
7718 lines in the buffer is |in_open+1|, and we have |in_open=index|
7719 when we are not reading a token list.
7720
7721 If we are not currently reading from the terminal, or from an input
7722 stream, we are reading from the file variable |input_file[index]|. We use
7723 the notation |terminal_input| as a convenient abbreviation for |name=0|,
7724 and |cur_file| as an abbreviation for |input_file[index]|.
7725
7726 The global variable |line| contains the line number in the topmost
7727 open file, for use in error messages. If we are not reading from
7728 the terminal, |line_stack[index]| holds the line number for the
7729 enclosing level, so that |line| can be restored when the current
7730 file has been read. Line numbers should never be negative, since the
7731 negative of the current line number is used to identify the user's output
7732 routine in the |mode_line| field of the semantic nest entries.
7733
7734 If more information about the input state is needed, it can be
7735 included in small arrays like those shown here. For example,
7736 the current page or segment number in the input file might be
7737 put into a variable |@!page|, maintained for enclosing levels in
7738 `\ignorespaces|@!page_stack:array[1..max_in_open] of integer|\unskip'
7739 by analogy with |line_stack|.
7740 @^system dependencies@>
7741
7742 @d terminal_input==(name=0) {are we reading from the terminal?}
7743 @d cur_file==input_file[index] {the current |alpha_file| variable}
7744
7745 @<Glob...@>=
7746 @!in_open : 0..max_in_open; {the number of lines in the buffer, less one}
7747 @!open_parens : 0..max_in_open; {the number of open text files}
7748 @!input_file : array[1..max_in_open] of alpha_file;
7749 @!line : integer; {current line number in the current source file}
7750 @!line_stack : array[1..max_in_open] of integer;
7751
7752 @ Users of \TeX\ sometimes forget to balance left and right braces properly,
7753 and one of the ways \TeX\ tries to spot such errors is by considering an
7754 input file as broken into subfiles by control sequences that
7755 are declared to be \.{\\outer}.
7756
7757 A variable called |scanner_status| tells \TeX\ whether or not to complain
7758 when a subfile ends. This variable has six possible values:
7759
7760 \yskip\hang|normal|, means that a subfile can safely end here without incident.
7761
7762 \yskip\hang|skipping|, means that a subfile can safely end here, but not a file,
7763 because we're reading past some conditional text that was not selected.
7764
7765 \yskip\hang|defining|, means that a subfile shouldn't end now because a
7766 macro is being defined.
7767
7768 \yskip\hang|matching|, means that a subfile shouldn't end now because a
7769 macro is being used and we are searching for the end of its arguments.
7770
7771 \yskip\hang|aligning|, means that a subfile shouldn't end now because we are
7772 not finished with the preamble of an \.{\\halign} or \.{\\valign}.
7773
7774 \yskip\hang|absorbing|, means that a subfile shouldn't end now because we are
7775 reading a balanced token list for \.{\\message}, \.{\\write}, etc.
7776
7777 \yskip\noindent
7778 If the |scanner_status| is not |normal|, the variable |warning_index| points
7779 to the |eqtb| location for the relevant control sequence name to print
7780 in an error message.
7781
7782 @d skipping=1 {|scanner_status| when passing conditional text}
7783 @d defining=2 {|scanner_status| when reading a macro definition}
7784 @d matching=3 {|scanner_status| when reading macro arguments}
7785 @d aligning=4 {|scanner_status| when reading an alignment preamble}
7786 @d absorbing=5 {|scanner_status| when reading a balanced text}
7787
7788 @<Glob...@>=
7789 @!scanner_status : normal..absorbing; {can a subfile end now?}
7790 @!warning_index : pointer; {identifier relevant to non-|normal| scanner status}
7791 @!def_ref : pointer; {reference count of token list being defined}
7792
7793 @ Here is a procedure that uses |scanner_status| to print a warning message
7794 when a subfile has ended, and at certain other crucial times:
7795
7796 @<Declare the procedure called |runaway|@>=
7797 procedure runaway;
7798 var p:pointer; {head of runaway list}
7799 begin if scanner_status>skipping then
7800 begin print_nl("Runaway ");
7801 @.Runaway...@>
7802 case scanner_status of
7803 defining: begin print("definition"); p:=def_ref;
7804 end;
7805 matching: begin print("argument"); p:=temp_head;
7806 end;
7807 aligning: begin print("preamble"); p:=hold_head;
7808 end;
7809 absorbing: begin print("text"); p:=def_ref;
7810 end;
7811 end; {there are no other cases}
7812 print_char("?");print_ln; show_token_list(link(p),null,error_line-10);
7813 end;
7814 end;
7815
7816 @ However, all this discussion about input state really applies only to the
7817 case that we are inputting from a file. There is another important case,
7818 namely when we are currently getting input from a token list. In this case
7819 |state=token_list|, and the conventions about the other state variables
7820 are different:
7821
7822 \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
7823 the node that will be read next. If |loc=null|, the token list has been
7824 fully read.
7825
7826 \yskip\hang|start| points to the first node of the token list; this node
7827 may or may not contain a reference count, depending on the type of token
7828 list involved.
7829
7830 \yskip\hang|token_type|, which takes the place of |index| in the
7831 discussion above, is a code number that explains what kind of token list
7832 is being scanned.
7833
7834 \yskip\hang|name| points to the |eqtb| address of the control sequence
7835 being expanded, if the current token list is a macro.
7836
7837 \yskip\hang|param_start|, which takes the place of |limit|, tells where
7838 the parameters of the current macro begin in the |param_stack|, if the
7839 current token list is a macro.
7840
7841 \yskip\noindent The |token_type| can take several values, depending on
7842 where the current token list came from:
7843
7844 \yskip\hang|parameter|, if a parameter is being scanned;
7845
7846 \hang|u_template|, if the \<u_j> part of an alignment
7847 template is being scanned;
7848
7849 \hang|v_template|, if the \<v_j> part of an alignment
7850 template is being scanned;
7851
7852 \hang|backed_up|, if the token list being scanned has been inserted as
7853 `to be read again';
7854
7855 \hang|inserted|, if the token list being scanned has been inserted as
7856 the text expansion of a \.{\\count} or similar variable;
7857
7858 \hang|macro|, if a user-defined control sequence is being scanned;
7859
7860 \hang|output_text|, if an \.{\\output} routine is being scanned;
7861
7862 \hang|every_par_text|, if the text of \.{\\everypar} is being scanned;
7863
7864 \hang|every_math_text|, if the text of \.{\\everymath} is being scanned;
7865
7866 \hang|every_display_text|, if the text of \.{\\everydisplay} is being scanned;
7867
7868 \hang|every_hbox_text|, if the text of \.{\\everyhbox} is being scanned;
7869
7870 \hang|every_vbox_text|, if the text of \.{\\everyvbox} is being scanned;
7871
7872 \hang|every_job_text|, if the text of \.{\\everyjob} is being scanned;
7873
7874 \hang|every_cr_text|, if the text of \.{\\everycr} is being scanned;
7875
7876 \hang|mark_text|, if the text of a \.{\\mark} is being scanned;
7877
7878 \hang|write_text|, if the text of a \.{\\write} is being scanned.
7879
7880 \yskip\noindent
7881 The codes for |output_text|, |every_par_text|, etc., are equal to a constant
7882 plus the corresponding codes for token list parameters |output_routine_loc|,
7883 |every_par_loc|, etc. The token list begins with a reference count if and
7884 only if |token_type>=macro|.
7885 @^reference counts@>
7886
7887 Since \eTeX's additional token list parameters precede |toks_base|, the
7888 corresponding token types must precede |write_text|.
7889
7890 @d token_list=0 {|state| code when scanning a token list}
7891 @d token_type==index {type of current token list}
7892 @d param_start==limit {base of macro parameters in |param_stack|}
7893 @d parameter=0 {|token_type| code for parameter}
7894 @d u_template=1 {|token_type| code for \<u_j> template}
7895 @d v_template=2 {|token_type| code for \<v_j> template}
7896 @d backed_up=3 {|token_type| code for text to be reread}
7897 @d backed_up_char=4 {special code for backed-up char from \\XeTeXinterchartoks hook}
7898 @d inserted=5 {|token_type| code for inserted texts}
7899 @d macro=6 {|token_type| code for defined control sequences}
7900 @d output_text=7 {|token_type| code for output routines}
7901 @d every_par_text=8 {|token_type| code for \.{\\everypar}}
7902 @d every_math_text=9 {|token_type| code for \.{\\everymath}}
7903 @d every_display_text=10 {|token_type| code for \.{\\everydisplay}}
7904 @d every_hbox_text=11 {|token_type| code for \.{\\everyhbox}}
7905 @d every_vbox_text=12 {|token_type| code for \.{\\everyvbox}}
7906 @d every_job_text=13 {|token_type| code for \.{\\everyjob}}
7907 @d every_cr_text=14 {|token_type| code for \.{\\everycr}}
7908 @d mark_text=15 {|token_type| code for \.{\\topmark}, etc.}
7909 @#
7910 @d eTeX_text_offset=output_routine_loc-output_text
7911 @d every_eof_text=every_eof_loc-eTeX_text_offset
7912 {|token_type| code for \.{\\everyeof}}
7913 @#
7914 @d inter_char_text=XeTeX_inter_char_loc-eTeX_text_offset
7915 {|token_type| code for \.{\\XeTeXinterchartoks}}
7916 @#
7917 @d write_text=toks_base-eTeX_text_offset {|token_type| code for \.{\\write}}
7918
7919 @ The |param_stack| is an auxiliary array used to hold pointers to the token
7920 lists for parameters at the current level and subsidiary levels of input.
7921 This stack is maintained with convention (2), and it grows at a different
7922 rate from the others.
7923
7924 @<Glob...@>=
7925 @!param_stack:array [0..param_size] of pointer;
7926 {token list pointers for parameters}
7927 @!param_ptr:0..param_size; {first unused entry in |param_stack|}
7928 @!max_param_stack:integer;
7929 {largest value of |param_ptr|, will be |<=param_size+9|}
7930
7931 @ The input routines must also interact with the processing of
7932 \.{\\halign} and \.{\\valign}, since the appearance of tab marks and
7933 \.{\\cr} in certain places is supposed to trigger the beginning of special
7934 \<v_j> template text in the scanner. This magic is accomplished by an
7935 |align_state| variable that is increased by~1 when a `\.{\char'173}' is
7936 scanned and decreased by~1 when a `\.{\char'175}' is scanned. The |align_state|
7937 is nonzero during the \<u_j> template, after which it is set to zero; the
7938 \<v_j> template begins when a tab mark or \.{\\cr} occurs at a time that
7939 |align_state=0|.
7940
7941 @<Glob...@>=
7942 @!align_state:integer; {group level with respect to current alignment}
7943
7944 @ Thus, the ``current input state'' can be very complicated indeed; there
7945 can be many levels and each level can arise in a variety of ways. The
7946 |show_context| procedure, which is used by \TeX's error-reporting routine to
7947 print out the current input state on all levels down to the most recent
7948 line of characters from an input file, illustrates most of these conventions.
7949 The global variable |base_ptr| contains the lowest level that was
7950 displayed by this procedure.
7951
7952 @<Glob...@>=
7953 @!base_ptr:0..stack_size; {shallowest level shown by |show_context|}
7954
7955 @ The status at each level is indicated by printing two lines, where the first
7956 line indicates what was read so far and the second line shows what remains
7957 to be read. The context is cropped, if necessary, so that the first line
7958 contains at most |half_error_line| characters, and the second contains
7959 at most |error_line|. Non-current input levels whose |token_type| is
7960 `|backed_up|' are shown only if they have not been fully read.
7961
7962 @p procedure show_context; {prints where the scanner is}
7963 label done;
7964 var old_setting:0..max_selector; {saved |selector| setting}
7965 @!nn:integer; {number of contexts shown so far, less one}
7966 @!bottom_line:boolean; {have we reached the final context to be shown?}
7967 @<Local variables for formatting calculations@>@/
7968 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
7969 {store current state}
7970 nn:=-1; bottom_line:=false;
7971 loop@+begin cur_input:=input_stack[base_ptr]; {enter into the context}
7972 if (state<>token_list) then
7973 if (name>19) or (base_ptr=0) then bottom_line:=true;
7974 if (base_ptr=input_ptr)or bottom_line or(nn<error_context_lines) then
7975 @<Display the current context@>
7976 else if nn=error_context_lines then
7977 begin print_nl("..."); incr(nn); {omitted if |error_context_lines<0|}
7978 end;
7979 if bottom_line then goto done;
7980 decr(base_ptr);
7981 end;
7982 done: cur_input:=input_stack[input_ptr]; {restore original state}
7983 end;
7984
7985 @ @<Display the current context@>=
7986 begin if (base_ptr=input_ptr) or (state<>token_list) or
7987 (token_type<>backed_up) or (loc<>null) then
7988 {we omit backed-up token lists that have already been read}
7989 begin tally:=0; {get ready to count characters}
7990 old_setting:=selector;
7991 if state<>token_list then
7992 begin @<Print location of current line@>;
7993 @<Pseudoprint the line@>;
7994 end
7995 else begin @<Print type of token list@>;
7996 @<Pseudoprint the token list@>;
7997 end;
7998 selector:=old_setting; {stop pseudoprinting}
7999 @<Print two lines using the tricky pseudoprinted information@>;
8000 incr(nn);
8001 end;
8002 end
8003
8004 @ This routine should be changed, if necessary, to give the best possible
8005 indication of where the current line resides in the input file.
8006 For example, on some systems it is best to print both a page and line number.
8007 @^system dependencies@>
8008
8009 @<Print location of current line@>=
8010 if name<=17 then
8011 if terminal_input then
8012 if base_ptr=0 then print_nl("<*>") else print_nl("<insert> ")
8013 else begin print_nl("<read ");
8014 if name=17 then print_char("*")@+else print_int(name-1);
8015 @.*\relax@>
8016 print_char(">");
8017 end
8018 else begin print_nl("l.");
8019 if index=in_open then print_int(line)
8020 else print_int(line_stack[index+1]); {input from a pseudo file}
8021 end;
8022 print_char(" ")
8023
8024 @ @<Print type of token list@>=
8025 case token_type of
8026 parameter: print_nl("<argument> ");
8027 u_template,v_template: print_nl("<template> ");
8028 backed_up,backed_up_char: if loc=null then print_nl("<recently read> ")
8029 else print_nl("<to be read again> ");
8030 inserted: print_nl("<inserted text> ");
8031 macro: begin print_ln; print_cs(name);
8032 end;
8033 output_text: print_nl("<output> ");
8034 every_par_text: print_nl("<everypar> ");
8035 every_math_text: print_nl("<everymath> ");
8036 every_display_text: print_nl("<everydisplay> ");
8037 every_hbox_text: print_nl("<everyhbox> ");
8038 every_vbox_text: print_nl("<everyvbox> ");
8039 every_job_text: print_nl("<everyjob> ");
8040 every_cr_text: print_nl("<everycr> ");
8041 mark_text: print_nl("<mark> ");
8042 every_eof_text: print_nl("<everyeof> ");
8043 inter_char_text: print_nl("<XeTeXinterchartoks> ");
8044 write_text: print_nl("<write> ");
8045 othercases print_nl("?") {this should never happen}
8046 endcases
8047
8048 @ Here it is necessary to explain a little trick. We don't want to store a long
8049 string that corresponds to a token list, because that string might take up
8050 lots of memory; and we are printing during a time when an error message is
8051 being given, so we dare not do anything that might overflow one of \TeX's
8052 tables. So `pseudoprinting' is the answer: We enter a mode of printing
8053 that stores characters into a buffer of length |error_line|, where character
8054 $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
8055 |k<trick_count|, otherwise character |k| is dropped. Initially we set
8056 |tally:=0| and |trick_count:=1000000|; then when we reach the
8057 point where transition from line 1 to line 2 should occur, we
8058 set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
8059 tally+1+error_line-half_error_line)|. At the end of the
8060 pseudoprinting, the values of |first_count|, |tally|, and
8061 |trick_count| give us all the information we need to print the two lines,
8062 and all of the necessary text is in |trick_buf|.
8063
8064 Namely, let |l| be the length of the descriptive information that appears
8065 on the first line. The length of the context information gathered for that
8066 line is |k=first_count|, and the length of the context information
8067 gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
8068 where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
8069 descriptive information on line~1, and set |n:=l+k|; here |n| is the
8070 length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
8071 and print `\.{...}' followed by
8072 $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
8073 where subscripts of |trick_buf| are circular modulo |error_line|. The
8074 second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
8075 unless |n+m>error_line|; in the latter case, further cropping is done.
8076 This is easier to program than to explain.
8077
8078 @<Local variables for formatting...@>=
8079 @!i:0..buf_size; {index into |buffer|}
8080 @!j:0..buf_size; {end of current line in |buffer|}
8081 @!l:0..half_error_line; {length of descriptive information on line 1}
8082 @!m:integer; {context information gathered for line 2}
8083 @!n:0..error_line; {length of line 1}
8084 @!p: integer; {starting or ending place in |trick_buf|}
8085 @!q: integer; {temporary index}
8086
8087 @ The following code sets up the print routines so that they will gather
8088 the desired information.
8089
8090 @d begin_pseudoprint==
8091 begin l:=tally; tally:=0; selector:=pseudo;
8092 trick_count:=1000000;
8093 end
8094 @d set_trick_count==
8095 begin first_count:=tally;
8096 trick_count:=tally+1+error_line-half_error_line;
8097 if trick_count<error_line then trick_count:=error_line;
8098 end
8099
8100 @ And the following code uses the information after it has been gathered.
8101
8102 @<Print two lines using the tricky pseudoprinted information@>=
8103 if trick_count=1000000 then set_trick_count;
8104 {|set_trick_count| must be performed}
8105 if tally<trick_count then m:=tally-first_count
8106 else m:=trick_count-first_count; {context on line 2}
8107 if l+first_count<=half_error_line then
8108 begin p:=0; n:=l+first_count;
8109 end
8110 else begin print("..."); p:=l+first_count-half_error_line+3;
8111 n:=half_error_line;
8112 end;
8113 for q:=p to first_count-1 do print_char(trick_buf[q mod error_line]);
8114 print_ln;
8115 for q:=1 to n do print_visible_char(" "); {print |n| spaces to begin line~2}
8116 if m+n<=error_line then p:=first_count+m else p:=first_count+(error_line-n-3);
8117 for q:=first_count to p-1 do print_char(trick_buf[q mod error_line]);
8118 if m+n>error_line then print("...")
8119
8120 @ But the trick is distracting us from our current goal, which is to
8121 understand the input state. So let's concentrate on the data structures that
8122 are being pseudoprinted as we finish up the |show_context| procedure.
8123
8124 @<Pseudoprint the line@>=
8125 begin_pseudoprint;
8126 if buffer[limit]=end_line_char then j:=limit
8127 else j:=limit+1; {determine the effective end of the line}
8128 if j>0 then for i:=start to j-1 do
8129 begin if i=loc then set_trick_count;
8130 print_char(buffer[i]);
8131 end
8132
8133 @ @<Pseudoprint the token list@>=
8134 begin_pseudoprint;
8135 if token_type<macro then show_token_list(start,loc,100000)
8136 else show_token_list(link(start),loc,100000) {avoid reference count}
8137
8138 @ Here is the missing piece of |show_token_list| that is activated when the
8139 token beginning line~2 is about to be shown:
8140
8141 @<Do magic computation@>=set_trick_count
8142
8143 @* \[23] Maintaining the input stacks.
8144 The following subroutines change the input status in commonly needed ways.
8145
8146 First comes |push_input|, which stores the current state and creates a
8147 new level (having, initially, the same properties as the old).
8148
8149 @d push_input==@t@> {enter a new input level, save the old}
8150 begin if input_ptr>max_in_stack then
8151 begin max_in_stack:=input_ptr;
8152 if input_ptr=stack_size then overflow("input stack size",stack_size);
8153 @:TeX capacity exceeded input stack size}{\quad input stack size@>
8154 end;
8155 input_stack[input_ptr]:=cur_input; {stack the record}
8156 incr(input_ptr);
8157 end
8158
8159 @ And of course what goes up must come down.
8160
8161 @d pop_input==@t@> {leave an input level, re-enter the old}
8162 begin decr(input_ptr); cur_input:=input_stack[input_ptr];
8163 end
8164
8165 @ Here is a procedure that starts a new level of token-list input, given
8166 a token list |p| and its type |t|. If |t=macro|, the calling routine should
8167 set |name| and |loc|.
8168
8169 @d back_list(#)==begin_token_list(#,backed_up) {backs up a simple token list}
8170 @d ins_list(#)==begin_token_list(#,inserted) {inserts a simple token list}
8171
8172 @p procedure begin_token_list(@!p:pointer;@!t:quarterword);
8173 begin push_input; state:=token_list; start:=p; token_type:=t;
8174 if t>=macro then {the token list starts with a reference count}
8175 begin add_token_ref(p);
8176 if t=macro then param_start:=param_ptr
8177 else begin loc:=link(p);
8178 if tracing_macros>1 then
8179 begin begin_diagnostic; print_nl("");
8180 case t of
8181 mark_text:print_esc("mark");
8182 write_text:print_esc("write");
8183 othercases print_cmd_chr(assign_toks,t-output_text+output_routine_loc)
8184 endcases;@/
8185 print("->"); token_show(p); end_diagnostic(false);
8186 end;
8187 end;
8188 end
8189 else loc:=p;
8190 end;
8191
8192 @ When a token list has been fully scanned, the following computations
8193 should be done as we leave that level of input. The |token_type| tends
8194 to be equal to either |backed_up| or |inserted| about 2/3 of the time.
8195 @^inner loop@>
8196
8197 @p procedure end_token_list; {leave a token-list input level}
8198 begin if token_type>=backed_up then {token list to be deleted}
8199 begin if token_type<=inserted then flush_list(start)
8200 else begin delete_token_ref(start); {update reference count}
8201 if token_type=macro then {parameters must be flushed}
8202 while param_ptr>param_start do
8203 begin decr(param_ptr);
8204 flush_list(param_stack[param_ptr]);
8205 end;
8206 end;
8207 end
8208 else if token_type=u_template then
8209 if align_state>500000 then align_state:=0
8210 else fatal_error("(interwoven alignment preambles are not allowed)");
8211 @.interwoven alignment preambles...@>
8212 pop_input;
8213 check_interrupt;
8214 end;
8215
8216 @ Sometimes \TeX\ has read too far and wants to ``unscan'' what it has
8217 seen. The |back_input| procedure takes care of this by putting the token
8218 just scanned back into the input stream, ready to be read again. This
8219 procedure can be used only if |cur_tok| represents the token to be
8220 replaced. Some applications of \TeX\ use this procedure a lot,
8221 so it has been slightly optimized for speed.
8222 @^inner loop@>
8223
8224 @p procedure back_input; {undoes one token of input}
8225 var p:pointer; {a token list of length one}
8226 begin while (state=token_list)and(loc=null)and(token_type<>v_template) do
8227 end_token_list; {conserve stack space}
8228 p:=get_avail; info(p):=cur_tok;
8229 if cur_tok<right_brace_limit then
8230 if cur_tok<left_brace_limit then decr(align_state)
8231 else incr(align_state);
8232 push_input; state:=token_list; start:=p; token_type:=backed_up;
8233 loc:=p; {that was |back_list(p)|, without procedure overhead}
8234 end;
8235
8236 @ @<Insert token |p| into \TeX's input@>=
8237 begin t:=cur_tok; cur_tok:=p;
8238 if a then
8239 begin p:=get_avail; info(p):=cur_tok; link(p):=loc; loc:=p; start:=p;
8240 if cur_tok<right_brace_limit then
8241 if cur_tok<left_brace_limit then decr(align_state)
8242 else incr(align_state);
8243 end
8244 else begin back_input; a:=eTeX_ex;
8245 end;
8246 cur_tok:=t;
8247 end
8248
8249 @ The |back_error| routine is used when we want to replace an offending token
8250 just before issuing an error message. This routine, like |back_input|,
8251 requires that |cur_tok| has been set. We disable interrupts during the
8252 call of |back_input| so that the help message won't be lost.
8253
8254 @p procedure back_error; {back up one token and call |error|}
8255 begin OK_to_interrupt:=false; back_input; OK_to_interrupt:=true; error;
8256 end;
8257 @#
8258 procedure ins_error; {back up one inserted token and call |error|}
8259 begin OK_to_interrupt:=false; back_input; token_type:=inserted;
8260 OK_to_interrupt:=true; error;
8261 end;
8262
8263 @ The |begin_file_reading| procedure starts a new level of input for lines
8264 of characters to be read from a file, or as an insertion from the
8265 terminal. It does not take care of opening the file, nor does it set |loc|
8266 or |limit| or |line|.
8267 @^system dependencies@>
8268
8269 @p procedure begin_file_reading;
8270 begin if in_open=max_in_open then overflow("text input levels",max_in_open);
8271 @:TeX capacity exceeded text input levels}{\quad text input levels@>
8272 if first=buf_size then overflow("buffer size",buf_size);
8273 @:TeX capacity exceeded buffer size}{\quad buffer size@>
8274 incr(in_open); push_input; index:=in_open;
8275 eof_seen[index]:=false;
8276 grp_stack[index]:=cur_boundary; if_stack[index]:=cond_ptr;
8277 line_stack[index]:=line; start:=first; state:=mid_line;
8278 name:=0; {|terminal_input| is now |true|}
8279 end;
8280
8281 @ Conversely, the variables must be downdated when such a level of input
8282 is finished:
8283
8284 @p procedure end_file_reading;
8285 begin first:=start; line:=line_stack[index];
8286 if (name=18)or(name=19) then pseudo_close else
8287 if name>17 then u_close(cur_file); {forget it}
8288 pop_input; decr(in_open);
8289 end;
8290
8291 @ In order to keep the stack from overflowing during a long sequence of
8292 inserted `\.{\\show}' commands, the following routine removes completed
8293 error-inserted lines from memory.
8294
8295 @p procedure clear_for_error_prompt;
8296 begin while (state<>token_list)and terminal_input and@|
8297 (input_ptr>0)and(loc>limit) do end_file_reading;
8298 print_ln; clear_terminal;
8299 end;
8300
8301 @ To get \TeX's whole input mechanism going, we perform the following
8302 actions.
8303
8304 @<Initialize the input routines@>=
8305 begin input_ptr:=0; max_in_stack:=0;
8306 in_open:=0; open_parens:=0; max_buf_stack:=0;
8307 grp_stack[0]:=0; if_stack[0]:=null;
8308 param_ptr:=0; max_param_stack:=0;
8309 first:=buf_size; repeat buffer[first]:=0; decr(first); until first=0;
8310 scanner_status:=normal; warning_index:=null; first:=1;
8311 state:=new_line; start:=1; index:=0; line:=0; name:=0;
8312 force_eof:=false;
8313 align_state:=1000000;@/
8314 if not init_terminal then goto final_end;
8315 limit:=last; first:=last+1; {|init_terminal| has set |loc| and |last|}
8316 end
8317
8318 @* \[24] Getting the next token.
8319 The heart of \TeX's input mechanism is the |get_next| procedure, which
8320 we shall develop in the next few sections of the program. Perhaps we
8321 shouldn't actually call it the ``heart,'' however, because it really acts
8322 as \TeX's eyes and mouth, reading the source files and gobbling them up.
8323 And it also helps \TeX\ to regurgitate stored token lists that are to be
8324 processed again.
8325 @^eyes and mouth@>
8326
8327 The main duty of |get_next| is to input one token and to set |cur_cmd|
8328 and |cur_chr| to that token's command code and modifier. Furthermore, if
8329 the input token is a control sequence, the |eqtb| location of that control
8330 sequence is stored in |cur_cs|; otherwise |cur_cs| is set to zero.
8331
8332 Underlying this simple description is a certain amount of complexity
8333 because of all the cases that need to be handled.
8334 However, the inner loop of |get_next| is reasonably short and fast.
8335
8336 When |get_next| is asked to get the next token of a \.{\\read} line,
8337 it sets |cur_cmd=cur_chr=cur_cs=0| in the case that no more tokens
8338 appear on that line. (There might not be any tokens at all, if the
8339 |end_line_char| has |ignore| as its catcode.)
8340
8341 @ The value of |par_loc| is the |eqtb| address of `\.{\\par}'. This quantity
8342 is needed because a blank line of input is supposed to be exactly equivalent
8343 to the appearance of \.{\\par}; we must set |cur_cs:=par_loc|
8344 when detecting a blank line.
8345
8346 @<Glob...@>=
8347 @!par_loc:pointer; {location of `\.{\\par}' in |eqtb|}
8348 @!par_token:halfword; {token representing `\.{\\par}'}
8349
8350 @ @<Put each...@>=
8351 primitive("par",par_end,too_big_usv); {cf.\ |scan_file_name|}
8352 @!@:par_}{\.{\\par} primitive@>
8353 par_loc:=cur_val; par_token:=cs_token_flag+par_loc;
8354
8355 @ @<Cases of |print_cmd_chr|...@>=
8356 par_end:print_esc("par");
8357
8358 @ Before getting into |get_next|, let's consider the subroutine that
8359 is called when an `\.{\\outer}' control sequence has been scanned or
8360 when the end of a file has been reached. These two cases are distinguished
8361 by |cur_cs|, which is zero at the end of a file.
8362
8363 @p procedure check_outer_validity;
8364 var p:pointer; {points to inserted token list}
8365 @!q:pointer; {auxiliary pointer}
8366 begin if scanner_status<>normal then
8367 begin deletions_allowed:=false;
8368 @<Back up an outer control sequence so that it can be reread@>;
8369 if scanner_status>skipping then
8370 @<Tell the user what has run away and try to recover@>
8371 else begin print_err("Incomplete "); print_cmd_chr(if_test,cur_if);
8372 @.Incomplete \\if...@>
8373 print("; all text was ignored after line "); print_int(skip_line);
8374 help3("A forbidden control sequence occurred in skipped text.")@/
8375 ("This kind of error happens when you say `\if...' and forget")@/
8376 ("the matching `\fi'. I've inserted a `\fi'; this might work.");
8377 if cur_cs<>0 then cur_cs:=0
8378 else help_line[2]:=@|
8379 "The file ended while I was skipping conditional text.";
8380 cur_tok:=cs_token_flag+frozen_fi; ins_error;
8381 end;
8382 deletions_allowed:=true;
8383 end;
8384 end;
8385
8386 @ An outer control sequence that occurs in a \.{\\read} will not be reread,
8387 since the error recovery for \.{\\read} is not very powerful.
8388
8389 @<Back up an outer control sequence so that it can be reread@>=
8390 if cur_cs<>0 then
8391 begin if (state=token_list)or(name<1)or(name>17) then
8392 begin p:=get_avail; info(p):=cs_token_flag+cur_cs;
8393 back_list(p); {prepare to read the control sequence again}
8394 end;
8395 cur_cmd:=spacer; cur_chr:=" "; {replace it by a space}
8396 end
8397
8398 @ @<Tell the user what has run away...@>=
8399 begin runaway; {print a definition, argument, or preamble}
8400 if cur_cs=0 then print_err("File ended")
8401 @.File ended while scanning...@>
8402 else begin cur_cs:=0; print_err("Forbidden control sequence found");
8403 @.Forbidden control sequence...@>
8404 end;
8405 print(" while scanning ");
8406 @<Print either `\.{definition}' or `\.{use}' or `\.{preamble}' or `\.{text}',
8407 and insert tokens that should lead to recovery@>;
8408 print(" of "); sprint_cs(warning_index);
8409 help4("I suspect you have forgotten a `}', causing me")@/
8410 ("to read past where you wanted me to stop.")@/
8411 ("I'll try to recover; but if the error is serious,")@/
8412 ("you'd better type `E' or `X' now and fix your file.");@/
8413 error;
8414 end
8415
8416 @ The recovery procedure can't be fully understood without knowing more
8417 about the \TeX\ routines that should be aborted, but we can sketch the
8418 ideas here: For a runaway definition or a runaway balanced text
8419 we will insert a right brace; for a
8420 runaway preamble, we will insert a special \.{\\cr} token and a right
8421 brace; and for a runaway argument, we will set |long_state| to
8422 |outer_call| and insert \.{\\par}.
8423
8424 @<Print either `\.{definition}' or ...@>=
8425 p:=get_avail;
8426 case scanner_status of
8427 defining:begin print("definition"); info(p):=right_brace_token+"}";
8428 end;
8429 matching:begin print("use"); info(p):=par_token; long_state:=outer_call;
8430 end;
8431 aligning:begin print("preamble"); info(p):=right_brace_token+"}"; q:=p;
8432 p:=get_avail; link(p):=q; info(p):=cs_token_flag+frozen_cr;
8433 align_state:=-1000000;
8434 end;
8435 absorbing:begin print("text"); info(p):=right_brace_token+"}";
8436 end;
8437 end; {there are no other cases}
8438 ins_list(p)
8439
8440 @ We need to mention a procedure here that may be called by |get_next|.
8441
8442 @p procedure@?firm_up_the_line; forward;
8443
8444 @ Now we're ready to take the plunge into |get_next| itself. Parts of
8445 this routine are executed more often than any other instructions of \TeX.
8446 @^mastication@>@^inner loop@>
8447
8448 @d switch=25 {a label in |get_next|}
8449 @d start_cs=26 {another}
8450 @d not_exp=27
8451
8452 @p procedure get_next; {sets |cur_cmd|, |cur_chr|, |cur_cs| to next token}
8453 label restart, {go here to get the next input token}
8454 switch, {go here to eat the next character from a file}
8455 reswitch, {go here to digest it again}
8456 start_cs, {go here to start looking for a control sequence}
8457 found, {go here when a control sequence has been found}
8458 not_exp, {go here when ^^ turned out not to start an expanded code}
8459 exit; {go here when the next input token has been got}
8460 var k:0..buf_size; {an index into |buffer|}
8461 @!t:halfword; {a token}
8462 @!cat:0..max_char_code; {|cat_code(cur_chr)|, usually}
8463 @!c:UnicodeScalar; {constituent of a possible expanded code}
8464 @!lower:UTF16_code; {lower surrogate of a possible UTF-16 compound}
8465 @!d:small_number; {number of excess characters in an expanded code}
8466 @!sup_count:small_number; {number of identical |sup_mark| characters}
8467 begin restart: cur_cs:=0;
8468 if state<>token_list then
8469 @<Input from external file, |goto restart| if no input found@>
8470 else @<Input from token list, |goto restart| if end of list or
8471 if a parameter needs to be expanded@>;
8472 @<If an alignment entry has just ended, take appropriate action@>;
8473 exit:end;
8474
8475 @ An alignment entry ends when a tab or \.{\\cr} occurs, provided that the
8476 current level of braces is the same as the level that was present at the
8477 beginning of that alignment entry; i.e., provided that |align_state| has
8478 returned to the value it had after the \<u_j> template for that entry.
8479 @^inner loop@>
8480
8481 @<If an alignment entry has just ended, take appropriate action@>=
8482 if cur_cmd<=car_ret then if cur_cmd>=tab_mark then if align_state=0 then
8483 @<Insert the \(v)\<v_j> template and |goto restart|@>
8484
8485 @ @<Input from external file, |goto restart| if no input found@>=
8486 @^inner loop@>
8487 begin switch: if loc<=limit then {current line not yet finished}
8488 begin cur_chr:=buffer[loc]; incr(loc);
8489 if (cur_chr >= @"D800) and (cur_chr < @"DC00)
8490 and (loc <= limit) and (buffer[loc] >= @"DC00) and (buffer[loc] < @"E000) then
8491 begin
8492 lower := buffer[loc] - @"DC00;
8493 incr(loc);
8494 cur_chr := @"10000 + (cur_chr - @"D800) * 1024 + lower;
8495 end;
8496 reswitch: cur_cmd:=cat_code(cur_chr);
8497 @<Change state if necessary, and |goto switch| if the
8498 current character should be ignored,
8499 or |goto reswitch| if the current character
8500 changes to another@>;
8501 end
8502 else begin state:=new_line;@/
8503 @<Move to next line of file,
8504 or |goto restart| if there is no next line,
8505 or |return| if a \.{\\read} line has finished@>;
8506 check_interrupt;
8507 goto switch;
8508 end;
8509 end
8510
8511 @ The following 48-way switch accomplishes the scanning quickly, assuming
8512 that a decent \PASCAL\ compiler has translated the code. Note that the numeric
8513 values for |mid_line|, |skip_blanks|, and |new_line| are spaced
8514 apart from each other by |max_char_code+1|, so we can add a character's
8515 command code to the state to get a single number that characterizes both.
8516
8517 @d any_state_plus(#) == mid_line+#,skip_blanks+#,new_line+#
8518
8519 @<Change state if necessary...@>=
8520 case state+cur_cmd of
8521 @<Cases where character is ignored@>: goto switch;
8522 any_state_plus(escape): @<Scan a control sequence
8523 and set |state:=skip_blanks| or |mid_line|@>;
8524 any_state_plus(active_char): @<Process an active-character control sequence
8525 and set |state:=mid_line|@>;
8526 any_state_plus(sup_mark): @<If this |sup_mark| starts an expanded character
8527 like~\.{\^\^A} or~\.{\^\^df}, then |goto reswitch|,
8528 otherwise set |state:=mid_line|@>;
8529 any_state_plus(invalid_char): @<Decry the invalid character and
8530 |goto restart|@>;
8531 @t\4@>@<Handle situations involving spaces, braces, changes of state@>@;
8532 othercases do_nothing
8533 endcases
8534
8535 @ @<Cases where character is ignored@>=
8536 any_state_plus(ignore),skip_blanks+spacer,new_line+spacer
8537
8538 @ We go to |restart| instead of to |switch|, because |state| might equal
8539 |token_list| after the error has been dealt with
8540 (cf.\ |clear_for_error_prompt|).
8541
8542 @<Decry the invalid...@>=
8543 begin print_err("Text line contains an invalid character");
8544 @.Text line contains...@>
8545 help2("A funny symbol that I can't read has just been input.")@/
8546 ("Continue, and I'll forget that it ever happened.");@/
8547 deletions_allowed:=false; error; deletions_allowed:=true;
8548 goto restart;
8549 end
8550
8551 @ @d add_delims_to(#)==#+math_shift,#+tab_mark,#+mac_param,
8552 #+sub_mark,#+letter,#+other_char
8553
8554 @<Handle situations involving spaces, braces, changes of state@>=
8555 mid_line+spacer:@<Enter |skip_blanks| state, emit a space@>;
8556 mid_line+car_ret:@<Finish line, emit a space@>;
8557 skip_blanks+car_ret,any_state_plus(comment):
8558 @<Finish line, |goto switch|@>;
8559 new_line+car_ret:@<Finish line, emit a \.{\\par}@>;
8560 mid_line+left_brace: incr(align_state);
8561 skip_blanks+left_brace,new_line+left_brace: begin
8562 state:=mid_line; incr(align_state);
8563 end;
8564 mid_line+right_brace: decr(align_state);
8565 skip_blanks+right_brace,new_line+right_brace: begin
8566 state:=mid_line; decr(align_state);
8567 end;
8568 add_delims_to(skip_blanks),add_delims_to(new_line): state:=mid_line;
8569
8570 @ When a character of type |spacer| gets through, its character code is
8571 changed to $\.{"\ "}=@'40$. This means that the ASCII codes for tab and space,
8572 and for the space inserted at the end of a line, will
8573 be treated alike when macro parameters are being matched. We do this
8574 since such characters are indistinguishable on most computer terminal displays.
8575
8576 @<Finish line, emit a space@>=
8577 begin loc:=limit+1; cur_cmd:=spacer; cur_chr:=" ";
8578 end
8579
8580 @ The following code is performed only when |cur_cmd=spacer|.
8581
8582 @<Enter |skip_blanks| state, emit a space@>=
8583 begin state:=skip_blanks; cur_chr:=" ";
8584 end
8585
8586 @ @<Finish line, |goto switch|@>=
8587 begin loc:=limit+1; goto switch;
8588 end
8589
8590 @ @<Finish line, emit a \.{\\par}@>=
8591 begin loc:=limit+1; cur_cs:=par_loc; cur_cmd:=eq_type(cur_cs);
8592 cur_chr:=equiv(cur_cs);
8593 if cur_cmd>=outer_call then check_outer_validity;
8594 end
8595
8596 @ Notice that a code like \.{\^\^8} becomes \.x if not followed by a hex digit.
8597
8598 @d is_hex(#)==(((#>="0")and(#<="9"))or((#>="a")and(#<="f")))
8599 @d hex_to_cur_chr==
8600 if c<="9" then cur_chr:=c-"0" @+else cur_chr:=c-"a"+10;
8601 if cc<="9" then cur_chr:=16*cur_chr+cc-"0"
8602 else cur_chr:=16*cur_chr+cc-"a"+10
8603 @d long_hex_to_cur_chr==
8604 if c<="9" then cur_chr:=c-"0" @+else cur_chr:=c-"a"+10;
8605 if cc<="9" then cur_chr:=16*cur_chr+cc-"0"
8606 else cur_chr:=16*cur_chr+cc-"a"+10;
8607 if ccc<="9" then cur_chr:=16*cur_chr+ccc-"0"
8608 else cur_chr:=16*cur_chr+ccc-"a"+10;
8609 if cccc<="9" then cur_chr:=16*cur_chr+cccc-"0"
8610 else cur_chr:=16*cur_chr+cccc-"a"+10
8611
8612 @<If this |sup_mark| starts an expanded character...@>=
8613 begin if cur_chr=buffer[loc] then if loc<limit then
8614 begin sup_count:=2;
8615 {we have |^^| and another char; check how many |^|s we have altogether, up to a max of 6}
8616 while (sup_count<6) and (loc+2*sup_count-2<=limit) and (cur_chr=buffer[loc+sup_count-1]) do
8617 incr(sup_count);
8618 {check whether we have enough hex chars for the number of |^|s}
8619 for d:=1 to sup_count do
8620 if not is_hex(buffer[loc+sup_count-2+d]) then {found a non-hex char, so do single |^^X| style}
8621 begin c:=buffer[loc+1];
8622 if c<@'200 then
8623 begin loc:=loc+2;
8624 if c<@'100 then cur_chr:=c+@'100 @+else cur_chr:=c-@'100;
8625 goto reswitch;
8626 end;
8627 goto not_exp;
8628 end;
8629 {there were the right number of hex chars, so convert them}
8630 cur_chr:=0;
8631 for d:=1 to sup_count do
8632 begin c:=buffer[loc+sup_count-2+d];
8633 if c<="9" then cur_chr:=16*cur_chr+c-"0"
8634 else cur_chr:=16*cur_chr+c-"a"+10;
8635 end;
8636 {check the resulting value is within the valid range}
8637 if cur_chr>biggest_usv then
8638 begin cur_chr:=buffer[loc];
8639 goto not_exp;
8640 end;
8641 loc:=loc+2*sup_count-1;
8642 goto reswitch;
8643 end;
8644 not_exp:
8645 state:=mid_line;
8646 end
8647
8648 @ @<Process an active-character...@>=
8649 begin cur_cs:=cur_chr+active_base;
8650 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs); state:=mid_line;
8651 if cur_cmd>=outer_call then check_outer_validity;
8652 end
8653
8654 @ Control sequence names are scanned only when they appear in some line of
8655 a file; once they have been scanned the first time, their |eqtb| location
8656 serves as a unique identification, so \TeX\ doesn't need to refer to the
8657 original name any more except when it prints the equivalent in symbolic form.
8658
8659 The program that scans a control sequence has been written carefully
8660 in order to avoid the blowups that might otherwise occur if a malicious
8661 user tried something like `\.{\\catcode\'15=0}'. The algorithm might
8662 look at |buffer[limit+1]|, but it never looks at |buffer[limit+2]|.
8663
8664 If expanded characters like `\.{\^\^A}' or `\.{\^\^df}'
8665 appear in or just following
8666 a control sequence name, they are converted to single characters in the
8667 buffer and the process is repeated, slowly but surely.
8668
8669 @<Scan a control...@>=
8670 begin if loc>limit then cur_cs:=null_cs {|state| is irrelevant in this case}
8671 else begin start_cs: k:=loc; cur_chr:=buffer[k]; cat:=cat_code(cur_chr);
8672 incr(k);
8673 if cat=letter then state:=skip_blanks
8674 else if cat=spacer then state:=skip_blanks
8675 else state:=mid_line;
8676 if (cat=letter)and(k<=limit) then
8677 @<Scan ahead in the buffer until finding a nonletter;
8678 if an expanded code is encountered, reduce it
8679 and |goto start_cs|; otherwise if a multiletter control
8680 sequence is found, adjust |cur_cs| and |loc|, and
8681 |goto found|@>
8682 else @<If an expanded code is present, reduce it and |goto start_cs|@>;
8683 {At this point, we have a single-character cs name in the buffer.
8684 But if the character code is ${}>|@"FFFF|$, we treat it like a multiletter name
8685 for string purposes, because we use UTF-16 in the string pool.}
8686 if buffer[loc]>@"FFFF then begin
8687 cur_cs:=id_lookup(loc,1); incr(loc); goto found;
8688 end;
8689 cur_cs:=single_base+buffer[loc]; incr(loc);
8690 end;
8691 found: cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
8692 if cur_cmd>=outer_call then check_outer_validity;
8693 end
8694
8695 @ Whenever we reach the following piece of code, we will have
8696 |cur_chr=buffer[k-1]| and |k<=limit+1| and |cat=cat_code(cur_chr)|. If an
8697 expanded code like \.{\^\^A} or \.{\^\^df} appears in |buffer[(k-1)..(k+1)]|
8698 or |buffer[(k-1)..(k+2)]|, we
8699 will store the corresponding code in |buffer[k-1]| and shift the rest of
8700 the buffer left two or three places.
8701
8702 @<If an expanded...@>=
8703 begin if (cat=sup_mark) and (buffer[k]=cur_chr) and (k<limit) then
8704 begin sup_count:=2;
8705 {we have |^^| and another char; check how many |^|s we have altogether, up to a max of 6}
8706 while (sup_count<6) and (k+2*sup_count-2<=limit) and (buffer[k+sup_count-1]=cur_chr) do
8707 incr(sup_count);
8708 {check whether we have enough hex chars for the number of |^|s}
8709 for d:=1 to sup_count do
8710 if not is_hex(buffer[k+sup_count-2+d]) then {found a non-hex char, so do single |^^X| style}
8711 begin c:=buffer[k+1];
8712 if c<@'200 then
8713 begin if c<@'100 then buffer[k-1]:=c+@'100 @+else buffer[k-1]:=c-@'100;
8714 d:=2; limit:=limit-d;
8715 while k<=limit do
8716 begin buffer[k]:=buffer[k+d]; incr(k);
8717 end;
8718 goto start_cs;
8719 end
8720 else sup_count:=0;
8721 end;
8722 if sup_count>0 then {there were the right number of hex chars, so convert them}
8723 begin cur_chr:=0;
8724 for d:=1 to sup_count do
8725 begin c:=buffer[k+sup_count-2+d];
8726 if c<="9" then cur_chr:=16*cur_chr+c-"0"
8727 else cur_chr:=16*cur_chr+c-"a"+10;
8728 end;
8729 {check the resulting value is within the valid range}
8730 if cur_chr>biggest_usv then cur_chr:=buffer[k]
8731 else begin buffer[k-1]:=cur_chr;
8732 d:=2*sup_count-1;
8733 {shift the rest of the buffer left by |d| chars}
8734 limit:=limit-d;
8735 while k<=limit do
8736 begin buffer[k]:=buffer[k+d]; incr(k);
8737 end;
8738 goto start_cs;
8739 end
8740 end
8741 end
8742 end
8743
8744 @ @<Scan ahead in the buffer...@>=
8745 begin repeat cur_chr:=buffer[k]; cat:=cat_code(cur_chr); incr(k);
8746 until (cat<>letter)or(k>limit);
8747 @<If an expanded...@>;
8748 if cat<>letter then decr(k);
8749 {now |k| points to first nonletter}
8750 if k>loc+1 then {multiletter control sequence has been scanned}
8751 begin cur_cs:=id_lookup(loc,k-loc); loc:=k; goto found;
8752 end;
8753 end
8754
8755 @ Let's consider now what happens when |get_next| is looking at a token list.
8756
8757 @<Input from token list, |goto restart| if end of list or
8758 if a parameter needs to be expanded@>=
8759 if loc<>null then {list not exhausted}
8760 @^inner loop@>
8761 begin t:=info(loc); loc:=link(loc); {move to next}
8762 if t>=cs_token_flag then {a control sequence token}
8763 begin cur_cs:=t-cs_token_flag;
8764 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
8765 if cur_cmd>=outer_call then
8766 if cur_cmd=dont_expand then
8767 @<Get the next token, suppressing expansion@>
8768 else check_outer_validity;
8769 end
8770 else begin cur_cmd:=t div max_char_val; cur_chr:=t mod max_char_val;
8771 case cur_cmd of
8772 left_brace: incr(align_state);
8773 right_brace: decr(align_state);
8774 out_param: @<Insert macro parameter and |goto restart|@>;
8775 othercases do_nothing
8776 endcases;
8777 end;
8778 end
8779 else begin {we are done with this token list}
8780 end_token_list; goto restart; {resume previous level}
8781 end
8782
8783 @ The present point in the program is reached only when the |expand|
8784 routine has inserted a special marker into the input. In this special
8785 case, |info(loc)| is known to be a control sequence token, and |link(loc)=null|.
8786
8787 @d no_expand_flag=special_char {this characterizes a special variant of |relax|}
8788
8789 @<Get the next token, suppressing expansion@>=
8790 begin cur_cs:=info(loc)-cs_token_flag; loc:=null;@/
8791 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
8792 if cur_cmd>max_command then
8793 begin cur_cmd:=relax; cur_chr:=no_expand_flag;
8794 end;
8795 end
8796
8797 @ @<Insert macro parameter...@>=
8798 begin begin_token_list(param_stack[param_start+cur_chr-1],parameter);
8799 goto restart;
8800 end
8801
8802 @ All of the easy branches of |get_next| have now been taken care of.
8803 There is one more branch.
8804
8805 @d end_line_char_inactive == (end_line_char<0)or(end_line_char>255)
8806
8807 @<Move to next line of file, or |goto restart|...@>=
8808 if name>17 then @<Read next line of file into |buffer|, or
8809 |goto restart| if the file has ended@>
8810 else begin if not terminal_input then {\.{\\read} line has ended}
8811 begin cur_cmd:=0; cur_chr:=0; return;
8812 end;
8813 if input_ptr>0 then {text was inserted during error recovery}
8814 begin end_file_reading; goto restart; {resume previous level}
8815 end;
8816 if selector<log_only then open_log_file;
8817 if interaction>nonstop_mode then
8818 begin if end_line_char_inactive then incr(limit);
8819 if limit=start then {previous line was empty}
8820 print_nl("(Please type a command or say `\end')");
8821 @.Please type...@>
8822 print_ln; first:=start;
8823 prompt_input("*"); {input on-line into |buffer|}
8824 @.*\relax@>
8825 limit:=last;
8826 if end_line_char_inactive then decr(limit)
8827 else buffer[limit]:=end_line_char;
8828 first:=limit+1;
8829 loc:=start;
8830 end
8831 else fatal_error("*** (job aborted, no legal \end found)");
8832 @.job aborted@>
8833 {nonstop mode, which is intended for overnight batch processing,
8834 never waits for on-line input}
8835 end
8836
8837 @ The global variable |force_eof| is normally |false|; it is set |true|
8838 by an \.{\\endinput} command.
8839
8840 @<Glob...@>=
8841 @!force_eof:boolean; {should the next \.{\\input} be aborted early?}
8842
8843 @ @<Read next line of file into |buffer|, or
8844 |goto restart| if the file has ended@>=
8845 begin incr(line); first:=start;
8846 if not force_eof then
8847 if name<=19 then
8848 begin if pseudo_input then {not end of file}
8849 firm_up_the_line {this sets |limit|}
8850 else if (every_eof<>null)and not eof_seen[index] then
8851 begin limit:=first-1; eof_seen[index]:=true; {fake one empty line}
8852 begin_token_list(every_eof,every_eof_text); goto restart;
8853 end
8854 else force_eof:=true;
8855 end
8856 else
8857 begin if input_ln(cur_file,true) then {not end of file}
8858 firm_up_the_line {this sets |limit|}
8859 else if (every_eof<>null)and not eof_seen[index] then
8860 begin limit:=first-1; eof_seen[index]:=true; {fake one empty line}
8861 begin_token_list(every_eof,every_eof_text); goto restart;
8862 end
8863 else force_eof:=true;
8864 end;
8865 if force_eof then
8866 begin if tracing_nesting>0 then
8867 if (grp_stack[in_open]<>cur_boundary)or@|
8868 (if_stack[in_open]<>cond_ptr) then file_warning;
8869 {give warning for some unfinished groups and/or conditionals}
8870 if name>=19 then
8871 begin print_char(")"); decr(open_parens);
8872 update_terminal; {show user that file has been read}
8873 end;
8874 force_eof:=false;
8875 end_file_reading; {resume previous level}
8876 check_outer_validity; goto restart;
8877 end;
8878 if end_line_char_inactive then decr(limit)
8879 else buffer[limit]:=end_line_char;
8880 first:=limit+1; loc:=start; {ready to read}
8881 end
8882
8883 @ If the user has set the |pausing| parameter to some positive value,
8884 and if nonstop mode has not been selected, each line of input is displayed
8885 on the terminal and the transcript file, followed by `\.{=>}'.
8886 \TeX\ waits for a response. If the response is simply |carriage_return|, the
8887 line is accepted as it stands, otherwise the line typed is
8888 used instead of the line in the file.
8889
8890 @p procedure firm_up_the_line;
8891 var k:0..buf_size; {an index into |buffer|}
8892 begin limit:=last;
8893 if pausing>0 then if interaction>nonstop_mode then
8894 begin wake_up_terminal; print_ln;
8895 if start<limit then for k:=start to limit-1 do print(buffer[k]);
8896 first:=limit; prompt_input("=>"); {wait for user response}
8897 @.=>@>
8898 if last>first then
8899 begin for k:=first to last-1 do {move line down in buffer}
8900 buffer[k+start-first]:=buffer[k];
8901 limit:=start+last-first;
8902 end;
8903 end;
8904 end;
8905
8906 @ Since |get_next| is used so frequently in \TeX, it is convenient
8907 to define three related procedures that do a little more:
8908
8909 \yskip\hang|get_token| not only sets |cur_cmd| and |cur_chr|, it
8910 also sets |cur_tok|, a packed halfword version of the current token.
8911
8912 \yskip\hang|get_x_token|, meaning ``get an expanded token,'' is like
8913 |get_token|, but if the current token turns out to be a user-defined
8914 control sequence (i.e., a macro call), or a conditional,
8915 or something like \.{\\topmark} or \.{\\expandafter} or \.{\\csname},
8916 it is eliminated from the input by beginning the expansion of the macro
8917 or the evaluation of the conditional.
8918
8919 \yskip\hang|x_token| is like |get_x_token| except that it assumes that
8920 |get_next| has already been called.
8921
8922 \yskip\noindent
8923 In fact, these three procedures account for almost every use of |get_next|.
8924
8925 @ No new control sequences will be defined except during a call of
8926 |get_token|, or when \.{\\csname} compresses a token list, because
8927 |no_new_control_sequence| is always |true| at other times.
8928
8929 @p procedure get_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|}
8930 begin no_new_control_sequence:=false; get_next; no_new_control_sequence:=true;
8931 @^inner loop@>
8932 if cur_cs=0 then cur_tok:=(cur_cmd*max_char_val)+cur_chr
8933 else cur_tok:=cs_token_flag+cur_cs;
8934 end;
8935
8936 @* \[25] Expanding the next token.
8937 Only a dozen or so command codes |>max_command| can possibly be returned by
8938 |get_next|; in increasing order, they are |undefined_cs|, |expand_after|,
8939 |no_expand|, |input|, |if_test|, |fi_or_else|, |cs_name|, |convert|, |the|,
8940 |top_bot_mark|, |call|, |long_call|, |outer_call|, |long_outer_call|, and
8941 |end_template|.{\emergencystretch=40pt\par}
8942
8943 The |expand| subroutine is used when |cur_cmd>max_command|. It removes a
8944 ``call'' or a conditional or one of the other special operations just
8945 listed. It follows that |expand| might invoke itself recursively. In all
8946 cases, |expand| destroys the current token, but it sets things up so that
8947 the next |get_next| will deliver the appropriate next token. The value of
8948 |cur_tok| need not be known when |expand| is called.
8949
8950 Since several of the basic scanning routines communicate via global variables,
8951 their values are saved as local variables of |expand| so that
8952 recursive calls don't invalidate them.
8953 @^recursion@>
8954
8955 @p@t\4@>@<Declare the procedure called |macro_call|@>@;@/
8956 @t\4@>@<Declare the procedure called |insert_relax|@>@;@/
8957 @t\4@>@<Declare \eTeX\ procedures for expanding@>@;@/
8958 procedure@?pass_text; forward;@t\2@>
8959 procedure@?start_input; forward;@t\2@>
8960 procedure@?conditional; forward;@t\2@>
8961 procedure@?get_x_token; forward;@t\2@>
8962 procedure@?conv_toks; forward;@t\2@>
8963 procedure@?ins_the_toks; forward;@t\2@>
8964 procedure expand;
8965 label reswitch;
8966 var t:halfword; {token that is being ``expanded after''}
8967 @!b:boolean; {keep track of nested csnames}
8968 @!p,@!q,@!r:pointer; {for list manipulation}
8969 @!j:0..buf_size; {index into |buffer|}
8970 @!cv_backup:integer; {to save the global quantity |cur_val|}
8971 @!cvl_backup,@!radix_backup,@!co_backup:small_number;
8972 {to save |cur_val_level|, etc.}
8973 @!backup_backup:pointer; {to save |link(backup_head)|}
8974 @!save_scanner_status:small_number; {temporary storage of |scanner_status|}
8975 begin cv_backup:=cur_val; cvl_backup:=cur_val_level; radix_backup:=radix;
8976 co_backup:=cur_order; backup_backup:=link(backup_head);
8977 reswitch:
8978 if cur_cmd<call then @<Expand a nonmacro@>
8979 else if cur_cmd<end_template then macro_call
8980 else @<Insert a token containing |frozen_endv|@>;
8981 cur_val:=cv_backup; cur_val_level:=cvl_backup; radix:=radix_backup;
8982 cur_order:=co_backup; link(backup_head):=backup_backup;
8983 end;
8984
8985 @ @<Glob...@>=
8986 @!is_in_csname: boolean;
8987
8988 @ @<Set init...@>=
8989 is_in_csname:=false;
8990
8991 @ @<Expand a nonmacro@>=
8992 begin if tracing_commands>1 then show_cur_cmd_chr;
8993 case cur_cmd of
8994 top_bot_mark:@<Insert the \(a)appropriate mark text into the scanner@>;
8995 expand_after:if cur_chr=0 then @<Expand the token after the next token@>
8996 else @<Negate a boolean conditional and |goto reswitch|@>;
8997 no_expand: if cur_chr=0 then @<Suppress expansion of the next token@>
8998 else @<Implement \.{\\primitive}@>;
8999 cs_name:@<Manufacture a control sequence name@>;
9000 convert:conv_toks; {this procedure is discussed in Part 27 below}
9001 the:ins_the_toks; {this procedure is discussed in Part 27 below}
9002 if_test:conditional; {this procedure is discussed in Part 28 below}
9003 fi_or_else:@<Terminate the current conditional and skip to \.{\\fi}@>;
9004 input:@<Initiate or terminate input from a file@>;
9005 othercases @<Complain about an undefined macro@>
9006 endcases;
9007 end
9008
9009 @ It takes only a little shuffling to do what \TeX\ calls \.{\\expandafter}.
9010
9011 @<Expand the token after...@>=
9012 begin get_token; t:=cur_tok; get_token;
9013 if cur_cmd>max_command then expand@+else back_input;
9014 cur_tok:=t; back_input;
9015 end
9016
9017 @ The implementation of \.{\\noexpand} is a bit trickier, because it is
9018 necessary to insert a special `|dont_expand|' marker into \TeX's reading
9019 mechanism. This special marker is processed by |get_next|, but it does
9020 not slow down the inner loop.
9021
9022 Since \.{\\outer} macros might arise here, we must also
9023 clear the |scanner_status| temporarily.
9024
9025 @<Suppress expansion...@>=
9026 begin save_scanner_status:=scanner_status; scanner_status:=normal;
9027 get_token; scanner_status:=save_scanner_status; t:=cur_tok;
9028 back_input; {now |start| and |loc| point to the backed-up token |t|}
9029 if t>=cs_token_flag then
9030 begin p:=get_avail; info(p):=cs_token_flag+frozen_dont_expand;
9031 link(p):=loc; start:=p; loc:=p;
9032 end;
9033 end
9034
9035 @ The \.{\\primitive} handling. If the primitive meaning of the next
9036 token is an expandable command, it suffices to replace the current
9037 token with the primitive one and restart |expand|/
9038
9039 Otherwise, the token we just read has to be pushed back, as well
9040 as a token matching the internal form of \.{\\primitive}, that is
9041 sneaked in as an alternate form of |ignore_spaces|.
9042 @!@:primitive_}{\.{\\primitive} primitive (internalized)@>
9043
9044 Simply pushing back a token that matches the correct internal command
9045 does not work, because approach would not survive roundtripping to a
9046 temporary file.
9047
9048 @<Implement \.{\\primitive}@>=
9049 begin save_scanner_status:=scanner_status; scanner_status:=normal;
9050 get_token; scanner_status:=save_scanner_status;
9051 if cur_cs < hash_base then
9052 cur_cs:=prim_lookup(cur_cs-single_base)
9053 else
9054 cur_cs:=prim_lookup(text(cur_cs));
9055 if cur_cs<>undefined_primitive then begin
9056 t:=prim_eq_type(cur_cs);
9057 if t>max_command then begin
9058 cur_cmd:=t;
9059 cur_chr:=prim_equiv(cur_cs);
9060 cur_tok:=(cur_cmd*max_char_val)+cur_chr;
9061 cur_cs :=0;
9062 goto reswitch;
9063 end
9064 else begin
9065 back_input; { now |loc| and |start| point to a one-item list }
9066 p:=get_avail; info(p):=cs_token_flag+frozen_primitive;
9067 link(p):=loc; loc:=p; start:=p;
9068 end;
9069 end;
9070 end
9071
9072 @ This block deals with unexpandable \.{\\primitive} appearing at a spot where
9073 an integer or an internal values should have been found. It fetches the
9074 next token then resets |cur_cmd|, |cur_cs|, and |cur_tok|, based on the
9075 primitive value of that token. No expansion takes place, because the
9076 next token may be all sorts of things. This could trigger further
9077 expansion creating new errors.
9078
9079 @<Reset |cur_tok| for unexpandable primitives, goto restart @>=
9080 begin
9081 get_token;
9082 if cur_cs < hash_base then
9083 cur_cs := prim_lookup(cur_cs-single_base)
9084 else
9085 cur_cs := prim_lookup(text(cur_cs));
9086 if cur_cs<>undefined_primitive then begin
9087 cur_cmd := prim_eq_type(cur_cs);
9088 cur_chr := prim_equiv(cur_cs);
9089 cur_cs := prim_eqtb_base+cur_cs;
9090 cur_tok := cs_token_flag+cur_cs;
9091 end
9092 else begin
9093 cur_cmd := relax;
9094 cur_chr := 0;
9095 cur_tok := cs_token_flag+frozen_relax;
9096 cur_cs := frozen_relax;
9097 end;
9098 goto restart;
9099 end
9100
9101 @ @<Complain about an undefined macro@>=
9102 begin print_err("Undefined control sequence");
9103 @.Undefined control sequence@>
9104 help5("The control sequence at the end of the top line")@/
9105 ("of your error message was never \def'ed. If you have")@/
9106 ("misspelled it (e.g., `\hobx'), type `I' and the correct")@/
9107 ("spelling (e.g., `I\hbox'). Otherwise just continue,")@/
9108 ("and I'll forget about whatever was undefined.");
9109 error;
9110 end
9111
9112 @ The |expand| procedure and some other routines that construct token
9113 lists find it convenient to use the following macros, which are valid only if
9114 the variables |p| and |q| are reserved for token-list building.
9115
9116 @d store_new_token(#)==begin q:=get_avail; link(p):=q; info(q):=#;
9117 p:=q; {|link(p)| is |null|}
9118 end
9119 @d fast_store_new_token(#)==begin fast_get_avail(q); link(p):=q; info(q):=#;
9120 p:=q; {|link(p)| is |null|}
9121 end
9122
9123 @ @<Manufacture a control...@>=
9124 begin r:=get_avail; p:=r; {head of the list of characters}
9125 b:=is_in_csname; is_in_csname:=true;
9126 repeat get_x_token;
9127 if cur_cs=0 then store_new_token(cur_tok);
9128 until cur_cs<>0;
9129 if cur_cmd<>end_cs_name then @<Complain about missing \.{\\endcsname}@>;
9130 is_in_csname:=b;
9131 @<Look up the characters of list |r| in the hash table, and set |cur_cs|@>;
9132 flush_list(r);
9133 if eq_type(cur_cs)=undefined_cs then
9134 begin eq_define(cur_cs,relax,too_big_usv);
9135 {N.B.: The |save_stack| might change}
9136 end; {the control sequence will now match `\.{\\relax}'}
9137 cur_tok:=cur_cs+cs_token_flag; back_input;
9138 end
9139
9140 @ @<Complain about missing \.{\\endcsname}@>=
9141 begin print_err("Missing "); print_esc("endcsname"); print(" inserted");
9142 @.Missing \\endcsname...@>
9143 help2("The control sequence marked <to be read again> should")@/
9144 ("not appear between \csname and \endcsname.");
9145 back_error;
9146 end
9147
9148 @ @<Look up the characters of list |r| in the hash table...@>=
9149 j:=first; p:=link(r);
9150 while p<>null do
9151 begin if j>=max_buf_stack then
9152 begin max_buf_stack:=j+1;
9153 if max_buf_stack=buf_size then
9154 overflow("buffer size",buf_size);
9155 @:TeX capacity exceeded buffer size}{\quad buffer size@>
9156 end;
9157 buffer[j]:=info(p) mod max_char_val; incr(j); p:=link(p);
9158 end;
9159 if (j>first+1) or (buffer[first]>@"FFFF) then
9160 begin no_new_control_sequence:=false; cur_cs:=id_lookup(first,j-first);
9161 no_new_control_sequence:=true;
9162 end
9163 else if j=first then cur_cs:=null_cs {the list is empty}
9164 else cur_cs:=single_base+buffer[first] {the list has length one}
9165
9166 @ An |end_template| command is effectively changed to an |endv| command
9167 by the following code. (The reason for this is discussed below; the
9168 |frozen_end_template| at the end of the template has passed the
9169 |check_outer_validity| test, so its mission of error detection has been
9170 accomplished.)
9171
9172 @<Insert a token containing |frozen_endv|@>=
9173 begin cur_tok:=cs_token_flag+frozen_endv; back_input;
9174 end
9175
9176 @ The processing of \.{\\input} involves the |start_input| subroutine,
9177 which will be declared later; the processing of \.{\\endinput} is trivial.
9178
9179 @<Put each...@>=
9180 primitive("input",input,0);@/
9181 @!@:input_}{\.{\\input} primitive@>
9182 primitive("endinput",input,1);@/
9183 @!@:end_input_}{\.{\\endinput} primitive@>
9184
9185 @ @<Cases of |print_cmd_chr|...@>=
9186 input: if chr_code=0 then print_esc("input")
9187 @/@<Cases of |input| for |print_cmd_chr|@>@/
9188 else print_esc("endinput");
9189
9190 @ @<Initiate or terminate input...@>=
9191 if cur_chr=1 then force_eof:=true
9192 @/@<Cases for |input|@>@/
9193 else if name_in_progress then insert_relax
9194 else start_input
9195
9196 @ Sometimes the expansion looks too far ahead, so we want to insert
9197 a harmless \.{\\relax} into the user's input.
9198
9199 @<Declare the procedure called |insert_relax|@>=
9200 procedure insert_relax;
9201 begin cur_tok:=cs_token_flag+cur_cs; back_input;
9202 cur_tok:=cs_token_flag+frozen_relax; back_input; token_type:=inserted;
9203 end;
9204
9205 @ Here is a recursive procedure that is \TeX's usual way to get the
9206 next token of input. It has been slightly optimized to take account of
9207 common cases.
9208
9209 @p procedure get_x_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|,
9210 and expands macros}
9211 label restart,done;
9212 begin restart: get_next;
9213 @^inner loop@>
9214 if cur_cmd<=max_command then goto done;
9215 if cur_cmd>=call then
9216 if cur_cmd<end_template then macro_call
9217 else begin cur_cs:=frozen_endv; cur_cmd:=endv;
9218 goto done; {|cur_chr=null_list|}
9219 end
9220 else expand;
9221 goto restart;
9222 done: if cur_cs=0 then cur_tok:=(cur_cmd*max_char_val)+cur_chr
9223 else cur_tok:=cs_token_flag+cur_cs;
9224 end;
9225
9226 @ The |get_x_token| procedure is essentially equivalent to two consecutive
9227 procedure calls: |get_next; x_token|.
9228
9229 @p procedure x_token; {|get_x_token| without the initial |get_next|}
9230 begin while cur_cmd>max_command do
9231 begin expand;
9232 get_next;
9233 end;
9234 if cur_cs=0 then cur_tok:=(cur_cmd*max_char_val)+cur_chr
9235 else cur_tok:=cs_token_flag+cur_cs;
9236 end;
9237
9238 @ A control sequence that has been \.{\\def}'ed by the user is expanded by
9239 \TeX's |macro_call| procedure.
9240
9241 Before we get into the details of |macro_call|, however, let's consider the
9242 treatment of primitives like \.{\\topmark}, since they are essentially
9243 macros without parameters. The token lists for such marks are kept in a
9244 global array of five pointers; we refer to the individual entries of this
9245 array by symbolic names |top_mark|, etc. The value of |top_mark| is either
9246 |null| or a pointer to the reference count of a token list.
9247
9248 @d marks_code==5 {add this for \.{\\topmarks} etc.}
9249 @#
9250 @d top_mark_code=0 {the mark in effect at the previous page break}
9251 @d first_mark_code=1 {the first mark between |top_mark| and |bot_mark|}
9252 @d bot_mark_code=2 {the mark in effect at the current page break}
9253 @d split_first_mark_code=3 {the first mark found by \.{\\vsplit}}
9254 @d split_bot_mark_code=4 {the last mark found by \.{\\vsplit}}
9255 @d top_mark==cur_mark[top_mark_code]
9256 @d first_mark==cur_mark[first_mark_code]
9257 @d bot_mark==cur_mark[bot_mark_code]
9258 @d split_first_mark==cur_mark[split_first_mark_code]
9259 @d split_bot_mark==cur_mark[split_bot_mark_code]
9260
9261 @<Glob...@>=
9262 @!cur_mark:array[top_mark_code..split_bot_mark_code] of pointer;
9263 {token lists for marks}
9264
9265 @ @<Set init...@>=
9266 top_mark:=null; first_mark:=null; bot_mark:=null;
9267 split_first_mark:=null; split_bot_mark:=null;
9268
9269 @ @<Put each...@>=
9270 primitive("topmark",top_bot_mark,top_mark_code);
9271 @!@:top_mark_}{\.{\\topmark} primitive@>
9272 primitive("firstmark",top_bot_mark,first_mark_code);
9273 @!@:first_mark_}{\.{\\firstmark} primitive@>
9274 primitive("botmark",top_bot_mark,bot_mark_code);
9275 @!@:bot_mark_}{\.{\\botmark} primitive@>
9276 primitive("splitfirstmark",top_bot_mark,split_first_mark_code);
9277 @!@:split_first_mark_}{\.{\\splitfirstmark} primitive@>
9278 primitive("splitbotmark",top_bot_mark,split_bot_mark_code);
9279 @!@:split_bot_mark_}{\.{\\splitbotmark} primitive@>
9280
9281 @ @<Cases of |print_cmd_chr|...@>=
9282 top_bot_mark: begin case (chr_code mod marks_code) of
9283 first_mark_code: print_esc("firstmark");
9284 bot_mark_code: print_esc("botmark");
9285 split_first_mark_code: print_esc("splitfirstmark");
9286 split_bot_mark_code: print_esc("splitbotmark");
9287 othercases print_esc("topmark")
9288 endcases;
9289 if chr_code>=marks_code then print_char("s");
9290 end;
9291
9292 @ The following code is activated when |cur_cmd=top_bot_mark| and
9293 when |cur_chr| is a code like |top_mark_code|.
9294
9295 @<Insert the \(a)appropriate mark text into the scanner@>=
9296 begin t:=cur_chr mod marks_code;
9297 if cur_chr>=marks_code then scan_register_num@+else cur_val:=0;
9298 if cur_val=0 then cur_ptr:=cur_mark[t]
9299 else @<Compute the mark pointer for mark type |t| and class |cur_val|@>;
9300 if cur_ptr<>null then begin_token_list(cur_ptr,mark_text);
9301 end
9302
9303 @ Now let's consider |macro_call| itself, which is invoked when \TeX\ is
9304 scanning a control sequence whose |cur_cmd| is either |call|, |long_call|,
9305 |outer_call|, or |long_outer_call|. The control sequence definition
9306 appears in the token list whose reference count is in location |cur_chr|
9307 of |mem|.
9308
9309 The global variable |long_state| will be set to |call| or to |long_call|,
9310 depending on whether or not the control sequence disallows \.{\\par}
9311 in its parameters. The |get_next| routine will set |long_state| to
9312 |outer_call| and emit \.{\\par}, if a file ends or if an \.{\\outer}
9313 control sequence occurs in the midst of an argument.
9314
9315 @<Glob...@>=
9316 @!long_state:call..long_outer_call; {governs the acceptance of \.{\\par}}
9317
9318 @ The parameters, if any, must be scanned before the macro is expanded.
9319 Parameters are token lists without reference counts. They are placed on
9320 an auxiliary stack called |pstack| while they are being scanned, since
9321 the |param_stack| may be losing entries during the matching process.
9322 (Note that |param_stack| can't be gaining entries, since |macro_call| is
9323 the only routine that puts anything onto |param_stack|, and it
9324 is not recursive.)
9325
9326 @<Glob...@>=
9327 @!pstack:array[0..8] of pointer; {arguments supplied to a macro}
9328
9329 @ After parameter scanning is complete, the parameters are moved to the
9330 |param_stack|. Then the macro body is fed to the scanner; in other words,
9331 |macro_call| places the defined text of the control sequence at the
9332 top of\/ \TeX's input stack, so that |get_next| will proceed to read it
9333 next.
9334
9335 The global variable |cur_cs| contains the |eqtb| address of the control sequence
9336 being expanded, when |macro_call| begins. If this control sequence has not been
9337 declared \.{\\long}, i.e., if its command code in the |eq_type| field is
9338 not |long_call| or |long_outer_call|, its parameters are not allowed to contain
9339 the control sequence \.{\\par}. If an illegal \.{\\par} appears, the macro
9340 call is aborted, and the \.{\\par} will be rescanned.
9341
9342 @<Declare the procedure called |macro_call|@>=
9343 procedure macro_call; {invokes a user-defined control sequence}
9344 label exit, continue, done, done1, found;
9345 var r:pointer; {current node in the macro's token list}
9346 @!p:pointer; {current node in parameter token list being built}
9347 @!q:pointer; {new node being put into the token list}
9348 @!s:pointer; {backup pointer for parameter matching}
9349 @!t:pointer; {cycle pointer for backup recovery}
9350 @!u,@!v:pointer; {auxiliary pointers for backup recovery}
9351 @!rbrace_ptr:pointer; {one step before the last |right_brace| token}
9352 @!n:small_number; {the number of parameters scanned}
9353 @!unbalance:halfword; {unmatched left braces in current parameter}
9354 @!m:halfword; {the number of tokens or groups (usually)}
9355 @!ref_count:pointer; {start of the token list}
9356 @!save_scanner_status:small_number; {|scanner_status| upon entry}
9357 @!save_warning_index:pointer; {|warning_index| upon entry}
9358 @!match_chr:ASCII_code; {character used in parameter}
9359 begin save_scanner_status:=scanner_status; save_warning_index:=warning_index;
9360 warning_index:=cur_cs; ref_count:=cur_chr; r:=link(ref_count); n:=0;
9361 if tracing_macros>0 then @<Show the text of the macro being expanded@>;
9362 if info(r)=protected_token then r:=link(r);
9363 if info(r)<>end_match_token then
9364 @<Scan the parameters and make |link(r)| point to the macro body; but
9365 |return| if an illegal \.{\\par} is detected@>;
9366 @<Feed the macro body and its parameters to the scanner@>;
9367 exit:scanner_status:=save_scanner_status; warning_index:=save_warning_index;
9368 end;
9369
9370 @ Before we put a new token list on the input stack, it is wise to clean off
9371 all token lists that have recently been depleted. Then a user macro that ends
9372 with a call to itself will not require unbounded stack space.
9373
9374 @<Feed the macro body and its parameters to the scanner@>=
9375 while (state=token_list)and(loc=null)and(token_type<>v_template) do
9376 end_token_list; {conserve stack space}
9377 begin_token_list(ref_count,macro); name:=warning_index; loc:=link(r);
9378 if n>0 then
9379 begin if param_ptr+n>max_param_stack then
9380 begin max_param_stack:=param_ptr+n;
9381 if max_param_stack>param_size then
9382 overflow("parameter stack size",param_size);
9383 @:TeX capacity exceeded parameter stack size}{\quad parameter stack size@>
9384 end;
9385 for m:=0 to n-1 do param_stack[param_ptr+m]:=pstack[m];
9386 param_ptr:=param_ptr+n;
9387 end
9388
9389 @ At this point, the reader will find it advisable to review the explanation
9390 of token list format that was presented earlier, since many aspects of that
9391 format are of importance chiefly in the |macro_call| routine.
9392
9393 The token list might begin with a string of compulsory tokens before the
9394 first |match| or |end_match|. In that case the macro name is supposed to be
9395 followed by those tokens; the following program will set |s=null| to
9396 represent this restriction. Otherwise |s| will be set to the first token of
9397 a string that will delimit the next parameter.
9398
9399 @<Scan the parameters and make |link(r)| point to the macro body...@>=
9400 begin scanner_status:=matching; unbalance:=0;
9401 long_state:=eq_type(cur_cs);
9402 if long_state>=outer_call then long_state:=long_state-2;
9403 repeat link(temp_head):=null;
9404 if (info(r)>=end_match_token)or(info(r)<match_token) then s:=null
9405 else begin match_chr:=info(r)-match_token; s:=link(r); r:=s;
9406 p:=temp_head; m:=0;
9407 end;
9408 @<Scan a parameter until its delimiter string has been found; or, if |s=null|,
9409 simply scan the delimiter string@>;@/
9410 {now |info(r)| is a token whose command code is either |match| or |end_match|}
9411 until info(r)=end_match_token;
9412 end
9413
9414 @ If |info(r)| is a |match| or |end_match| command, it cannot be equal to
9415 any token found by |get_token|. Therefore an undelimited parameter---i.e.,
9416 a |match| that is immediately followed by |match| or |end_match|---will
9417 always fail the test `|cur_tok=info(r)|' in the following algorithm.
9418
9419 @<Scan a parameter until its delimiter string has been found; or, ...@>=
9420 continue: get_token; {set |cur_tok| to the next token of input}
9421 if cur_tok=info(r) then
9422 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been
9423 fully matched, otherwise |goto continue|@>;
9424 @<Contribute the recently matched tokens to the current parameter, and
9425 |goto continue| if a partial match is still in effect;
9426 but abort if |s=null|@>;
9427 if cur_tok=par_token then if long_state<>long_call then
9428 @<Report a runaway argument and abort@>;
9429 if cur_tok<right_brace_limit then
9430 if cur_tok<left_brace_limit then
9431 @<Contribute an entire group to the current parameter@>
9432 else @<Report an extra right brace and |goto continue|@>
9433 else @<Store the current token, but |goto continue| if it is
9434 a blank space that would become an undelimited parameter@>;
9435 incr(m);
9436 if info(r)>end_match_token then goto continue;
9437 if info(r)<match_token then goto continue;
9438 found: if s<>null then @<Tidy up the parameter just scanned, and tuck it away@>
9439
9440 @ @<Store the current token, but |goto continue| if it is...@>=
9441 begin if cur_tok=space_token then
9442 if info(r)<=end_match_token then
9443 if info(r)>=match_token then goto continue;
9444 store_new_token(cur_tok);
9445 end
9446
9447 @ A slightly subtle point arises here: When the parameter delimiter ends
9448 with `\.{\#\{}', the token list will have a left brace both before and
9449 after the |end_match|\kern-.4pt. Only one of these should affect the
9450 |align_state|, but both will be scanned, so we must make a correction.
9451
9452 @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully...@>=
9453 begin r:=link(r);
9454 if (info(r)>=match_token)and(info(r)<=end_match_token) then
9455 begin if cur_tok<left_brace_limit then decr(align_state);
9456 goto found;
9457 end
9458 else goto continue;
9459 end
9460
9461 @ @<Report an extra right brace and |goto continue|@>=
9462 begin back_input; print_err("Argument of "); sprint_cs(warning_index);
9463 @.Argument of \\x has...@>
9464 print(" has an extra }");
9465 help6("I've run across a `}' that doesn't seem to match anything.")@/
9466 ("For example, `\def\a#1{...}' and `\a}' would produce")@/
9467 ("this error. If you simply proceed now, the `\par' that")@/
9468 ("I've just inserted will cause me to report a runaway")@/
9469 ("argument that might be the root of the problem. But if")@/
9470 ("your `}' was spurious, just type `2' and it will go away.");
9471 incr(align_state); long_state:=call; cur_tok:=par_token; ins_error;
9472 goto continue;
9473 end {a white lie; the \.{\\par} won't always trigger a runaway}
9474
9475 @ If |long_state=outer_call|, a runaway argument has already been reported.
9476
9477 @<Report a runaway argument and abort@>=
9478 begin if long_state=call then
9479 begin runaway; print_err("Paragraph ended before ");
9480 @.Paragraph ended before...@>
9481 sprint_cs(warning_index); print(" was complete");
9482 help3("I suspect you've forgotten a `}', causing me to apply this")@/
9483 ("control sequence to too much text. How can we recover?")@/
9484 ("My plan is to forget the whole thing and hope for the best.");
9485 back_error;
9486 end;
9487 pstack[n]:=link(temp_head); align_state:=align_state-unbalance;
9488 for m:=0 to n do flush_list(pstack[m]);
9489 return;
9490 end
9491
9492 @ When the following code becomes active, we have matched tokens from |s| to
9493 the predecessor of |r|, and we have found that |cur_tok<>info(r)|. An
9494 interesting situation now presents itself: If the parameter is to be
9495 delimited by a string such as `\.{ab}', and if we have scanned `\.{aa}',
9496 we want to contribute one `\.a' to the current parameter and resume
9497 looking for a `\.b'. The program must account for such partial matches and
9498 for others that can be quite complex. But most of the time we have |s=r|
9499 and nothing needs to be done.
9500
9501 Incidentally, it is possible for \.{\\par} tokens to sneak in to certain
9502 parameters of non-\.{\\long} macros. For example, consider a case like
9503 `\.{\\def\\a\#1\\par!\{...\}}' where the first \.{\\par} is not followed
9504 by an exclamation point. In such situations it does not seem appropriate
9505 to prohibit the \.{\\par}, so \TeX\ keeps quiet about this bending of
9506 the rules.
9507
9508 @<Contribute the recently matched tokens to the current parameter...@>=
9509 if s<>r then
9510 if s=null then @<Report an improper use of the macro and abort@>
9511 else begin t:=s;
9512 repeat store_new_token(info(t)); incr(m); u:=link(t); v:=s;
9513 loop@+ begin if u=r then
9514 if cur_tok<>info(v) then goto done
9515 else begin r:=link(v); goto continue;
9516 end;
9517 if info(u)<>info(v) then goto done;
9518 u:=link(u); v:=link(v);
9519 end;
9520 done: t:=link(t);
9521 until t=r;
9522 r:=s; {at this point, no tokens are recently matched}
9523 end
9524
9525 @ @<Report an improper use...@>=
9526 begin print_err("Use of "); sprint_cs(warning_index);
9527 @.Use of x doesn't match...@>
9528 print(" doesn't match its definition");
9529 help4("If you say, e.g., `\def\a1{...}', then you must always")@/
9530 ("put `1' after `\a', since control sequence names are")@/
9531 ("made up of letters only. The macro here has not been")@/
9532 ("followed by the required stuff, so I'm ignoring it.");
9533 error; return;
9534 end
9535
9536 @ @<Contribute an entire group to the current parameter@>=
9537 begin unbalance:=1;
9538 @^inner loop@>
9539 loop@+ begin fast_store_new_token(cur_tok); get_token;
9540 if cur_tok=par_token then if long_state<>long_call then
9541 @<Report a runaway argument and abort@>;
9542 if cur_tok<right_brace_limit then
9543 if cur_tok<left_brace_limit then incr(unbalance)
9544 else begin decr(unbalance);
9545 if unbalance=0 then goto done1;
9546 end;
9547 end;
9548 done1: rbrace_ptr:=p; store_new_token(cur_tok);
9549 end
9550
9551 @ If the parameter consists of a single group enclosed in braces, we must
9552 strip off the enclosing braces. That's why |rbrace_ptr| was introduced.
9553
9554 @<Tidy up the parameter just scanned, and tuck it away@>=
9555 begin if (m=1)and(info(p)<right_brace_limit) then
9556 begin link(rbrace_ptr):=null; free_avail(p);
9557 p:=link(temp_head); pstack[n]:=link(p); free_avail(p);
9558 end
9559 else pstack[n]:=link(temp_head);
9560 incr(n);
9561 if tracing_macros>0 then
9562 begin begin_diagnostic; print_nl(match_chr); print_int(n);
9563 print("<-"); show_token_list(pstack[n-1],null,1000);
9564 end_diagnostic(false);
9565 end;
9566 end
9567
9568 @ @<Show the text of the macro being expanded@>=
9569 begin begin_diagnostic; print_ln; print_cs(warning_index);
9570 token_show(ref_count); end_diagnostic(false);
9571 end
9572
9573 @* \[26] Basic scanning subroutines.
9574 Let's turn now to some procedures that \TeX\ calls upon frequently to digest
9575 certain kinds of patterns in the input. Most of these are quite simple;
9576 some are quite elaborate. Almost all of the routines call |get_x_token|,
9577 which can cause them to be invoked recursively.
9578 @^stomach@>
9579 @^recursion@>
9580
9581 @ The |scan_left_brace| routine is called when a left brace is supposed to be
9582 the next non-blank token. (The term ``left brace'' means, more precisely,
9583 a character whose catcode is |left_brace|.) \TeX\ allows \.{\\relax} to
9584 appear before the |left_brace|.
9585
9586 @p procedure scan_left_brace; {reads a mandatory |left_brace|}
9587 begin @<Get the next non-blank non-relax non-call token@>;
9588 if cur_cmd<>left_brace then
9589 begin print_err("Missing { inserted");
9590 @.Missing \{ inserted@>
9591 help4("A left brace was mandatory here, so I've put one in.")@/
9592 ("You might want to delete and/or insert some corrections")@/
9593 ("so that I will find a matching right brace soon.")@/
9594 ("(If you're confused by all this, try typing `I}' now.)");
9595 back_error; cur_tok:=left_brace_token+"{"; cur_cmd:=left_brace;
9596 cur_chr:="{"; incr(align_state);
9597 end;
9598 end;
9599
9600 @ @<Get the next non-blank non-relax non-call token@>=
9601 repeat get_x_token;
9602 until (cur_cmd<>spacer)and(cur_cmd<>relax)
9603
9604 @ The |scan_optional_equals| routine looks for an optional `\.=' sign preceded
9605 by optional spaces; `\.{\\relax}' is not ignored here.
9606
9607 @p procedure scan_optional_equals;
9608 begin @<Get the next non-blank non-call token@>;
9609 if cur_tok<>other_token+"=" then back_input;
9610 end;
9611
9612 @ @<Get the next non-blank non-call token@>=
9613 repeat get_x_token;
9614 until cur_cmd<>spacer
9615
9616 @ In case you are getting bored, here is a slightly less trivial routine:
9617 Given a string of lowercase letters, like `\.{pt}' or `\.{plus}' or
9618 `\.{width}', the |scan_keyword| routine checks to see whether the next
9619 tokens of input match this string. The match must be exact, except that
9620 uppercase letters will match their lowercase counterparts; uppercase
9621 equivalents are determined by subtracting |"a"-"A"|, rather than using the
9622 |uc_code| table, since \TeX\ uses this routine only for its own limited
9623 set of keywords.
9624
9625 If a match is found, the characters are effectively removed from the input
9626 and |true| is returned. Otherwise |false| is returned, and the input
9627 is left essentially unchanged (except for the fact that some macros
9628 may have been expanded, etc.).
9629 @^inner loop@>
9630
9631 @p function scan_keyword(@!s:str_number):boolean; {look for a given string}
9632 label exit;
9633 var p:pointer; {tail of the backup list}
9634 @!q:pointer; {new node being added to the token list via |store_new_token|}
9635 @!k:pool_pointer; {index into |str_pool|}
9636 @!save_cur_cs:pointer; {to save |cur_cs|}
9637 begin p:=backup_head; link(p):=null;
9638 if s<too_big_char then begin
9639 while true do
9640 begin get_x_token; {recursion is possible here}
9641 @^recursion@>
9642 if (cur_cs=0)and@|
9643 ((cur_chr=s)or(cur_chr=s-"a"+"A")) then
9644 begin store_new_token(cur_tok);
9645 flush_list(link(backup_head)); scan_keyword:=true; return;
9646 end
9647 else if (cur_cmd<>spacer)or(p<>backup_head) then
9648 begin back_input;
9649 if p<>backup_head then back_list(link(backup_head));
9650 scan_keyword:=false; return;
9651 end;
9652 end;
9653 end;
9654 k:=str_start_macro(s);
9655 save_cur_cs:=cur_cs;
9656 while k<str_start_macro(s+1) do
9657 begin get_x_token; {recursion is possible here}
9658 @^recursion@>
9659 if (cur_cs=0)and@|
9660 ((cur_chr=so(str_pool[k]))or(cur_chr=so(str_pool[k])-"a"+"A")) then
9661 begin store_new_token(cur_tok); incr(k);
9662 end
9663 else if (cur_cmd<>spacer)or(p<>backup_head) then
9664 begin back_input;
9665 if p<>backup_head then back_list(link(backup_head));
9666 cur_cs:=save_cur_cs;
9667 scan_keyword:=false; return;
9668 end;
9669 end;
9670 flush_list(link(backup_head)); scan_keyword:=true;
9671 exit:end;
9672
9673 @ Here is a procedure that sounds an alarm when mu and non-mu units
9674 are being switched.
9675
9676 @p procedure mu_error;
9677 begin print_err("Incompatible glue units");
9678 @.Incompatible glue units@>
9679 help1("I'm going to assume that 1mu=1pt when they're mixed.");
9680 error;
9681 end;
9682
9683 @ The next routine `|scan_something_internal|' is used to fetch internal
9684 numeric quantities like `\.{\\hsize}', and also to handle the `\.{\\the}'
9685 when expanding constructions like `\.{\\the\\toks0}' and
9686 `\.{\\the\\baselineskip}'. Soon we will be considering the |scan_int|
9687 procedure, which calls |scan_something_internal|; on the other hand,
9688 |scan_something_internal| also calls |scan_int|, for constructions like
9689 `\.{\\catcode\`\\\$}' or `\.{\\fontdimen} \.3 \.{\\ff}'. So we
9690 have to declare |scan_int| as a |forward| procedure. A few other
9691 procedures are also declared at this point.
9692
9693 @p procedure@?scan_int; forward; {scans an integer value}
9694 @t\4\4@>@<Declare procedures that scan restricted classes of integers@>@;
9695 @t\4\4@>@<Declare \eTeX\ procedures for scanning@>@;
9696 @t\4\4@>@<Declare procedures that scan font-related stuff@>
9697
9698 @ \TeX\ doesn't know exactly what to expect when |scan_something_internal|
9699 begins. For example, an integer or dimension or glue value could occur
9700 immediately after `\.{\\hskip}'; and one can even say \.{\\the} with
9701 respect to token lists in constructions like
9702 `\.{\\xdef\\o\{\\the\\output\}}'. On the other hand, only integers are
9703 allowed after a construction like `\.{\\count}'. To handle the various
9704 possibilities, |scan_something_internal| has a |level| parameter, which
9705 tells the ``highest'' kind of quantity that |scan_something_internal| is
9706 allowed to produce. Six levels are distinguished, namely |int_val|,
9707 |dimen_val|, |glue_val|, |mu_val|, |ident_val|, and |tok_val|.
9708
9709 The output of |scan_something_internal| (and of the other routines
9710 |scan_int|, |scan_dimen|, and |scan_glue| below) is put into the global
9711 variable |cur_val|, and its level is put into |cur_val_level|. The highest
9712 values of |cur_val_level| are special: |mu_val| is used only when
9713 |cur_val| points to something in a ``muskip'' register, or to one of the
9714 three parameters \.{\\thinmuskip}, \.{\\medmuskip}, \.{\\thickmuskip};
9715 |ident_val| is used only when |cur_val| points to a font identifier;
9716 |tok_val| is used only when |cur_val| points to |null| or to the reference
9717 count of a token list. The last two cases are allowed only when
9718 |scan_something_internal| is called with |level=tok_val|.
9719
9720 If the output is glue, |cur_val| will point to a glue specification, and
9721 the reference count of that glue will have been updated to reflect this
9722 reference; if the output is a nonempty token list, |cur_val| will point to
9723 its reference count, but in this case the count will not have been updated.
9724 Otherwise |cur_val| will contain the integer or scaled value in question.
9725
9726 @d int_val=0 {integer values}
9727 @d dimen_val=1 {dimension values}
9728 @d glue_val=2 {glue specifications}
9729 @d mu_val=3 {math glue specifications}
9730 @d ident_val=4 {font identifier}
9731 @d tok_val=5 {token lists}
9732 @d inter_char_val=6 {inter-character (class) token lists}
9733
9734 @<Glob...@>=
9735 @!cur_val:integer; {value returned by numeric scanners}
9736 @!cur_val1:integer; {value returned by numeric scanners}
9737 @!cur_val_level:int_val..tok_val; {the ``level'' of this value}
9738
9739 @ The hash table is initialized with `\.{\\count}', `\.{\\dimen}', `\.{\\skip}',
9740 and `\.{\\muskip}' all having |register| as their command code; they are
9741 distinguished by the |chr_code|, which is either |int_val|, |dimen_val|,
9742 |glue_val|, or |mu_val| more than |mem_bot| (dynamic variable-size nodes
9743 cannot have these values)
9744
9745 @<Put each...@>=
9746 primitive("count",register,mem_bot+int_val);
9747 @!@:count_}{\.{\\count} primitive@>
9748 primitive("dimen",register,mem_bot+dimen_val);
9749 @!@:dimen_}{\.{\\dimen} primitive@>
9750 primitive("skip",register,mem_bot+glue_val);
9751 @!@:skip_}{\.{\\skip} primitive@>
9752 primitive("muskip",register,mem_bot+mu_val);
9753 @!@:mu_skip_}{\.{\\muskip} primitive@>
9754
9755 @ @<Cases of |print_cmd_chr|...@>=
9756 register: @<Cases of |register| for |print_cmd_chr|@>;
9757
9758 @ OK, we're ready for |scan_something_internal| itself. A second parameter,
9759 |negative|, is set |true| if the value that is found should be negated.
9760 It is assumed that |cur_cmd| and |cur_chr| represent the first token of
9761 the internal quantity to be scanned; an error will be signalled if
9762 |cur_cmd<min_internal| or |cur_cmd>max_internal|.
9763
9764 @d scanned_result_end(#)==cur_val_level:=#;@+end
9765 @d scanned_result(#)==@+begin cur_val:=#;scanned_result_end
9766
9767 @d char_class_limit = @"1000
9768 @d char_class_ignored == char_class_limit
9769 @d char_class_boundary == (char_class_ignored - 1)
9770
9771 @p procedure scan_something_internal(@!level:small_number;@!negative:boolean);
9772 {fetch an internal parameter}
9773 label exit, restart;
9774 var m:halfword; {|chr_code| part of the operand token}
9775 n, k, kk: integer; {accumulators}
9776 @!q,@!r:pointer; {general purpose indices}
9777 @!tx:pointer; {effective tail node}
9778 @!i:four_quarters; {character info}
9779 @!p:0..nest_size; {index into |nest|}
9780 begin restart: m:=cur_chr;
9781 case cur_cmd of
9782 def_code: @<Fetch a character code from some table@>;
9783 XeTeX_def_code:
9784 begin
9785 scan_usv_num;
9786 if m=sf_code_base then begin
9787 scanned_result(ho(sf_code(cur_val) div @"10000))(int_val)
9788 end
9789 else if m=math_code_base then begin
9790 scanned_result(ho(math_code(cur_val)))(int_val)
9791 end
9792 else if m=math_code_base+1 then begin
9793 print_err("Can't use \Umathcode as a number (try \Umathcodenum)");
9794 help2("\Umathcode is for setting a mathcode from separate values;")@/
9795 ("use \Umathcodenum to access them as single values."); error;
9796 scanned_result(0)(int_val)
9797 end
9798 else if m=del_code_base then begin
9799 scanned_result(ho(del_code(cur_val)))(int_val)
9800 end else begin
9801 print_err("Can't use \Udelcode as a number (try \Udelcodenum)");
9802 help2("\Udelcode is for setting a delcode from separate values;")@/
9803 ("use \Udelcodenum to access them as single values."); error;
9804 scanned_result(0)(int_val);
9805 end;
9806 end;
9807 toks_register,assign_toks,def_family,set_font,def_font: @<Fetch a token list or
9808 font identifier, provided that |level=tok_val|@>;
9809 assign_int: scanned_result(eqtb[m].int)(int_val);
9810 assign_dimen: scanned_result(eqtb[m].sc)(dimen_val);
9811 assign_glue: scanned_result(equiv(m))(glue_val);
9812 assign_mu_glue: scanned_result(equiv(m))(mu_val);
9813 set_aux: @<Fetch the |space_factor| or the |prev_depth|@>;
9814 set_prev_graf: @<Fetch the |prev_graf|@>;
9815 set_page_int:@<Fetch the |dead_cycles| or the |insert_penalties|@>;
9816 set_page_dimen: @<Fetch something on the |page_so_far|@>;
9817 set_shape: @<Fetch the |par_shape| size@>;
9818 set_box_dimen: @<Fetch a box dimension@>;
9819 char_given,math_given,XeTeX_math_given: scanned_result(cur_chr)(int_val);
9820 assign_font_dimen: @<Fetch a font dimension@>;
9821 assign_font_int: @<Fetch a font integer@>;
9822 register: @<Fetch a register@>;
9823 last_item: @<Fetch an item in the current node, if appropriate@>;
9824 ignore_spaces: {trap unexpandable primitives}
9825 if cur_chr=1 then @<Reset |cur_tok| for unexpandable primitives, goto restart@>;
9826 othercases @<Complain that \.{\\the} can't do this; give zero result@>
9827 endcases;@/
9828 while cur_val_level>level do @<Convert \(c)|cur_val| to a lower level@>;
9829 @<Fix the reference count, if any, and negate |cur_val| if |negative|@>;
9830 exit:end;
9831
9832 @ @<Fetch a character code from some table@>=
9833 begin scan_usv_num;
9834 if m=math_code_base then begin
9835 cur_val1:=ho(math_code(cur_val));
9836 if is_active_math_char(cur_val1) then
9837 cur_val1:=@"8000
9838 else if (math_class_field(cur_val1)>7) or
9839 (math_fam_field(cur_val1)>15) or
9840 (math_char_field(cur_val1)>255) then
9841 begin print_err("Extended mathchar used as mathchar");
9842 @.Bad mathchar@>
9843 help2("A mathchar number must be between 0 and ""7FFF.")@/
9844 ("I changed this one to zero."); int_error(cur_val1); cur_val1:=0;
9845 end;
9846 cur_val1:=(math_class_field(cur_val1)*@"1000) +
9847 (math_fam_field(cur_val1)*@"100) +
9848 math_char_field(cur_val1);
9849 scanned_result(cur_val1)(int_val)
9850 end
9851 else if m=del_code_base then begin
9852 cur_val1:=del_code(cur_val);
9853 if cur_val1>=@"40000000 then begin
9854 print_err("Extended delcode used as delcode");
9855 @.Bad delcode@>
9856 help2("A delimiter code must be between 0 and ""7FFFFFF.")@/
9857 ("I changed this one to zero."); error;
9858 scanned_result(0)(int_val);
9859 end else begin
9860 scanned_result(cur_val1)(int_val);
9861 end
9862 end
9863 else if m<sf_code_base then scanned_result(equiv(m+cur_val))(int_val)
9864 else if m<math_code_base then scanned_result(equiv(m+cur_val) mod @"10000)(int_val)
9865 else scanned_result(eqtb[m+cur_val].int)(int_val);
9866 end
9867
9868 @ @<Fetch a token list...@>=
9869 if level<>tok_val then
9870 begin print_err("Missing number, treated as zero");
9871 @.Missing number...@>
9872 help3("A number should have been here; I inserted `0'.")@/
9873 ("(If you can't figure out why I needed to see a number,")@/
9874 ("look up `weird error' in the index to The TeXbook.)");
9875 @:TeXbook}{\sl The \TeX book@>
9876 back_error; scanned_result(0)(dimen_val);
9877 end
9878 else if cur_cmd<=assign_toks then
9879 begin if cur_cmd<assign_toks then {|cur_cmd=toks_register|}
9880 if m=mem_bot then
9881 begin scan_register_num;
9882 if cur_val<256 then cur_val:=equiv(toks_base+cur_val)
9883 else begin find_sa_element(tok_val,cur_val,false);
9884 if cur_ptr=null then cur_val:=null
9885 else cur_val:=sa_ptr(cur_ptr);
9886 end;
9887 end
9888 else cur_val:=sa_ptr(m)
9889 else if cur_chr=XeTeX_inter_char_loc then begin
9890 scan_char_class_not_ignored; cur_ptr:=cur_val;
9891 scan_char_class_not_ignored;
9892 find_sa_element(inter_char_val, cur_ptr*char_class_limit + cur_val, false);
9893 if cur_ptr=null then cur_val:=null
9894 else cur_val:=sa_ptr(cur_ptr);
9895 end else cur_val:=equiv(m);
9896 cur_val_level:=tok_val;
9897 end
9898 else begin back_input; scan_font_ident;
9899 scanned_result(font_id_base+cur_val)(ident_val);
9900 end
9901
9902 @ Users refer to `\.{\\the\\spacefactor}' only in horizontal
9903 mode, and to `\.{\\the\\prevdepth}' only in vertical mode; so we put the
9904 associated mode in the modifier part of the |set_aux| command.
9905 The |set_page_int| command has modifier 0 or 1, for `\.{\\deadcycles}' and
9906 `\.{\\insertpenalties}', respectively. The |set_box_dimen| command is
9907 modified by either |width_offset|, |height_offset|, or |depth_offset|.
9908 And the |last_item| command is modified by either |int_val|, |dimen_val|,
9909 |glue_val|, |input_line_no_code|, or |badness_code|.
9910 \eTeX\ inserts |last_node_type_code| after |glue_val| and adds
9911 the codes for its extensions: |eTeX_version_code|, \dots\ .
9912
9913 @d last_node_type_code=glue_val+1 {code for \.{\\lastnodetype}}
9914 @d input_line_no_code=glue_val+2 {code for \.{\\inputlineno}}
9915 @d badness_code=input_line_no_code+1 {code for \.{\\badness}}
9916 @#
9917 @d pdftex_first_rint_code = badness_code + 1 {base for \pdfTeX's command codes}
9918 @d pdf_last_x_pos_code = pdftex_first_rint_code + 6 {code for \.{\\pdflastxpos}}
9919 @d pdf_last_y_pos_code = pdftex_first_rint_code + 7 {code for \.{\\pdflastypos}}
9920 @d elapsed_time_code = pdftex_first_rint_code + 10 {code for \.{\\elapsedtime}}
9921 @d pdf_shell_escape_code = pdftex_first_rint_code + 11 {code for \.{\\shellescape}}
9922 @d random_seed_code = pdftex_first_rint_code + 12 {code for \.{\\randomseed}}
9923 @d pdftex_last_item_codes = pdftex_first_rint_code + 12 {end of \pdfTeX's command codes}
9924 @#
9925 @d eTeX_int=pdftex_last_item_codes + 1 {first of \eTeX\ codes for integers}
9926 @#
9927 @d XeTeX_int = eTeX_int + 8 {base for \XeTeX's command codes}
9928 @d XeTeX_version_code = XeTeX_int + 0 {code for \.{\\XeTeXversion}}
9929 @d XeTeX_count_glyphs_code = XeTeX_int + 1 {code for \.{\\XeTeXcountglyphs}}
9930 @d XeTeX_count_variations_code = XeTeX_int + 2 {Deprecated}
9931 @d XeTeX_variation_code = XeTeX_int + 3 {Deprecated}
9932 @d XeTeX_find_variation_by_name_code = XeTeX_int + 4 {Deprecated}
9933 @d XeTeX_variation_min_code = XeTeX_int + 5 {Deprecated}
9934 @d XeTeX_variation_max_code = XeTeX_int + 6 {Deprecated}
9935 @d XeTeX_variation_default_code = XeTeX_int + 7 {Deprecated}
9936 @d XeTeX_count_features_code = XeTeX_int + 8 {code for \.{\\XeTeXcountfeatures}}
9937 @d XeTeX_feature_code_code = XeTeX_int + 9 {code for \.{\\XeTeXfeaturecode}}
9938 @d XeTeX_find_feature_by_name_code = XeTeX_int + 10 {code for \.{\\XeTeXfindfeaturebyname}}
9939 @d XeTeX_is_exclusive_feature_code = XeTeX_int + 11 {code for \.{\\XeTeXisexclusivefeature}}
9940 @d XeTeX_count_selectors_code = XeTeX_int + 12 {code for \.{\\XeTeXcountselectors}}
9941 @d XeTeX_selector_code_code = XeTeX_int + 13 {code for \.{\\XeTeXselectorcode}}
9942 @d XeTeX_find_selector_by_name_code = XeTeX_int + 14 {code for \.{\\XeTeXfindselectorbyname}}
9943 @d XeTeX_is_default_selector_code = XeTeX_int + 15 {code for \.{\\XeTeXisdefaultselector}}
9944 @d XeTeX_OT_count_scripts_code = XeTeX_int + 16 {code for \.{\\XeTeXOTcountscripts}}
9945 @d XeTeX_OT_count_languages_code = XeTeX_int + 17 {code for \.{\\XeTeXOTcountlanguages}}
9946 @d XeTeX_OT_count_features_code = XeTeX_int + 18 {code for \.{\\XeTeXOTcountfeatures}}
9947 @d XeTeX_OT_script_code = XeTeX_int + 19 {code for \.{\\XeTeXOTscripttag}}
9948 @d XeTeX_OT_language_code = XeTeX_int + 20 {code for \.{\\XeTeXOTlanguagetag}}
9949 @d XeTeX_OT_feature_code = XeTeX_int + 21 {code for \.{\\XeTeXOTfeaturetag}}
9950 @d XeTeX_map_char_to_glyph_code = XeTeX_int + 22 {code for \.{\\XeTeXcharglyph}}
9951 @d XeTeX_glyph_index_code = XeTeX_int + 23 {code for \.{\\XeTeXglyphindex}}
9952 @d XeTeX_font_type_code = XeTeX_int + 24 {code for \.{\\XeTeXfonttype}}
9953 @d XeTeX_first_char_code = XeTeX_int + 25 {code for \.{\\XeTeXfirstfontchar}}
9954 @d XeTeX_last_char_code = XeTeX_int + 26 {code for \.{\\XeTeXlastfontchar}}
9955 @d XeTeX_pdf_page_count_code = XeTeX_int + 27 {code for \.{\\XeTeXpdfpagecount}}
9956 @d XeTeX_last_item_codes = XeTeX_int + 27 {end of \XeTeX's command codes}
9957 @#
9958 @d XeTeX_dim = XeTeX_last_item_codes + 1 {first of \XeTeX\ codes for dimensions}
9959 @d XeTeX_glyph_bounds_code = XeTeX_dim + 0 {code for \.{\\XeTeXglyphbounds}}
9960 @d XeTeX_last_dim_codes = XeTeX_dim + 0 {end of \XeTeX's command codes}
9961 @#
9962 @d eTeX_dim=XeTeX_last_dim_codes+1 {first of \eTeX\ codes for dimensions}
9963 @d eTeX_glue=eTeX_dim+9 {first of \eTeX\ codes for glue}
9964 @d eTeX_mu=eTeX_glue+1 {first of \eTeX\ codes for muglue}
9965 @d eTeX_expr=eTeX_mu+1 {first of \eTeX\ codes for expressions}
9966
9967 @<Put each...@>=
9968 primitive("spacefactor",set_aux,hmode);
9969 @!@:space_factor_}{\.{\\spacefactor} primitive@>
9970 primitive("prevdepth",set_aux,vmode);@/
9971 @!@:prev_depth_}{\.{\\prevdepth} primitive@>
9972 primitive("deadcycles",set_page_int,0);
9973 @!@:dead_cycles_}{\.{\\deadcycles} primitive@>
9974 primitive("insertpenalties",set_page_int,1);
9975 @!@:insert_penalties_}{\.{\\insertpenalties} primitive@>
9976 primitive("wd",set_box_dimen,width_offset);
9977 @!@:wd_}{\.{\\wd} primitive@>
9978 primitive("ht",set_box_dimen,height_offset);
9979 @!@:ht_}{\.{\\ht} primitive@>
9980 primitive("dp",set_box_dimen,depth_offset);
9981 @!@:dp_}{\.{\\dp} primitive@>
9982 primitive("lastpenalty",last_item,int_val);
9983 @!@:last_penalty_}{\.{\\lastpenalty} primitive@>
9984 primitive("lastkern",last_item,dimen_val);
9985 @!@:last_kern_}{\.{\\lastkern} primitive@>
9986 primitive("lastskip",last_item,glue_val);
9987 @!@:last_skip_}{\.{\\lastskip} primitive@>
9988 primitive("inputlineno",last_item,input_line_no_code);
9989 @!@:input_line_no_}{\.{\\inputlineno} primitive@>
9990 primitive("badness",last_item,badness_code);
9991 @!@:badness_}{\.{\\badness} primitive@>
9992 primitive("pdflastxpos",last_item,pdf_last_x_pos_code);@/
9993 @!@:pdf_last_x_pos_}{\.{\\pdflastxpos} primitive@>
9994 primitive("pdflastypos",last_item,pdf_last_y_pos_code);@/
9995 @!@:pdf_last_y_pos_}{\.{\\pdflastypos} primitive@>
9996 primitive("elapsedtime",last_item,elapsed_time_code);
9997 @!@:elapsed_time_}{\.{\\elapsedtime} primitive@>
9998 primitive("shellescape",last_item,pdf_shell_escape_code);
9999 @!@:pdf_shell_escape_}{\.{\\shellescape} primitive@>
10000 primitive("randomseed",last_item,random_seed_code);
10001 @!@:random_seed_}{\.{\\randomseed} primitive@>
10002
10003
10004 @ @<Cases of |print_cmd_chr|...@>=
10005 set_aux: if chr_code=vmode then print_esc("prevdepth")
10006 @+else print_esc("spacefactor");
10007 set_page_int: if chr_code=0 then print_esc("deadcycles")
10008 @/@<Cases of |set_page_int| for |print_cmd_chr|@>@/
10009 @+else print_esc("insertpenalties");
10010 set_box_dimen: if chr_code=width_offset then print_esc("wd")
10011 else if chr_code=height_offset then print_esc("ht")
10012 else print_esc("dp");
10013 last_item: case chr_code of
10014 int_val: print_esc("lastpenalty");
10015 dimen_val: print_esc("lastkern");
10016 glue_val: print_esc("lastskip");
10017 input_line_no_code: print_esc("inputlineno");
10018 @/@<Cases of |last_item| for |print_cmd_chr|@>@/
10019 pdf_last_x_pos_code: print_esc("pdflastxpos");
10020 pdf_last_y_pos_code: print_esc("pdflastypos");
10021 elapsed_time_code: print_esc("elapsedtime");
10022 pdf_shell_escape_code: print_esc("shellescape");
10023 random_seed_code: print_esc("randomseed");
10024 othercases print_esc("badness")
10025 endcases;
10026
10027 @ @<Fetch the |space_factor| or the |prev_depth|@>=
10028 if abs(mode)<>m then
10029 begin print_err("Improper "); print_cmd_chr(set_aux,m);
10030 @.Improper \\spacefactor@>
10031 @.Improper \\prevdepth@>
10032 help4("You can refer to \spacefactor only in horizontal mode;")@/
10033 ("you can refer to \prevdepth only in vertical mode; and")@/
10034 ("neither of these is meaningful inside \write. So")@/
10035 ("I'm forgetting what you said and using zero instead.");
10036 error;
10037 if level<>tok_val then scanned_result(0)(dimen_val)
10038 else scanned_result(0)(int_val);
10039 end
10040 else if m=vmode then scanned_result(prev_depth)(dimen_val)
10041 else scanned_result(space_factor)(int_val)
10042
10043 @ @<Fetch the |dead_cycles| or the |insert_penalties|@>=
10044 begin if m=0 then cur_val:=dead_cycles
10045 @/@<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>@/
10046 else cur_val:=insert_penalties;
10047 cur_val_level:=int_val;
10048 end
10049
10050 @ @<Fetch a box dimension@>=
10051 begin scan_register_num; fetch_box(q);
10052 if q=null then cur_val:=0 @+else cur_val:=mem[q+m].sc;
10053 cur_val_level:=dimen_val;
10054 end
10055
10056 @ Inside an \.{\\output} routine, a user may wish to look at the page totals
10057 that were present at the moment when output was triggered.
10058
10059 @d max_dimen==@'7777777777 {$2^{30}-1$}
10060
10061 @<Fetch something on the |page_so_far|@>=
10062 begin if (page_contents=empty) and (not output_active) then
10063 if m=0 then cur_val:=max_dimen@+else cur_val:=0
10064 else cur_val:=page_so_far[m];
10065 cur_val_level:=dimen_val;
10066 end
10067
10068 @ @<Fetch the |prev_graf|@>=
10069 if mode=0 then scanned_result(0)(int_val) {|prev_graf=0| within \.{\\write}}
10070 else begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
10071 while abs(nest[p].mode_field)<>vmode do decr(p);
10072 scanned_result(nest[p].pg_field)(int_val);
10073 end
10074
10075 @ @<Fetch the |par_shape| size@>=
10076 begin if m>par_shape_loc then @<Fetch a penalties array element@>
10077 else if par_shape_ptr=null then cur_val:=0
10078 else cur_val:=info(par_shape_ptr);
10079 cur_val_level:=int_val;
10080 end
10081
10082 @ Here is where \.{\\lastpenalty}, \.{\\lastkern}, \.{\\lastskip}, and
10083 \.{\\lastnodetype} are
10084 implemented. The reference count for \.{\\lastskip} will be updated later.
10085
10086 We also handle \.{\\inputlineno} and \.{\\badness} here, because they are
10087 legal in similar contexts.
10088
10089 The macro |find_effective_tail_eTeX| sets |tx| to the last non-\.{\\endM}
10090 node of the current list.
10091
10092 @d find_effective_tail_eTeX==
10093 tx:=tail;
10094 if not is_char_node(tx) then
10095 if (type(tx)=math_node)and(subtype(tx)=end_M_code) then
10096 begin r:=head;
10097 repeat q:=r; r:=link(q);
10098 until r=tx;
10099 tx:=q;
10100 end
10101 @#
10102 @d find_effective_tail==find_effective_tail_eTeX
10103
10104 @<Fetch an item in the current node...@>=
10105 if m>=input_line_no_code then
10106 if m>=eTeX_glue then @<Process an expression and |return|@>@;
10107 else if m>=XeTeX_dim then
10108 begin case m of
10109 @/@<Cases for fetching a dimension value@>@/
10110 end; {there are no other cases}
10111 cur_val_level:=dimen_val;
10112 end
10113 else begin case m of
10114 input_line_no_code: cur_val:=line;
10115 badness_code: cur_val:=last_badness;
10116 elapsed_time_code: cur_val := get_microinterval;
10117 random_seed_code: cur_val := random_seed;
10118 pdf_shell_escape_code:
10119 begin
10120 if shellenabledp then begin
10121 if restrictedshell then cur_val:=2
10122 else cur_val:=1;
10123 end
10124 else cur_val:=0;
10125 end;
10126 @/@<Cases for fetching an integer value@>@/
10127 end; {there are no other cases}
10128 cur_val_level:=int_val;
10129 end
10130 else begin if cur_chr=glue_val then cur_val:=zero_glue@+else cur_val:=0;
10131 find_effective_tail;
10132 if cur_chr=last_node_type_code then
10133 begin cur_val_level:=int_val;
10134 if (tx=head)or(mode=0) then cur_val:=-1;
10135 end
10136 else cur_val_level:=cur_chr;
10137 if not is_char_node(tx)and(mode<>0) then
10138 case cur_chr of
10139 int_val: if type(tx)=penalty_node then cur_val:=penalty(tx);
10140 dimen_val: if type(tx)=kern_node then cur_val:=width(tx);
10141 glue_val: if type(tx)=glue_node then
10142 begin cur_val:=glue_ptr(tx);
10143 if subtype(tx)=mu_glue then cur_val_level:=mu_val;
10144 end;
10145 last_node_type_code: if type(tx)<=unset_node then cur_val:=type(tx)+1
10146 else cur_val:=unset_node+2;
10147 end {there are no other cases}
10148 else if (mode=vmode)and(tx=head) then
10149 case cur_chr of
10150 int_val: cur_val:=last_penalty;
10151 dimen_val: cur_val:=last_kern;
10152 glue_val: if last_glue<>max_halfword then cur_val:=last_glue;
10153 last_node_type_code: cur_val:=last_node_type;
10154 end; {there are no other cases}
10155 end
10156
10157 @ @<Fetch a font dimension@>=
10158 begin find_font_dimen(false); font_info[fmem_ptr].sc:=0;
10159 scanned_result(font_info[cur_val].sc)(dimen_val);
10160 end
10161
10162 @ @<Fetch a font integer@>=
10163 begin scan_font_ident;
10164 if m=0 then scanned_result(hyphen_char[cur_val])(int_val)
10165 else if m=1 then scanned_result(skew_char[cur_val])(int_val)
10166 else begin
10167 n:=cur_val;
10168 if is_native_font(n) then scan_glyph_number(n)
10169 else scan_char_num;
10170 k:=cur_val;
10171 case m of
10172 lp_code_base: scanned_result(get_cp_code(n, k, left_side))(int_val);
10173 rp_code_base: scanned_result(get_cp_code(n, k, right_side))(int_val);
10174 end;
10175 end;
10176 end
10177
10178 @ @<Fetch a register@>=
10179 begin if (m<mem_bot)or(m>lo_mem_stat_max) then
10180 begin cur_val_level:=sa_type(m);
10181 if cur_val_level<glue_val then cur_val:=sa_int(m)
10182 else cur_val:=sa_ptr(m);
10183 end
10184 else begin scan_register_num; cur_val_level:=m-mem_bot;
10185 if cur_val>255 then
10186 begin find_sa_element(cur_val_level,cur_val,false);
10187 if cur_ptr=null then
10188 if cur_val_level<glue_val then cur_val:=0
10189 else cur_val:=zero_glue
10190 else if cur_val_level<glue_val then cur_val:=sa_int(cur_ptr)
10191 else cur_val:=sa_ptr(cur_ptr);
10192 end
10193 else
10194 case cur_val_level of
10195 int_val:cur_val:=count(cur_val);
10196 dimen_val:cur_val:=dimen(cur_val);
10197 glue_val: cur_val:=skip(cur_val);
10198 mu_val: cur_val:=mu_skip(cur_val);
10199 end; {there are no other cases}
10200 end;
10201 end
10202
10203 @ @<Complain that \.{\\the} can't do this; give zero result@>=
10204 begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
10205 @.You can't use x after ...@>
10206 print("' after "); print_esc("the");
10207 help1("I'm forgetting what you said and using zero instead.");
10208 error;
10209 if level<>tok_val then scanned_result(0)(dimen_val)
10210 else scanned_result(0)(int_val);
10211 end
10212
10213 @ When a |glue_val| changes to a |dimen_val|, we use the width component
10214 of the glue; there is no need to decrease the reference count, since it
10215 has not yet been increased. When a |dimen_val| changes to an |int_val|,
10216 we use scaled points so that the value doesn't actually change. And when a
10217 |mu_val| changes to a |glue_val|, the value doesn't change either.
10218
10219 @<Convert \(c)|cur_val| to a lower level@>=
10220 begin if cur_val_level=glue_val then cur_val:=width(cur_val)
10221 else if cur_val_level=mu_val then mu_error;
10222 decr(cur_val_level);
10223 end
10224
10225 @ If |cur_val| points to a glue specification at this point, the reference
10226 count for the glue does not yet include the reference by |cur_val|.
10227 If |negative| is |true|, |cur_val_level| is known to be |<=mu_val|.
10228
10229 @<Fix the reference count, if any, ...@>=
10230 if negative then
10231 if cur_val_level>=glue_val then
10232 begin cur_val:=new_spec(cur_val);
10233 @<Negate all three glue components of |cur_val|@>;
10234 end
10235 else negate(cur_val)
10236 else if (cur_val_level>=glue_val)and(cur_val_level<=mu_val) then
10237 add_glue_ref(cur_val)
10238
10239 @ @<Negate all three...@>=
10240 begin negate(width(cur_val));
10241 negate(stretch(cur_val));
10242 negate(shrink(cur_val));
10243 end
10244
10245 @ Our next goal is to write the |scan_int| procedure, which scans anything that
10246 \TeX\ treats as an integer. But first we might as well look at some simple
10247 applications of |scan_int| that have already been made inside of
10248 |scan_something_internal|.
10249
10250 @ @<Declare procedures that scan restricted classes of integers@>=
10251
10252 procedure scan_glyph_number(f: internal_font_number);
10253 { scan a glyph ID for native font |f|, identified by Unicode value or name or glyph number }
10254 begin
10255 if scan_keyword("/") then {set cp value by glyph name}
10256 begin
10257 scan_and_pack_name; {result is in |nameoffile|}
10258 scanned_result(map_glyph_to_index(f))(int_val);
10259 end else if scan_keyword("u") then {set cp value by unicode}
10260 begin
10261 scan_char_num;
10262 scanned_result(map_char_to_glyph(f,cur_val))(int_val);
10263 end else
10264 scan_int;
10265 end;
10266
10267 procedure scan_char_class;
10268 begin scan_int;
10269 if (cur_val<0)or(cur_val>char_class_limit) then
10270 begin print_err("Bad character class");
10271 @.Bad character code@>
10272 help2("A character class must be between 0 and 4096.")@/
10273 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10274 end;
10275 end;
10276
10277 procedure scan_char_class_not_ignored;
10278 begin scan_int;
10279 if (cur_val<0)or(cur_val>char_class_limit) then
10280 begin print_err("Bad character class");
10281 @.Bad character code@>
10282 help2("A class for inter-character transitions must be between 0 and 4095.")@/
10283 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10284 end;
10285 end;
10286
10287 procedure scan_eight_bit_int;
10288 begin scan_int;
10289 if (cur_val<0)or(cur_val>255) then
10290 begin print_err("Bad register code");
10291 @.Bad register code@>
10292 help2("A register code or char class must be between 0 and 255.")@/
10293 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10294 end;
10295 end;
10296
10297 @ @<Declare procedures that scan restricted classes of integers@>=
10298 procedure scan_usv_num;
10299 begin scan_int;
10300 if (cur_val<0)or(cur_val>biggest_usv) then
10301 begin print_err("Bad character code");
10302 @.Bad character code@>
10303 help2("A Unicode scalar value must be between 0 and ""10FFFF.")@/
10304 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10305 end;
10306 end;
10307
10308 procedure scan_char_num;
10309 begin scan_int;
10310 if (cur_val<0)or(cur_val>biggest_char) then
10311 begin print_err("Bad character code");
10312 @.Bad character code@>
10313 help2("A character number must be between 0 and 65535.")@/
10314 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10315 end;
10316 end;
10317
10318 @ While we're at it, we might as well deal with similar routines that
10319 will be needed later.
10320
10321 @<Declare procedures that scan restricted classes of integers@>=
10322 procedure scan_xetex_math_char_int;
10323 begin scan_int;
10324 if is_active_math_char(cur_val) then begin
10325 if cur_val <> active_math_char then begin
10326 print_err("Bad active XeTeX math code");
10327 help2("Since I ignore class and family for active math chars,")@/
10328 ("I changed this one to ""1FFFFF."); int_error(cur_val);
10329 cur_val:=active_math_char;
10330 end
10331 end else if math_char_field(cur_val)>biggest_usv then begin
10332 print_err("Bad XeTeX math character code");
10333 help2("Since I expected a character number between 0 and ""10FFFF,")@/
10334 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10335 end;
10336 end;
10337
10338 procedure scan_math_class_int;
10339 begin scan_int;
10340 if (cur_val<0)or(cur_val>7) then
10341 begin print_err("Bad math class");
10342 @.Bad number@>
10343 help2("Since I expected to read a number between 0 and 7,")@/
10344 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10345 end;
10346 end;
10347
10348 procedure scan_math_fam_int;
10349 begin scan_int;
10350 if (cur_val<0)or(cur_val>number_math_families-1) then
10351 begin print_err("Bad math family");
10352 @.Bad number@>
10353 help2("Since I expected to read a number between 0 and 255,")@/
10354 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10355 end;
10356 end;
10357
10358 procedure scan_four_bit_int;
10359 begin scan_int;
10360 if (cur_val<0)or(cur_val>15) then
10361 begin print_err("Bad number");
10362 @.Bad number@>
10363 help2("Since I expected to read a number between 0 and 15,")@/
10364 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10365 end;
10366 end;
10367
10368 @ @<Declare procedures that scan restricted classes of integers@>=
10369 procedure scan_fifteen_bit_int;
10370 begin scan_int;
10371 if (cur_val<0)or(cur_val>@'77777) then
10372 begin print_err("Bad mathchar");
10373 @.Bad mathchar@>
10374 help2("A mathchar number must be between 0 and 32767.")@/
10375 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10376 end;
10377 end;
10378
10379 @ @<Declare procedures that scan restricted classes of integers@>=
10380 procedure scan_delimiter_int;
10381 begin scan_int;
10382 if (cur_val<0)or(cur_val>@'777777777) then
10383 begin print_err("Bad delimiter code");
10384 @.Bad delimiter code@>
10385 help2("A numeric delimiter code must be between 0 and 2^{27}-1.")@/
10386 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
10387 end;
10388 end;
10389
10390 @ An integer number can be preceded by any number of spaces and `\.+' or
10391 `\.-' signs. Then comes either a decimal constant (i.e., radix 10), an
10392 octal constant (i.e., radix 8, preceded by~\.\'), a hexadecimal constant
10393 (radix 16, preceded by~\."), an alphabetic constant (preceded by~\.\`), or
10394 an internal variable. After scanning is complete,
10395 |cur_val| will contain the answer, which must be at most
10396 $2^{31}-1=2147483647$ in absolute value. The value of |radix| is set to
10397 10, 8, or 16 in the cases of decimal, octal, or hexadecimal constants,
10398 otherwise |radix| is set to zero. An optional space follows a constant.
10399
10400 @d octal_token=other_token+"'" {apostrophe, indicates an octal constant}
10401 @d hex_token=other_token+"""" {double quote, indicates a hex constant}
10402 @d alpha_token=other_token+"`" {reverse apostrophe, precedes alpha constants}
10403 @d point_token=other_token+"." {decimal point}
10404 @d continental_point_token=other_token+"," {decimal point, Eurostyle}
10405
10406 @<Glob...@>=
10407 @!radix:small_number; {|scan_int| sets this to 8, 10, 16, or zero}
10408
10409 @ We initialize the following global variables just in case |expand|
10410 comes into action before any of the basic scanning routines has assigned
10411 them a value.
10412
10413 @<Set init...@>=
10414 cur_val:=0; cur_val_level:=int_val; radix:=0; cur_order:=normal;
10415
10416 @ The |scan_int| routine is used also to scan the integer part of a
10417 fraction; for example, the `\.3' in `\.{3.14159}' will be found by
10418 |scan_int|. The |scan_dimen| routine assumes that |cur_tok=point_token|
10419 after the integer part of such a fraction has been scanned by |scan_int|,
10420 and that the decimal point has been backed up to be scanned again.
10421
10422 @p procedure scan_int; {sets |cur_val| to an integer}
10423 label done, restart;
10424 var negative:boolean; {should the answer be negated?}
10425 @!m:integer; {|@t$2^{31}$@> div radix|, the threshold of danger}
10426 @!d:small_number; {the digit just scanned}
10427 @!vacuous:boolean; {have no digits appeared?}
10428 @!OK_so_far:boolean; {has an error message been issued?}
10429 begin radix:=0; OK_so_far:=true;@/
10430 @<Get the next non-blank non-sign token; set |negative| appropriately@>;
10431 restart:
10432 if cur_tok=alpha_token then @<Scan an alphabetic character code into |cur_val|@>
10433 else if cur_tok=cs_token_flag+frozen_primitive then
10434 @<Reset |cur_tok| for unexpandable primitives, goto restart@>
10435 else if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
10436 scan_something_internal(int_val,false)
10437 else @<Scan a numeric constant@>;
10438 if negative then negate(cur_val);
10439 end;
10440
10441 @ @<Get the next non-blank non-sign token...@>=
10442 negative:=false;
10443 repeat @<Get the next non-blank non-call token@>;
10444 if cur_tok=other_token+"-" then
10445 begin negative:=not negative; cur_tok:=other_token+"+";
10446 end;
10447 until cur_tok<>other_token+"+"
10448
10449 @ A space is ignored after an alphabetic character constant, so that
10450 such constants behave like numeric ones.
10451
10452 @<Scan an alphabetic character code into |cur_val|@>=
10453 begin get_token; {suppress macro expansion}
10454 if cur_tok<cs_token_flag then
10455 begin cur_val:=cur_chr;
10456 if cur_cmd<=right_brace then
10457 if cur_cmd=right_brace then incr(align_state)
10458 else decr(align_state);
10459 end
10460 else if cur_tok<cs_token_flag+single_base then
10461 cur_val:=cur_tok-cs_token_flag-active_base
10462 else if cur_tok<cs_token_flag+null_cs then
10463 cur_val:=cur_tok-cs_token_flag-single_base
10464 else { check the cs is a single-letter whose character code is ${}>|@"FFFF|$ }
10465 begin m:=text(cur_tok-cs_token_flag);
10466 if str_start_macro(m+1)=2+str_start_macro(m) then begin
10467 m:=str_start_macro(m);
10468 if (so(str_pool[m])>=@"D800) and (so(str_pool[m])<=@"DBFF)
10469 and (so(str_pool[m+1])>=@"DC00) and (so(str_pool[m+1])<=@"DFFF) then
10470 cur_val:=@"10000 + (so(str_pool[m])-@"D800) * @"400 + so(str_pool[m+1])-@"DC00
10471 else cur_val:=too_big_usv;
10472 end
10473 else cur_val:=too_big_usv;
10474 end;
10475 if cur_val>biggest_usv then
10476 begin print_err("Improper alphabetic constant");
10477 @.Improper alphabetic constant@>
10478 help2("A one-character control sequence belongs after a ` mark.")@/
10479 ("So I'm essentially inserting \0 here.");
10480 cur_val:="0"; back_error;
10481 end
10482 else @<Scan an optional space@>;
10483 end
10484
10485 @ @<Scan an optional space@>=
10486 begin get_x_token; if cur_cmd<>spacer then back_input;
10487 end
10488
10489 @ @<Scan a numeric constant@>=
10490 begin radix:=10; m:=214748364;
10491 if cur_tok=octal_token then
10492 begin radix:=8; m:=@'2000000000; get_x_token;
10493 end
10494 else if cur_tok=hex_token then
10495 begin radix:=16; m:=@'1000000000; get_x_token;
10496 end;
10497 vacuous:=true; cur_val:=0;@/
10498 @<Accumulate the constant until |cur_tok| is not a suitable digit@>;
10499 if vacuous then @<Express astonishment that no number was here@>
10500 else if cur_cmd<>spacer then back_input;
10501 end
10502
10503 @ @d infinity==@'17777777777 {the largest positive value that \TeX\ knows}
10504 @d zero_token=other_token+"0" {zero, the smallest digit}
10505 @d A_token=letter_token+"A" {the smallest special hex digit}
10506 @d other_A_token=other_token+"A" {special hex digit of type |other_char|}
10507
10508 @<Accumulate the constant...@>=
10509 loop@+ begin if (cur_tok<zero_token+radix)and(cur_tok>=zero_token)and
10510 (cur_tok<=zero_token+9) then d:=cur_tok-zero_token
10511 else if radix=16 then
10512 if (cur_tok<=A_token+5)and(cur_tok>=A_token) then d:=cur_tok-A_token+10
10513 else if (cur_tok<=other_A_token+5)and(cur_tok>=other_A_token) then
10514 d:=cur_tok-other_A_token+10
10515 else goto done
10516 else goto done;
10517 vacuous:=false;
10518 if (cur_val>=m)and((cur_val>m)or(d>7)or(radix<>10)) then
10519 begin if OK_so_far then
10520 begin print_err("Number too big");
10521 @.Number too big@>
10522 help2("I can only go up to 2147483647='17777777777=""7FFFFFFF,")@/
10523 ("so I'm using that number instead of yours.");
10524 error; cur_val:=infinity; OK_so_far:=false;
10525 end;
10526 end
10527 else cur_val:=cur_val*radix+d;
10528 get_x_token;
10529 end;
10530 done:
10531
10532 @ @<Express astonishment...@>=
10533 begin print_err("Missing number, treated as zero");
10534 @.Missing number...@>
10535 help3("A number should have been here; I inserted `0'.")@/
10536 ("(If you can't figure out why I needed to see a number,")@/
10537 ("look up `weird error' in the index to The TeXbook.)");
10538 @:TeXbook}{\sl The \TeX book@>
10539 back_error;
10540 end
10541
10542 @ The |scan_dimen| routine is similar to |scan_int|, but it sets |cur_val| to
10543 a |scaled| value, i.e., an integral number of sp. One of its main tasks
10544 is therefore to interpret the abbreviations for various kinds of units and
10545 to convert measurements to scaled points.
10546
10547 There are three parameters: |mu| is |true| if the finite units must be
10548 `\.{mu}', while |mu| is |false| if `\.{mu}' units are disallowed;
10549 |inf| is |true| if the infinite units `\.{fil}', `\.{fill}', `\.{filll}'
10550 are permitted; and |shortcut| is |true| if |cur_val| already contains
10551 an integer and only the units need to be considered.
10552
10553 The order of infinity that was found in the case of infinite glue is returned
10554 in the global variable |cur_order|.
10555
10556 @<Glob...@>=
10557 @!cur_order:glue_ord; {order of infinity found by |scan_dimen|}
10558
10559 @ Constructions like `\.{-\'77 pt}' are legal dimensions, so |scan_dimen|
10560 may begin with |scan_int|. This explains why it is convenient to use
10561 |scan_int| also for the integer part of a decimal fraction.
10562
10563 Several branches of |scan_dimen| work with |cur_val| as an integer and
10564 with an auxiliary fraction |f|, so that the actual quantity of interest is
10565 $|cur_val|+|f|/2^{16}$. At the end of the routine, this ``unpacked''
10566 representation is put into the single word |cur_val|, which suddenly
10567 switches significance from |integer| to |scaled|.
10568
10569 @d attach_fraction=88 {go here to pack |cur_val| and |f| into |cur_val|}
10570 @d attach_sign=89 {go here when |cur_val| is correct except perhaps for sign}
10571 @d scan_normal_dimen==scan_dimen(false,false,false)
10572
10573 @p procedure xetex_scan_dimen(@!mu,@!inf,@!shortcut,@!requires_units:boolean);
10574 {sets |cur_val| to a dimension}
10575 label done, done1, done2, found, not_found, attach_fraction, attach_sign;
10576 var negative:boolean; {should the answer be negated?}
10577 @!f:integer; {numerator of a fraction whose denominator is $2^{16}$}
10578 @<Local variables for dimension calculations@>@;
10579 begin f:=0; arith_error:=false; cur_order:=normal; negative:=false;
10580 if not shortcut then
10581 begin @<Get the next non-blank non-sign...@>;
10582 if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
10583 @<Fetch an internal dimension and |goto attach_sign|,
10584 or fetch an internal integer@>
10585 else begin back_input;
10586 if cur_tok=continental_point_token then cur_tok:=point_token;
10587 if cur_tok<>point_token then scan_int
10588 else begin radix:=10; cur_val:=0;
10589 end;
10590 if cur_tok=continental_point_token then cur_tok:=point_token;
10591 if (radix=10)and(cur_tok=point_token) then @<Scan decimal fraction@>;
10592 end;
10593 end;
10594 if cur_val<0 then {in this case |f=0|}
10595 begin negative:=not negative; negate(cur_val);
10596 end;
10597 if requires_units then begin
10598 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$, where there
10599 are |x| sp per unit; |goto attach_sign| if the units are internal@>;
10600 @<Scan an optional space@>;
10601 end else begin
10602 if cur_val>=@'40000 then arith_error:=true
10603 else cur_val:=cur_val*unity+f;
10604 end;
10605 attach_sign: if arith_error or(abs(cur_val)>=@'10000000000) then
10606 @<Report that this dimension is out of range@>;
10607 if negative then negate(cur_val);
10608 end;
10609
10610 procedure scan_dimen(@!mu,@!inf,@!shortcut:boolean);
10611 begin
10612 xetex_scan_dimen(mu,inf,shortcut,true);
10613 end;
10614
10615 @ For XeTeX, we have an additional version |scan_decimal|, like |scan_dimen|
10616 but without any scanning of units.
10617
10618 @p procedure scan_decimal;
10619 {sets |cur_val| to a quantity expressed as a decimal fraction}
10620 begin
10621 xetex_scan_dimen(false, false, false, false);
10622 end;
10623
10624 @ @<Fetch an internal dimension and |goto attach_sign|...@>=
10625 if mu then
10626 begin scan_something_internal(mu_val,false);
10627 @<Coerce glue to a dimension@>;
10628 if cur_val_level=mu_val then goto attach_sign;
10629 if cur_val_level<>int_val then mu_error;
10630 end
10631 else begin scan_something_internal(dimen_val,false);
10632 if cur_val_level=dimen_val then goto attach_sign;
10633 end
10634
10635 @ @<Local variables for dimension calculations@>=
10636 @!num,@!denom:1..65536; {conversion ratio for the scanned units}
10637 @!k,@!kk:small_number; {number of digits in a decimal fraction}
10638 @!p,@!q:pointer; {top of decimal digit stack}
10639 @!v:scaled; {an internal dimension}
10640 @!save_cur_val:integer; {temporary storage of |cur_val|}
10641
10642 @ The following code is executed when |scan_something_internal| was
10643 called asking for |mu_val|, when we really wanted a ``mudimen'' instead
10644 of ``muglue.''
10645
10646 @<Coerce glue to a dimension@>=
10647 if cur_val_level>=glue_val then
10648 begin v:=width(cur_val); delete_glue_ref(cur_val); cur_val:=v;
10649 end
10650
10651 @ When the following code is executed, we have |cur_tok=point_token|, but this
10652 token has been backed up using |back_input|; we must first discard it.
10653
10654 It turns out that a decimal point all by itself is equivalent to `\.{0.0}'.
10655 Let's hope people don't use that fact.
10656
10657 @<Scan decimal fraction@>=
10658 begin k:=0; p:=null; get_token; {|point_token| is being re-scanned}
10659 loop@+ begin get_x_token;
10660 if (cur_tok>zero_token+9)or(cur_tok<zero_token) then goto done1;
10661 if k<17 then {digits for |k>=17| cannot affect the result}
10662 begin q:=get_avail; link(q):=p; info(q):=cur_tok-zero_token;
10663 p:=q; incr(k);
10664 end;
10665 end;
10666 done1: for kk:=k downto 1 do
10667 begin dig[kk-1]:=info(p); q:=p; p:=link(p); free_avail(q);
10668 end;
10669 f:=round_decimals(k);
10670 if cur_cmd<>spacer then back_input;
10671 end
10672
10673 @ Now comes the harder part: At this point in the program, |cur_val| is a
10674 nonnegative integer and $f/2^{16}$ is a nonnegative fraction less than 1;
10675 we want to multiply the sum of these two quantities by the appropriate
10676 factor, based on the specified units, in order to produce a |scaled|
10677 result, and we want to do the calculation with fixed point arithmetic that
10678 does not overflow.
10679
10680 @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$...@>=
10681 if inf then @<Scan for \(f)\.{fil} units; |goto attach_fraction| if found@>;
10682 @<Scan for \(u)units that are internal dimensions;
10683 |goto attach_sign| with |cur_val| set if found@>;
10684 if mu then @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>;
10685 if scan_keyword("true") then @<Adjust \(f)for the magnification ratio@>;
10686 @.true@>
10687 if scan_keyword("pt") then goto attach_fraction; {the easy case}
10688 @.pt@>
10689 @<Scan for \(a)all other units and adjust |cur_val| and |f| accordingly;
10690 |goto done| in the case of scaled points@>;
10691 attach_fraction: if cur_val>=@'40000 then arith_error:=true
10692 else cur_val:=cur_val*unity+f;
10693 done:
10694
10695 @ A specification like `\.{filllll}' or `\.{fill L L L}' will lead to two
10696 error messages (one for each additional keyword \.{"l"}).
10697
10698 @<Scan for \(f)\.{fil} units...@>=
10699 if scan_keyword("fil") then
10700 @.fil@>
10701 begin cur_order:=fil;
10702 while scan_keyword("l") do
10703 begin if cur_order=filll then
10704 begin print_err("Illegal unit of measure (");
10705 @.Illegal unit of measure@>
10706 print("replaced by filll)");
10707 help1("I dddon't go any higher than filll."); error;
10708 end
10709 else incr(cur_order);
10710 end;
10711 goto attach_fraction;
10712 end
10713
10714 @ @<Scan for \(u)units that are internal dimensions...@>=
10715 save_cur_val:=cur_val;
10716 @<Get the next non-blank non-call...@>;
10717 if (cur_cmd<min_internal)or(cur_cmd>max_internal) then back_input
10718 else begin if mu then
10719 begin scan_something_internal(mu_val,false); @<Coerce glue...@>;
10720 if cur_val_level<>mu_val then mu_error;
10721 end
10722 else scan_something_internal(dimen_val,false);
10723 v:=cur_val; goto found;
10724 end;
10725 if mu then goto not_found;
10726 if scan_keyword("em") then v:=(@<The em width for |cur_font|@>)
10727 @.em@>
10728 else if scan_keyword("ex") then v:=(@<The x-height for |cur_font|@>)
10729 @.ex@>
10730 else goto not_found;
10731 @<Scan an optional space@>;
10732 found:cur_val:=nx_plus_y(save_cur_val,v,xn_over_d(v,f,@'200000));
10733 goto attach_sign;
10734 not_found:
10735
10736 @ @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>=
10737 if scan_keyword("mu") then goto attach_fraction
10738 @.mu@>
10739 else begin print_err("Illegal unit of measure ("); print("mu inserted)");
10740 @.Illegal unit of measure@>
10741 help4("The unit of measurement in math glue must be mu.")@/
10742 ("To recover gracefully from this error, it's best to")@/
10743 ("delete the erroneous units; e.g., type `2' to delete")@/
10744 ("two letters. (See Chapter 27 of The TeXbook.)");
10745 @:TeXbook}{\sl The \TeX book@>
10746 error; goto attach_fraction;
10747 end
10748
10749 @ @<Adjust \(f)for the magnification ratio@>=
10750 begin prepare_mag;
10751 if mag<>1000 then
10752 begin cur_val:=xn_over_d(cur_val,1000,mag);
10753 f:=(1000*f+@'200000*remainder) div mag;
10754 cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
10755 end;
10756 end
10757
10758 @ The necessary conversion factors can all be specified exactly as
10759 fractions whose numerator and denominator sum to 32768 or less.
10760 According to the definitions here, $\rm2660\,dd\approx1000.33297\,mm$;
10761 this agrees well with the value $\rm1000.333\,mm$ cited by Bosshard
10762 @^Bosshard, Hans Rudolf@>
10763 in {\sl Technische Grundlagen zur Satzherstellung\/} (Bern, 1980).
10764
10765 @d set_conversion_end(#)== denom:=#; end
10766 @d set_conversion(#)==@+begin num:=#; set_conversion_end
10767
10768 @<Scan for \(a)all other units and adjust |cur_val| and |f|...@>=
10769 if scan_keyword("in") then set_conversion(7227)(100)
10770 @.in@>
10771 else if scan_keyword("pc") then set_conversion(12)(1)
10772 @.pc@>
10773 else if scan_keyword("cm") then set_conversion(7227)(254)
10774 @.cm@>
10775 else if scan_keyword("mm") then set_conversion(7227)(2540)
10776 @.mm@>
10777 else if scan_keyword("bp") then set_conversion(7227)(7200)
10778 @.bp@>
10779 else if scan_keyword("dd") then set_conversion(1238)(1157)
10780 @.dd@>
10781 else if scan_keyword("cc") then set_conversion(14856)(1157)
10782 @.cc@>
10783 else if scan_keyword("sp") then goto done
10784 @.sp@>
10785 else @<Complain about unknown unit and |goto done2|@>;
10786 cur_val:=xn_over_d(cur_val,num,denom);
10787 f:=(num*f+@'200000*remainder) div denom;@/
10788 cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
10789 done2:
10790
10791 @ @<Complain about unknown unit...@>=
10792 begin print_err("Illegal unit of measure ("); print("pt inserted)");
10793 @.Illegal unit of measure@>
10794 help6("Dimensions can be in units of em, ex, in, pt, pc,")@/
10795 ("cm, mm, dd, cc, bp, or sp; but yours is a new one!")@/
10796 ("I'll assume that you meant to say pt, for printer's points.")@/
10797 ("To recover gracefully from this error, it's best to")@/
10798 ("delete the erroneous units; e.g., type `2' to delete")@/
10799 ("two letters. (See Chapter 27 of The TeXbook.)");
10800 @:TeXbook}{\sl The \TeX book@>
10801 error; goto done2;
10802 end
10803
10804
10805 @ @<Report that this dimension is out of range@>=
10806 begin print_err("Dimension too large");
10807 @.Dimension too large@>
10808 help2("I can't work with sizes bigger than about 19 feet.")@/
10809 ("Continue and I'll use the largest value I can.");@/
10810 error; cur_val:=max_dimen; arith_error:=false;
10811 end
10812
10813 @ The final member of \TeX's value-scanning trio is |scan_glue|, which
10814 makes |cur_val| point to a glue specification. The reference count of that
10815 glue spec will take account of the fact that |cur_val| is pointing to~it.
10816
10817 The |level| parameter should be either |glue_val| or |mu_val|.
10818
10819 Since |scan_dimen| was so much more complex than |scan_int|, we might expect
10820 |scan_glue| to be even worse. But fortunately, it is very simple, since
10821 most of the work has already been done.
10822
10823 @p procedure scan_glue(@!level:small_number);
10824 {sets |cur_val| to a glue spec pointer}
10825 label exit;
10826 var negative:boolean; {should the answer be negated?}
10827 @!q:pointer; {new glue specification}
10828 @!mu:boolean; {does |level=mu_val|?}
10829 begin mu:=(level=mu_val); @<Get the next non-blank non-sign...@>;
10830 if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
10831 begin scan_something_internal(level,negative);
10832 if cur_val_level>=glue_val then
10833 begin if cur_val_level<>level then mu_error;
10834 return;
10835 end;
10836 if cur_val_level=int_val then scan_dimen(mu,false,true)
10837 else if level=mu_val then mu_error;
10838 end
10839 else begin back_input; scan_dimen(mu,false,false);
10840 if negative then negate(cur_val);
10841 end;
10842 @<Create a new glue specification whose width is |cur_val|; scan for its
10843 stretch and shrink components@>;
10844 exit:end;
10845 @#
10846 @<Declare procedures needed for expressions@>@;
10847
10848 @ @<Create a new glue specification whose width is |cur_val|...@>=
10849 q:=new_spec(zero_glue); width(q):=cur_val;
10850 if scan_keyword("plus") then
10851 @.plus@>
10852 begin scan_dimen(mu,true,false);
10853 stretch(q):=cur_val; stretch_order(q):=cur_order;
10854 end;
10855 if scan_keyword("minus") then
10856 @.minus@>
10857 begin scan_dimen(mu,true,false);
10858 shrink(q):=cur_val; shrink_order(q):=cur_order;
10859 end;
10860 cur_val:=q
10861
10862 @ Here's a similar procedure that returns a pointer to a rule node. This
10863 routine is called just after \TeX\ has seen \.{\\hrule} or \.{\\vrule};
10864 therefore |cur_cmd| will be either |hrule| or |vrule|. The idea is to store
10865 the default rule dimensions in the node, then to override them if
10866 `\.{height}' or `\.{width}' or `\.{depth}' specifications are
10867 found (in any order).
10868
10869 @d default_rule=26214 {0.4\thinspace pt}
10870
10871 @p function scan_rule_spec:pointer;
10872 label reswitch;
10873 var q:pointer; {the rule node being created}
10874 begin q:=new_rule; {|width|, |depth|, and |height| all equal |null_flag| now}
10875 if cur_cmd=vrule then width(q):=default_rule
10876 else begin height(q):=default_rule; depth(q):=0;
10877 end;
10878 reswitch: if scan_keyword("width") then
10879 @.width@>
10880 begin scan_normal_dimen; width(q):=cur_val; goto reswitch;
10881 end;
10882 if scan_keyword("height") then
10883 @.height@>
10884 begin scan_normal_dimen; height(q):=cur_val; goto reswitch;
10885 end;
10886 if scan_keyword("depth") then
10887 @.depth@>
10888 begin scan_normal_dimen; depth(q):=cur_val; goto reswitch;
10889 end;
10890 scan_rule_spec:=q;
10891 end;
10892
10893 @* \[27] Building token lists.
10894 The token lists for macros and for other things like \.{\\mark} and \.{\\output}
10895 and \.{\\write} are produced by a procedure called |scan_toks|.
10896
10897 Before we get into the details of |scan_toks|, let's consider a much
10898 simpler task, that of converting the current string into a token list.
10899 The |str_toks| function does this; it classifies spaces as type |spacer|
10900 and everything else as type |other_char|.
10901
10902 The token list created by |str_toks| begins at |link(temp_head)| and ends
10903 at the value |p| that is returned. (If |p=temp_head|, the list is empty.)
10904
10905 The |str_toks_cat| function is the same, except that the catcode |cat| is
10906 stamped on all the characters, unless zero is passed in which case it
10907 chooses |spacer| or |other_char| automatically.
10908
10909 @p @t\4@>@<Declare \eTeX\ procedures for token lists@>@;@/
10910 function str_toks_cat(@!b:pool_pointer;@!cat:small_number):pointer;
10911 {changes the string |str_pool[b..pool_ptr]| to a token list}
10912 var p:pointer; {tail of the token list}
10913 @!q:pointer; {new node being added to the token list via |store_new_token|}
10914 @!t:halfword; {token being appended}
10915 @!k:pool_pointer; {index into |str_pool|}
10916 begin str_room(1);
10917 p:=temp_head; link(p):=null; k:=b;
10918 while k<pool_ptr do
10919 begin t:=so(str_pool[k]);
10920 if (t=" ") and (cat=0) then t:=space_token
10921 else begin if (t >= @"D800) and (t <= @"DBFF) and (k+1 < pool_ptr)
10922 and (so(str_pool[k+1]) >= @"DC00) and (so(str_pool[k+1]) <= @"DFFF) then
10923 begin
10924 incr(k);
10925 t := @"10000 + (t - @"D800) * @"400 + (so(str_pool[k]) - @"DC00);
10926 end;
10927 if cat=0 then t := other_token + t
10928 else if cat=active_char then t := cs_token_flag + active_base + t
10929 else t := max_char_val * cat + t;
10930 end;
10931 fast_store_new_token(t);
10932 incr(k);
10933 end;
10934 pool_ptr:=b; str_toks_cat:=p;
10935 end;
10936
10937 function str_toks(@!b:pool_pointer):pointer;
10938 begin str_toks:=str_toks_cat(b,0); end;
10939
10940 @ The main reason for wanting |str_toks| is the next function,
10941 |the_toks|, which has similar input/output characteristics.
10942
10943 This procedure is supposed to scan something like `\.{\\skip\\count12}',
10944 i.e., whatever can follow `\.{\\the}', and it constructs a token list
10945 containing something like `\.{-3.0pt minus 0.5fill}'.
10946
10947 @p function the_toks:pointer;
10948 label exit;
10949 var old_setting:0..max_selector; {holds |selector| setting}
10950 @!p,@!q,@!r:pointer; {used for copying a token list}
10951 @!b:pool_pointer; {base of temporary string}
10952 @!c:small_number; {value of |cur_chr|}
10953 begin @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>;@/
10954 get_x_token; scan_something_internal(tok_val,false);
10955 if cur_val_level>=ident_val then @<Copy the token list@>
10956 else begin old_setting:=selector; selector:=new_string; b:=pool_ptr;
10957 case cur_val_level of
10958 int_val:print_int(cur_val);
10959 dimen_val:begin print_scaled(cur_val); print("pt");
10960 end;
10961 glue_val: begin print_spec(cur_val,"pt"); delete_glue_ref(cur_val);
10962 end;
10963 mu_val: begin print_spec(cur_val,"mu"); delete_glue_ref(cur_val);
10964 end;
10965 end; {there are no other cases}
10966 selector:=old_setting; the_toks:=str_toks(b);
10967 end;
10968 exit:end;
10969
10970 @ @<Copy the token list@>=
10971 begin p:=temp_head; link(p):=null;
10972 if cur_val_level=ident_val then store_new_token(cs_token_flag+cur_val)
10973 else if cur_val<>null then
10974 begin r:=link(cur_val); {do not copy the reference count}
10975 while r<>null do
10976 begin fast_store_new_token(info(r)); r:=link(r);
10977 end;
10978 end;
10979 the_toks:=p;
10980 end
10981
10982 @ Here's part of the |expand| subroutine that we are now ready to complete:
10983
10984 @p procedure ins_the_toks;
10985 begin link(garbage):=the_toks; ins_list(link(temp_head));
10986 end;
10987
10988 @ The primitives \.{\\number}, \.{\\romannumeral}, \.{\\string}, \.{\\meaning},
10989 \.{\\fontname}, and \.{\\jobname} are defined as follows.
10990
10991 \eTeX\ adds \.{\\eTeXrevision} such that |job_name_code| remains last.
10992
10993 @d number_code=0 {command code for \.{\\number}}
10994 @d roman_numeral_code=1 {command code for \.{\\romannumeral}}
10995 @d string_code=2 {command code for \.{\\string}}
10996 @d meaning_code=3 {command code for \.{\\meaning}}
10997 @d font_name_code=4 {command code for \.{\\fontname}}
10998 @d etex_convert_base=5 {base for \eTeX's command codes}
10999 @d eTeX_revision_code=etex_convert_base {command code for \.{\\eTeXrevision}}
11000 @d etex_convert_codes=etex_convert_base+1 {end of \eTeX's command codes}
11001 @d expanded_code=etex_convert_codes {command code for \.{\\expanded}}
11002 @d pdftex_first_expand_code = expanded_code + 1 {base for \pdfTeX's command codes}
11003 @d left_margin_kern_code = pdftex_first_expand_code + 9 {command code for \.{\\leftmarginkern}}
11004 @d right_margin_kern_code = pdftex_first_expand_code + 10 {command code for \.{\\rightmarginkern}}
11005 @d pdf_strcmp_code = pdftex_first_expand_code + 11 {command code for \.{\\strcmp}}
11006 @d pdf_creation_date_code = pdftex_first_expand_code + 15 {command code for \.{\\creationdate}}
11007 @d pdf_file_mod_date_code = pdftex_first_expand_code + 16 {command code for \.{\\filemoddate}}
11008 @d pdf_file_size_code = pdftex_first_expand_code + 17 {command code for \.{\\filesize}}
11009 @d pdf_mdfive_sum_code = pdftex_first_expand_code + 18 {command code for \.{\\mdfivesum}}
11010 @d pdf_file_dump_code = pdftex_first_expand_code + 19 {command code for \.{\\filedump}}
11011 @d uniform_deviate_code = pdftex_first_expand_code + 22 {command code for \.{\\uniformdeviate}}
11012 @d normal_deviate_code = pdftex_first_expand_code + 23 {command code for \.{\\normaldeviate}}
11013 @d pdftex_convert_codes = pdftex_first_expand_code + 26 {end of \pdfTeX's command codes}
11014 @d XeTeX_first_expand_code = pdftex_convert_codes {base for \XeTeX's command codes}
11015 @d XeTeX_revision_code = XeTeX_first_expand_code + 0 {command code for \.{\\XeTeXrevision}}
11016 @d XeTeX_variation_name_code = XeTeX_first_expand_code + 1 {command code for \.{\\XeTeXvariationname}}
11017 @d XeTeX_feature_name_code = XeTeX_first_expand_code + 2 {command code for \.{\\XeTeXfeaturename}}
11018 @d XeTeX_selector_name_code = XeTeX_first_expand_code + 3 {command code for \.{\\XeTeXselectornamename}}
11019 @d XeTeX_glyph_name_code = XeTeX_first_expand_code + 4 {command code for \.{\\XeTeXglyphname}}
11020 @d XeTeX_Uchar_code = XeTeX_first_expand_code + 5 {command code for \.{\\Uchar}}
11021 @d XeTeX_Ucharcat_code = XeTeX_first_expand_code + 6 {command code for \.{\\Ucharcat}}
11022 @d XeTeX_convert_codes = XeTeX_first_expand_code + 7 {end of \XeTeX's command codes}
11023 @d job_name_code=XeTeX_convert_codes {command code for \.{\\jobname}}
11024
11025 @<Put each...@>=
11026 primitive("number",convert,number_code);@/
11027 @!@:number_}{\.{\\number} primitive@>
11028 primitive("romannumeral",convert,roman_numeral_code);@/
11029 @!@:roman_numeral_}{\.{\\romannumeral} primitive@>
11030 primitive("string",convert,string_code);@/
11031 @!@:string_}{\.{\\string} primitive@>
11032 primitive("meaning",convert,meaning_code);@/
11033 @!@:meaning_}{\.{\\meaning} primitive@>
11034 primitive("fontname",convert,font_name_code);@/
11035 @!@:font_name_}{\.{\\fontname} primitive@>
11036 @#
11037 @#
11038 primitive("expanded",convert,expanded_code);@/
11039 @!@:expanded_}{\.{\\expanded} primitive@>
11040 @#
11041 primitive("leftmarginkern",convert,left_margin_kern_code);@/
11042 @!@:left_margin_kern_}{\.{\\leftmarginkern} primitive@>
11043 primitive("rightmarginkern",convert,right_margin_kern_code);@/
11044 @!@:right_margin_kern_}{\.{\\rightmarginkern} primitive@>
11045 primitive("creationdate",convert,pdf_creation_date_code);@/
11046 @!@:pdf_creation_date_}{\.{\\creationdate} primitive@>
11047 primitive("filemoddate",convert,pdf_file_mod_date_code);@/
11048 @!@:pdf_file_mod_date_}{\.{\\filemoddate} primitive@>
11049 primitive("filesize",convert,pdf_file_size_code);@/
11050 @!@:pdf_file_size_}{\.{\\filesize} primitive@>
11051 primitive("mdfivesum",convert,pdf_mdfive_sum_code);@/
11052 @!@:pdf_mdfive_sum_}{\.{\\mdfivesum} primitive@>
11053 primitive("filedump",convert,pdf_file_dump_code);@/
11054 @!@:pdf_file_dump_}{\.{\\filedump} primitive@>
11055 primitive("strcmp",convert,pdf_strcmp_code);@/
11056 @!@:pdf_strcmp_}{\.{\\strcmp} primitive@>
11057 primitive("uniformdeviate",convert,uniform_deviate_code);@/
11058 @!@:uniform_deviate_}{\.{\\uniformdeviate} primitive@>
11059 primitive("normaldeviate",convert,normal_deviate_code);@/
11060 @!@:normal_deviate_}{\.{\\normaldeviate} primitive@>
11061
11062 @#
11063 primitive("jobname",convert,job_name_code);@/
11064 @!@:job_name_}{\.{\\jobname} primitive@>
11065
11066 primitive("Uchar",convert,XeTeX_Uchar_code);@/
11067 @!@:XeTeX_Uchar_}{\.{\\Uchar} primitive@>
11068 primitive("Ucharcat",convert,XeTeX_Ucharcat_code);@/
11069 @!@:XeTeX_Ucharcat_}{\.{\\Ucharcat} primitive@>
11070
11071 @ @<Cases of |print_cmd_chr|...@>=
11072 convert: case chr_code of
11073 number_code: print_esc("number");
11074 roman_numeral_code: print_esc("romannumeral");
11075 string_code: print_esc("string");
11076 meaning_code: print_esc("meaning");
11077 font_name_code: print_esc("fontname");
11078 eTeX_revision_code: print_esc("eTeXrevision");
11079 expanded_code: print_esc("expanded");
11080 left_margin_kern_code: print_esc("leftmarginkern");
11081 right_margin_kern_code: print_esc("rightmarginkern");
11082 pdf_creation_date_code: print_esc("creationdate");
11083 pdf_file_mod_date_code: print_esc("filemoddate");
11084 pdf_file_size_code: print_esc("filesize");
11085 pdf_mdfive_sum_code: print_esc("mdfivesum");
11086 pdf_file_dump_code: print_esc("filedump");
11087 pdf_strcmp_code: print_esc("strcmp");
11088 uniform_deviate_code: print_esc("uniformdeviate");
11089 normal_deviate_code: print_esc("normaldeviate");
11090 @/@<Cases of |convert| for |print_cmd_chr|@>@/
11091 othercases print_esc("jobname")
11092 endcases;
11093
11094 @ The procedure |conv_toks| uses |str_toks| to insert the token list
11095 for |convert| functions into the scanner; `\.{\\outer}' control sequences
11096 are allowed to follow `\.{\\string}' and `\.{\\meaning}'.
11097
11098 The extra temp string |u| is needed because |pdf_scan_ext_toks| incorporates
11099 any pending string in its output. In order to save such a pending string,
11100 we have to create a temporary string that is destroyed immediately after.
11101
11102 @d save_cur_string==if str_start_macro(str_ptr)<pool_ptr then u:=make_string else u:=0
11103 @d restore_cur_string==if u<>0 then decr(str_ptr)
11104
11105 @p procedure conv_toks;
11106 var old_setting:0..max_selector; {holds |selector| setting}
11107 @!save_warning_index, @!save_def_ref:pointer;
11108 @!boolvar: boolean; {temp boolean}
11109 @!s: str_number;
11110 @!u: str_number;
11111 @!j: integer;
11112 @!c:small_number; {desired type of conversion}
11113 @!save_scanner_status:small_number; {|scanner_status| upon entry}
11114 @!b:pool_pointer; {base of temporary string}
11115 @!fnt,@!arg1,@!arg2:integer; {args for \XeTeX\ extensions}
11116 @!font_name_str:str_number; {local vars for \.{\\fontname} quoting extension}
11117 @!i:small_number;
11118 @!quote_char:UTF16_code;
11119 @!cat:small_number; {desired catcode, or 0 for automatic |spacer|/|other_char| selection}
11120 @!saved_chr:UnicodeScalar;
11121 p, q: pointer;
11122 begin cat:=0; c:=cur_chr; @<Scan the argument for command |c|@>;
11123 old_setting:=selector; selector:=new_string; b:=pool_ptr;
11124 @<Print the result of command |c|@>;
11125 selector:=old_setting; link(garbage):=str_toks_cat(b,cat); ins_list(link(temp_head));
11126 end;
11127
11128 @ Not all catcode values are allowed by \.{\\Ucharcat}:
11129 @d illegal_Ucharcat_catcode(#)==(#<left_brace)or(#>active_char)or(#=out_param)or(#=ignore)
11130
11131 @<Scan the argument for command |c|@>=
11132 case c of
11133 number_code,roman_numeral_code: scan_int;
11134 string_code, meaning_code: begin save_scanner_status:=scanner_status;
11135 scanner_status:=normal; get_token; scanner_status:=save_scanner_status;
11136 end;
11137 font_name_code: scan_font_ident;
11138 eTeX_revision_code: do_nothing;
11139 expanded_code:
11140 begin
11141 save_scanner_status := scanner_status;
11142 save_warning_index := warning_index;
11143 save_def_ref := def_ref;
11144 save_cur_string;
11145 scan_pdf_ext_toks;
11146 warning_index := save_warning_index;
11147 scanner_status := save_scanner_status;
11148 ins_list(link(def_ref));
11149 free_avail(def_ref);
11150 def_ref := save_def_ref;
11151 restore_cur_string;
11152 return;
11153 end;
11154 left_margin_kern_code, right_margin_kern_code: begin
11155 scan_register_num;
11156 fetch_box(p);
11157 if (p = null) or (type(p) <> hlist_node) then
11158 pdf_error("marginkern", "a non-empty hbox expected")
11159 end;
11160 pdf_creation_date_code:
11161 begin
11162 b := pool_ptr;
11163 getcreationdate;
11164 link(garbage) := str_toks(b);
11165 ins_list(link(temp_head));
11166 return;
11167 end;
11168 pdf_file_mod_date_code:
11169 begin
11170 save_scanner_status := scanner_status;
11171 save_warning_index := warning_index;
11172 save_def_ref := def_ref;
11173 save_cur_string;
11174 scan_pdf_ext_toks;
11175
11176 if selector = new_string then
11177 pdf_error("tokens", "tokens_to_string() called while selector = new_string");
11178 old_setting:=selector; selector:=new_string;
11179 show_token_list(link(def_ref),null,pool_size-pool_ptr);
11180 selector:=old_setting;
11181 s:=make_string;
11182
11183 delete_token_ref(def_ref);
11184 def_ref := save_def_ref;
11185 warning_index := save_warning_index;
11186 scanner_status := save_scanner_status;
11187 b := pool_ptr;
11188 getfilemoddate(s);
11189 link(garbage) := str_toks(b);
11190
11191 if flushable(s) then
11192 flush_string;
11193
11194 ins_list(link(temp_head));
11195 restore_cur_string;
11196 return;
11197 end;
11198 pdf_file_size_code:
11199 begin
11200 save_scanner_status := scanner_status;
11201 save_warning_index := warning_index;
11202 save_def_ref := def_ref;
11203 save_cur_string;
11204 scan_pdf_ext_toks;
11205
11206 if selector = new_string then
11207 pdf_error("tokens", "tokens_to_string() called while selector = new_string");
11208 old_setting:=selector; selector:=new_string;
11209 show_token_list(link(def_ref),null,pool_size-pool_ptr);
11210 selector:=old_setting;
11211 s:=make_string;
11212
11213 delete_token_ref(def_ref);
11214 def_ref := save_def_ref;
11215 warning_index := save_warning_index;
11216 scanner_status := save_scanner_status;
11217 b := pool_ptr;
11218 getfilesize(s);
11219 link(garbage) := str_toks(b);
11220
11221 if flushable(s) then
11222 flush_string;
11223
11224 ins_list(link(temp_head));
11225 restore_cur_string;
11226 return;
11227 end;
11228 pdf_mdfive_sum_code:
11229 begin
11230 save_scanner_status := scanner_status;
11231 save_warning_index := warning_index;
11232 save_def_ref := def_ref;
11233 save_cur_string;
11234 boolvar := scan_keyword("file");
11235 scan_pdf_ext_toks;
11236
11237 if selector = new_string then
11238 pdf_error("tokens", "tokens_to_string() called while selector = new_string");
11239 old_setting:=selector; selector:=new_string;
11240 show_token_list(link(def_ref),null,pool_size-pool_ptr);
11241 selector:=old_setting;
11242 s:=make_string;
11243
11244 delete_token_ref(def_ref);
11245 def_ref := save_def_ref;
11246 warning_index := save_warning_index;
11247 scanner_status := save_scanner_status;
11248 b := pool_ptr;
11249 getmd5sum(s, boolvar);
11250 link(garbage) := str_toks(b);
11251
11252 if flushable(s) then
11253 flush_string;
11254
11255 ins_list(link(temp_head));
11256 restore_cur_string;
11257 return;
11258 end;
11259 pdf_file_dump_code:
11260 begin
11261 save_scanner_status := scanner_status;
11262 save_warning_index := warning_index;
11263 save_def_ref := def_ref;
11264 save_cur_string;
11265 {scan offset}
11266 cur_val := 0;
11267 if (scan_keyword("offset")) then begin
11268 scan_int;
11269 if (cur_val < 0) then begin
11270 print_err("Bad file offset");
11271 @.Bad file offset@>
11272 help2("A file offset must be between 0 and 2^{31}-1,")@/
11273 ("I changed this one to zero.");
11274 int_error(cur_val);
11275 cur_val := 0;
11276 end;
11277 end;
11278 i := cur_val;
11279 {scan length}
11280 cur_val := 0;
11281 if (scan_keyword("length")) then begin
11282 scan_int;
11283 if (cur_val < 0) then begin
11284 print_err("Bad dump length");
11285 @.Bad dump length@>
11286 help2("A dump length must be between 0 and 2^{31}-1,")@/
11287 ("I changed this one to zero.");
11288 int_error(cur_val);
11289 cur_val := 0;
11290 end;
11291 end;
11292 j := cur_val;
11293 {scan file name}
11294 scan_pdf_ext_toks;
11295
11296 if selector = new_string then
11297 pdf_error("tokens", "tokens_to_string() called while selector = new_string");
11298 old_setting:=selector; selector:=new_string;
11299 show_token_list(link(def_ref),null,pool_size-pool_ptr);
11300 selector:=old_setting;
11301 s:=make_string;
11302
11303 delete_token_ref(def_ref);
11304 def_ref := save_def_ref;
11305 warning_index := save_warning_index;
11306 scanner_status := save_scanner_status;
11307 b := pool_ptr;
11308 getfiledump(s, i, j);
11309 link(garbage) := str_toks(b);
11310
11311 if flushable(s) then
11312 flush_string;
11313
11314 ins_list(link(temp_head));
11315 restore_cur_string;
11316 return;
11317 end;
11318 pdf_strcmp_code:
11319 begin
11320 save_scanner_status:=scanner_status;
11321 save_warning_index:=warning_index;
11322 save_def_ref:=def_ref;
11323 save_cur_string;
11324 compare_strings;
11325 def_ref:=save_def_ref;
11326 warning_index:=save_warning_index;
11327 scanner_status:=save_scanner_status;
11328 restore_cur_string;
11329 end;
11330 XeTeX_Uchar_code: scan_usv_num;
11331 XeTeX_Ucharcat_code:
11332 begin
11333 scan_usv_num;
11334 saved_chr:=cur_val;
11335 scan_int;
11336 if illegal_Ucharcat_catcode(cur_val) then
11337 begin print_err("Invalid code ("); print_int(cur_val);
11338 @.Invalid code@>
11339 print("), should be in the ranges 1..4, 6..8, 10..13");
11340 help1("I'm going to use 12 instead of that illegal code value.");@/
11341 error; cat:=12;
11342 end else
11343 cat:=cur_val;
11344 cur_val:=saved_chr;
11345 end;
11346 @/@<Cases of `Scan the argument for command |c|'@>@/
11347 job_name_code: if job_name=0 then open_log_file;
11348 uniform_deviate_code: scan_int;
11349 normal_deviate_code: do_nothing;
11350 end {there are no other cases}
11351
11352 @ @<Print the result of command |c|@>=
11353 case c of
11354 number_code: print_int(cur_val);
11355 roman_numeral_code: print_roman_int(cur_val);
11356 string_code:if cur_cs<>0 then sprint_cs(cur_cs)
11357 else print_char(cur_chr);
11358 meaning_code: print_meaning;
11359 font_name_code: begin
11360 font_name_str:=font_name[cur_val];
11361 if is_native_font(cur_val) then begin
11362 quote_char:="""";
11363 for i:=0 to length(font_name_str) - 1 do
11364 if str_pool[str_start_macro(font_name_str) + i] = """" then quote_char:="'";
11365 print_char(quote_char);
11366 print(font_name_str);
11367 print_char(quote_char);
11368 end else
11369 print(font_name_str);
11370 if font_size[cur_val]<>font_dsize[cur_val] then
11371 begin print(" at "); print_scaled(font_size[cur_val]);
11372 print("pt");
11373 end;
11374 end;
11375 eTeX_revision_code: print(eTeX_revision);
11376 left_margin_kern_code: begin
11377 p:=list_ptr(p);
11378 while (p <> null) and
11379 (cp_skipable(p) or
11380 ((not is_char_node(p)) and (type(p) = glue_node) and (subtype(p) = left_skip_code + 1)))
11381 do
11382 p:=link(p);
11383 if (p <> null) and (not is_char_node(p)) and (type(p) = margin_kern_node) and (subtype(p) = left_side) then
11384 print_scaled(width(p))
11385 else
11386 print("0");
11387 print("pt");
11388 end;
11389 right_margin_kern_code: begin
11390 q:=list_ptr(p);
11391 p:=prev_rightmost(q, null);
11392 while (p <> null) and
11393 (cp_skipable(p) or
11394 ((not is_char_node(p)) and (type(p) = glue_node) and (subtype(p) = right_skip_code + 1)))
11395 do
11396 p:=prev_rightmost(q, p);
11397 if (p <> null) and (not is_char_node(p)) and (type(p) = margin_kern_node) and (subtype(p) = right_side) then
11398 print_scaled(width(p))
11399 else
11400 print("0");
11401 print("pt");
11402 end;
11403 pdf_strcmp_code: print_int(cur_val);
11404 uniform_deviate_code: print_int(unif_rand(cur_val));
11405 normal_deviate_code: print_int(norm_rand);
11406 XeTeX_Uchar_code,
11407 XeTeX_Ucharcat_code: print_char(cur_val);
11408 @/@<Cases of `Print the result of command |c|'@>@/
11409 job_name_code: print_file_name(job_name, 0, 0);
11410 end {there are no other cases}
11411
11412 @ Now we can't postpone the difficulties any longer; we must bravely tackle
11413 |scan_toks|. This function returns a pointer to the tail of a new token
11414 list, and it also makes |def_ref| point to the reference count at the
11415 head of that list.
11416
11417 There are two boolean parameters, |macro_def| and |xpand|. If |macro_def|
11418 is true, the goal is to create the token list for a macro definition;
11419 otherwise the goal is to create the token list for some other \TeX\
11420 primitive: \.{\\mark}, \.{\\output}, \.{\\everypar}, \.{\\lowercase},
11421 \.{\\uppercase}, \.{\\message}, \.{\\errmessage}, \.{\\write}, or
11422 \.{\\special}. In the latter cases a left brace must be scanned next; this
11423 left brace will not be part of the token list, nor will the matching right
11424 brace that comes at the end. If |xpand| is false, the token list will
11425 simply be copied from the input using |get_token|. Otherwise all expandable
11426 tokens will be expanded until unexpandable tokens are left, except that
11427 the results of expanding `\.{\\the}' are not expanded further.
11428 If both |macro_def| and |xpand| are true, the expansion applies
11429 only to the macro body (i.e., to the material following the first
11430 |left_brace| character).
11431
11432 The value of |cur_cs| when |scan_toks| begins should be the |eqtb|
11433 address of the control sequence to display in ``runaway'' error
11434 messages.
11435
11436 @p function scan_toks(@!macro_def,@!xpand:boolean):pointer;
11437 label found,continue,done,done1,done2;
11438 var t:halfword; {token representing the highest parameter number}
11439 @!s:halfword; {saved token}
11440 @!p:pointer; {tail of the token list being built}
11441 @!q:pointer; {new node being added to the token list via |store_new_token|}
11442 @!unbalance:halfword; {number of unmatched left braces}
11443 @!hash_brace:halfword; {possible `\.{\#\{}' token}
11444 begin if macro_def then scanner_status:=defining
11445 @+else scanner_status:=absorbing;
11446 warning_index:=cur_cs; def_ref:=get_avail; token_ref_count(def_ref):=null;
11447 p:=def_ref; hash_brace:=0; t:=zero_token;
11448 if macro_def then @<Scan and build the parameter part of the macro definition@>
11449 else scan_left_brace; {remove the compulsory left brace}
11450 @<Scan and build the body of the token list; |goto found| when finished@>;
11451 found: scanner_status:=normal;
11452 if hash_brace<>0 then store_new_token(hash_brace);
11453 scan_toks:=p;
11454 end;
11455
11456 @ @<Scan and build the parameter part...@>=
11457 begin loop begin continue: get_token; {set |cur_cmd|, |cur_chr|, |cur_tok|}
11458 if cur_tok<right_brace_limit then goto done1;
11459 if cur_cmd=mac_param then
11460 @<If the next character is a parameter number, make |cur_tok|
11461 a |match| token; but if it is a left brace, store
11462 `|left_brace|, |end_match|', set |hash_brace|, and |goto done|@>;
11463 store_new_token(cur_tok);
11464 end;
11465 done1: store_new_token(end_match_token);
11466 if cur_cmd=right_brace then
11467 @<Express shock at the missing left brace; |goto found|@>;
11468 done: end
11469
11470 @ @<Express shock...@>=
11471 begin print_err("Missing { inserted"); incr(align_state);
11472 @.Missing \{ inserted@>
11473 help2("Where was the left brace? You said something like `\def\a}',")@/
11474 ("which I'm going to interpret as `\def\a{}'."); error; goto found;
11475 end
11476
11477 @ @<If the next character is a parameter number...@>=
11478 begin s:=match_token+cur_chr; get_token;
11479 if cur_tok<left_brace_limit then
11480 begin hash_brace:=cur_tok;
11481 store_new_token(cur_tok); store_new_token(end_match_token);
11482 goto done;
11483 end;
11484 if t=zero_token+9 then
11485 begin print_err("You already have nine parameters");
11486 @.You already have nine...@>
11487 help2("I'm going to ignore the # sign you just used,")@/
11488 ("as well as the token that followed it."); error; goto continue;
11489 end
11490 else begin incr(t);
11491 if cur_tok<>t then
11492 begin print_err("Parameters must be numbered consecutively");
11493 @.Parameters...consecutively@>
11494 help2("I've inserted the digit you should have used after the #.")@/
11495 ("Type `1' to delete what you did use."); back_error;
11496 end;
11497 cur_tok:=s;
11498 end;
11499 end
11500
11501 @ @<Scan and build the body of the token list; |goto found| when finished@>=
11502 unbalance:=1;
11503 loop@+ begin if xpand then @<Expand the next part of the input@>
11504 else get_token;
11505 if cur_tok<right_brace_limit then
11506 if cur_cmd<right_brace then incr(unbalance)
11507 else begin decr(unbalance);
11508 if unbalance=0 then goto found;
11509 end
11510 else if cur_cmd=mac_param then
11511 if macro_def then @<Look for parameter number or \.{\#\#}@>;
11512 store_new_token(cur_tok);
11513 end
11514
11515 @ Here we insert an entire token list created by |the_toks| without
11516 expanding it further.
11517
11518 @<Expand the next part of the input@>=
11519 begin loop begin get_next;
11520 if cur_cmd>=call then
11521 if info(link(cur_chr))=protected_token then
11522 begin cur_cmd:=relax; cur_chr:=no_expand_flag;
11523 end;
11524 if cur_cmd<=max_command then goto done2;
11525 if cur_cmd<>the then expand
11526 else begin q:=the_toks;
11527 if link(temp_head)<>null then
11528 begin link(p):=link(temp_head); p:=q;
11529 end;
11530 end;
11531 end;
11532 done2: x_token
11533 end
11534
11535 @ @<Look for parameter number...@>=
11536 begin s:=cur_tok;
11537 if xpand then get_x_token else get_token;
11538 if cur_cmd<>mac_param then
11539 if (cur_tok<=zero_token)or(cur_tok>t) then
11540 begin print_err("Illegal parameter number in definition of ");
11541 @.Illegal parameter number...@>
11542 sprint_cs(warning_index);
11543 help3("You meant to type ## instead of #, right?")@/
11544 ("Or maybe a } was forgotten somewhere earlier, and things")@/
11545 ("are all screwed up? I'm going to assume that you meant ##.");
11546 back_error; cur_tok:=s;
11547 end
11548 else cur_tok:=out_param_token-"0"+cur_chr;
11549 end
11550
11551 @ Another way to create a token list is via the \.{\\read} command. The
11552 sixteen files potentially usable for reading appear in the following
11553 global variables. The value of |read_open[n]| will be |closed| if
11554 stream number |n| has not been opened or if it has been fully read;
11555 |just_open| if an \.{\\openin} but not a \.{\\read} has been done;
11556 and |normal| if it is open and ready to read the next line.
11557
11558 @d closed=2 {not open, or at end of file}
11559 @d just_open=1 {newly opened, first line not yet read}
11560
11561 @<Glob...@>=
11562 @!read_file:array[0..15] of unicode_file; {used for \.{\\read}}
11563 @!read_open:array[0..16] of normal..closed; {state of |read_file[n]|}
11564
11565 @ @<Set init...@>=
11566 for k:=0 to 16 do read_open[k]:=closed;
11567
11568 @ The |read_toks| procedure constructs a token list like that for any
11569 macro definition, and makes |cur_val| point to it. Parameter |r| points
11570 to the control sequence that will receive this token list.
11571
11572 @p procedure read_toks(@!n:integer;@!r:pointer;@!j:halfword);
11573 label done;
11574 var p:pointer; {tail of the token list}
11575 @!q:pointer; {new node being added to the token list via |store_new_token|}
11576 @!s:integer; {saved value of |align_state|}
11577 @!m:small_number; {stream number}
11578 begin scanner_status:=defining; warning_index:=r;
11579 def_ref:=get_avail; token_ref_count(def_ref):=null;
11580 p:=def_ref; {the reference count}
11581 store_new_token(end_match_token);
11582 if (n<0)or(n>15) then m:=16@+else m:=n;
11583 s:=align_state; align_state:=1000000; {disable tab marks, etc.}
11584 repeat @<Input and store tokens from the next line of the file@>;
11585 until align_state=1000000;
11586 cur_val:=def_ref; scanner_status:=normal; align_state:=s;
11587 end;
11588
11589 @ @<Input and store tokens from the next line of the file@>=
11590 begin_file_reading; name:=m+1;
11591 if read_open[m]=closed then @<Input for \.{\\read} from the terminal@>
11592 else if read_open[m]=just_open then @<Input the first line of |read_file[m]|@>
11593 else @<Input the next line of |read_file[m]|@>;
11594 limit:=last;
11595 if end_line_char_inactive then decr(limit)
11596 else buffer[limit]:=end_line_char;
11597 first:=limit+1; loc:=start; state:=new_line;@/
11598 @<Handle \.{\\readline} and |goto done|@>;@/
11599 loop@+ begin get_token;
11600 if cur_tok=0 then goto done;
11601 {|cur_cmd=cur_chr=0| will occur at the end of the line}
11602 if align_state<1000000 then {unmatched `\.\}' aborts the line}
11603 begin repeat get_token; until cur_tok=0;
11604 align_state:=1000000; goto done;
11605 end;
11606 store_new_token(cur_tok);
11607 end;
11608 done: end_file_reading
11609
11610 @ Here we input on-line into the |buffer| array, prompting the user explicitly
11611 if |n>=0|. The value of |n| is set negative so that additional prompts
11612 will not be given in the case of multi-line input.
11613
11614 @<Input for \.{\\read} from the terminal@>=
11615 if interaction>nonstop_mode then
11616 if n<0 then prompt_input("")
11617 else begin wake_up_terminal;
11618 print_ln; sprint_cs(r); prompt_input("="); n:=-1;
11619 end
11620 else fatal_error("*** (cannot \read from terminal in nonstop modes)")
11621 @.cannot \\read@>
11622
11623 @ The first line of a file must be treated specially, since |input_ln|
11624 must be told not to start with |get|.
11625 @^system dependencies@>
11626
11627 @<Input the first line of |read_file[m]|@>=
11628 if input_ln(read_file[m],false) then read_open[m]:=normal
11629 else begin u_close(read_file[m]); read_open[m]:=closed;
11630 end
11631
11632 @ An empty line is appended at the end of a |read_file|.
11633 @^empty line at end of file@>
11634
11635 @<Input the next line of |read_file[m]|@>=
11636 begin if not input_ln(read_file[m],true) then
11637 begin u_close(read_file[m]); read_open[m]:=closed;
11638 if align_state<>1000000 then
11639 begin runaway;
11640 print_err("File ended within "); print_esc("read");
11641 @.File ended within \\read@>
11642 help1("This \read has unbalanced braces.");
11643 align_state:=1000000; limit:=0; error;
11644 end;
11645 end;
11646 end
11647
11648 @* \[28] Conditional processing.
11649 We consider now the way \TeX\ handles various kinds of \.{\\if} commands.
11650
11651 @d unless_code=32 {amount added for `\.{\\unless}' prefix}
11652 @#
11653 @d if_char_code=0 { `\.{\\if}' }
11654 @d if_cat_code=1 { `\.{\\ifcat}' }
11655 @d if_int_code=2 { `\.{\\ifnum}' }
11656 @d if_dim_code=3 { `\.{\\ifdim}' }
11657 @d if_odd_code=4 { `\.{\\ifodd}' }
11658 @d if_vmode_code=5 { `\.{\\ifvmode}' }
11659 @d if_hmode_code=6 { `\.{\\ifhmode}' }
11660 @d if_mmode_code=7 { `\.{\\ifmmode}' }
11661 @d if_inner_code=8 { `\.{\\ifinner}' }
11662 @d if_void_code=9 { `\.{\\ifvoid}' }
11663 @d if_hbox_code=10 { `\.{\\ifhbox}' }
11664 @d if_vbox_code=11 { `\.{\\ifvbox}' }
11665 @d ifx_code=12 { `\.{\\ifx}' }
11666 @d if_eof_code=13 { `\.{\\ifeof}' }
11667 @d if_true_code=14 { `\.{\\iftrue}' }
11668 @d if_false_code=15 { `\.{\\iffalse}' }
11669 @d if_case_code=16 { `\.{\\ifcase}' }
11670 @d if_primitive_code=21 { `\.{\\ifprimitive}' }
11671
11672 @<Put each...@>=
11673 primitive("if",if_test,if_char_code);
11674 @!@:if_char_}{\.{\\if} primitive@>
11675 primitive("ifcat",if_test,if_cat_code);
11676 @!@:if_cat_code_}{\.{\\ifcat} primitive@>
11677 primitive("ifnum",if_test,if_int_code);
11678 @!@:if_int_}{\.{\\ifnum} primitive@>
11679 primitive("ifdim",if_test,if_dim_code);
11680 @!@:if_dim_}{\.{\\ifdim} primitive@>
11681 primitive("ifodd",if_test,if_odd_code);
11682 @!@:if_odd_}{\.{\\ifodd} primitive@>
11683 primitive("ifvmode",if_test,if_vmode_code);
11684 @!@:if_vmode_}{\.{\\ifvmode} primitive@>
11685 primitive("ifhmode",if_test,if_hmode_code);
11686 @!@:if_hmode_}{\.{\\ifhmode} primitive@>
11687 primitive("ifmmode",if_test,if_mmode_code);
11688 @!@:if_mmode_}{\.{\\ifmmode} primitive@>
11689 primitive("ifinner",if_test,if_inner_code);
11690 @!@:if_inner_}{\.{\\ifinner} primitive@>
11691 primitive("ifvoid",if_test,if_void_code);
11692 @!@:if_void_}{\.{\\ifvoid} primitive@>
11693 primitive("ifhbox",if_test,if_hbox_code);
11694 @!@:if_hbox_}{\.{\\ifhbox} primitive@>
11695 primitive("ifvbox",if_test,if_vbox_code);
11696 @!@:if_vbox_}{\.{\\ifvbox} primitive@>
11697 primitive("ifx",if_test,ifx_code);
11698 @!@:ifx_}{\.{\\ifx} primitive@>
11699 primitive("ifeof",if_test,if_eof_code);
11700 @!@:if_eof_}{\.{\\ifeof} primitive@>
11701 primitive("iftrue",if_test,if_true_code);
11702 @!@:if_true_}{\.{\\iftrue} primitive@>
11703 primitive("iffalse",if_test,if_false_code);
11704 @!@:if_false_}{\.{\\iffalse} primitive@>
11705 primitive("ifcase",if_test,if_case_code);
11706 @!@:if_case_}{\.{\\ifcase} primitive@>
11707 primitive("ifprimitive",if_test,if_primitive_code);
11708 @!@:if_primitive_}{\.{\\ifprimitive} primitive@>
11709
11710 @ @<Cases of |print_cmd_chr|...@>=
11711 if_test: begin if chr_code>=unless_code then print_esc("unless");
11712 case chr_code mod unless_code of
11713 if_cat_code:print_esc("ifcat");
11714 if_int_code:print_esc("ifnum");
11715 if_dim_code:print_esc("ifdim");
11716 if_odd_code:print_esc("ifodd");
11717 if_vmode_code:print_esc("ifvmode");
11718 if_hmode_code:print_esc("ifhmode");
11719 if_mmode_code:print_esc("ifmmode");
11720 if_inner_code:print_esc("ifinner");
11721 if_void_code:print_esc("ifvoid");
11722 if_hbox_code:print_esc("ifhbox");
11723 if_vbox_code:print_esc("ifvbox");
11724 ifx_code:print_esc("ifx");
11725 if_eof_code:print_esc("ifeof");
11726 if_true_code:print_esc("iftrue");
11727 if_false_code:print_esc("iffalse");
11728 if_case_code:print_esc("ifcase");
11729 if_primitive_code:print_esc("ifprimitive");
11730 @/@<Cases of |if_test| for |print_cmd_chr|@>@/
11731 othercases print_esc("if")
11732 endcases;
11733 end;
11734
11735 @ Conditions can be inside conditions, and this nesting has a stack
11736 that is independent of the |save_stack|.
11737
11738 Four global variables represent the top of the condition stack:
11739 |cond_ptr| points to pushed-down entries, if any; |if_limit| specifies
11740 the largest code of a |fi_or_else| command that is syntactically legal;
11741 |cur_if| is the name of the current type of conditional; and |if_line|
11742 is the line number at which it began.
11743
11744 If no conditions are currently in progress, the condition stack has the
11745 special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
11746 Otherwise |cond_ptr| points to a two-word node; the |type|, |subtype|, and
11747 |link| fields of the first word contain |if_limit|, |cur_if|, and
11748 |cond_ptr| at the next level, and the second word contains the
11749 corresponding |if_line|.
11750
11751 @d if_node_size=2 {number of words in stack entry for conditionals}
11752 @d if_line_field(#)==mem[#+1].int
11753 @d if_code=1 {code for \.{\\if...} being evaluated}
11754 @d fi_code=2 {code for \.{\\fi}}
11755 @d else_code=3 {code for \.{\\else}}
11756 @d or_code=4 {code for \.{\\or}}
11757
11758 @<Glob...@>=
11759 @!cond_ptr:pointer; {top of the condition stack}
11760 @!if_limit:normal..or_code; {upper bound on |fi_or_else| codes}
11761 @!cur_if:small_number; {type of conditional being worked on}
11762 @!if_line:integer; {line where that conditional began}
11763
11764 @ @<Set init...@>=
11765 cond_ptr:=null; if_limit:=normal; cur_if:=0; if_line:=0;
11766
11767 @ @<Put each...@>=
11768 primitive("fi",fi_or_else,fi_code);
11769 @!@:fi_}{\.{\\fi} primitive@>
11770 text(frozen_fi):="fi"; eqtb[frozen_fi]:=eqtb[cur_val];
11771 primitive("or",fi_or_else,or_code);
11772 @!@:or_}{\.{\\or} primitive@>
11773 primitive("else",fi_or_else,else_code);
11774 @!@:else_}{\.{\\else} primitive@>
11775
11776 @ @<Cases of |print_cmd_chr|...@>=
11777 fi_or_else: if chr_code=fi_code then print_esc("fi")
11778 else if chr_code=or_code then print_esc("or")
11779 else print_esc("else");
11780
11781 @ When we skip conditional text, we keep track of the line number
11782 where skipping began, for use in error messages.
11783
11784 @<Glob...@>=
11785 @!skip_line:integer; {skipping began here}
11786
11787 @ Here is a procedure that ignores text until coming to an \.{\\or},
11788 \.{\\else}, or \.{\\fi} at the current level of $\.{\\if}\ldots\.{\\fi}$
11789 nesting. After it has acted, |cur_chr| will indicate the token that
11790 was found, but |cur_tok| will not be set (because this makes the
11791 procedure run faster).
11792
11793 @p procedure pass_text;
11794 label done;
11795 var l:integer; {level of $\.{\\if}\ldots\.{\\fi}$ nesting}
11796 @!save_scanner_status:small_number; {|scanner_status| upon entry}
11797 begin save_scanner_status:=scanner_status; scanner_status:=skipping; l:=0;
11798 skip_line:=line;
11799 loop@+ begin get_next;
11800 if cur_cmd=fi_or_else then
11801 begin if l=0 then goto done;
11802 if cur_chr=fi_code then decr(l);
11803 end
11804 else if cur_cmd=if_test then incr(l);
11805 end;
11806 done: scanner_status:=save_scanner_status;
11807 if tracing_ifs>0 then show_cur_cmd_chr;
11808 end;
11809
11810 @ When we begin to process a new \.{\\if}, we set |if_limit:=if_code|; then
11811 if\/ \.{\\or} or \.{\\else} or \.{\\fi} occurs before the current \.{\\if}
11812 condition has been evaluated, \.{\\relax} will be inserted.
11813 For example, a sequence of commands like `\.{\\ifvoid1\\else...\\fi}'
11814 would otherwise require something after the `\.1'.
11815
11816 @<Push the condition stack@>=
11817 begin p:=get_node(if_node_size); link(p):=cond_ptr; type(p):=if_limit;
11818 subtype(p):=cur_if; if_line_field(p):=if_line;
11819 cond_ptr:=p; cur_if:=cur_chr; if_limit:=if_code; if_line:=line;
11820 end
11821
11822 @ @<Pop the condition stack@>=
11823 begin if if_stack[in_open]=cond_ptr then if_warning;
11824 {conditionals possibly not properly nested with files}
11825 p:=cond_ptr; if_line:=if_line_field(p);
11826 cur_if:=subtype(p); if_limit:=type(p); cond_ptr:=link(p);
11827 free_node(p,if_node_size);
11828 end
11829
11830 @ Here's a procedure that changes the |if_limit| code corresponding to
11831 a given value of |cond_ptr|.
11832
11833 @p procedure change_if_limit(@!l:small_number;@!p:pointer);
11834 label exit;
11835 var q:pointer;
11836 begin if p=cond_ptr then if_limit:=l {that's the easy case}
11837 else begin q:=cond_ptr;
11838 loop@+ begin if q=null then confusion("if");
11839 @:this can't happen if}{\quad if@>
11840 if link(q)=p then
11841 begin type(q):=l; return;
11842 end;
11843 q:=link(q);
11844 end;
11845 end;
11846 exit:end;
11847
11848 @ A condition is started when the |expand| procedure encounters
11849 an |if_test| command; in that case |expand| reduces to |conditional|,
11850 which is a recursive procedure.
11851 @^recursion@>
11852
11853 @p procedure conditional;
11854 label exit,common_ending;
11855 var b:boolean; {is the condition true?}
11856 @!e:boolean; {keep track of nested csnames}
11857 @!r:"<"..">"; {relation to be evaluated}
11858 @!m,@!n:integer; {to be tested against the second operand}
11859 @!p,@!q:pointer; {for traversing token lists in \.{\\ifx} tests}
11860 @!save_scanner_status:small_number; {|scanner_status| upon entry}
11861 @!save_cond_ptr:pointer; {|cond_ptr| corresponding to this conditional}
11862 @!this_if:small_number; {type of this conditional}
11863 @!is_unless:boolean; {was this if preceded by `\.{\\unless}' ?}
11864 begin if tracing_ifs>0 then if tracing_commands<=1 then show_cur_cmd_chr;
11865 @<Push the condition stack@>;@+save_cond_ptr:=cond_ptr;
11866 is_unless:=(cur_chr>=unless_code); this_if:=cur_chr mod unless_code;@/
11867 @<Either process \.{\\ifcase} or set |b| to the value of a boolean condition@>;
11868 if is_unless then b:=not b;
11869 if tracing_commands>1 then @<Display the value of |b|@>;
11870 if b then
11871 begin change_if_limit(else_code,save_cond_ptr);
11872 return; {wait for \.{\\else} or \.{\\fi}}
11873 end;
11874 @<Skip to \.{\\else} or \.{\\fi}, then |goto common_ending|@>;
11875 common_ending: if cur_chr=fi_code then @<Pop the condition stack@>
11876 else if_limit:=fi_code; {wait for \.{\\fi}}
11877 exit:end;
11878
11879 @ In a construction like `\.{\\if\\iftrue abc\\else d\\fi}', the first
11880 \.{\\else} that we come to after learning that the \.{\\if} is false is
11881 not the \.{\\else} we're looking for. Hence the following curious
11882 logic is needed.
11883
11884 @ @<Skip to \.{\\else} or \.{\\fi}...@>=
11885 loop@+ begin pass_text;
11886 if cond_ptr=save_cond_ptr then
11887 begin if cur_chr<>or_code then goto common_ending;
11888 print_err("Extra "); print_esc("or");
11889 @.Extra \\or@>
11890 help1("I'm ignoring this; it doesn't match any \if.");
11891 error;
11892 end
11893 else if cur_chr=fi_code then @<Pop the condition stack@>;
11894 end
11895
11896 @ @<Either process \.{\\ifcase} or set |b|...@>=
11897 case this_if of
11898 if_char_code, if_cat_code: @<Test if two characters match@>;
11899 if_int_code, if_dim_code: @<Test relation between integers or dimensions@>;
11900 if_odd_code: @<Test if an integer is odd@>;
11901 if_vmode_code: b:=(abs(mode)=vmode);
11902 if_hmode_code: b:=(abs(mode)=hmode);
11903 if_mmode_code: b:=(abs(mode)=mmode);
11904 if_inner_code: b:=(mode<0);
11905 if_void_code, if_hbox_code, if_vbox_code: @<Test box register status@>;
11906 ifx_code: @<Test if two tokens match@>;
11907 if_eof_code: begin scan_four_bit_int; b:=(read_open[cur_val]=closed);
11908 end;
11909 if_true_code: b:=true;
11910 if_false_code: b:=false;
11911 @/@<Cases for |conditional|@>@/
11912 if_case_code: @<Select the appropriate case
11913 and |return| or |goto common_ending|@>;
11914 if_primitive_code: begin
11915 save_scanner_status:=scanner_status;
11916 scanner_status:=normal;
11917 get_next;
11918 scanner_status:=save_scanner_status;
11919 if cur_cs < hash_base then
11920 m:=prim_lookup(cur_cs-single_base)
11921 else
11922 m:=prim_lookup(text(cur_cs));
11923 b :=((cur_cmd<>undefined_cs) and
11924 (m<>undefined_primitive) and
11925 (cur_cmd=prim_eq_type(m)) and
11926 (cur_chr=prim_equiv(m)));
11927 end;
11928 end {there are no other cases}
11929
11930 @ @<Display the value of |b|@>=
11931 begin begin_diagnostic;
11932 if b then print("{true}")@+else print("{false}");
11933 end_diagnostic(false);
11934 end
11935
11936 @ Here we use the fact that |"<"|, |"="|, and |">"| are consecutive ASCII
11937 codes.
11938 @^ASCII code@>
11939
11940 @<Test relation between integers or dimensions@>=
11941 begin if this_if=if_int_code then scan_int@+else scan_normal_dimen;
11942 n:=cur_val; @<Get the next non-blank non-call...@>;
11943 if (cur_tok>=other_token+"<")and(cur_tok<=other_token+">") then
11944 r:=cur_tok-other_token
11945 else begin print_err("Missing = inserted for ");
11946 @.Missing = inserted@>
11947 print_cmd_chr(if_test,this_if);
11948 help1("I was expecting to see `<', `=', or `>'. Didn't.");
11949 back_error; r:="=";
11950 end;
11951 if this_if=if_int_code then scan_int@+else scan_normal_dimen;
11952 case r of
11953 "<": b:=(n<cur_val);
11954 "=": b:=(n=cur_val);
11955 ">": b:=(n>cur_val);
11956 end;
11957 end
11958
11959 @ @<Test if an integer is odd@>=
11960 begin scan_int; b:=odd(cur_val);
11961 end
11962
11963 @ @<Test box register status@>=
11964 begin scan_register_num; fetch_box(p);
11965 if this_if=if_void_code then b:=(p=null)
11966 else if p=null then b:=false
11967 else if this_if=if_hbox_code then b:=(type(p)=hlist_node)
11968 else b:=(type(p)=vlist_node);
11969 end
11970
11971 @ An active character will be treated as category 13 following
11972 \.{\\if\\noexpand} or following \.{\\ifcat\\noexpand}. We use the fact that
11973 active characters have the smallest tokens, among all control sequences.
11974
11975 @d get_x_token_or_active_char==@t@>@;
11976 begin get_x_token;
11977 if cur_cmd=relax then if cur_chr=no_expand_flag then
11978 begin cur_cmd:=active_char;
11979 cur_chr:=cur_tok-cs_token_flag-active_base;
11980 end;
11981 end
11982
11983 @<Test if two characters match@>=
11984 begin get_x_token_or_active_char;
11985 if (cur_cmd>active_char)or(cur_chr>biggest_usv) then {not a character}
11986 begin m:=relax; n:=too_big_usv;
11987 end
11988 else begin m:=cur_cmd; n:=cur_chr;
11989 end;
11990 get_x_token_or_active_char;
11991 if (cur_cmd>active_char)or(cur_chr>biggest_usv) then
11992 begin cur_cmd:=relax; cur_chr:=too_big_usv;
11993 end;
11994 if this_if=if_char_code then b:=(n=cur_chr)@+else b:=(m=cur_cmd);
11995 end
11996
11997 @ Note that `\.{\\ifx}' will declare two macros different if one is \\{long}
11998 or \\{outer} and the other isn't, even though the texts of the macros are
11999 the same.
12000
12001 We need to reset |scanner_status|, since \.{\\outer} control sequences
12002 are allowed, but we might be scanning a macro definition or preamble.
12003
12004 @<Test if two tokens match@>=
12005 begin save_scanner_status:=scanner_status; scanner_status:=normal;
12006 get_next; n:=cur_cs; p:=cur_cmd; q:=cur_chr;
12007 get_next; if cur_cmd<>p then b:=false
12008 else if cur_cmd<call then b:=(cur_chr=q)
12009 else @<Test if two macro texts match@>;
12010 scanner_status:=save_scanner_status;
12011 end
12012
12013 @ Note also that `\.{\\ifx}' decides that macros \.{\\a} and \.{\\b} are
12014 different in examples like this:
12015 $$\vbox{\halign{\.{#}\hfil&\qquad\.{#}\hfil\cr
12016 {}\\def\\a\{\\c\}&
12017 {}\\def\\c\{\}\cr
12018 {}\\def\\b\{\\d\}&
12019 {}\\def\\d\{\}\cr}}$$
12020
12021 @<Test if two macro texts match@>=
12022 begin p:=link(cur_chr); q:=link(equiv(n)); {omit reference counts}
12023 if p=q then b:=true
12024 else begin while (p<>null)and(q<>null) do
12025 if info(p)<>info(q) then p:=null
12026 else begin p:=link(p); q:=link(q);
12027 end;
12028 b:=((p=null)and(q=null));
12029 end;
12030 end
12031
12032 @ @<Select the appropriate case and |return| or |goto common_ending|@>=
12033 begin scan_int; n:=cur_val; {|n| is the number of cases to pass}
12034 if tracing_commands>1 then
12035 begin begin_diagnostic; print("{case "); print_int(n); print_char("}");
12036 end_diagnostic(false);
12037 end;
12038 while n<>0 do
12039 begin pass_text;
12040 if cond_ptr=save_cond_ptr then
12041 if cur_chr=or_code then decr(n)
12042 else goto common_ending
12043 else if cur_chr=fi_code then @<Pop the condition stack@>;
12044 end;
12045 change_if_limit(or_code,save_cond_ptr);
12046 return; {wait for \.{\\or}, \.{\\else}, or \.{\\fi}}
12047 end
12048
12049 @ The processing of conditionals is complete except for the following
12050 code, which is actually part of |expand|. It comes into play when
12051 \.{\\or}, \.{\\else}, or \.{\\fi} is scanned.
12052
12053 @<Terminate the current conditional and skip to \.{\\fi}@>=
12054 begin if tracing_ifs>0 then if tracing_commands<=1 then show_cur_cmd_chr;
12055 if cur_chr>if_limit then
12056 if if_limit=if_code then insert_relax {condition not yet evaluated}
12057 else begin print_err("Extra "); print_cmd_chr(fi_or_else,cur_chr);
12058 @.Extra \\or@>
12059 @.Extra \\else@>
12060 @.Extra \\fi@>
12061 help1("I'm ignoring this; it doesn't match any \if.");
12062 error;
12063 end
12064 else begin while cur_chr<>fi_code do pass_text; {skip to \.{\\fi}}
12065 @<Pop the condition stack@>;
12066 end;
12067 end
12068
12069 @* \[29] File names.
12070 It's time now to fret about file names. Besides the fact that different
12071 operating systems treat files in different ways, we must cope with the
12072 fact that completely different naming conventions are used by different
12073 groups of people. The following programs show what is required for one
12074 particular operating system; similar routines for other systems are not
12075 difficult to devise.
12076 @^fingers@>
12077 @^system dependencies@>
12078
12079 \TeX\ assumes that a file name has three parts: the name proper; its
12080 ``extension''; and a ``file area'' where it is found in an external file
12081 system. The extension of an input file or a write file is assumed to be
12082 `\.{.tex}' unless otherwise specified; it is `\.{.log}' on the
12083 transcript file that records each run of \TeX; it is `\.{.tfm}' on the font
12084 metric files that describe characters in the fonts \TeX\ uses; it is
12085 `\.{.dvi}' on the output files that specify typesetting information; and it
12086 is `\.{.fmt}' on the format files written by \.{INITEX} to initialize \TeX.
12087 The file area can be arbitrary on input files, but files are usually
12088 output to the user's current area. If an input file cannot be
12089 found on the specified area, \TeX\ will look for it on a special system
12090 area; this special area is intended for commonly used input files like
12091 \.{webmac.tex}.
12092
12093 Simple uses of \TeX\ refer only to file names that have no explicit
12094 extension or area. For example, a person usually says `\.{\\input} \.{paper}'
12095 or `\.{\\font\\tenrm} \.= \.{helvetica}' instead of `\.{\\input}
12096 \.{paper.new}' or `\.{\\font\\tenrm} \.= \.{<csd.knuth>test}'. Simple file
12097 names are best, because they make the \TeX\ source files portable;
12098 whenever a file name consists entirely of letters and digits, it should be
12099 treated in the same way by all implementations of \TeX. However, users
12100 need the ability to refer to other files in their environment, especially
12101 when responding to error messages concerning unopenable files; therefore
12102 we want to let them use the syntax that appears in their favorite
12103 operating system.
12104
12105 @ In order to isolate the system-dependent aspects of file names, the
12106 @^system dependencies@>
12107 system-independent parts of \TeX\ are expressed in terms
12108 of three system-dependent
12109 procedures called |begin_name|, |more_name|, and |end_name|. In
12110 essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
12111 the system-independent driver program does the operations
12112 $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;\,|more_name|(c_n);
12113 \,|end_name|.$$
12114 These three procedures communicate with each other via global variables.
12115 Afterwards the file name will appear in the string pool as three strings
12116 called |cur_name|\penalty10000\hskip-.05em,
12117 |cur_area|, and |cur_ext|; the latter two are null (i.e.,
12118 |""|), unless they were explicitly specified by the user.
12119
12120 Actually the situation is slightly more complicated, because \TeX\ needs
12121 to know when the file name ends. The |more_name| routine is a function
12122 (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
12123 \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
12124 returns |false|; or, it returns |true| and the token following $c_n$ is
12125 something like `\.{\\hbox}' (i.e., not a character). In other words,
12126 |more_name| is supposed to return |true| unless it is sure that the
12127 file name has been completely scanned; and |end_name| is supposed to be able
12128 to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
12129 whether $|more_name|(c_n)$ returned |true| or |false|.
12130
12131 @<Glob...@>=
12132 @!cur_name:str_number; {name of file just scanned}
12133 @!cur_area:str_number; {file area just scanned, or \.{""}}
12134 @!cur_ext:str_number; {file extension just scanned, or \.{""}}
12135
12136 @ The file names we shall deal with for illustrative purposes have the
12137 following structure: If the name contains `\.>' or `\.:', the file area
12138 consists of all characters up to and including the final such character;
12139 otherwise the file area is null. If the remaining file name contains
12140 `\..', the file extension consists of all such characters from the first
12141 remaining `\..' to the end, otherwise the file extension is null.
12142 @^system dependencies@>
12143
12144 We can scan such file names easily by using two global variables that keep track
12145 of the occurrences of area and extension delimiters:
12146
12147 @<Glob...@>=
12148 @!area_delimiter:pool_pointer; {the most recent `\.>' or `\.:', if any}
12149 @!ext_delimiter:pool_pointer; {the relevant `\..', if any}
12150 @!file_name_quote_char:UTF16_code;
12151
12152 @ Input files that can't be found in the user's area may appear in a standard
12153 system area called |TEX_area|. Font metric files whose areas are not given
12154 explicitly are assumed to appear in a standard system area called
12155 |TEX_font_area|. These system area names will, of course, vary from place
12156 to place.
12157 @^system dependencies@>
12158
12159 @d TEX_area=="TeXinputs:"
12160 @.TeXinputs@>
12161 @d TEX_font_area=="TeXfonts:"
12162 @.TeXfonts@>
12163
12164 @ Here now is the first of the system-dependent routines for file name scanning.
12165 @^system dependencies@>
12166
12167 @p procedure begin_name;
12168 begin area_delimiter:=0; ext_delimiter:=0;
12169 file_name_quote_char:=0;
12170 end;
12171
12172 @ And here's the second. The string pool might change as the file name is
12173 being scanned, since a new \.{\\csname} might be entered; therefore we keep
12174 |area_delimiter| and |ext_delimiter| relative to the beginning of the current
12175 string, instead of assigning an absolute address like |pool_ptr| to them.
12176 @^system dependencies@>
12177
12178 @p function more_name(@!c:UnicodeScalar):boolean;
12179 begin if c=" " then more_name:=false
12180 else begin
12181 if (c>@"FFFF) then str_room(2)
12182 else str_room(1);
12183 append_char(c); {contribute |c| to the current string}
12184 if (c=">")or(c=":") then
12185 begin area_delimiter:=cur_length; ext_delimiter:=0;
12186 end
12187 else if (c=".")and(ext_delimiter=0) then ext_delimiter:=cur_length;
12188 more_name:=true;
12189 end;
12190 end;
12191
12192 @ The third.
12193 @^system dependencies@>
12194
12195 @p procedure end_name;
12196 begin if str_ptr+3>max_strings then
12197 overflow("number of strings",max_strings-init_str_ptr);
12198 @:TeX capacity exceeded number of strings}{\quad number of strings@>
12199 if area_delimiter=0 then cur_area:=""
12200 else begin cur_area:=str_ptr;
12201 str_start_macro(str_ptr+1):=str_start_macro(str_ptr)+area_delimiter; incr(str_ptr);
12202 end;
12203 if ext_delimiter=0 then
12204 begin cur_ext:=""; cur_name:=make_string;
12205 end
12206 else begin cur_name:=str_ptr;
12207 str_start_macro(str_ptr+1):=str_start_macro(str_ptr)+ext_delimiter-area_delimiter-1;
12208 incr(str_ptr); cur_ext:=make_string;
12209 end;
12210 end;
12211
12212 @ Conversely, here is a routine that takes three strings and prints a file
12213 name that might have produced them. (The routine is system dependent, because
12214 some operating systems put the file area last instead of first.)
12215 @^system dependencies@>
12216
12217 @<Basic printing...@>=
12218 procedure print_file_name(@!n,@!a,@!e:integer);
12219 begin slow_print(a); slow_print(n); slow_print(e);
12220 end;
12221
12222 @ Another system-dependent routine is needed to convert three internal
12223 \TeX\ strings
12224 into the |name_of_file| value that is used to open files. The present code
12225 allows both lowercase and uppercase letters in the file name.
12226 @^system dependencies@>
12227
12228 @d append_to_name(#)==begin c:=#; incr(k);
12229 if k<=file_name_size then name_of_file[k]:=xchr[c];
12230 end
12231
12232 @p procedure pack_file_name(@!n,@!a,@!e:str_number);
12233 var k:integer; {number of positions filled in |name_of_file|}
12234 @!c: UnicodeScalar; {character being packed}
12235 @!j:pool_pointer; {index into |str_pool|}
12236 begin k:=0;
12237 for j:=str_start_macro(a) to str_start_macro(a+1)-1 do append_to_name(so(str_pool[j]));
12238 for j:=str_start_macro(n) to str_start_macro(n+1)-1 do append_to_name(so(str_pool[j]));
12239 for j:=str_start_macro(e) to str_start_macro(e+1)-1 do append_to_name(so(str_pool[j]));
12240 if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
12241 for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
12242 end;
12243
12244 @ A messier routine is also needed, since format file names must be scanned
12245 before \TeX's string mechanism has been initialized. We shall use the
12246 global variable |TEX_format_default| to supply the text for default system areas
12247 and extensions related to format files.
12248 @^system dependencies@>
12249
12250 @d format_default_length=20 {length of the |TEX_format_default| string}
12251 @d format_area_length=11 {length of its area part}
12252 @d format_ext_length=4 {length of its `\.{.fmt}' part}
12253 @d format_extension=".fmt" {the extension, as a \.{WEB} constant}
12254
12255 @<Glob...@>=
12256 @!TEX_format_default:packed array[1..format_default_length] of char;
12257
12258 @ @<Set init...@>=
12259 TEX_format_default:='TeXformats:plain.fmt';
12260 @.TeXformats@>
12261 @.plain@>
12262 @^system dependencies@>
12263
12264 @ @<Check the ``constant'' values for consistency@>=
12265 if format_default_length>file_name_size then bad:=31;
12266
12267 @ Here is the messy routine that was just mentioned. It sets |name_of_file|
12268 from the first |n| characters of |TEX_format_default|, followed by
12269 |buffer[a..b]|, followed by the last |format_ext_length| characters of
12270 |TEX_format_default|.
12271
12272 We dare not give error messages here, since \TeX\ calls this routine before
12273 the |error| routine is ready to roll. Instead, we simply drop excess characters,
12274 since the error will be detected in another way when a strange file name
12275 isn't found.
12276 @^system dependencies@>
12277
12278 @p procedure pack_buffered_name(@!n:small_number;@!a,@!b:integer);
12279 var k:integer; {number of positions filled in |name_of_file|}
12280 @!c: ASCII_code; {character being packed}
12281 @!j:integer; {index into |buffer| or |TEX_format_default|}
12282 begin if n+b-a+1+format_ext_length>file_name_size then
12283 b:=a+file_name_size-n-1-format_ext_length;
12284 k:=0;
12285 for j:=1 to n do append_to_name(xord[TEX_format_default[j]]);
12286 for j:=a to b do append_to_name(buffer[j]);
12287 for j:=format_default_length-format_ext_length+1 to format_default_length do
12288 append_to_name(xord[TEX_format_default[j]]);
12289 if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
12290 for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
12291 end;
12292
12293 @ Here is the only place we use |pack_buffered_name|. This part of the program
12294 becomes active when a ``virgin'' \TeX\ is trying to get going, just after
12295 the preliminary initialization, or when the user is substituting another
12296 format file by typing `\.\&' after the initial `\.{**}' prompt. The buffer
12297 contains the first line of input in |buffer[loc..(last-1)]|, where
12298 |loc<last| and |buffer[loc]<>" "|.
12299
12300 @<Declare the function called |open_fmt_file|@>=
12301 function open_fmt_file:boolean;
12302 label found,exit;
12303 var j:0..buf_size; {the first space after the format file name}
12304 begin j:=loc;
12305 if buffer[loc]="&" then
12306 begin incr(loc); j:=loc; buffer[last]:=" ";
12307 while buffer[j]<>" " do incr(j);
12308 pack_buffered_name(0,loc,j-1); {try first without the system file area}
12309 if w_open_in(fmt_file) then goto found;
12310 pack_buffered_name(format_area_length,loc,j-1);
12311 {now try the system format file area}
12312 if w_open_in(fmt_file) then goto found;
12313 wake_up_terminal;
12314 wterm_ln('Sorry, I can''t find that format;',' will try PLAIN.');
12315 @.Sorry, I can't find...@>
12316 update_terminal;
12317 end;
12318 {now pull out all the stops: try for the system \.{plain} file}
12319 pack_buffered_name(format_default_length-format_ext_length,1,0);
12320 if not w_open_in(fmt_file) then
12321 begin wake_up_terminal;
12322 wterm_ln('I can''t find the PLAIN format file!');
12323 @.I can't find PLAIN...@>
12324 @.plain@>
12325 open_fmt_file:=false; return;
12326 end;
12327 found:loc:=j; open_fmt_file:=true;
12328 exit:end;
12329
12330 @ Operating systems often make it possible to determine the exact name (and
12331 possible version number) of a file that has been opened. The following routine,
12332 which simply makes a \TeX\ string from the value of |name_of_file|, should
12333 ideally be changed to deduce the full name of file~|f|, which is the file
12334 most recently opened, if it is possible to do this in a \PASCAL\ program.
12335 @^system dependencies@>
12336
12337 This routine might be called after string memory has overflowed, hence
12338 we dare not use `|str_room|'.
12339
12340 @p function make_name_string:str_number;
12341 var k:0..file_name_size; {index into |name_of_file|}
12342 begin if (pool_ptr+name_length>pool_size)or(str_ptr=max_strings)or
12343 (cur_length>0) then
12344 make_name_string:="?"
12345 else begin
12346 make_utf16_name;
12347 for k:=0 to name_length16-1 do append_char(name_of_file16[k]);
12348 make_name_string:=make_string;
12349 end;
12350 end;
12351 function u_make_name_string(var f:unicode_file):str_number;
12352 begin u_make_name_string:=make_name_string;
12353 end;
12354 function a_make_name_string(var f:alpha_file):str_number;
12355 begin a_make_name_string:=make_name_string;
12356 end;
12357 function b_make_name_string(var f:byte_file):str_number;
12358 begin b_make_name_string:=make_name_string;
12359 end;
12360 function w_make_name_string(var f:word_file):str_number;
12361 begin w_make_name_string:=make_name_string;
12362 end;
12363
12364 @ Now let's consider the ``driver''
12365 routines by which \TeX\ deals with file names
12366 in a system-independent manner. First comes a procedure that looks for a
12367 file name in the input by calling |get_x_token| for the information.
12368
12369 @p procedure scan_file_name;
12370 label done;
12371 begin name_in_progress:=true; begin_name;
12372 @<Get the next non-blank non-call...@>;
12373 loop@+begin if (cur_cmd>other_char)or(cur_chr>biggest_usv) then
12374 {not a character}
12375 begin back_input; goto done;
12376 end;
12377 if not more_name(cur_chr) then goto done;
12378 get_x_token;
12379 end;
12380 done: end_name; name_in_progress:=false;
12381 end;
12382
12383 @ The global variable |name_in_progress| is used to prevent recursive
12384 use of |scan_file_name|, since the |begin_name| and other procedures
12385 communicate via global variables. Recursion would arise only by
12386 devious tricks like `\.{\\input\\input f}'; such attempts at sabotage
12387 must be thwarted. Furthermore, |name_in_progress| prevents \.{\\input}
12388 @^recursion@>
12389 from being initiated when a font size specification is being scanned.
12390
12391 Another global variable, |job_name|, contains the file name that was first
12392 \.{\\input} by the user. This name is extended by `\.{.log}' and `\.{.dvi}'
12393 and `\.{.fmt}' in the names of \TeX's output files.
12394
12395 @<Glob...@>=
12396 @!name_in_progress:boolean; {is a file name being scanned?}
12397 @!job_name:str_number; {principal file name}
12398 @!log_opened:boolean; {has the transcript file been opened?}
12399
12400 @ Initially |job_name=0|; it becomes nonzero as soon as the true name is known.
12401 We have |job_name=0| if and only if the `\.{log}' file has not been opened,
12402 except of course for a short time just after |job_name| has become nonzero.
12403
12404 @<Initialize the output...@>=
12405 job_name:=0; name_in_progress:=false; log_opened:=false;
12406
12407 @ Here is a routine that manufactures the output file names, assuming that
12408 |job_name<>0|. It ignores and changes the current settings of |cur_area|
12409 and |cur_ext|.
12410
12411 @d pack_cur_name==pack_file_name(cur_name,cur_area,cur_ext)
12412
12413 @p procedure pack_job_name(@!s:str_number); {|s = ".log"|, |output_file_extension|, or
12414 |format_extension|}
12415 begin cur_area:=""; cur_ext:=s;
12416 cur_name:=job_name; pack_cur_name;
12417 end;
12418
12419 @ If some trouble arises when \TeX\ tries to open a file, the following
12420 routine calls upon the user to supply another file name. Parameter~|s|
12421 is used in the error message to identify the type of file; parameter~|e|
12422 is the default extension if none is given. Upon exit from the routine,
12423 variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
12424 ready for another attempt at file opening.
12425
12426 @p procedure prompt_file_name(@!s,@!e:str_number);
12427 label done;
12428 var k:0..buf_size; {index into |buffer|}
12429 begin if interaction=scroll_mode then wake_up_terminal;
12430 if s="input file name" then print_err("I can't find file `")
12431 @.I can't find file x@>
12432 else print_err("I can't write on file `");
12433 @.I can't write on file x@>
12434 print_file_name(cur_name,cur_area,cur_ext); print("'.");
12435 if e=".tex" then show_context;
12436 print_nl("Please type another "); print(s);
12437 @.Please type...@>
12438 if interaction<scroll_mode then
12439 fatal_error("*** (job aborted, file error in nonstop mode)");
12440 @.job aborted, file error...@>
12441 clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
12442 if cur_ext="" then cur_ext:=e;
12443 pack_cur_name;
12444 end;
12445
12446 @ @<Scan file name in the buffer@>=
12447 begin begin_name; k:=first;
12448 while (buffer[k]=" ")and(k<last) do incr(k);
12449 loop@+ begin if k=last then goto done;
12450 if not more_name(buffer[k]) then goto done;
12451 incr(k);
12452 end;
12453 done:end_name;
12454 end
12455
12456 @ Here's an example of how these conventions are used. Whenever it is time to
12457 ship out a box of stuff, we shall use the macro |ensure_dvi_open|.
12458
12459 @d ensure_dvi_open==if output_file_name=0 then
12460 begin if job_name=0 then open_log_file;
12461 pack_job_name(output_file_extension);
12462 while not dvi_open_out(dvi_file) do
12463 prompt_file_name("file name for output",output_file_extension);
12464 output_file_name:=b_make_name_string(dvi_file);
12465 end
12466
12467 @<Glob...@>=
12468 @!output_file_extension: str_number;
12469 @!no_pdf_output: boolean;
12470 @!dvi_file: byte_file; {the device-independent output goes here}
12471 @!output_file_name: str_number; {full name of the output file}
12472 @!log_name:str_number; {full name of the log file}
12473
12474 @ @<Initialize the output...@>=
12475 output_file_name:=0;
12476 if no_pdf_output then output_file_extension:=".xdv"
12477 else output_file_extension:=".pdf";
12478
12479 @ The |open_log_file| routine is used to open the transcript file and to help
12480 it catch up to what has previously been printed on the terminal.
12481
12482 @p procedure open_log_file;
12483 var old_setting:0..max_selector; {previous |selector| setting}
12484 @!k:0..buf_size; {index into |months| and |buffer|}
12485 @!l:0..buf_size; {end of first input line}
12486 @!months:packed array [1..36] of char; {abbreviations of month names}
12487 begin old_setting:=selector;
12488 if job_name=0 then job_name:="texput";
12489 @.texput@>
12490 pack_job_name(".log");
12491 while not a_open_out(log_file) do @<Try to get a different log file name@>;
12492 log_name:=a_make_name_string(log_file);
12493 selector:=log_only; log_opened:=true;
12494 @<Print the banner line, including the date and time@>;
12495 input_stack[input_ptr]:=cur_input; {make sure bottom level is in memory}
12496 print_nl("**");
12497 @.**@>
12498 l:=input_stack[0].limit_field; {last position of first line}
12499 if buffer[l]=end_line_char then decr(l);
12500 for k:=1 to l do print(buffer[k]);
12501 print_ln; {now the transcript file contains the first line of input}
12502 selector:=old_setting+2; {|log_only| or |term_and_log|}
12503 end;
12504
12505 @ Sometimes |open_log_file| is called at awkward moments when \TeX\ is
12506 unable to print error messages or even to |show_context|.
12507 The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
12508 routine will not be invoked because |log_opened| will be false.
12509
12510 The normal idea of |batch_mode| is that nothing at all should be written
12511 on the terminal. However, in the unusual case that
12512 no log file could be opened, we make an exception and allow
12513 an explanatory message to be seen.
12514
12515 Incidentally, the program always refers to the log file as a `\.{transcript
12516 file}', because some systems cannot use the extension `\.{.log}' for
12517 this file.
12518
12519 @<Try to get a different log file name@>=
12520 begin selector:=term_only;
12521 prompt_file_name("transcript file name",".log");
12522 end
12523
12524 @ @<Print the banner...@>=
12525 begin wlog(banner);
12526 slow_print(format_ident); print(" ");
12527 print_int(sys_day); print_char(" ");
12528 months:='JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC';
12529 for k:=3*sys_month-2 to 3*sys_month do wlog(months[k]);
12530 print_char(" "); print_int(sys_year); print_char(" ");
12531 print_two(sys_time div 60); print_char(":"); print_two(sys_time mod 60);
12532 if eTeX_ex then
12533 begin; wlog_cr; wlog('entering extended mode');
12534 end;
12535 end
12536
12537 @ Let's turn now to the procedure that is used to initiate file reading
12538 when an `\.{\\input}' command is being processed.
12539 Beware: For historic reasons, this code foolishly conserves a tiny bit
12540 of string pool space; but that can confuse the interactive `\.E' option.
12541 @^system dependencies@>
12542
12543 @p procedure start_input; {\TeX\ will \.{\\input} something}
12544 label done;
12545 begin scan_file_name; {set |cur_name| to desired file name}
12546 if cur_ext="" then cur_ext:=".tex";
12547 pack_cur_name;
12548 loop@+ begin begin_file_reading; {set up |cur_file| and new level of input}
12549 if a_open_in(cur_file) then goto done;
12550 if cur_area="" then
12551 begin pack_file_name(cur_name,TEX_area,cur_ext);
12552 if a_open_in(cur_file) then goto done;
12553 end;
12554 end_file_reading; {remove the level that didn't work}
12555 prompt_file_name("input file name",".tex");
12556 end;
12557 done: name:=a_make_name_string(cur_file);
12558 if job_name=0 then
12559 begin job_name:=cur_name; open_log_file;
12560 end; {|open_log_file| doesn't |show_context|, so |limit|
12561 and |loc| needn't be set to meaningful values yet}
12562 if term_offset+length(name)>max_print_line-2 then print_ln
12563 else if (term_offset>0)or(file_offset>0) then print_char(" ");
12564 print_char("("); incr(open_parens); slow_print(name); update_terminal;
12565 state:=new_line;
12566 if name=str_ptr-1 then {conserve string pool space (but see note above)}
12567 begin flush_string; name:=cur_name;
12568 end;
12569 @<Read the first line of the new file@>;
12570 end;
12571
12572 @ Here we have to remember to tell the |input_ln| routine not to
12573 start with a |get|. If the file is empty, it is considered to
12574 contain a single blank line.
12575 @^system dependencies@>
12576 @^empty line at end of file@>
12577
12578 @<Read the first line...@>=
12579 begin line:=1;
12580 if input_ln(cur_file,false) then do_nothing;
12581 firm_up_the_line;
12582 if end_line_char_inactive then decr(limit)
12583 else buffer[limit]:=end_line_char;
12584 first:=limit+1; loc:=start;
12585 end
12586
12587 @* \[30] Font metric data.
12588 \TeX\ gets its knowledge about fonts from font metric files, also called
12589 \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
12590 but other programs know about them too.
12591 @:TFM files}{\.{TFM} files@>
12592 @^font metric files@>
12593
12594 The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
12595 Since the number of bytes is always a multiple of 4, we could
12596 also regard the file as a sequence of 32-bit words, but \TeX\ uses the
12597 byte interpretation. The format of \.{TFM} files was designed by
12598 Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
12599 @^Ramshaw, Lyle Harold@>
12600 of information in a compact but useful form.
12601
12602 @<Glob...@>=
12603 @!tfm_file:byte_file;
12604
12605 @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
12606 integers that give the lengths of the various subsequent portions
12607 of the file. These twelve integers are, in order:
12608 $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
12609 |lf|&length of the entire file, in words;\cr
12610 |lh|&length of the header data, in words;\cr
12611 |bc|&smallest character code in the font;\cr
12612 |ec|&largest character code in the font;\cr
12613 |nw|&number of words in the width table;\cr
12614 |nh|&number of words in the height table;\cr
12615 |nd|&number of words in the depth table;\cr
12616 |ni|&number of words in the italic correction table;\cr
12617 |nl|&number of words in the lig/kern table;\cr
12618 |nk|&number of words in the kern table;\cr
12619 |ne|&number of words in the extensible character table;\cr
12620 |np|&number of font parameter words.\cr}}$$
12621 They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
12622 and
12623 $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
12624 Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
12625 and as few as 0 characters (if |bc=ec+1|).
12626
12627 Incidentally, when two or more 8-bit bytes are combined to form an integer of
12628 16 or more bits, the most significant bytes appear first in the file.
12629 This is called BigEndian order.
12630 @!@^BigEndian order@>
12631
12632 @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
12633 arrays having the informal specification
12634 $$\def\arr$[#1]#2${\&{array} $[#1]$ \&{of} #2}
12635 \vbox{\halign{\hfil\\{#}&$\,:\,$\arr#\hfil\cr
12636 header&|[0..lh-1]@t\\{stuff}@>|\cr
12637 char\_info&|[bc..ec]char_info_word|\cr
12638 width&|[0..nw-1]fix_word|\cr
12639 height&|[0..nh-1]fix_word|\cr
12640 depth&|[0..nd-1]fix_word|\cr
12641 italic&|[0..ni-1]fix_word|\cr
12642 lig\_kern&|[0..nl-1]lig_kern_command|\cr
12643 kern&|[0..nk-1]fix_word|\cr
12644 exten&|[0..ne-1]extensible_recipe|\cr
12645 param&|[1..np]fix_word|\cr}}$$
12646 The most important data type used here is a |@!fix_word|, which is
12647 a 32-bit representation of a binary fraction. A |fix_word| is a signed
12648 quantity, with the two's complement of the entire word used to represent
12649 negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
12650 binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
12651 the smallest is $-2048$. We will see below, however, that all but two of
12652 the |fix_word| values must lie between $-16$ and $+16$.
12653
12654 @ The first data array is a block of header information, which contains
12655 general facts about the font. The header must contain at least two words,
12656 |header[0]| and |header[1]|, whose meaning is explained below.
12657 Additional header information of use to other software routines might
12658 also be included, but \TeX82 does not need to know about such details.
12659 For example, 16 more words of header information are in use at the Xerox
12660 Palo Alto Research Center; the first ten specify the character coding
12661 scheme used (e.g., `\.{XEROX text}' or `\.{TeX math symbols}'), the next five
12662 give the font identifier (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
12663 last gives the ``face byte.'' The program that converts \.{DVI} files
12664 to Xerox printing format gets this information by looking at the \.{TFM}
12665 file, which it needs to read anyway because of other information that
12666 is not explicitly repeated in \.{DVI}~format.
12667
12668 \yskip\hang|header[0]| is a 32-bit check sum that \TeX\ will copy into
12669 the \.{DVI} output file. Later on when the \.{DVI} file is printed,
12670 possibly on another computer, the actual font that gets used is supposed
12671 to have a check sum that agrees with the one in the \.{TFM} file used by
12672 \TeX. In this way, users will be warned about potential incompatibilities.
12673 (However, if the check sum is zero in either the font file or the \.{TFM}
12674 file, no check is made.) The actual relation between this check sum and
12675 the rest of the \.{TFM} file is not important; the check sum is simply an
12676 identification number with the property that incompatible fonts almost
12677 always have distinct check sums.
12678 @^check sum@>
12679
12680 \yskip\hang|header[1]| is a |fix_word| containing the design size of
12681 the font, in units of \TeX\ points. This number must be at least 1.0; it is
12682 fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
12683 font, i.e., a font that was designed to look best at a 10-point size,
12684 whatever that really means. When a \TeX\ user asks for a font
12685 `\.{at} $\delta$ \.{pt}', the effect is to override the design size
12686 and replace it by $\delta$, and to multiply the $x$ and~$y$ coordinates
12687 of the points in the font image by a factor of $\delta$ divided by the
12688 design size. {\sl All other dimensions in the\/ \.{TFM} file are
12689 |fix_word|\kern-1pt\ numbers in design-size units}, with the exception of
12690 |param[1]| (which denotes the slant ratio). Thus, for example, the value
12691 of |param[6]|, which defines the \.{em} unit, is often the |fix_word| value
12692 $2^{20}=1.0$, since many fonts have a design size equal to one em.
12693 The other dimensions must be less than 16 design-size units in absolute
12694 value; thus, |header[1]| and |param[1]| are the only |fix_word|
12695 entries in the whole \.{TFM} file whose first byte might be something
12696 besides 0 or 255.
12697
12698 @ Next comes the |char_info| array, which contains one |@!char_info_word|
12699 per character. Each word in this part of the file contains six fields
12700 packed into four bytes as follows.
12701
12702 \yskip\hang first byte: |@!width_index| (8 bits)\par
12703 \hang second byte: |@!height_index| (4 bits) times 16, plus |@!depth_index|
12704 (4~bits)\par
12705 \hang third byte: |@!italic_index| (6 bits) times 4, plus |@!tag|
12706 (2~bits)\par
12707 \hang fourth byte: |@!remainder| (8 bits)\par
12708 \yskip\noindent
12709 The actual width of a character is \\{width}|[width_index]|, in design-size
12710 units; this is a device for compressing information, since many characters
12711 have the same width. Since it is quite common for many characters
12712 to have the same height, depth, or italic correction, the \.{TFM} format
12713 imposes a limit of 16 different heights, 16 different depths, and
12714 64 different italic corrections.
12715
12716 @!@^italic correction@>
12717 The italic correction of a character has two different uses.
12718 (a)~In ordinary text, the italic correction is added to the width only if
12719 the \TeX\ user specifies `\.{\\/}' after the character.
12720 (b)~In math formulas, the italic correction is always added to the width,
12721 except with respect to the positioning of subscripts.
12722
12723 Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
12724 \\{italic}[0]=0$ should always hold, so that an index of zero implies a
12725 value of zero. The |width_index| should never be zero unless the
12726 character does not exist in the font, since a character is valid if and
12727 only if it lies between |bc| and |ec| and has a nonzero |width_index|.
12728
12729 @ The |tag| field in a |char_info_word| has four values that explain how to
12730 interpret the |remainder| field.
12731
12732 \yskip\hangg|tag=0| (|no_tag|) means that |remainder| is unused.\par
12733 \hangg|tag=1| (|lig_tag|) means that this character has a ligature/kerning
12734 program starting at position |remainder| in the |lig_kern| array.\par
12735 \hangg|tag=2| (|list_tag|) means that this character is part of a chain of
12736 characters of ascending sizes, and not the largest in the chain. The
12737 |remainder| field gives the character code of the next larger character.\par
12738 \hangg|tag=3| (|ext_tag|) means that this character code represents an
12739 extensible character, i.e., a character that is built up of smaller pieces
12740 so that it can be made arbitrarily large. The pieces are specified in
12741 |@!exten[remainder]|.\par
12742 \yskip\noindent
12743 Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
12744 unless they are used in special circumstances in math formulas. For example,
12745 the \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
12746 operation looks for both |list_tag| and |ext_tag|.
12747
12748 @d no_tag=0 {vanilla character}
12749 @d lig_tag=1 {character has a ligature/kerning program}
12750 @d list_tag=2 {character has a successor in a charlist}
12751 @d ext_tag=3 {character is extensible}
12752
12753 @ The |lig_kern| array contains instructions in a simple programming language
12754 that explains what to do for special letter pairs. Each word in this array is a
12755 |@!lig_kern_command| of four bytes.
12756
12757 \yskip\hang first byte: |skip_byte|, indicates that this is the final program
12758 step if the byte is 128 or more, otherwise the next step is obtained by
12759 skipping this number of intervening steps.\par
12760 \hang second byte: |next_char|, ``if |next_char| follows the current character,
12761 then perform the operation and stop, otherwise continue.''\par
12762 \hang third byte: |op_byte|, indicates a ligature step if less than~128,
12763 a kern step otherwise.\par
12764 \hang fourth byte: |remainder|.\par
12765 \yskip\noindent
12766 In a kern step, an
12767 additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
12768 between the current character and |next_char|. This amount is
12769 often negative, so that the characters are brought closer together
12770 by kerning; but it might be positive.
12771
12772 There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
12773 $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
12774 |remainder| is inserted between the current character and |next_char|;
12775 then the current character is deleted if $b=0$, and |next_char| is
12776 deleted if $c=0$; then we pass over $a$~characters to reach the next
12777 current character (which may have a ligature/kerning program of its own).
12778
12779 If the very first instruction of the |lig_kern| array has |skip_byte=255|,
12780 the |next_char| byte is the so-called boundary character of this font;
12781 the value of |next_char| need not lie between |bc| and~|ec|.
12782 If the very last instruction of the |lig_kern| array has |skip_byte=255|,
12783 there is a special ligature/kerning program for a boundary character at the
12784 left, beginning at location |256*op_byte+remainder|.
12785 The interpretation is that \TeX\ puts implicit boundary characters
12786 before and after each consecutive string of characters from the same font.
12787 These implicit characters do not appear in the output, but they can affect
12788 ligatures and kerning.
12789
12790 If the very first instruction of a character's |lig_kern| program has
12791 |skip_byte>128|, the program actually begins in location
12792 |256*op_byte+remainder|. This feature allows access to large |lig_kern|
12793 arrays, because the first instruction must otherwise
12794 appear in a location |<=255|.
12795
12796 Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
12797 the condition
12798 $$\hbox{|256*op_byte+remainder<nl|.}$$
12799 If such an instruction is encountered during
12800 normal program execution, it denotes an unconditional halt; no ligature
12801 or kerning command is performed.
12802
12803 @d stop_flag==qi(128) {value indicating `\.{STOP}' in a lig/kern program}
12804 @d kern_flag==qi(128) {op code for a kern step}
12805 @d skip_byte(#)==#.b0
12806 @d next_char(#)==#.b1
12807 @d op_byte(#)==#.b2
12808 @d rem_byte(#)==#.b3
12809
12810 @ Extensible characters are specified by an |@!extensible_recipe|, which
12811 consists of four bytes called |@!top|, |@!mid|, |@!bot|, and |@!rep| (in this
12812 order). These bytes are the character codes of individual pieces used to
12813 build up a large symbol. If |top|, |mid|, or |bot| are zero, they are not
12814 present in the built-up result. For example, an extensible vertical line is
12815 like an extensible bracket, except that the top and bottom pieces are missing.
12816
12817 Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
12818 if the piece isn't present. Then the extensible characters have the form
12819 $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
12820 in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
12821 The width of the extensible character is the width of $R$; and the
12822 height-plus-depth is the sum of the individual height-plus-depths of the
12823 components used, since the pieces are butted together in a vertical list.
12824
12825 @d ext_top(#)==#.b0 {|top| piece in a recipe}
12826 @d ext_mid(#)==#.b1 {|mid| piece in a recipe}
12827 @d ext_bot(#)==#.b2 {|bot| piece in a recipe}
12828 @d ext_rep(#)==#.b3 {|rep| piece in a recipe}
12829
12830 @ The final portion of a \.{TFM} file is the |param| array, which is another
12831 sequence of |fix_word| values.
12832
12833 \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
12834 to help position accents. For example, |slant=.25| means that when you go
12835 up one unit, you also go .25 units to the right. The |slant| is a pure
12836 number; it's the only |fix_word| other than the design size itself that is
12837 not scaled by the design size.
12838
12839 \hang|param[2]=space| is the normal spacing between words in text.
12840 Note that character |" "| in the font need not have anything to do with
12841 blank spaces.
12842
12843 \hang|param[3]=space_stretch| is the amount of glue stretching between words.
12844
12845 \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
12846
12847 \hang|param[5]=x_height| is the size of one ex in the font; it is also
12848 the height of letters for which accents don't have to be raised or lowered.
12849
12850 \hang|param[6]=quad| is the size of one em in the font.
12851
12852 \hang|param[7]=extra_space| is the amount added to |param[2]| at the
12853 ends of sentences.
12854
12855 \yskip\noindent
12856 If fewer than seven parameters are present, \TeX\ sets the missing parameters
12857 to zero. Fonts used for math symbols are required to have
12858 additional parameter information, which is explained later.
12859
12860 @d slant_code=1
12861 @d space_code=2
12862 @d space_stretch_code=3
12863 @d space_shrink_code=4
12864 @d x_height_code=5
12865 @d quad_code=6
12866 @d extra_space_code=7
12867
12868 @ So that is what \.{TFM} files hold. Since \TeX\ has to absorb such information
12869 about lots of fonts, it stores most of the data in a large array called
12870 |font_info|. Each item of |font_info| is a |memory_word|; the |fix_word|
12871 data gets converted into |scaled| entries, while everything else goes into
12872 words of type |four_quarters|.
12873
12874 When the user defines \.{\\font\\f}, say, \TeX\ assigns an internal number
12875 to the user's font~\.{\\f}. Adding this number to |font_id_base| gives the
12876 |eqtb| location of a ``frozen'' control sequence that will always select
12877 the font.
12878
12879 @<Types...@>=
12880 @!internal_font_number=font_base..font_max; {|font| in a |char_node|}
12881 @!font_index=0..font_mem_size; {index into |font_info|}
12882
12883 @ Here now is the (rather formidable) array of font arrays.
12884
12885 @d otgr_font_flag=@"FFFE
12886 @d aat_font_flag=@"FFFF
12887 @d is_aat_font(#)==(font_area[#]=aat_font_flag)
12888 @d is_ot_font(#)==((font_area[#]=otgr_font_flag) and (usingOpenType(font_layout_engine[#])))
12889 @d is_gr_font(#)==((font_area[#]=otgr_font_flag) and (usingGraphite(font_layout_engine[#])))
12890 @d is_otgr_font(#)==(font_area[#]=otgr_font_flag)
12891 @d is_native_font(#)==(is_aat_font(#) or is_otgr_font(#))
12892 {native fonts have |font_area| = 65534 or 65535,
12893 which would be a string containing an invalid Unicode character}
12894 @d is_new_mathfont(#)==((font_area[#]=otgr_font_flag) and (isOpenTypeMathFont(font_layout_engine[#])))
12895
12896 @d non_char==qi(too_big_char) {a |halfword| code that can't match a real character}
12897 @d non_address=0 {a spurious |bchar_label|}
12898
12899 @<Glob...@>=
12900 @!font_info:array[font_index] of memory_word;
12901 {the big collection of font data}
12902 @!fmem_ptr:font_index; {first unused word of |font_info|}
12903 @!font_ptr:internal_font_number; {largest internal font number in use}
12904 @!font_check:array[internal_font_number] of four_quarters; {check sum}
12905 @!font_size:array[internal_font_number] of scaled; {``at'' size}
12906 @!font_dsize:array[internal_font_number] of scaled; {``design'' size}
12907 @!font_params:array[internal_font_number] of font_index; {how many font
12908 parameters are present}
12909 @!font_name:array[internal_font_number] of str_number; {name of the font}
12910 @!font_area:array[internal_font_number] of str_number; {area of the font}
12911 @!font_bc:array[internal_font_number] of eight_bits;
12912 {beginning (smallest) character code}
12913 @!font_ec:array[internal_font_number] of eight_bits;
12914 {ending (largest) character code}
12915 @!font_glue:array[internal_font_number] of pointer;
12916 {glue specification for interword space, |null| if not allocated}
12917 @!font_used:array[internal_font_number] of boolean;
12918 {has a character from this font actually appeared in the output?}
12919 @!hyphen_char:array[internal_font_number] of integer;
12920 {current \.{\\hyphenchar} values}
12921 @!skew_char:array[internal_font_number] of integer;
12922 {current \.{\\skewchar} values}
12923 @!bchar_label:array[internal_font_number] of font_index;
12924 {start of |lig_kern| program for left boundary character,
12925 |non_address| if there is none}
12926 @!font_bchar:array[internal_font_number] of min_quarterword..non_char;
12927 {boundary character, |non_char| if there is none}
12928 @!font_false_bchar:array[internal_font_number] of min_quarterword..non_char;
12929 {|font_bchar| if it doesn't exist in the font, otherwise |non_char|}
12930
12931 @ Besides the arrays just enumerated, we have directory arrays that make it
12932 easy to get at the individual entries in |font_info|. For example, the
12933 |char_info| data for character |c| in font |f| will be in
12934 |font_info[char_base[f]+c].qqqq|; and if |w| is the |width_index|
12935 part of this word (the |b0| field), the width of the character is
12936 |font_info[width_base[f]+w].sc|. (These formulas assume that
12937 |min_quarterword| has already been added to |c| and to |w|, since \TeX\
12938 stores its quarterwords that way.)
12939
12940 @<Glob...@>=
12941 @!char_base:array[internal_font_number] of integer;
12942 {base addresses for |char_info|}
12943 @!width_base:array[internal_font_number] of integer;
12944 {base addresses for widths}
12945 @!height_base:array[internal_font_number] of integer;
12946 {base addresses for heights}
12947 @!depth_base:array[internal_font_number] of integer;
12948 {base addresses for depths}
12949 @!italic_base:array[internal_font_number] of integer;
12950 {base addresses for italic corrections}
12951 @!lig_kern_base:array[internal_font_number] of integer;
12952 {base addresses for ligature/kerning programs}
12953 @!kern_base:array[internal_font_number] of integer;
12954 {base addresses for kerns}
12955 @!exten_base:array[internal_font_number] of integer;
12956 {base addresses for extensible recipes}
12957 @!param_base:array[internal_font_number] of integer;
12958 {base addresses for font parameters}
12959
12960 @ @<Set init...@>=
12961 for k:=font_base to font_max do font_used[k]:=false;
12962
12963 @ \TeX\ always knows at least one font, namely the null font. It has no
12964 characters, and its seven parameters are all equal to zero.
12965
12966 @<Initialize table...@>=
12967 font_ptr:=null_font; fmem_ptr:=7;
12968 font_name[null_font]:="nullfont"; font_area[null_font]:="";
12969 hyphen_char[null_font]:="-"; skew_char[null_font]:=-1;
12970 bchar_label[null_font]:=non_address;
12971 font_bchar[null_font]:=non_char; font_false_bchar[null_font]:=non_char;
12972 font_bc[null_font]:=1; font_ec[null_font]:=0;
12973 font_size[null_font]:=0; font_dsize[null_font]:=0;
12974 char_base[null_font]:=0; width_base[null_font]:=0;
12975 height_base[null_font]:=0; depth_base[null_font]:=0;
12976 italic_base[null_font]:=0; lig_kern_base[null_font]:=0;
12977 kern_base[null_font]:=0; exten_base[null_font]:=0;
12978 font_glue[null_font]:=null; font_params[null_font]:=7;
12979 param_base[null_font]:=-1;
12980 for k:=0 to 6 do font_info[k].sc:=0;
12981
12982 @ @<Put each...@>=
12983 primitive("nullfont",set_font,null_font);
12984 @!@:null_font_}{\.{\\nullfont} primitive@>
12985 text(frozen_null_font):="nullfont"; eqtb[frozen_null_font]:=eqtb[cur_val];
12986
12987 @ Of course we want to define macros that suppress the detail of how font
12988 information is actually packed, so that we don't have to write things like
12989 $$\hbox{|font_info[width_base[f]+font_info[char_base[f]+c].qqqq.b0].sc|}$$
12990 too often. The \.{WEB} definitions here make |char_info(f)(c)| the
12991 |four_quarters| word of font information corresponding to character
12992 |c| of font |f|. If |q| is such a word, |char_width(f)(q)| will be
12993 the character's width; hence the long formula above is at least
12994 abbreviated to
12995 $$\hbox{|char_width(f)(char_info(f)(c))|.}$$
12996 Usually, of course, we will fetch |q| first and look at several of its
12997 fields at the same time.
12998
12999 The italic correction of a character will be denoted by
13000 |char_italic(f)(q)|, so it is analogous to |char_width|. But we will get
13001 at the height and depth in a slightly different way, since we usually want
13002 to compute both height and depth if we want either one. The value of
13003 |height_depth(q)| will be the 8-bit quantity
13004 $$b=|height_index|\times16+|depth_index|,$$ and if |b| is such a byte we
13005 will write |char_height(f)(b)| and |char_depth(f)(b)| for the height and
13006 depth of the character |c| for which |q=char_info(f)(c)|. Got that?
13007
13008 The tag field will be called |char_tag(q)|; the remainder byte will be
13009 called |rem_byte(q)|, using a macro that we have already defined above.
13010
13011 Access to a character's |width|, |height|, |depth|, and |tag| fields is
13012 part of \TeX's inner loop, so we want these macros to produce code that is
13013 as fast as possible under the circumstances.
13014 @^inner loop@>
13015
13016 @d char_info_end(#)==#].qqqq
13017 @d char_info(#)==font_info[char_base[#]+char_info_end
13018 @d char_width_end(#)==#.b0].sc
13019 @d char_width(#)==font_info[width_base[#]+char_width_end
13020 @d char_exists(#)==(#.b0>min_quarterword)
13021 @d char_italic_end(#)==(qo(#.b2)) div 4].sc
13022 @d char_italic(#)==font_info[italic_base[#]+char_italic_end
13023 @d height_depth(#)==qo(#.b1)
13024 @d char_height_end(#)==(#) div 16].sc
13025 @d char_height(#)==font_info[height_base[#]+char_height_end
13026 @d char_depth_end(#)==(#) mod 16].sc
13027 @d char_depth(#)==font_info[depth_base[#]+char_depth_end
13028 @d char_tag(#)==((qo(#.b2)) mod 4)
13029
13030 @ The global variable |null_character| is set up to be a word of
13031 |char_info| for a character that doesn't exist. Such a word provides a
13032 convenient way to deal with erroneous situations.
13033
13034 @<Glob...@>=
13035 @!null_character:four_quarters; {nonexistent character information}
13036
13037 @ @<Set init...@>=
13038 null_character.b0:=min_quarterword; null_character.b1:=min_quarterword;
13039 null_character.b2:=min_quarterword; null_character.b3:=min_quarterword;
13040
13041 @ Here are some macros that help process ligatures and kerns.
13042 We write |char_kern(f)(j)| to find the amount of kerning specified by
13043 kerning command~|j| in font~|f|. If |j| is the |char_info| for a character
13044 with a ligature/kern program, the first instruction of that program is either
13045 |i=font_info[lig_kern_start(f)(j)]| or |font_info[lig_kern_restart(f)(i)]|,
13046 depending on whether or not |skip_byte(i)<=stop_flag|.
13047
13048 The constant |kern_base_offset| should be simplified, for \PASCAL\ compilers
13049 that do not do local optimization.
13050 @^system dependencies@>
13051
13052 @d char_kern_end(#)==256*op_byte(#)+rem_byte(#)].sc
13053 @d char_kern(#)==font_info[kern_base[#]+char_kern_end
13054 @d kern_base_offset==256*(128+min_quarterword)
13055 @d lig_kern_start(#)==lig_kern_base[#]+rem_byte {beginning of lig/kern program}
13056 @d lig_kern_restart_end(#)==256*op_byte(#)+rem_byte(#)+32768-kern_base_offset
13057 @d lig_kern_restart(#)==lig_kern_base[#]+lig_kern_restart_end
13058
13059 @ Font parameters are referred to as |slant(f)|, |space(f)|, etc.
13060
13061 @d param_end(#)==param_base[#]].sc
13062 @d param(#)==font_info[#+param_end
13063 @d slant==param(slant_code) {slant to the right, per unit distance upward}
13064 @d space==param(space_code) {normal space between words}
13065 @d space_stretch==param(space_stretch_code) {stretch between words}
13066 @d space_shrink==param(space_shrink_code) {shrink between words}
13067 @d x_height==param(x_height_code) {one ex}
13068 @d quad==param(quad_code) {one em}
13069 @d extra_space==param(extra_space_code) {additional space at end of sentence}
13070
13071 @<The em width for |cur_font|@>=quad(cur_font)
13072
13073 @ @<The x-height for |cur_font|@>=x_height(cur_font)
13074
13075 @ \TeX\ checks the information of a \.{TFM} file for validity as the
13076 file is being read in, so that no further checks will be needed when
13077 typesetting is going on. The somewhat tedious subroutine that does this
13078 is called |read_font_info|. It has four parameters: the user font
13079 identifier~|u|, the file name and area strings |nom| and |aire|, and the
13080 ``at'' size~|s|. If |s|~is negative, it's the negative of a scale factor
13081 to be applied to the design size; |s=-1000| is the normal case.
13082 Otherwise |s| will be substituted for the design size; in this
13083 case, |s| must be positive and less than $2048\rm\,pt$
13084 (i.e., it must be less than $2^{27}$ when considered as an integer).
13085
13086 The subroutine opens and closes a global file variable called |tfm_file|.
13087 It returns the value of the internal font number that was just loaded.
13088 If an error is detected, an error message is issued and no font
13089 information is stored; |null_font| is returned in this case.
13090
13091 @d bad_tfm=11 {label for |read_font_info|}
13092 @d abort==goto bad_tfm {do this when the \.{TFM} data is wrong}
13093
13094 @p function read_font_info(@!u:pointer;@!nom,@!aire:str_number;
13095 @!s:scaled):internal_font_number; {input a \.{TFM} file}
13096 label done,bad_tfm,not_found;
13097 var k:font_index; {index into |font_info|}
13098 @!file_opened:boolean; {was |tfm_file| successfully opened?}
13099 @!lf,@!lh,@!bc,@!ec,@!nw,@!nh,@!nd,@!ni,@!nl,@!nk,@!ne,@!np:halfword;
13100 {sizes of subfiles}
13101 @!f:internal_font_number; {the new font's number}
13102 @!g:internal_font_number; {the number to return}
13103 @!a,@!b,@!c,@!d:eight_bits; {byte variables}
13104 @!qw:four_quarters;@!sw:scaled; {accumulators}
13105 @!bch_label:integer; {left boundary start location, or infinity}
13106 @!bchar:0..256; {boundary character, or 256}
13107 @!z:scaled; {the design size or the ``at'' size}
13108 @!alpha:integer;@!beta:1..16;
13109 {auxiliary quantities used in fixed-point multiplication}
13110 begin g:=null_font;@/
13111 file_opened:=false;
13112 pack_file_name(nom,aire,cur_ext);
13113 if XeTeX_tracing_fonts_state>0 then begin
13114 begin_diagnostic;
13115 print_nl("Requested font """);
13116 print_c_string(stringcast(name_of_file+1));
13117 print('"');
13118 if s < 0 then begin
13119 print(" scaled ");
13120 print_int(-s);
13121 end else begin
13122 print(" at ");
13123 print_scaled(s);
13124 print("pt");
13125 end;
13126 end_diagnostic(false);
13127 end;
13128 if quoted_filename then begin
13129 { quoted name, so try for a native font }
13130 g:=load_native_font(u,nom,aire,s);
13131 if g<>null_font then goto done;
13132 end;
13133 { it was an unquoted name, or not found as an installed font, so try for a TFM file }
13134 @<Read and check the font data if file exists;
13135 |abort| if the \.{TFM} file is
13136 malformed; if there's no room for this font, say so and |goto
13137 done|; otherwise |incr(font_ptr)| and |goto done|@>;
13138 if g<>null_font then goto done;
13139 if not quoted_filename then begin
13140 { we failed to find a TFM file, so try for a native font }
13141 g:=load_native_font(u,nom,aire,s);
13142 if g<>null_font then goto done
13143 end;
13144 bad_tfm:
13145 if suppress_fontnotfound_error=0 then begin
13146 @<Report that the font won't be loaded@>;
13147 end;
13148 done: if file_opened then b_close(tfm_file);
13149 if XeTeX_tracing_fonts_state>0 then begin
13150 if g=null_font then begin
13151 begin_diagnostic;
13152 print_nl(" -> font not found, using ""nullfont""");
13153 end_diagnostic(false);
13154 end else if file_opened then begin
13155 begin_diagnostic;
13156 print_nl(" -> ");
13157 print_c_string(stringcast(name_of_file+1));
13158 end_diagnostic(false);
13159 end;
13160 end;
13161 read_font_info:=g;
13162 end;
13163
13164 @ There are programs called \.{TFtoPL} and \.{PLtoTF} that convert
13165 between the \.{TFM} format and a symbolic property-list format
13166 that can be easily edited. These programs contain extensive
13167 diagnostic information, so \TeX\ does not have to bother giving
13168 precise details about why it rejects a particular \.{TFM} file.
13169 @.TFtoPL@> @.PLtoTF@>
13170
13171 @d start_font_error_message==print_err("Font "); sprint_cs(u);
13172 print_char("=");
13173 if file_name_quote_char<>0 then print_char(file_name_quote_char);
13174 print_file_name(nom,aire,cur_ext);
13175 if file_name_quote_char<>0 then print_char(file_name_quote_char);
13176 if s>=0 then
13177 begin print(" at "); print_scaled(s); print("pt");
13178 end
13179 else if s<>-1000 then
13180 begin print(" scaled "); print_int(-s);
13181 end
13182
13183 @<Report that the font won't be loaded@>=
13184 start_font_error_message;
13185 @.Font x=xx not loadable...@>
13186 if file_opened then print(" not loadable: Bad metric (TFM) file")
13187 else print(" not loadable: Metric (TFM) file not found");
13188 help5("I wasn't able to read the size data for this font,")@/
13189 ("so I will ignore the font specification.")@/
13190 ("[Wizards can fix TFM files using TFtoPL/PLtoTF.]")@/
13191 ("You might try inserting a different font spec;")@/
13192 ("e.g., type `I\font<same font id>=<substitute font name>'.");
13193 error
13194
13195 @ @<Read and check...@>=
13196 @<Open |tfm_file| for input and |begin|@>;
13197 @<Read the {\.{TFM}} size fields@>;
13198 @<Use size fields to allocate font information@>;
13199 @<Read the {\.{TFM}} header@>;
13200 @<Read character data@>;
13201 @<Read box dimensions@>;
13202 @<Read ligature/kern program@>;
13203 @<Read extensible character recipes@>;
13204 @<Read font parameters@>;
13205 @<Make final adjustments and |goto done|@>;
13206 end
13207
13208 @ @<Open |tfm_file| for input...@>=
13209 if aire="" then pack_file_name(nom,TEX_font_area,".tfm")
13210 else pack_file_name(nom,aire,".tfm");
13211 check_for_tfm_font_mapping;
13212 if b_open_in(tfm_file) then begin
13213 file_opened:=true
13214
13215 @ Note: A malformed \.{TFM} file might be shorter than it claims to be;
13216 thus |eof(tfm_file)| might be true when |read_font_info| refers to
13217 |tfm_file^| or when it says |get(tfm_file)|. If such circumstances
13218 cause system error messages, you will have to defeat them somehow,
13219 for example by defining |fget| to be `\ignorespaces|begin get(tfm_file);|
13220 |if eof(tfm_file) then abort; end|\unskip'.
13221 @^system dependencies@>
13222
13223 @d fget==get(tfm_file)
13224 @d fbyte==tfm_file^
13225 @d read_sixteen(#)==begin #:=fbyte;
13226 if #>127 then abort;
13227 fget; #:=#*@'400+fbyte;
13228 end
13229 @d store_four_quarters(#)==begin fget; a:=fbyte; qw.b0:=qi(a);
13230 fget; b:=fbyte; qw.b1:=qi(b);
13231 fget; c:=fbyte; qw.b2:=qi(c);
13232 fget; d:=fbyte; qw.b3:=qi(d);
13233 #:=qw;
13234 end
13235
13236 @ @<Read the {\.{TFM}} size fields@>=
13237 begin read_sixteen(lf);
13238 fget; read_sixteen(lh);
13239 fget; read_sixteen(bc);
13240 fget; read_sixteen(ec);
13241 if (bc>ec+1)or(ec>255) then abort;
13242 if bc>255 then {|bc=256| and |ec=255|}
13243 begin bc:=1; ec:=0;
13244 end;
13245 fget; read_sixteen(nw);
13246 fget; read_sixteen(nh);
13247 fget; read_sixteen(nd);
13248 fget; read_sixteen(ni);
13249 fget; read_sixteen(nl);
13250 fget; read_sixteen(nk);
13251 fget; read_sixteen(ne);
13252 fget; read_sixteen(np);
13253 if lf<>6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np then abort;
13254 if (nw=0)or(nh=0)or(nd=0)or(ni=0) then abort;
13255 end
13256
13257 @ The preliminary settings of the index-offset variables |char_base|,
13258 |width_base|, |lig_kern_base|, |kern_base|, and |exten_base| will be
13259 corrected later by subtracting |min_quarterword| from them; and we will
13260 subtract 1 from |param_base| too. It's best to forget about such anomalies
13261 until later.
13262
13263 @<Use size fields to allocate font information@>=
13264 lf:=lf-6-lh; {|lf| words should be loaded into |font_info|}
13265 if np<7 then lf:=lf+7-np; {at least seven parameters will appear}
13266 if (font_ptr=font_max)or(fmem_ptr+lf>font_mem_size) then
13267 @<Apologize for not loading the font, |goto done|@>;
13268 f:=font_ptr+1;
13269 char_base[f]:=fmem_ptr-bc;
13270 width_base[f]:=char_base[f]+ec+1;
13271 height_base[f]:=width_base[f]+nw;
13272 depth_base[f]:=height_base[f]+nh;
13273 italic_base[f]:=depth_base[f]+nd;
13274 lig_kern_base[f]:=italic_base[f]+ni;
13275 kern_base[f]:=lig_kern_base[f]+nl-kern_base_offset;
13276 exten_base[f]:=kern_base[f]+kern_base_offset+nk;
13277 param_base[f]:=exten_base[f]+ne
13278
13279 @ @<Apologize for not loading...@>=
13280 begin start_font_error_message;
13281 print(" not loaded: Not enough room left");
13282 @.Font x=xx not loaded...@>
13283 help4("I'm afraid I won't be able to make use of this font,")@/
13284 ("because my memory for character-size data is too small.")@/
13285 ("If you're really stuck, ask a wizard to enlarge me.")@/
13286 ("Or maybe try `I\font<same font id>=<name of loaded font>'.");
13287 error; goto done;
13288 end
13289
13290 @ Only the first two words of the header are needed by \TeX82.
13291
13292 @<Read the {\.{TFM}} header@>=
13293 begin if lh<2 then abort;
13294 store_four_quarters(font_check[f]);
13295 fget; read_sixteen(z); {this rejects a negative design size}
13296 fget; z:=z*@'400+fbyte; fget; z:=(z*@'20)+(fbyte div@'20);
13297 if z<unity then abort;
13298 while lh>2 do
13299 begin fget;fget;fget;fget;decr(lh); {ignore the rest of the header}
13300 end;
13301 font_dsize[f]:=z;
13302 if s<>-1000 then
13303 if s>=0 then z:=s
13304 else z:=xn_over_d(z,-s,1000);
13305 font_size[f]:=z;
13306 end
13307
13308 @ @<Read character data@>=
13309 for k:=fmem_ptr to width_base[f]-1 do
13310 begin store_four_quarters(font_info[k].qqqq);
13311 if (a>=nw)or(b div @'20>=nh)or(b mod @'20>=nd)or
13312 (c div 4>=ni) then abort;
13313 case c mod 4 of
13314 lig_tag: if d>=nl then abort;
13315 ext_tag: if d>=ne then abort;
13316 list_tag: @<Check for charlist cycle@>;
13317 othercases do_nothing {|no_tag|}
13318 endcases;
13319 end
13320
13321 @ We want to make sure that there is no cycle of characters linked together
13322 by |list_tag| entries, since such a cycle would get \TeX\ into an endless
13323 loop. If such a cycle exists, the routine here detects it when processing
13324 the largest character code in the cycle.
13325
13326 @d check_byte_range(#)==begin if (#<bc)or(#>ec) then abort@+end
13327 @d current_character_being_worked_on==k+bc-fmem_ptr
13328
13329 @<Check for charlist cycle@>=
13330 begin check_byte_range(d);
13331 while d<current_character_being_worked_on do
13332 begin qw:=char_info(f)(d);
13333 {N.B.: not |qi(d)|, since |char_base[f]| hasn't been adjusted yet}
13334 if char_tag(qw)<>list_tag then goto not_found;
13335 d:=qo(rem_byte(qw)); {next character on the list}
13336 end;
13337 if d=current_character_being_worked_on then abort; {yes, there's a cycle}
13338 not_found:end
13339
13340 @ A |fix_word| whose four bytes are $(a,b,c,d)$ from left to right represents
13341 the number
13342 $$x=\left\{\vcenter{\halign{$#$,\hfil\qquad&if $#$\hfil\cr
13343 b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=0;\cr
13344 -16+b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=255.\cr}}\right.$$
13345 (No other choices of |a| are allowed, since the magnitude of a number in
13346 design-size units must be less than 16.) We want to multiply this
13347 quantity by the integer~|z|, which is known to be less than $2^{27}$.
13348 If $|z|<2^{23}$, the individual multiplications $b\cdot z$,
13349 $c\cdot z$, $d\cdot z$ cannot overflow; otherwise we will divide |z| by 2,
13350 4, 8, or 16, to obtain a multiplier less than $2^{23}$, and we can
13351 compensate for this later. If |z| has thereby been replaced by
13352 $|z|^\prime=|z|/2^e$, let $\beta=2^{4-e}$; we shall compute
13353 $$\lfloor(b+c\cdot2^{-8}+d\cdot2^{-16})\,z^\prime/\beta\rfloor$$
13354 if $a=0$, or the same quantity minus $\alpha=2^{4+e}z^\prime$ if $a=255$.
13355 This calculation must be done exactly, in order to guarantee portability
13356 of \TeX\ between computers.
13357
13358 @d store_scaled(#)==begin fget; a:=fbyte; fget; b:=fbyte;
13359 fget; c:=fbyte; fget; d:=fbyte;@/
13360 sw:=(((((d*z)div@'400)+(c*z))div@'400)+(b*z))div beta;
13361 if a=0 then #:=sw@+else if a=255 then #:=sw-alpha@+else abort;
13362 end
13363
13364 @<Read box dimensions@>=
13365 begin @<Replace |z| by $|z|^\prime$ and compute $\alpha,\beta$@>;
13366 for k:=width_base[f] to lig_kern_base[f]-1 do
13367 store_scaled(font_info[k].sc);
13368 if font_info[width_base[f]].sc<>0 then abort; {\\{width}[0] must be zero}
13369 if font_info[height_base[f]].sc<>0 then abort; {\\{height}[0] must be zero}
13370 if font_info[depth_base[f]].sc<>0 then abort; {\\{depth}[0] must be zero}
13371 if font_info[italic_base[f]].sc<>0 then abort; {\\{italic}[0] must be zero}
13372 end
13373
13374 @ @<Replace |z|...@>=
13375 begin alpha:=16;
13376 while z>=@'40000000 do
13377 begin z:=z div 2; alpha:=alpha+alpha;
13378 end;
13379 beta:=256 div alpha; alpha:=alpha*z;
13380 end
13381
13382 @ @d check_existence(#)==@t@>@;@/
13383 begin check_byte_range(#);
13384 qw:=char_info(f)(#); {N.B.: not |qi(#)|}
13385 if not char_exists(qw) then abort;
13386 end
13387
13388 @<Read ligature/kern program@>=
13389 bch_label:=@'77777; bchar:=256;
13390 if nl>0 then
13391 begin for k:=lig_kern_base[f] to kern_base[f]+kern_base_offset-1 do
13392 begin store_four_quarters(font_info[k].qqqq);
13393 if a>128 then
13394 begin if 256*c+d>=nl then abort;
13395 if a=255 then if k=lig_kern_base[f] then bchar:=b;
13396 end
13397 else begin if b<>bchar then check_existence(b);
13398 if c<128 then check_existence(d) {check ligature}
13399 else if 256*(c-128)+d>=nk then abort; {check kern}
13400 if a<128 then if k-lig_kern_base[f]+a+1>=nl then abort;
13401 end;
13402 end;
13403 if a=255 then bch_label:=256*c+d;
13404 end;
13405 for k:=kern_base[f]+kern_base_offset to exten_base[f]-1 do
13406 store_scaled(font_info[k].sc);
13407
13408 @ @<Read extensible character recipes@>=
13409 for k:=exten_base[f] to param_base[f]-1 do
13410 begin store_four_quarters(font_info[k].qqqq);
13411 if a<>0 then check_existence(a);
13412 if b<>0 then check_existence(b);
13413 if c<>0 then check_existence(c);
13414 check_existence(d);
13415 end
13416
13417 @ We check to see that the \.{TFM} file doesn't end prematurely; but
13418 no error message is given for files having more than |lf| words.
13419
13420 @<Read font parameters@>=
13421 begin for k:=1 to np do
13422 if k=1 then {the |slant| parameter is a pure number}
13423 begin fget; sw:=fbyte; if sw>127 then sw:=sw-256;
13424 fget; sw:=sw*@'400+fbyte; fget; sw:=sw*@'400+fbyte;
13425 fget; font_info[param_base[f]].sc:=
13426 (sw*@'20)+(fbyte div@'20);
13427 end
13428 else store_scaled(font_info[param_base[f]+k-1].sc);
13429 if eof(tfm_file) then abort;
13430 for k:=np+1 to 7 do font_info[param_base[f]+k-1].sc:=0;
13431 end
13432
13433 @ Now to wrap it up, we have checked all the necessary things about the \.{TFM}
13434 file, and all we need to do is put the finishing touches on the data for
13435 the new font.
13436
13437 @d adjust(#)==#[f]:=qo(#[f])
13438 {correct for the excess |min_quarterword| that was added}
13439
13440 @<Make final adjustments...@>=
13441 if np>=7 then font_params[f]:=np@+else font_params[f]:=7;
13442 hyphen_char[f]:=default_hyphen_char; skew_char[f]:=default_skew_char;
13443 if bch_label<nl then bchar_label[f]:=bch_label+lig_kern_base[f]
13444 else bchar_label[f]:=non_address;
13445 font_bchar[f]:=qi(bchar);
13446 font_false_bchar[f]:=qi(bchar);
13447 if bchar<=ec then if bchar>=bc then
13448 begin qw:=char_info(f)(bchar); {N.B.: not |qi(bchar)|}
13449 if char_exists(qw) then font_false_bchar[f]:=non_char;
13450 end;
13451 font_name[f]:=nom;
13452 font_area[f]:=aire;
13453 font_bc[f]:=bc; font_ec[f]:=ec; font_glue[f]:=null;
13454 adjust(char_base); adjust(width_base); adjust(lig_kern_base);
13455 adjust(kern_base); adjust(exten_base);
13456 decr(param_base[f]);
13457 fmem_ptr:=fmem_ptr+lf; font_ptr:=f; g:=f;
13458 font_mapping[f]:=load_tfm_font_mapping;
13459 goto done
13460
13461 @ Before we forget about the format of these tables, let's deal with two
13462 of \TeX's basic scanning routines related to font information.
13463
13464 @<Declare procedures that scan font-related stuff@>=
13465 procedure scan_font_ident;
13466 var f:internal_font_number;
13467 @!m:halfword;
13468 begin @<Get the next non-blank non-call...@>;
13469 if cur_cmd=def_font then f:=cur_font
13470 else if cur_cmd=set_font then f:=cur_chr
13471 else if cur_cmd=def_family then
13472 begin m:=cur_chr; scan_math_fam_int; f:=equiv(m+cur_val);
13473 end
13474 else begin print_err("Missing font identifier");
13475 @.Missing font identifier@>
13476 help2("I was looking for a control sequence whose")@/
13477 ("current meaning has been defined by \font.");
13478 back_error; f:=null_font;
13479 end;
13480 cur_val:=f;
13481 end;
13482
13483 @ The following routine is used to implement `\.{\\fontdimen} |n| |f|'.
13484 The boolean parameter |writing| is set |true| if the calling program
13485 intends to change the parameter value.
13486
13487 @<Declare procedures that scan font-related stuff@>=
13488 procedure find_font_dimen(@!writing:boolean);
13489 {sets |cur_val| to |font_info| location}
13490 var f:internal_font_number;
13491 @!n:integer; {the parameter number}
13492 begin scan_int; n:=cur_val; scan_font_ident; f:=cur_val;
13493 if n<=0 then cur_val:=fmem_ptr
13494 else begin if writing and(n<=space_shrink_code)and@|
13495 (n>=space_code)and(font_glue[f]<>null) then
13496 begin delete_glue_ref(font_glue[f]);
13497 font_glue[f]:=null;
13498 end;
13499 if n>font_params[f] then
13500 if f<font_ptr then cur_val:=fmem_ptr
13501 else @<Increase the number of parameters in the last font@>
13502 else cur_val:=n+param_base[f];
13503 end;
13504 @<Issue an error message if |cur_val=fmem_ptr|@>;
13505 end;
13506
13507 @ @<Issue an error message if |cur_val=fmem_ptr|@>=
13508 if cur_val=fmem_ptr then
13509 begin print_err("Font "); print_esc(font_id_text(f));
13510 print(" has only "); print_int(font_params[f]);
13511 print(" fontdimen parameters");
13512 @.Font x has only...@>
13513 help2("To increase the number of font parameters, you must")@/
13514 ("use \fontdimen immediately after the \font is loaded.");
13515 error;
13516 end
13517
13518 @ @<Increase the number of parameters...@>=
13519 begin repeat if fmem_ptr=font_mem_size then
13520 overflow("font memory",font_mem_size);
13521 @:TeX capacity exceeded font memory}{\quad font memory@>
13522 font_info[fmem_ptr].sc:=0; incr(fmem_ptr); incr(font_params[f]);
13523 until n=font_params[f];
13524 cur_val:=fmem_ptr-1; {this equals |param_base[f]+font_params[f]|}
13525 end
13526
13527 @ When \TeX\ wants to typeset a character that doesn't exist, the
13528 character node is not created; thus the output routine can assume
13529 that characters exist when it sees them. The following procedure
13530 prints a warning message unless the user has suppressed it.
13531
13532 @<Declare subroutines for |new_character|@>=
13533 procedure char_warning(@!f:internal_font_number;@!c:integer);
13534 var old_setting: integer; {saved value of |tracing_online|}
13535 begin if tracing_lost_chars>0 then
13536 begin old_setting:=tracing_online;
13537 if eTeX_ex and(tracing_lost_chars>1) then tracing_online:=1;
13538 begin begin_diagnostic;
13539 print_nl("Missing character: There is no ");
13540 @.Missing character@>
13541 if c < @"10000 then print_ASCII(c)
13542 else print_char(c); {non-Plane 0 Unicodes can't be sent through |print_ASCII|}
13543 print(" in font ");
13544 slow_print(font_name[f]); print_char("!"); end_diagnostic(false);
13545 end;
13546 tracing_online:=old_setting;
13547 end;
13548 end;
13549
13550 @ We need a few subroutines for |new_character|.
13551
13552 @p @t\4@>@<Declare subroutines for |new_character|@>@;
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 \XeTeX\ extends the format of \.{DVI} with its own commands, and thus produced
13596 ``extended device independent'' (\.{XDV}) files.
13597
13598 A \.{DVI} file consists of a ``preamble,'' followed by a sequence of one
13599 or more ``pages,'' followed by a ``postamble.'' The preamble is simply a
13600 |pre| command, with its parameters that define the dimensions used in the
13601 file; this must come first. Each ``page'' consists of a |bop| command,
13602 followed by any number of other commands that tell where characters are to
13603 be placed on a physical page, followed by an |eop| command. The pages
13604 appear in the order that \TeX\ generated them. If we ignore |nop| commands
13605 and \\{fnt\_def} commands (which are allowed between any two commands in
13606 the file), each |eop| command is immediately followed by a |bop| command,
13607 or by a |post| command; in the latter case, there are no more pages in the
13608 file, and the remaining bytes form the postamble. Further details about
13609 the postamble will be explained later.
13610
13611 Some parameters in \.{DVI} commands are ``pointers.'' These are four-byte
13612 quantities that give the location number of some other byte in the file;
13613 the first byte is number~0, then comes number~1, and so on. For example,
13614 one of the parameters of a |bop| command points to the previous |bop|;
13615 this makes it feasible to read the pages in backwards order, in case the
13616 results are being directed to a device that stacks its output face up.
13617 Suppose the preamble of a \.{DVI} file occupies bytes 0 to 99. Now if the
13618 first page occupies bytes 100 to 999, say, and if the second
13619 page occupies bytes 1000 to 1999, then the |bop| that starts in byte 1000
13620 points to 100 and the |bop| that starts in byte 2000 points to 1000. (The
13621 very first |bop|, i.e., the one starting in byte 100, has a pointer of~$-1$.)
13622
13623 @ The \.{DVI} format is intended to be both compact and easily interpreted
13624 by a machine. Compactness is achieved by making most of the information
13625 implicit instead of explicit. When a \.{DVI}-reading program reads the
13626 commands for a page, it keeps track of several quantities: (a)~The current
13627 font |f| is an integer; this value is changed only
13628 by \\{fnt} and \\{fnt\_num} commands. (b)~The current position on the page
13629 is given by two numbers called the horizontal and vertical coordinates,
13630 |h| and |v|. Both coordinates are zero at the upper left corner of the page;
13631 moving to the right corresponds to increasing the horizontal coordinate, and
13632 moving down corresponds to increasing the vertical coordinate. Thus, the
13633 coordinates are essentially Cartesian, except that vertical directions are
13634 flipped; the Cartesian version of |(h,v)| would be |(h,-v)|. (c)~The
13635 current spacing amounts are given by four numbers |w|, |x|, |y|, and |z|,
13636 where |w| and~|x| are used for horizontal spacing and where |y| and~|z|
13637 are used for vertical spacing. (d)~There is a stack containing
13638 |(h,v,w,x,y,z)| values; the \.{DVI} commands |push| and |pop| are used to
13639 change the current level of operation. Note that the current font~|f| is
13640 not pushed and popped; the stack contains only information about
13641 positioning.
13642
13643 The values of |h|, |v|, |w|, |x|, |y|, and |z| are signed integers having up
13644 to 32 bits, including the sign. Since they represent physical distances,
13645 there is a small unit of measurement such that increasing |h| by~1 means
13646 moving a certain tiny distance to the right. The actual unit of
13647 measurement is variable, as explained below; \TeX\ sets things up so that
13648 its \.{DVI} output is in sp units, i.e., scaled points, in agreement with
13649 all the |scaled| dimensions in \TeX's data structures.
13650
13651 @ Here is a list of all the commands that may appear in a \.{XDV} file. Each
13652 command is specified by its symbolic name (e.g., |bop|), its opcode byte
13653 (e.g., 139), and its parameters (if any). The parameters are followed
13654 by a bracketed number telling how many bytes they occupy; for example,
13655 `|p[4]|' means that parameter |p| is four bytes long.
13656
13657 \yskip\hang|set_char_0| 0. Typeset character number~0 from font~|f|
13658 such that the reference point of the character is at |(h,v)|. Then
13659 increase |h| by the width of that character. Note that a character may
13660 have zero or negative width, so one cannot be sure that |h| will advance
13661 after this command; but |h| usually does increase.
13662
13663 \yskip\hang\\{set\_char\_1} through \\{set\_char\_127} (opcodes 1 to 127).
13664 Do the operations of |set_char_0|; but use the character whose number
13665 matches the opcode, instead of character~0.
13666
13667 \yskip\hang|set1| 128 |c[1]|. Same as |set_char_0|, except that character
13668 number~|c| is typeset. \TeX82 uses this command for characters in the
13669 range |128<=c<256|.
13670
13671 \yskip\hang|@!set2| 129 |c[2]|. Same as |set1|, except that |c|~is two
13672 bytes long, so it is in the range |0<=c<65536|. \TeX82 never uses this
13673 command, but it should come in handy for extensions of \TeX\ that deal
13674 with oriental languages.
13675 @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
13676
13677 \yskip\hang|@!set3| 130 |c[3]|. Same as |set1|, except that |c|~is three
13678 bytes long, so it can be as large as $2^{24}-1$. Not even the Chinese
13679 language has this many characters, but this command might prove useful
13680 in some yet unforeseen extension.
13681
13682 \yskip\hang|@!set4| 131 |c[4]|. Same as |set1|, except that |c|~is four
13683 bytes long. Imagine that.
13684
13685 \yskip\hang|set_rule| 132 |a[4]| |b[4]|. Typeset a solid black rectangle
13686 of height~|a| and width~|b|, with its bottom left corner at |(h,v)|. Then
13687 set |h:=h+b|. If either |a<=0| or |b<=0|, nothing should be typeset. Note
13688 that if |b<0|, the value of |h| will decrease even though nothing else happens.
13689 See below for details about how to typeset rules so that consistency with
13690 \MF\ is guaranteed.
13691
13692 \yskip\hang|@!put1| 133 |c[1]|. Typeset character number~|c| from font~|f|
13693 such that the reference point of the character is at |(h,v)|. (The `put'
13694 commands are exactly like the `set' commands, except that they simply put out a
13695 character or a rule without moving the reference point afterwards.)
13696
13697 \yskip\hang|@!put2| 134 |c[2]|. Same as |set2|, except that |h| is not changed.
13698
13699 \yskip\hang|@!put3| 135 |c[3]|. Same as |set3|, except that |h| is not changed.
13700
13701 \yskip\hang|@!put4| 136 |c[4]|. Same as |set4|, except that |h| is not changed.
13702
13703 \yskip\hang|put_rule| 137 |a[4]| |b[4]|. Same as |set_rule|, except that
13704 |h| is not changed.
13705
13706 \yskip\hang|nop| 138. No operation, do nothing. Any number of |nop|'s
13707 may occur between \.{DVI} commands, but a |nop| cannot be inserted between
13708 a command and its parameters or between two parameters.
13709
13710 \yskip\hang|bop| 139 $c_0[4]$ $c_1[4]$ $\ldots$ $c_9[4]$ $p[4]$. Beginning
13711 of a page: Set |(h,v,w,x,y,z):=(0,0,0,0,0,0)| and set the stack empty. Set
13712 the current font |f| to an undefined value. The ten $c_i$ parameters hold
13713 the values of \.{\\count0} $\ldots$ \.{\\count9} in \TeX\ at the time
13714 \.{\\shipout} was invoked for this page; they can be used to identify
13715 pages, if a user wants to print only part of a \.{DVI} file. The parameter
13716 |p| points to the previous |bop| in the file; the first
13717 |bop| has $p=-1$.
13718
13719 \yskip\hang|eop| 140. End of page: Print what you have read since the
13720 previous |bop|. At this point the stack should be empty. (The \.{DVI}-reading
13721 programs that drive most output devices will have kept a buffer of the
13722 material that appears on the page that has just ended. This material is
13723 largely, but not entirely, in order by |v| coordinate and (for fixed |v|) by
13724 |h|~coordinate; so it usually needs to be sorted into some order that is
13725 appropriate for the device in question.)
13726
13727 \yskip\hang|push| 141. Push the current values of |(h,v,w,x,y,z)| onto the
13728 top of the stack; do not change any of these values. Note that |f| is
13729 not pushed.
13730
13731 \yskip\hang|pop| 142. Pop the top six values off of the stack and assign
13732 them respectively to |(h,v,w,x,y,z)|. The number of pops should never
13733 exceed the number of pushes, since it would be highly embarrassing if the
13734 stack were empty at the time of a |pop| command.
13735
13736 \yskip\hang|right1| 143 |b[1]|. Set |h:=h+b|, i.e., move right |b| units.
13737 The parameter is a signed number in two's complement notation, |-128<=b<128|;
13738 if |b<0|, the reference point moves left.
13739
13740 \yskip\hang|@!right2| 144 |b[2]|. Same as |right1|, except that |b| is a
13741 two-byte quantity in the range |-32768<=b<32768|.
13742
13743 \yskip\hang|@!right3| 145 |b[3]|. Same as |right1|, except that |b| is a
13744 three-byte quantity in the range |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
13745
13746 \yskip\hang|@!right4| 146 |b[4]|. Same as |right1|, except that |b| is a
13747 four-byte quantity in the range |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
13748
13749 \yskip\hang|w0| 147. Set |h:=h+w|; i.e., move right |w| units. With luck,
13750 this parameterless command will usually suffice, because the same kind of motion
13751 will occur several times in succession; the following commands explain how
13752 |w| gets particular values.
13753
13754 \yskip\hang|w1| 148 |b[1]|. Set |w:=b| and |h:=h+b|. The value of |b| is a
13755 signed quantity in two's complement notation, |-128<=b<128|. This command
13756 changes the current |w|~spacing and moves right by |b|.
13757
13758 \yskip\hang|@!w2| 149 |b[2]|. Same as |w1|, but |b| is two bytes long,
13759 |-32768<=b<32768|.
13760
13761 \yskip\hang|@!w3| 150 |b[3]|. Same as |w1|, but |b| is three bytes long,
13762 |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
13763
13764 \yskip\hang|@!w4| 151 |b[4]|. Same as |w1|, but |b| is four bytes long,
13765 |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
13766
13767 \yskip\hang|x0| 152. Set |h:=h+x|; i.e., move right |x| units. The `|x|'
13768 commands are like the `|w|' commands except that they involve |x| instead
13769 of |w|.
13770
13771 \yskip\hang|x1| 153 |b[1]|. Set |x:=b| and |h:=h+b|. The value of |b| is a
13772 signed quantity in two's complement notation, |-128<=b<128|. This command
13773 changes the current |x|~spacing and moves right by |b|.
13774
13775 \yskip\hang|@!x2| 154 |b[2]|. Same as |x1|, but |b| is two bytes long,
13776 |-32768<=b<32768|.
13777
13778 \yskip\hang|@!x3| 155 |b[3]|. Same as |x1|, but |b| is three bytes long,
13779 |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
13780
13781 \yskip\hang|@!x4| 156 |b[4]|. Same as |x1|, but |b| is four bytes long,
13782 |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
13783
13784 \yskip\hang|down1| 157 |a[1]|. Set |v:=v+a|, i.e., move down |a| units.
13785 The parameter is a signed number in two's complement notation, |-128<=a<128|;
13786 if |a<0|, the reference point moves up.
13787
13788 \yskip\hang|@!down2| 158 |a[2]|. Same as |down1|, except that |a| is a
13789 two-byte quantity in the range |-32768<=a<32768|.
13790
13791 \yskip\hang|@!down3| 159 |a[3]|. Same as |down1|, except that |a| is a
13792 three-byte quantity in the range |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
13793
13794 \yskip\hang|@!down4| 160 |a[4]|. Same as |down1|, except that |a| is a
13795 four-byte quantity in the range |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
13796
13797 \yskip\hang|y0| 161. Set |v:=v+y|; i.e., move down |y| units. With luck,
13798 this parameterless command will usually suffice, because the same kind of motion
13799 will occur several times in succession; the following commands explain how
13800 |y| gets particular values.
13801
13802 \yskip\hang|y1| 162 |a[1]|. Set |y:=a| and |v:=v+a|. The value of |a| is a
13803 signed quantity in two's complement notation, |-128<=a<128|. This command
13804 changes the current |y|~spacing and moves down by |a|.
13805
13806 \yskip\hang|@!y2| 163 |a[2]|. Same as |y1|, but |a| is two bytes long,
13807 |-32768<=a<32768|.
13808
13809 \yskip\hang|@!y3| 164 |a[3]|. Same as |y1|, but |a| is three bytes long,
13810 |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
13811
13812 \yskip\hang|@!y4| 165 |a[4]|. Same as |y1|, but |a| is four bytes long,
13813 |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
13814
13815 \yskip\hang|z0| 166. Set |v:=v+z|; i.e., move down |z| units. The `|z|' commands
13816 are like the `|y|' commands except that they involve |z| instead of |y|.
13817
13818 \yskip\hang|z1| 167 |a[1]|. Set |z:=a| and |v:=v+a|. The value of |a| is a
13819 signed quantity in two's complement notation, |-128<=a<128|. This command
13820 changes the current |z|~spacing and moves down by |a|.
13821
13822 \yskip\hang|@!z2| 168 |a[2]|. Same as |z1|, but |a| is two bytes long,
13823 |-32768<=a<32768|.
13824
13825 \yskip\hang|@!z3| 169 |a[3]|. Same as |z1|, but |a| is three bytes long,
13826 |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
13827
13828 \yskip\hang|@!z4| 170 |a[4]|. Same as |z1|, but |a| is four bytes long,
13829 |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
13830
13831 \yskip\hang|fnt_num_0| 171. Set |f:=0|. Font 0 must previously have been
13832 defined by a \\{fnt\_def} instruction, as explained below.
13833
13834 \yskip\hang\\{fnt\_num\_1} through \\{fnt\_num\_63} (opcodes 172 to 234). Set
13835 |f:=1|, \dots, \hbox{|f:=63|}, respectively.
13836
13837 \yskip\hang|fnt1| 235 |k[1]|. Set |f:=k|. \TeX82 uses this command for font
13838 numbers in the range |64<=k<256|.
13839
13840 \yskip\hang|@!fnt2| 236 |k[2]|. Same as |fnt1|, except that |k|~is two
13841 bytes long, so it is in the range |0<=k<65536|. \TeX82 never generates this
13842 command, but large font numbers may prove useful for specifications of
13843 color or texture, or they may be used for special fonts that have fixed
13844 numbers in some external coding scheme.
13845
13846 \yskip\hang|@!fnt3| 237 |k[3]|. Same as |fnt1|, except that |k|~is three
13847 bytes long, so it can be as large as $2^{24}-1$.
13848
13849 \yskip\hang|@!fnt4| 238 |k[4]|. Same as |fnt1|, except that |k|~is four
13850 bytes long; this is for the really big font numbers (and for the negative ones).
13851
13852 \yskip\hang|xxx1| 239 |k[1]| |x[k]|. This command is undefined in
13853 general; it functions as a $(k+2)$-byte |nop| unless special \.{DVI}-reading
13854 programs are being used. \TeX82 generates |xxx1| when a short enough
13855 \.{\\special} appears, setting |k| to the number of bytes being sent. It
13856 is recommended that |x| be a string having the form of a keyword followed
13857 by possible parameters relevant to that keyword.
13858
13859 \yskip\hang|@!xxx2| 240 |k[2]| |x[k]|. Like |xxx1|, but |0<=k<65536|.
13860
13861 \yskip\hang|@!xxx3| 241 |k[3]| |x[k]|. Like |xxx1|, but |0<=k<@t$2^{24}$@>|.
13862
13863 \yskip\hang|xxx4| 242 |k[4]| |x[k]|. Like |xxx1|, but |k| can be ridiculously
13864 large. \TeX82 uses |xxx4| when sending a string of length 256 or more.
13865
13866 \yskip\hang|fnt_def1| 243 |k[1]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13867 Define font |k|, where |0<=k<256|; font definitions will be explained shortly.
13868
13869 \yskip\hang|@!fnt_def2| 244 |k[2]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13870 Define font |k|, where |0<=k<65536|.
13871
13872 \yskip\hang|@!fnt_def3| 245 |k[3]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13873 Define font |k|, where |0<=k<@t$2^{24}$@>|.
13874
13875 \yskip\hang|@!fnt_def4| 246 |k[4]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
13876 Define font |k|, where |@t$-2^{31}$@><=k<@t$2^{31}$@>|.
13877
13878 \yskip\hang|pre| 247 |i[1]| |num[4]| |den[4]| |mag[4]| |k[1]| |x[k]|.
13879 Beginning of the preamble; this must come at the very beginning of the
13880 file. Parameters |i|, |num|, |den|, |mag|, |k|, and |x| are explained below.
13881
13882 \yskip\hang|post| 248. Beginning of the postamble, see below.
13883
13884 \yskip\hang|post_post| 249. Ending of the postamble, see below.
13885
13886 \yskip\noindent Commands 250--255 are undefined in normal \.{DVI} files, but
13887 the following commands are used in \.{XDV} files.
13888
13889 \yskip\hang\vbox{\halign{#&#\hfil\cr
13890 |define_native_font| 252 & |k[4]| |s[4]| |flags[2]| |l[1]| |n[l]| |i[4]|\cr
13891 & |if (flags and COLORED) then| |rgba[4]|\cr
13892 & |if (flags and EXTEND) then| |extend[4]|\cr
13893 & |if (flags and SLANT) then| |slant[4]|\cr
13894 & |if (flags and EMBOLDEN) then| |embolden[4]|\cr
13895 }}
13896
13897 \yskip\hang|set_glyphs| 253 |w[4]| |k[2]| |xy[8k]| |g[2k]|.
13898
13899 \yskip\hang|set_text_and_glyphs| 254 |l[2]| |t[2l]| |w[4]| |k[2]| |xy[8k]| |g[2k]|.
13900
13901 \yskip\noindent Commands 250 and 255 are undefined in normal \.{XDV} files.
13902
13903 @ @d set_char_0=0 {typeset character 0 and move right}
13904 @d set1=128 {typeset a character and move right}
13905 @d set_rule=132 {typeset a rule and move right}
13906 @d put_rule=137 {typeset a rule}
13907 @d nop=138 {no operation}
13908 @d bop=139 {beginning of page}
13909 @d eop=140 {ending of page}
13910 @d push=141 {save the current positions}
13911 @d pop=142 {restore previous positions}
13912 @d right1=143 {move right}
13913 @d w0=147 {move right by |w|}
13914 @d w1=148 {move right and set |w|}
13915 @d x0=152 {move right by |x|}
13916 @d x1=153 {move right and set |x|}
13917 @d down1=157 {move down}
13918 @d y0=161 {move down by |y|}
13919 @d y1=162 {move down and set |y|}
13920 @d z0=166 {move down by |z|}
13921 @d z1=167 {move down and set |z|}
13922 @d fnt_num_0=171 {set current font to 0}
13923 @d fnt1=235 {set current font}
13924 @d xxx1=239 {extension to \.{DVI} primitives}
13925 @d xxx4=242 {potentially long extension to \.{DVI} primitives}
13926 @d fnt_def1=243 {define the meaning of a font number}
13927 @d pre=247 {preamble}
13928 @d post=248 {postamble beginning}
13929 @d post_post=249 {postamble ending}
13930
13931 @d define_native_font=252 {define native font}
13932 @d set_glyphs=253 {sequence of glyphs with individual x-y coordinates}
13933 @d set_text_and_glyphs=254 {run of Unicode (UTF16) text followed by positioned glyphs}
13934
13935 @ The preamble contains basic information about the file as a whole. As
13936 stated above, there are six parameters:
13937 $$\hbox{|@!i[1]| |@!num[4]| |@!den[4]| |@!mag[4]| |@!k[1]| |@!x[k]|.}$$
13938 The |i| byte identifies \.{DVI} format; in \XeTeX\ this byte is set to~7, as we
13939 have new \.{DVI} opcodes, while in \TeX82 it is always set to~2. (The value
13940 |i=3| is used for an extended format that allows a mixture of right-to-left and
13941 left-to-right typesetting. Older versions of \XeTeX\ used |i=4|, |i=5| and |i=6|.)
13942
13943 The next two parameters, |num| and |den|, are positive integers that define
13944 the units of measurement; they are the numerator and denominator of a
13945 fraction by which all dimensions in the \.{DVI} file could be multiplied
13946 in order to get lengths in units of $10^{-7}$ meters. Since $\rm 7227{pt} =
13947 254{cm}$, and since \TeX\ works with scaled points where there are $2^{16}$
13948 sp in a point, \TeX\ sets
13949 $|num|/|den|=(254\cdot10^5)/(7227\cdot2^{16})=25400000/473628672$.
13950 @^sp@>
13951
13952 The |mag| parameter is what \TeX\ calls \.{\\mag}, i.e., 1000 times the
13953 desired magnification. The actual fraction by which dimensions are
13954 multiplied is therefore $|mag|\cdot|num|/1000|den|$. Note that if a \TeX\
13955 source document does not call for any `\.{true}' dimensions, and if you
13956 change it only by specifying a different \.{\\mag} setting, the \.{DVI}
13957 file that \TeX\ creates will be completely unchanged except for the value
13958 of |mag| in the preamble and postamble. (Fancy \.{DVI}-reading programs allow
13959 users to override the |mag|~setting when a \.{DVI} file is being printed.)
13960
13961 Finally, |k| and |x| allow the \.{DVI} writer to include a comment, which is not
13962 interpreted further. The length of comment |x| is |k|, where |0<=k<256|.
13963
13964 @d id_byte=7 {identifies the kind of \.{DVI} files described here}
13965
13966 @ Font definitions for a given font number |k| contain further parameters
13967 $$\hbox{|c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.}$$
13968 The four-byte value |c| is the check sum that \TeX\ found in the \.{TFM}
13969 file for this font; |c| should match the check sum of the font found by
13970 programs that read this \.{DVI} file.
13971 @^check sum@>
13972
13973 Parameter |s| contains a fixed-point scale factor that is applied to
13974 the character widths in font |k|; font dimensions in \.{TFM} files and
13975 other font files are relative to this quantity, which is called the
13976 ``at size'' elsewhere in this documentation. The value of |s| is
13977 always positive and less than $2^{27}$. It is given in the same units
13978 as the other \.{DVI} dimensions, i.e., in sp when \TeX82 has made the
13979 file. Parameter |d| is similar to |s|; it is the ``design size,'' and
13980 (like~|s|) it is given in \.{DVI} units. Thus, font |k| is to be used
13981 at $|mag|\cdot s/1000d$ times its normal size.
13982
13983 The remaining part of a font definition gives the external name of the font,
13984 which is an ASCII string of length |a+l|. The number |a| is the length
13985 of the ``area'' or directory, and |l| is the length of the font name itself;
13986 the standard local system font area is supposed to be used when |a=0|.
13987 The |n| field contains the area in its first |a| bytes.
13988
13989 Font definitions must appear before the first use of a particular font number.
13990 Once font |k| is defined, it must not be defined again; however, we
13991 shall see below that font definitions appear in the postamble as well as
13992 in the pages, so in this sense each font number is defined exactly twice,
13993 if at all. Like |nop| commands, font definitions can
13994 appear before the first |bop|, or between an |eop| and a |bop|.
13995
13996 @ Sometimes it is desirable to make horizontal or vertical rules line up
13997 precisely with certain features in characters of a font. It is possible to
13998 guarantee the correct matching between \.{DVI} output and the characters
13999 generated by \MF\ by adhering to the following principles: (1)~The \MF\
14000 characters should be positioned so that a bottom edge or left edge that is
14001 supposed to line up with the bottom or left edge of a rule appears at the
14002 reference point, i.e., in row~0 and column~0 of the \MF\ raster. This
14003 ensures that the position of the rule will not be rounded differently when
14004 the pixel size is not a perfect multiple of the units of measurement in
14005 the \.{DVI} file. (2)~A typeset rule of height $a>0$ and width $b>0$
14006 should be equivalent to a \MF-generated character having black pixels in
14007 precisely those raster positions whose \MF\ coordinates satisfy
14008 |0<=x<@t$\alpha$@>b| and |0<=y<@t$\alpha$@>a|, where $\alpha$ is the number
14009 of pixels per \.{DVI} unit.
14010 @:METAFONT}{\MF@>
14011 @^alignment of rules with characters@>
14012 @^rules aligning with characters@>
14013
14014 @ The last page in a \.{DVI} file is followed by `|post|'; this command
14015 introduces the postamble, which summarizes important facts that \TeX\ has
14016 accumulated about the file, making it possible to print subsets of the data
14017 with reasonable efficiency. The postamble has the form
14018 $$\vbox{\halign{\hbox{#\hfil}\cr
14019 |post| |p[4]| |num[4]| |den[4]| |mag[4]| |l[4]| |u[4]| |s[2]| |t[2]|\cr
14020 $\langle\,$font definitions$\,\rangle$\cr
14021 |post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
14022 Here |p| is a pointer to the final |bop| in the file. The next three
14023 parameters, |num|, |den|, and |mag|, are duplicates of the quantities that
14024 appeared in the preamble.
14025
14026 Parameters |l| and |u| give respectively the height-plus-depth of the tallest
14027 page and the width of the widest page, in the same units as other dimensions
14028 of the file. These numbers might be used by a \.{DVI}-reading program to
14029 position individual ``pages'' on large sheets of film or paper; however,
14030 the standard convention for output on normal size paper is to position each
14031 page so that the upper left-hand corner is exactly one inch from the left
14032 and the top. Experience has shown that it is unwise to design \.{DVI}-to-printer
14033 software that attempts cleverly to center the output; a fixed position of
14034 the upper left corner is easiest for users to understand and to work with.
14035 Therefore |l| and~|u| are often ignored.
14036
14037 Parameter |s| is the maximum stack depth (i.e., the largest excess of
14038 |push| commands over |pop| commands) needed to process this file. Then
14039 comes |t|, the total number of pages (|bop| commands) present.
14040
14041 The postamble continues with font definitions, which are any number of
14042 \\{fnt\_def} commands as described above, possibly interspersed with |nop|
14043 commands. Each font number that is used in the \.{DVI} file must be defined
14044 exactly twice: Once before it is first selected by a \\{fnt} command, and once
14045 in the postamble.
14046
14047 @ The last part of the postamble, following the |post_post| byte that
14048 signifies the end of the font definitions, contains |q|, a pointer to the
14049 |post| command that started the postamble. An identification byte, |i|,
14050 comes next; this currently equals~2, as in the preamble.
14051
14052 The |i| byte is followed by four or more bytes that are all equal to
14053 the decimal number 223 (i.e., @'337 in octal). \TeX\ puts out four to seven of
14054 these trailing bytes, until the total length of the file is a multiple of
14055 four bytes, since this works out best on machines that pack four bytes per
14056 word; but any number of 223's is allowed, as long as there are at least four
14057 of them. In effect, 223 is a sort of signature that is added at the very end.
14058 @^Fuchs, David Raymond@>
14059
14060 This curious way to finish off a \.{DVI} file makes it feasible for
14061 \.{DVI}-reading programs to find the postamble first, on most computers,
14062 even though \TeX\ wants to write the postamble last. Most operating
14063 systems permit random access to individual words or bytes of a file, so
14064 the \.{DVI} reader can start at the end and skip backwards over the 223's
14065 until finding the identification byte. Then it can back up four bytes, read
14066 |q|, and move to byte |q| of the file. This byte should, of course,
14067 contain the value 248 (|post|); now the postamble can be read, so the
14068 \.{DVI} reader can discover all the information needed for typesetting the
14069 pages. Note that it is also possible to skip through the \.{DVI} file at
14070 reasonably high speed to locate a particular page, if that proves
14071 desirable. This saves a lot of time, since \.{DVI} files used in production
14072 jobs tend to be large.
14073
14074 Unfortunately, however, standard \PASCAL\ does not include the ability to
14075 @^system dependencies@>
14076 access a random position in a file, or even to determine the length of a file.
14077 Almost all systems nowadays provide the necessary capabilities, so \.{DVI}
14078 format has been designed to work most efficiently with modern operating systems.
14079 But if \.{DVI} files have to be processed under the restrictions of standard
14080 \PASCAL, one can simply read them from front to back, since the necessary
14081 header information is present in the preamble and in the font definitions.
14082 (The |l| and |u| and |s| and |t| parameters, which appear only in the
14083 postamble, are ``frills'' that are handy but not absolutely necessary.)
14084
14085 @* \[32] Shipping pages out.
14086 After considering \TeX's eyes and stomach, we come now to the bowels.
14087 @^bowels@>
14088
14089 The |ship_out| procedure is given a pointer to a box; its mission is
14090 to describe that box in \.{DVI} form, outputting a ``page'' to |dvi_file|.
14091 The \.{DVI} coordinates $(h,v)=(0,0)$ should correspond to the upper left
14092 corner of the box being shipped.
14093
14094 Since boxes can be inside of boxes inside of boxes, the main work of
14095 |ship_out| is done by two mutually recursive routines, |hlist_out|
14096 and |vlist_out|, which traverse the hlists and vlists inside of horizontal
14097 and vertical boxes.
14098
14099 As individual pages are being processed, we need to accumulate
14100 information about the entire set of pages, since such statistics must be
14101 reported in the postamble. The global variables |total_pages|, |max_v|,
14102 |max_h|, |max_push|, and |last_bop| are used to record this information.
14103
14104 The variable |doing_leaders| is |true| while leaders are being output.
14105 The variable |dead_cycles| contains the number of times an output routine
14106 has been initiated since the last |ship_out|.
14107
14108 A few additional global variables are also defined here for use in
14109 |vlist_out| and |hlist_out|. They could have been local variables, but
14110 that would waste stack space when boxes are deeply nested, since the
14111 values of these variables are not needed during recursive calls.
14112 @^recursion@>
14113
14114 @<Glob...@>=
14115 @!total_pages:integer; {the number of pages that have been shipped out}
14116 @!max_v:scaled; {maximum height-plus-depth of pages shipped so far}
14117 @!max_h:scaled; {maximum width of pages shipped so far}
14118 @!max_push:integer; {deepest nesting of |push| commands encountered so far}
14119 @!last_bop:integer; {location of previous |bop| in the \.{DVI} output}
14120 @!dead_cycles:integer; {recent outputs that didn't ship anything out}
14121 @!doing_leaders:boolean; {are we inside a leader box?}
14122 @#
14123 @!c,@!f:quarterword; {character and font in current |char_node|}
14124 @!rule_ht,@!rule_dp,@!rule_wd:scaled; {size of current rule being output}
14125 @!g:pointer; {current glue specification}
14126 @!lq,@!lr:integer; {quantities used in calculations for leaders}
14127
14128 @ @<Set init...@>=
14129 total_pages:=0; max_v:=0; max_h:=0; max_push:=0; last_bop:=-1;
14130 doing_leaders:=false; dead_cycles:=0; cur_s:=-1;
14131
14132 @ The \.{DVI} bytes are output to a buffer instead of being written directly
14133 to the output file. This makes it possible to reduce the overhead of
14134 subroutine calls, thereby measurably speeding up the computation, since
14135 output of \.{DVI} bytes is part of \TeX's inner loop. And it has another
14136 advantage as well, since we can change instructions in the buffer in order to
14137 make the output more compact. For example, a `|down2|' command can be
14138 changed to a `|y2|', thereby making a subsequent `|y0|' command possible,
14139 saving two bytes.
14140
14141 The output buffer is divided into two parts of equal size; the bytes found
14142 in |dvi_buf[0..half_buf-1]| constitute the first half, and those in
14143 |dvi_buf[half_buf..dvi_buf_size-1]| constitute the second. The global
14144 variable |dvi_ptr| points to the position that will receive the next
14145 output byte. When |dvi_ptr| reaches |dvi_limit|, which is always equal
14146 to one of the two values |half_buf| or |dvi_buf_size|, the half buffer that
14147 is about to be invaded next is sent to the output and |dvi_limit| is
14148 changed to its other value. Thus, there is always at least a half buffer's
14149 worth of information present, except at the very beginning of the job.
14150
14151 Bytes of the \.{DVI} file are numbered sequentially starting with 0;
14152 the next byte to be generated will be number |dvi_offset+dvi_ptr|.
14153 A byte is present in the buffer only if its number is |>=dvi_gone|.
14154
14155 @<Types...@>=
14156 @!dvi_index=0..dvi_buf_size; {an index into the output buffer}
14157
14158 @ Some systems may find it more efficient to make |dvi_buf| a |packed|
14159 array, since output of four bytes at once may be facilitated.
14160 @^system dependencies@>
14161
14162 @<Glob...@>=
14163 @!dvi_buf:array[dvi_index] of eight_bits; {buffer for \.{DVI} output}
14164 @!half_buf:dvi_index; {half of |dvi_buf_size|}
14165 @!dvi_limit:dvi_index; {end of the current half buffer}
14166 @!dvi_ptr:dvi_index; {the next available buffer address}
14167 @!dvi_offset:integer; {|dvi_buf_size| times the number of times the
14168 output buffer has been fully emptied}
14169 @!dvi_gone:integer; {the number of bytes already output to |dvi_file|}
14170
14171 @ Initially the buffer is all in one piece; we will output half of it only
14172 after it first fills up.
14173
14174 @<Set init...@>=
14175 half_buf:=dvi_buf_size div 2; dvi_limit:=dvi_buf_size; dvi_ptr:=0;
14176 dvi_offset:=0; dvi_gone:=0;
14177
14178 @ The actual output of |dvi_buf[a..b]| to |dvi_file| is performed by calling
14179 |write_dvi(a,b)|. For best results, this procedure should be optimized to
14180 run as fast as possible on each particular system, since it is part of
14181 \TeX's inner loop. It is safe to assume that |a| and |b+1| will both be
14182 multiples of 4 when |write_dvi(a,b)| is called; therefore it is possible on
14183 many machines to use efficient methods to pack four bytes per word and to
14184 output an array of words with one system call.
14185 @^system dependencies@>
14186 @^inner loop@>
14187 @^defecation@>
14188
14189 @p procedure write_dvi(@!a,@!b:dvi_index);
14190 var k:dvi_index;
14191 begin for k:=a to b do write(dvi_file,dvi_buf[k]);
14192 end;
14193
14194 @ To put a byte in the buffer without paying the cost of invoking a procedure
14195 each time, we use the macro |dvi_out|.
14196
14197 @d dvi_out(#)==@+begin dvi_buf[dvi_ptr]:=#; incr(dvi_ptr);
14198 if dvi_ptr=dvi_limit then dvi_swap;
14199 end
14200
14201 @p procedure dvi_swap; {outputs half of the buffer}
14202 begin if dvi_limit=dvi_buf_size then
14203 begin write_dvi(0,half_buf-1); dvi_limit:=half_buf;
14204 dvi_offset:=dvi_offset+dvi_buf_size; dvi_ptr:=0;
14205 end
14206 else begin write_dvi(half_buf,dvi_buf_size-1); dvi_limit:=dvi_buf_size;
14207 end;
14208 dvi_gone:=dvi_gone+half_buf;
14209 end;
14210
14211 @ Here is how we clean out the buffer when \TeX\ is all through; |dvi_ptr|
14212 will be a multiple of~4.
14213
14214 @<Empty the last bytes out of |dvi_buf|@>=
14215 if dvi_limit=half_buf then write_dvi(half_buf,dvi_buf_size-1);
14216 if dvi_ptr>0 then write_dvi(0,dvi_ptr-1)
14217
14218 @ The |dvi_four| procedure outputs four bytes in two's complement notation,
14219 without risking arithmetic overflow.
14220
14221 @p procedure dvi_four(@!x:integer);
14222 begin if x>=0 then dvi_out(x div @'100000000)
14223 else begin x:=x+@'10000000000;
14224 x:=x+@'10000000000;
14225 dvi_out((x div @'100000000) + 128);
14226 end;
14227 x:=x mod @'100000000; dvi_out(x div @'200000);
14228 x:=x mod @'200000; dvi_out(x div @'400);
14229 dvi_out(x mod @'400);
14230 end;
14231
14232 procedure dvi_two(s: UTF16_code);
14233 begin
14234 dvi_out(s div @'400);
14235 dvi_out(s mod @'400);
14236 end;
14237
14238 @ A mild optimization of the output is performed by the |dvi_pop|
14239 routine, which issues a |pop| unless it is possible to cancel a
14240 `|push| |pop|' pair. The parameter to |dvi_pop| is the byte address
14241 following the old |push| that matches the new |pop|.
14242
14243 @p procedure dvi_pop(@!l:integer);
14244 begin if (l=dvi_offset+dvi_ptr)and(dvi_ptr>0) then decr(dvi_ptr)
14245 else dvi_out(pop);
14246 end;
14247
14248 @ Here's a procedure that outputs a font definition. Since \TeX82 uses at
14249 most 256 different fonts per job, |fnt_def1| is always used as the command code.
14250
14251 @p procedure dvi_native_font_def(@!f:internal_font_number);
14252 var
14253 font_def_length, i: integer;
14254 begin
14255 dvi_out(define_native_font);
14256 dvi_four(f-font_base-1);
14257 font_def_length:=make_font_def(f);
14258 for i:=0 to font_def_length - 1 do dvi_out(xdv_buffer[i]);
14259 end;
14260
14261 procedure dvi_font_def(@!f:internal_font_number);
14262 var k:pool_pointer; {index into |str_pool|}
14263 l:integer; {length of name without mapping option}
14264 begin if is_native_font(f) then dvi_native_font_def(f) else
14265 begin dvi_out(fnt_def1);
14266 dvi_out(f-font_base-1);@/
14267 dvi_out(qo(font_check[f].b0));
14268 dvi_out(qo(font_check[f].b1));
14269 dvi_out(qo(font_check[f].b2));
14270 dvi_out(qo(font_check[f].b3));@/
14271 dvi_four(font_size[f]);
14272 dvi_four(font_dsize[f]);@/
14273 dvi_out(length(font_area[f]));
14274 @<Output the font name whose internal number is |f|@>;
14275 end;
14276
14277 @ @<Output the font name whose internal number is |f|@>=
14278 l:=0; k:=str_start_macro(font_name[f]);
14279 {search for colon; we will truncate the name there}
14280 while (l=0) and (k<str_start_macro(font_name[f]+1)) do begin
14281 if so(str_pool[k]) = ":" then l:=k-str_start_macro(font_name[f]);
14282 incr(k);
14283 end;
14284 if l=0 then l:=length(font_name[f]); {no colon found}
14285 dvi_out(l);
14286 for k:=str_start_macro(font_area[f]) to str_start_macro(font_area[f]+1)-1 do
14287 dvi_out(so(str_pool[k]));
14288 for k:=str_start_macro(font_name[f]) to str_start_macro(font_name[f])+l-1 do
14289 dvi_out(so(str_pool[k]));
14290 end;
14291
14292 @ Versions of \TeX\ intended for small computers might well choose to omit
14293 the ideas in the next few parts of this program, since it is not really
14294 necessary to optimize the \.{DVI} code by making use of the |w0|, |x0|,
14295 |y0|, and |z0| commands. Furthermore, the algorithm that we are about to
14296 describe does not pretend to give an optimum reduction in the length
14297 of the \.{DVI} code; after all, speed is more important than compactness.
14298 But the method is surprisingly effective, and it takes comparatively little
14299 time.
14300
14301 We can best understand the basic idea by first considering a simpler problem
14302 that has the same essential characteristics. Given a sequence of digits,
14303 say $3\,1\,4\,1\,5\,9\,2\,6\,5\,3\,5\,8\,9$, we want to assign subscripts
14304 $d$, $y$, or $z$ to each digit so as to maximize the number of ``$y$-hits''
14305 and ``$z$-hits''; a $y$-hit is an instance of two appearances of the same
14306 digit with the subscript $y$, where no $y$'s intervene between the two
14307 appearances, and a $z$-hit is defined similarly. For example, the sequence
14308 above could be decorated with subscripts as follows:
14309 $$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.$$
14310 There are three $y$-hits ($1_y\ldots1_y$ and $5_y\ldots5_y\ldots5_y$) and
14311 one $z$-hit ($3_z\ldots3_z$); there are no $d$-hits, since the two appearances
14312 of $9_d$ have $d$'s between them, but we don't count $d$-hits so it doesn't
14313 matter how many there are. These subscripts are analogous to the \.{DVI}
14314 commands called \\{down}, $y$, and $z$, and the digits are analogous to
14315 different amounts of vertical motion; a $y$-hit or $z$-hit corresponds to
14316 the opportunity to use the one-byte commands |y0| or |z0| in a \.{DVI} file.
14317
14318 \TeX's method of assigning subscripts works like this: Append a new digit,
14319 say $\delta$, to the right of the sequence. Now look back through the
14320 sequence until one of the following things happens: (a)~You see
14321 $\delta_y$ or $\delta_z$, and this was the first time you encountered a
14322 $y$ or $z$ subscript, respectively. Then assign $y$ or $z$ to the new
14323 $\delta$; you have scored a hit. (b)~You see $\delta_d$, and no $y$
14324 subscripts have been encountered so far during this search. Then change
14325 the previous $\delta_d$ to $\delta_y$ (this corresponds to changing a
14326 command in the output buffer), and assign $y$ to the new $\delta$; it's
14327 another hit. (c)~You see $\delta_d$, and a $y$ subscript has been seen
14328 but not a $z$. Change the previous $\delta_d$ to $\delta_z$ and assign
14329 $z$ to the new $\delta$. (d)~You encounter both $y$ and $z$ subscripts
14330 before encountering a suitable $\delta$, or you scan all the way to the
14331 front of the sequence. Assign $d$ to the new $\delta$; this assignment may
14332 be changed later.
14333
14334 The subscripts $3_z\,1_y\,4_d\ldots\,$ in the example above were, in fact,
14335 produced by this procedure, as the reader can verify. (Go ahead and try it.)
14336
14337 @ In order to implement such an idea, \TeX\ maintains a stack of pointers
14338 to the \\{down}, $y$, and $z$ commands that have been generated for the
14339 current page. And there is a similar stack for \\{right}, |w|, and |x|
14340 commands. These stacks are called the down stack and right stack, and their
14341 top elements are maintained in the variables |down_ptr| and |right_ptr|.
14342
14343 Each entry in these stacks contains four fields: The |width| field is
14344 the amount of motion down or to the right; the |location| field is the
14345 byte number of the \.{DVI} command in question (including the appropriate
14346 |dvi_offset|); the |link| field points to the next item below this one
14347 on the stack; and the |info| field encodes the options for possible change
14348 in the \.{DVI} command.
14349
14350 @d movement_node_size=3 {number of words per entry in the down and right stacks}
14351 @d location(#)==mem[#+2].int {\.{DVI} byte number for a movement command}
14352
14353 @<Glob...@>=
14354 @!down_ptr,@!right_ptr:pointer; {heads of the down and right stacks}
14355
14356 @ @<Set init...@>=
14357 down_ptr:=null; right_ptr:=null;
14358
14359 @ Here is a subroutine that produces a \.{DVI} command for some specified
14360 downward or rightward motion. It has two parameters: |w| is the amount
14361 of motion, and |o| is either |down1| or |right1|. We use the fact that
14362 the command codes have convenient arithmetic properties: |y1-down1=w1-right1|
14363 and |z1-down1=x1-right1|.
14364
14365 @p procedure movement(@!w:scaled;@!o:eight_bits);
14366 label exit,found,not_found,2,1;
14367 var mstate:small_number; {have we seen a |y| or |z|?}
14368 @!p,@!q:pointer; {current and top nodes on the stack}
14369 @!k:integer; {index into |dvi_buf|, modulo |dvi_buf_size|}
14370 begin q:=get_node(movement_node_size); {new node for the top of the stack}
14371 width(q):=w; location(q):=dvi_offset+dvi_ptr;
14372 if o=down1 then
14373 begin link(q):=down_ptr; down_ptr:=q;
14374 end
14375 else begin link(q):=right_ptr; right_ptr:=q;
14376 end;
14377 @<Look at the other stack entries until deciding what sort of \.{DVI} command
14378 to generate; |goto found| if node |p| is a ``hit''@>;
14379 @<Generate a |down| or |right| command for |w| and |return|@>;
14380 found: @<Generate a |y0| or |z0| command in order to reuse a previous
14381 appearance of~|w|@>;
14382 exit:end;
14383
14384 @ The |info| fields in the entries of the down stack or the right stack
14385 have six possible settings: |y_here| or |z_here| mean that the \.{DVI}
14386 command refers to |y| or |z|, respectively (or to |w| or |x|, in the
14387 case of horizontal motion); |yz_OK| means that the \.{DVI} command is
14388 \\{down} (or \\{right}) but can be changed to either |y| or |z| (or
14389 to either |w| or |x|); |y_OK| means that it is \\{down} and can be changed
14390 to |y| but not |z|; |z_OK| is similar; and |d_fixed| means it must stay
14391 \\{down}.
14392
14393 The four settings |yz_OK|, |y_OK|, |z_OK|, |d_fixed| would not need to
14394 be distinguished from each other if we were simply solving the
14395 digit-subscripting problem mentioned above. But in \TeX's case there is
14396 a complication because of the nested structure of |push| and |pop|
14397 commands. Suppose we add parentheses to the digit-subscripting problem,
14398 redefining hits so that $\delta_y\ldots \delta_y$ is a hit if all $y$'s between
14399 the $\delta$'s are enclosed in properly nested parentheses, and if the
14400 parenthesis level of the right-hand $\delta_y$ is deeper than or equal to
14401 that of the left-hand one. Thus, `(' and `)' correspond to `|push|'
14402 and `|pop|'. Now if we want to assign a subscript to the final 1 in the
14403 sequence
14404 $$2_y\,7_d\,1_d\,(\,8_z\,2_y\,8_z\,)\,1$$
14405 we cannot change the previous $1_d$ to $1_y$, since that would invalidate
14406 the $2_y\ldots2_y$ hit. But we can change it to $1_z$, scoring a hit
14407 since the intervening $8_z$'s are enclosed in parentheses.
14408
14409 The program below removes movement nodes that are introduced after a |push|,
14410 before it outputs the corresponding |pop|.
14411
14412 @d y_here=1 {|info| when the movement entry points to a |y| command}
14413 @d z_here=2 {|info| when the movement entry points to a |z| command}
14414 @d yz_OK=3 {|info| corresponding to an unconstrained \\{down} command}
14415 @d y_OK=4 {|info| corresponding to a \\{down} that can't become a |z|}
14416 @d z_OK=5 {|info| corresponding to a \\{down} that can't become a |y|}
14417 @d d_fixed=6 {|info| corresponding to a \\{down} that can't change}
14418
14419 @ When the |movement| procedure gets to the label |found|, the value of
14420 |info(p)| will be either |y_here| or |z_here|. If it is, say, |y_here|,
14421 the procedure generates a |y0| command (or a |w0| command), and marks
14422 all |info| fields between |q| and |p| so that |y| is not OK in that range.
14423
14424 @<Generate a |y0| or |z0| command...@>=
14425 info(q):=info(p);
14426 if info(q)=y_here then
14427 begin dvi_out(o+y0-down1); {|y0| or |w0|}
14428 while link(q)<>p do
14429 begin q:=link(q);
14430 case info(q) of
14431 yz_OK: info(q):=z_OK;
14432 y_OK: info(q):=d_fixed;
14433 othercases do_nothing
14434 endcases;
14435 end;
14436 end
14437 else begin dvi_out(o+z0-down1); {|z0| or |x0|}
14438 while link(q)<>p do
14439 begin q:=link(q);
14440 case info(q) of
14441 yz_OK: info(q):=y_OK;
14442 z_OK: info(q):=d_fixed;
14443 othercases do_nothing
14444 endcases;
14445 end;
14446 end
14447
14448 @ @<Generate a |down| or |right|...@>=
14449 info(q):=yz_OK;
14450 if abs(w)>=@'40000000 then
14451 begin dvi_out(o+3); {|down4| or |right4|}
14452 dvi_four(w); return;
14453 end;
14454 if abs(w)>=@'100000 then
14455 begin dvi_out(o+2); {|down3| or |right3|}
14456 if w<0 then w:=w+@'100000000;
14457 dvi_out(w div @'200000); w:=w mod @'200000; goto 2;
14458 end;
14459 if abs(w)>=@'200 then
14460 begin dvi_out(o+1); {|down2| or |right2|}
14461 if w<0 then w:=w+@'200000;
14462 goto 2;
14463 end;
14464 dvi_out(o); {|down1| or |right1|}
14465 if w<0 then w:=w+@'400;
14466 goto 1;
14467 2: dvi_out(w div @'400);
14468 1: dvi_out(w mod @'400); return
14469
14470 @ As we search through the stack, we are in one of three states,
14471 |y_seen|, |z_seen|, or |none_seen|, depending on whether we have
14472 encountered |y_here| or |z_here| nodes. These states are encoded as
14473 multiples of 6, so that they can be added to the |info| fields for quick
14474 decision-making.
14475 @^inner loop@>
14476
14477 @d none_seen=0 {no |y_here| or |z_here| nodes have been encountered yet}
14478 @d y_seen=6 {we have seen |y_here| but not |z_here|}
14479 @d z_seen=12 {we have seen |z_here| but not |y_here|}
14480
14481 @<Look at the other stack entries until deciding...@>=
14482 p:=link(q); mstate:=none_seen;
14483 while p<>null do
14484 begin if width(p)=w then @<Consider a node with matching width;
14485 |goto found| if it's a hit@>
14486 else case mstate+info(p) of
14487 none_seen+y_here: mstate:=y_seen;
14488 none_seen+z_here: mstate:=z_seen;
14489 y_seen+z_here,z_seen+y_here: goto not_found;
14490 othercases do_nothing
14491 endcases;
14492 p:=link(p);
14493 end;
14494 not_found:
14495
14496 @ We might find a valid hit in a |y| or |z| byte that is already gone
14497 from the buffer. But we can't change bytes that are gone forever; ``the
14498 moving finger writes, $\ldots\,\,$.''
14499
14500 @<Consider a node with matching width...@>=
14501 case mstate+info(p) of
14502 none_seen+yz_OK,none_seen+y_OK,z_seen+yz_OK,z_seen+y_OK:@t@>@;@/
14503 if location(p)<dvi_gone then goto not_found
14504 else @<Change buffered instruction to |y| or |w| and |goto found|@>;
14505 none_seen+z_OK,y_seen+yz_OK,y_seen+z_OK:@t@>@;@/
14506 if location(p)<dvi_gone then goto not_found
14507 else @<Change buffered instruction to |z| or |x| and |goto found|@>;
14508 none_seen+y_here,none_seen+z_here,y_seen+z_here,z_seen+y_here: goto found;
14509 othercases do_nothing
14510 endcases
14511
14512 @ @<Change buffered instruction to |y| or |w| and |goto found|@>=
14513 begin k:=location(p)-dvi_offset;
14514 if k<0 then k:=k+dvi_buf_size;
14515 dvi_buf[k]:=dvi_buf[k]+y1-down1;
14516 info(p):=y_here; goto found;
14517 end
14518
14519 @ @<Change buffered instruction to |z| or |x| and |goto found|@>=
14520 begin k:=location(p)-dvi_offset;
14521 if k<0 then k:=k+dvi_buf_size;
14522 dvi_buf[k]:=dvi_buf[k]+z1-down1;
14523 info(p):=z_here; goto found;
14524 end
14525
14526 @ In case you are wondering when all the movement nodes are removed from
14527 \TeX's memory, the answer is that they are recycled just before
14528 |hlist_out| and |vlist_out| finish outputting a box. This restores the
14529 down and right stacks to the state they were in before the box was output,
14530 except that some |info|'s may have become more restrictive.
14531
14532 @p procedure prune_movements(@!l:integer);
14533 {delete movement nodes with |location>=l|}
14534 label done,exit;
14535 var p:pointer; {node being deleted}
14536 begin while down_ptr<>null do
14537 begin if location(down_ptr)<l then goto done;
14538 p:=down_ptr; down_ptr:=link(p); free_node(p,movement_node_size);
14539 end;
14540 done: while right_ptr<>null do
14541 begin if location(right_ptr)<l then return;
14542 p:=right_ptr; right_ptr:=link(p); free_node(p,movement_node_size);
14543 end;
14544 exit:end;
14545
14546 @ The actual distances by which we want to move might be computed as the
14547 sum of several separate movements. For example, there might be several
14548 glue nodes in succession, or we might want to move right by the width of
14549 some box plus some amount of glue. More importantly, the baselineskip
14550 distances are computed in terms of glue together with the depth and
14551 height of adjacent boxes, and we want the \.{DVI} file to lump these
14552 three quantities together into a single motion.
14553
14554 Therefore, \TeX\ maintains two pairs of global variables: |dvi_h| and |dvi_v|
14555 are the |h| and |v| coordinates corresponding to the commands actually
14556 output to the \.{DVI} file, while |cur_h| and |cur_v| are the coordinates
14557 corresponding to the current state of the output routines. Coordinate
14558 changes will accumulate in |cur_h| and |cur_v| without being reflected
14559 in the output, until such a change becomes necessary or desirable; we
14560 can call the |movement| procedure whenever we want to make |dvi_h=cur_h|
14561 or |dvi_v=cur_v|.
14562
14563 The current font reflected in the \.{DVI} output is called |dvi_f|;
14564 there is no need for a `\\{cur\_f}' variable.
14565
14566 The depth of nesting of |hlist_out| and |vlist_out| is called |cur_s|;
14567 this is essentially the depth of |push| commands in the \.{DVI} output.
14568
14569 For mixed direction text (\TeXXeT) the current text direction is called
14570 |cur_dir|. As the box being shipped out will never be used again and
14571 soon be recycled, we can simply reverse any R-text (i.e., right-to-left)
14572 segments of hlist nodes as well as complete hlist nodes embedded in such
14573 segments. Moreover this can be done iteratively rather than recursively.
14574 There are, however, two complications related to leaders that require
14575 some additional bookkeeping: (1)~One and the same hlist node might be
14576 used more than once (but never inside both L- and R-text); and
14577 (2)~leader boxes inside hlists must be aligned with respect to the left
14578 edge of the original hlist.
14579
14580 A math node is changed into a kern node whenever the text direction
14581 remains the same, it is replaced by an |edge_node| if the text direction
14582 changes; the subtype of an an |hlist_node| inside R-text is changed to
14583 |reversed| once its hlist has been reversed.
14584 @!@^data structure assumptions@>
14585
14586 @d reversed=1 {subtype for an |hlist_node| whose hlist has been reversed}
14587 @d dlist=2 {subtype for an |hlist_node| from display math mode}
14588 @d box_lr(#) == (qo(subtype(#))) {direction mode of a box}
14589 @d set_box_lr(#) == subtype(#):=set_box_lr_end
14590 @d set_box_lr_end(#) == qi(#)
14591 @#
14592 @d left_to_right=0
14593 @d right_to_left=1
14594 @d reflected==1-cur_dir {the opposite of |cur_dir|}
14595 @#
14596 @d synch_h==if cur_h<>dvi_h then
14597 begin movement(cur_h-dvi_h,right1); dvi_h:=cur_h;
14598 end
14599 @d synch_v==if cur_v<>dvi_v then
14600 begin movement(cur_v-dvi_v,down1); dvi_v:=cur_v;
14601 end
14602
14603 @<Glob...@>=
14604 @!dvi_h,@!dvi_v:scaled; {a \.{DVI} reader program thinks we are here}
14605 @!cur_h,@!cur_v:scaled; {\TeX\ thinks we are here}
14606 @!dvi_f:internal_font_number; {the current font}
14607 @!cur_s:integer; {current depth of output box nesting, initially $-1$}
14608
14609 @ @<Initialize variables as |ship_out| begins@>=
14610 dvi_h:=0; dvi_v:=0; cur_h:=h_offset; dvi_f:=null_font;
14611 @<Calculate page dimensions and margins@>;
14612 ensure_dvi_open;
14613 if total_pages=0 then
14614 begin dvi_out(pre); dvi_out(id_byte); {output the preamble}
14615 @^preamble of \.{DVI} file@>
14616 dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
14617 prepare_mag; dvi_four(mag); {magnification factor is frozen}
14618 old_setting:=selector; selector:=new_string;
14619 print(" XeTeX output "); print_int(year); print_char(".");
14620 print_two(month); print_char("."); print_two(day);
14621 print_char(":"); print_two(time div 60);
14622 print_two(time mod 60);
14623 selector:=old_setting; dvi_out(cur_length);
14624 for s:=str_start_macro(str_ptr) to pool_ptr-1 do dvi_out(so(str_pool[s]));
14625 pool_ptr:=str_start_macro(str_ptr); {flush the current string}
14626 end
14627
14628 @ When |hlist_out| is called, its duty is to output the box represented
14629 by the |hlist_node| pointed to by |temp_ptr|. The reference point of that
14630 box has coordinates |(cur_h,cur_v)|.
14631
14632 Similarly, when |vlist_out| is called, its duty is to output the box represented
14633 by the |vlist_node| pointed to by |temp_ptr|. The reference point of that
14634 box has coordinates |(cur_h,cur_v)|.
14635 @^recursion@>
14636
14637 @p procedure@?vlist_out; forward; {|hlist_out| and |vlist_out| are mutually
14638 recursive}
14639
14640 @ The recursive procedures |hlist_out| and |vlist_out| each have local variables
14641 |save_h| and |save_v| to hold the values of |dvi_h| and |dvi_v| just before
14642 entering a new level of recursion. In effect, the values of |save_h| and
14643 |save_v| on \TeX's run-time stack correspond to the values of |h| and |v|
14644 that a \.{DVI}-reading program will push onto its coordinate stack.
14645
14646 @d move_past=13 {go to this label when advancing past glue or a rule}
14647 @d fin_rule=14 {go to this label to finish processing a rule}
14648 @d next_p=15 {go to this label when finished with node |p|}
14649
14650 @d check_next=1236
14651 @d end_node_run=1237
14652
14653 @p @t\4@>@<Declare procedures needed in |hlist_out|, |vlist_out|@>@t@>@/
14654 procedure hlist_out; {output an |hlist_node| box}
14655 label reswitch, move_past, fin_rule, next_p;
14656 var base_line: scaled; {the baseline coordinate for this box}
14657 @!left_edge: scaled; {the left coordinate for this box}
14658 @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
14659 @!this_box: pointer; {pointer to containing box}
14660 @!g_order: glue_ord; {applicable order of infinity for glue}
14661 @!g_sign: normal..shrinking; {selects type of glue}
14662 @!p:pointer; {current position in the hlist}
14663 @!save_loc:integer; {\.{DVI} byte location upon entry}
14664 @!leader_box:pointer; {the leader box being replicated}
14665 @!leader_wd:scaled; {width of leader box being replicated}
14666 @!lx:scaled; {extra space between leader boxes}
14667 @!outer_doing_leaders:boolean; {were we doing leaders?}
14668 @!edge:scaled; {right edge of sub-box or leader space}
14669 @!prev_p:pointer; {one step behind |p|}
14670 @!len: integer; {length of scratch string for native word output}
14671 @!q,@!r: pointer;
14672 @!k,@!j: integer;
14673 @!glue_temp:real; {glue value before rounding}
14674 @!cur_glue:real; {glue seen so far}
14675 @!cur_g:scaled; {rounded equivalent of |cur_glue| times the glue ratio}
14676 begin cur_g:=0; cur_glue:=float_constant(0);
14677 this_box:=temp_ptr; g_order:=glue_order(this_box);
14678 g_sign:=glue_sign(this_box);
14679 if XeTeX_interword_space_shaping_state > 1 then begin
14680 @<Merge sequences of words using native fonts and inter-word spaces into single nodes@>;
14681 end;
14682 p:=list_ptr(this_box);
14683 incr(cur_s);
14684 if cur_s>0 then dvi_out(push);
14685 if cur_s>max_push then max_push:=cur_s;
14686 save_loc:=dvi_offset+dvi_ptr; base_line:=cur_v;
14687 prev_p:=this_box+list_offset;
14688 @<Initialize |hlist_out| for mixed direction typesetting@>;
14689 left_edge:=cur_h;
14690 while p<>null do @<Output node |p| for |hlist_out| and move to the next node,
14691 maintaining the condition |cur_v=base_line|@>;
14692 @<Finish |hlist_out| for mixed direction typesetting@>;
14693 prune_movements(save_loc);
14694 if cur_s>0 then dvi_pop(save_loc);
14695 decr(cur_s);
14696 end;
14697
14698 @ Extra stuff for justifiable AAT text; need to merge runs of words and normal spaces.
14699
14700 @d is_native_word_node(#) == (((#)<>null)
14701 and (not is_char_node(#))
14702 and (type(#) = whatsit_node)
14703 and (is_native_word_subtype(#)))
14704 @d is_glyph_node(#) == (((#)<>null and (not is_char_node(#)) and (type(#) = whatsit_node) and (subtype(#) = glyph_node)))
14705
14706 @d node_is_invisible_to_interword_space(#)==
14707 not is_char_node(#) and
14708 ((type(#) = penalty_node) or
14709 (type(#) = ins_node) or
14710 (type(#) = mark_node) or
14711 (type(#) = adjust_node) or
14712 ((type(#) = whatsit_node) and (subtype(#) <= 4)))
14713 { This checks for |subtype|s in the range open/write/close/special/language,
14714 but the definitions haven't appeared yet in the .web file so we cheat. }
14715
14716 @<Merge sequences of words using native fonts and inter-word spaces into single nodes@>=
14717 p:=list_ptr(this_box);
14718 prev_p:=this_box+list_offset;
14719 while p<>null do begin
14720 if link(p) <> null then begin {not worth looking ahead at the end}
14721 if is_native_word_node(p) and (font_letter_space[native_font(p)] = 0) then begin
14722 {got a word in an AAT font, might be the start of a run}
14723 r:=p; {|r| is start of possible run}
14724 k:=native_length(r);
14725 q:=link(p);
14726 check_next:
14727 @<Advance |q| past ignorable nodes@>;
14728 if (q <> null) and not is_char_node(q) then begin
14729 if (type(q) = glue_node) and (subtype(q) = normal) then begin
14730 if (glue_ptr(q) = font_glue[native_font(r)]) then begin
14731 {found a normal space; if the next node is another word in the same font, we'll merge}
14732 q:=link(q);
14733 @<Advance |q| past ignorable nodes@>;
14734 if is_native_word_node(q) and (native_font(q) = native_font(r)) then begin
14735 p:=q; {record new tail of run in |p|}
14736 k:=k + 1 + native_length(q);
14737 q:=link(q);
14738 goto check_next;
14739 end
14740 end else q:=link(q);
14741 {we'll also merge if if space-adjustment was applied at this glue,
14742 even if it wasn't the font's standard inter-word space}
14743 if (q <> null) and not is_char_node(q) and (type(q) = kern_node) and
14744 (subtype(q) = space_adjustment) then begin
14745 q:=link(q);
14746 @<Advance |q| past ignorable nodes@>;
14747 if is_native_word_node(q) and (native_font(q) = native_font(r)) then begin
14748 p:=q; {record new tail of run in |p|}
14749 k:=k + 1 + native_length(q);
14750 q:=link(q);
14751 goto check_next;
14752 end
14753 end;
14754 goto end_node_run;
14755 end;
14756 if is_native_word_node(q) and (native_font(q) = native_font(r)) then begin
14757 p:=q; {record new tail of run in |p|}
14758 q:=link(q);
14759 goto check_next;
14760 end
14761 end;
14762 end_node_run: {now |r| points to first |native_word_node| of the run, and |p| to the last}
14763 if p <> r then begin {merge nodes from |r| to |p| inclusive; total text length is |k|}
14764 str_room(k);
14765 k:=0; {now we'll use this as accumulator for total width}
14766 q:=r;
14767 loop begin
14768 if type(q) = whatsit_node then begin
14769 if (is_native_word_subtype(q)) then begin
14770 for j:=0 to native_length(q)-1 do
14771 append_char(get_native_char(q, j));
14772 k:=k + width(q);
14773 end
14774 end else if type(q) = glue_node then begin
14775 append_char(" ");
14776 g:=glue_ptr(q);
14777 k:=k + width(g);
14778 if g_sign <> normal then begin
14779 if g_sign = stretching then begin
14780 if stretch_order(g) = g_order then begin
14781 k:=k + round(float(glue_set(this_box)) * stretch(g))
14782 end
14783 end else begin
14784 if shrink_order(g) = g_order then begin
14785 k:=k - round(float(glue_set(this_box)) * shrink(g))
14786 end
14787 end
14788 end
14789 end else if type(q) = kern_node then begin
14790 k:=k + width(q);
14791 end;
14792 {discretionary and deleted nodes can be discarded here}
14793 if q = p then break
14794 else q:=link(q);
14795 end;
14796 { create the new merged node |q| }
14797 q:=new_native_word_node(native_font(r), cur_length);
14798 subtype(q):=subtype(r);
14799 for j:=0 to cur_length - 1 do
14800 set_native_char(q, j, str_pool[str_start_macro(str_ptr) + j]);
14801 { impose the required width on |q|, and shape its text accordingly }
14802 width(q):=k;
14803 set_justified_native_glyphs(q);
14804 { link |q| into the list in place of |r|..|p| }
14805 link(prev_p):=q;
14806 link(q):=link(p);
14807 link(p):=null;
14808 { Extract any "invisible" nodes from the old list and insert them after the new node,
14809 so we don't lose them altogether. Note that the first node cannot be one of these,
14810 as we always start merging at a |native_word| node. }
14811 prev_p := r;
14812 p := link(r);
14813 while p <> null do begin
14814 if node_is_invisible_to_interword_space(p) then begin
14815 link(prev_p) := link(p);
14816 link(p) := link(q);
14817 link(q) := p;
14818 q := p;
14819 end;
14820 prev_p := p;
14821 p := link(p);
14822 end;
14823 { discard the remains of the old list }
14824 flush_node_list(r);
14825 { clean up and prepare for the next round }
14826 pool_ptr:=str_start_macro(str_ptr); {flush the temporary string data}
14827 p:=q;
14828 end
14829 end;
14830 prev_p:=p;
14831 end;
14832 p:=link(p);
14833 end
14834
14835 @ @<Advance |q| past ignorable nodes@>=
14836 while (q <> null) and node_is_invisible_to_interword_space(q) do
14837 q:=link(q)
14838
14839 @ We ought to give special care to the efficiency of one part of |hlist_out|,
14840 since it belongs to \TeX's inner loop. When a |char_node| is encountered,
14841 we save a little time by processing several nodes in succession until
14842 reaching a non-|char_node|. The program uses the fact that |set_char_0=0|.
14843 @^inner loop@>
14844
14845 @<Output node |p| for |hlist_out|...@>=
14846 reswitch: if is_char_node(p) then
14847 begin synch_h; synch_v;
14848 repeat f:=font(p); c:=character(p);
14849 if (p<>lig_trick) and (font_mapping[f]<>nil) then c:=apply_tfm_font_mapping(font_mapping[f],c);
14850 if f<>dvi_f then @<Change font |dvi_f| to |f|@>;
14851 if c>=qi(128) then dvi_out(set1);
14852 dvi_out(qo(c));@/
14853 cur_h:=cur_h+char_width(f)(char_info(f)(c));
14854 prev_p:=link(prev_p); {N.B.: not |prev_p:=p|, |p| might be |lig_trick|}
14855 p:=link(p);
14856 until not is_char_node(p);
14857 dvi_h:=cur_h;
14858 end
14859 else @<Output the non-|char_node| |p| for |hlist_out|
14860 and move to the next node@>
14861
14862 @ @<Change font |dvi_f| to |f|@>=
14863 begin if not font_used[f] then
14864 begin dvi_font_def(f); font_used[f]:=true;
14865 end;
14866 if f<=64+font_base then dvi_out(f-font_base-1+fnt_num_0)
14867 else begin dvi_out(fnt1); dvi_out(f-font_base-1);
14868 end;
14869 dvi_f:=f;
14870 end
14871
14872 @ @<Output the non-|char_node| |p| for |hlist_out|...@>=
14873 begin case type(p) of
14874 hlist_node,vlist_node:@<Output a box in an hlist@>;
14875 rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
14876 goto fin_rule;
14877 end;
14878 whatsit_node: @<Output the whatsit node |p| in an hlist@>;
14879 glue_node: @<Move right or output leaders@>;
14880 margin_kern_node: begin
14881 cur_h:=cur_h+width(p);
14882 end;
14883 kern_node:cur_h:=cur_h+width(p);
14884 math_node: @<Handle a math node in |hlist_out|@>;
14885 ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>;
14886 @/@<Cases of |hlist_out| that arise in mixed direction text only@>@;
14887 othercases do_nothing
14888 endcases;@/
14889 goto next_p;
14890 fin_rule: @<Output a rule in an hlist@>;
14891 move_past: cur_h:=cur_h+rule_wd;
14892 next_p:prev_p:=p; p:=link(p);
14893 end
14894
14895 @ @<Output a box in an hlist@>=
14896 if list_ptr(p)=null then cur_h:=cur_h+width(p)
14897 else begin save_h:=dvi_h; save_v:=dvi_v;
14898 cur_v:=base_line+shift_amount(p); {shift the box down}
14899 temp_ptr:=p; edge:=cur_h+width(p);
14900 if cur_dir=right_to_left then cur_h:=edge;
14901 if type(p)=vlist_node then vlist_out@+else hlist_out;
14902 dvi_h:=save_h; dvi_v:=save_v;
14903 cur_h:=edge; cur_v:=base_line;
14904 end
14905
14906 @ @<Output a rule in an hlist@>=
14907 if is_running(rule_ht) then rule_ht:=height(this_box);
14908 if is_running(rule_dp) then rule_dp:=depth(this_box);
14909 rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
14910 if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
14911 begin synch_h; cur_v:=base_line+rule_dp; synch_v;
14912 dvi_out(set_rule); dvi_four(rule_ht); dvi_four(rule_wd);
14913 cur_v:=base_line; dvi_h:=dvi_h+rule_wd;
14914 end
14915
14916 @ @d billion==float_constant(1000000000)
14917 @d vet_glue(#)== glue_temp:=#;
14918 if glue_temp>billion then
14919 glue_temp:=billion
14920 else if glue_temp<-billion then
14921 glue_temp:=-billion
14922 @#
14923 @d round_glue==g:=glue_ptr(p); rule_wd:=width(g)-cur_g;
14924 if g_sign<>normal then
14925 begin if g_sign=stretching then
14926 begin if stretch_order(g)=g_order then
14927 begin cur_glue:=cur_glue+stretch(g);
14928 vet_glue(float(glue_set(this_box))*cur_glue);
14929 @^real multiplication@>
14930 cur_g:=round(glue_temp);
14931 end;
14932 end
14933 else if shrink_order(g)=g_order then
14934 begin cur_glue:=cur_glue-shrink(g);
14935 vet_glue(float(glue_set(this_box))*cur_glue);
14936 cur_g:=round(glue_temp);
14937 end;
14938 end;
14939 rule_wd:=rule_wd+cur_g
14940
14941 @<Move right or output leaders@>=
14942 begin round_glue;
14943 if eTeX_ex then @<Handle a glue node for mixed direction typesetting@>;
14944 if subtype(p)>=a_leaders then
14945 @<Output leaders in an hlist, |goto fin_rule| if a rule
14946 or to |next_p| if done@>;
14947 goto move_past;
14948 end
14949
14950 @ @<Output leaders in an hlist...@>=
14951 begin leader_box:=leader_ptr(p);
14952 if type(leader_box)=rule_node then
14953 begin rule_ht:=height(leader_box); rule_dp:=depth(leader_box);
14954 goto fin_rule;
14955 end;
14956 leader_wd:=width(leader_box);
14957 if (leader_wd>0)and(rule_wd>0) then
14958 begin rule_wd:=rule_wd+10; {compensate for floating-point rounding}
14959 if cur_dir=right_to_left then cur_h:=cur_h-10;
14960 edge:=cur_h+rule_wd; lx:=0;
14961 @<Let |cur_h| be the position of the first box, and set |leader_wd+lx|
14962 to the spacing between corresponding parts of boxes@>;
14963 while cur_h+leader_wd<=edge do
14964 @<Output a leader box at |cur_h|,
14965 then advance |cur_h| by |leader_wd+lx|@>;
14966 if cur_dir=right_to_left then cur_h:=edge
14967 else cur_h:=edge-10;
14968 goto next_p;
14969 end;
14970 end
14971
14972 @ The calculations related to leaders require a bit of care. First, in the
14973 case of |a_leaders| (aligned leaders), we want to move |cur_h| to
14974 |left_edge| plus the smallest multiple of |leader_wd| for which the result
14975 is not less than the current value of |cur_h|; i.e., |cur_h| should become
14976 $|left_edge|+|leader_wd|\times\lceil
14977 (|cur_h|-|left_edge|)/|leader_wd|\rceil$. The program here should work in
14978 all cases even though some implementations of \PASCAL\ give nonstandard
14979 results for the |div| operation when |cur_h| is less than |left_edge|.
14980
14981 In the case of |c_leaders| (centered leaders), we want to increase |cur_h|
14982 by half of the excess space not occupied by the leaders; and in the
14983 case of |x_leaders| (expanded leaders) we increase |cur_h|
14984 by $1/(q+1)$ of this excess space, where $q$ is the number of times the
14985 leader box will be replicated. Slight inaccuracies in the division might
14986 accumulate; half of this rounding error is placed at each end of the leaders.
14987
14988 @<Let |cur_h| be the position of the first box, ...@>=
14989 if subtype(p)=a_leaders then
14990 begin save_h:=cur_h;
14991 cur_h:=left_edge+leader_wd*((cur_h-left_edge)@!div leader_wd);
14992 if cur_h<save_h then cur_h:=cur_h+leader_wd;
14993 end
14994 else begin lq:=rule_wd div leader_wd; {the number of box copies}
14995 lr:=rule_wd mod leader_wd; {the remaining space}
14996 if subtype(p)=c_leaders then cur_h:=cur_h+(lr div 2)
14997 else begin lx:=lr div (lq+1);
14998 cur_h:=cur_h+((lr-(lq-1)*lx) div 2);
14999 end;
15000 end
15001
15002 @ The `\\{synch}' operations here are intended to decrease the number of
15003 bytes needed to specify horizontal and vertical motion in the \.{DVI} output.
15004
15005 @<Output a leader box at |cur_h|, ...@>=
15006 begin cur_v:=base_line+shift_amount(leader_box); synch_v; save_v:=dvi_v;@/
15007 synch_h; save_h:=dvi_h; temp_ptr:=leader_box;
15008 if cur_dir=right_to_left then cur_h:=cur_h+leader_wd;
15009 outer_doing_leaders:=doing_leaders; doing_leaders:=true;
15010 if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
15011 doing_leaders:=outer_doing_leaders;
15012 dvi_v:=save_v; dvi_h:=save_h; cur_v:=base_line;
15013 cur_h:=save_h+leader_wd+lx;
15014 end
15015
15016 @ The |vlist_out| routine is similar to |hlist_out|, but a bit simpler.
15017
15018 @p procedure vlist_out; {output a |vlist_node| box}
15019 label move_past, fin_rule, next_p;
15020 var left_edge: scaled; {the left coordinate for this box}
15021 @!top_edge: scaled; {the top coordinate for this box}
15022 @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
15023 @!this_box: pointer; {pointer to containing box}
15024 @!g_order: glue_ord; {applicable order of infinity for glue}
15025 @!g_sign: normal..shrinking; {selects type of glue}
15026 @!p:pointer; {current position in the vlist}
15027 @!save_loc:integer; {\.{DVI} byte location upon entry}
15028 @!leader_box:pointer; {the leader box being replicated}
15029 @!leader_ht:scaled; {height of leader box being replicated}
15030 @!lx:scaled; {extra space between leader boxes}
15031 @!outer_doing_leaders:boolean; {were we doing leaders?}
15032 @!edge:scaled; {bottom boundary of leader space}
15033 @!glue_temp:real; {glue value before rounding}
15034 @!cur_glue:real; {glue seen so far}
15035 @!cur_g:scaled; {rounded equivalent of |cur_glue| times the glue ratio}
15036 @!upwards:boolean; {whether we're stacking upwards}
15037 begin cur_g:=0; cur_glue:=float_constant(0);
15038 this_box:=temp_ptr; g_order:=glue_order(this_box);
15039 g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
15040 upwards:=(subtype(this_box)=min_quarterword+1);
15041 incr(cur_s);
15042 if cur_s>0 then dvi_out(push);
15043 if cur_s>max_push then max_push:=cur_s;
15044 save_loc:=dvi_offset+dvi_ptr; left_edge:=cur_h;
15045 if upwards then cur_v:=cur_v+depth(this_box) else cur_v:=cur_v-height(this_box);
15046 top_edge:=cur_v;
15047 while p<>null do @<Output node |p| for |vlist_out| and move to the next node,
15048 maintaining the condition |cur_h=left_edge|@>;
15049 prune_movements(save_loc);
15050 if cur_s>0 then dvi_pop(save_loc);
15051 decr(cur_s);
15052 end;
15053
15054 @ @<Output node |p| for |vlist_out|...@>=
15055 begin if is_char_node(p) then confusion("vlistout")
15056 @:this can't happen vlistout}{\quad vlistout@>
15057 else @<Output the non-|char_node| |p| for |vlist_out|@>;
15058 next_p:p:=link(p);
15059 end
15060
15061 @ @<Output the non-|char_node| |p| for |vlist_out|@>=
15062 begin case type(p) of
15063 hlist_node,vlist_node:@<Output a box in a vlist@>;
15064 rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
15065 goto fin_rule;
15066 end;
15067 whatsit_node: @<Output the whatsit node |p| in a vlist@>;
15068 glue_node: @<Move down or output leaders@>;
15069 kern_node:if upwards then cur_v:=cur_v-width(p) else cur_v:=cur_v+width(p);
15070 othercases do_nothing
15071 endcases;@/
15072 goto next_p;
15073 fin_rule: @<Output a rule in a vlist, |goto next_p|@>;
15074 move_past: if upwards then cur_v:=cur_v-rule_ht else cur_v:=cur_v+rule_ht;
15075 end
15076
15077 @ The |synch_v| here allows the \.{DVI} output to use one-byte commands
15078 for adjusting |v| in most cases, since the baselineskip distance will
15079 usually be constant.
15080
15081 @<Output a box in a vlist@>=
15082 if list_ptr(p)=null then cur_v:=cur_v+height(p)+depth(p)
15083 else begin if upwards then cur_v:=cur_v-depth(p) else cur_v:=cur_v+height(p); synch_v;
15084 save_h:=dvi_h; save_v:=dvi_v;
15085 if cur_dir=right_to_left then cur_h:=left_edge-shift_amount(p)
15086 else cur_h:=left_edge+shift_amount(p); {shift the box right}
15087 temp_ptr:=p;
15088 if type(p)=vlist_node then vlist_out@+else hlist_out;
15089 dvi_h:=save_h; dvi_v:=save_v;
15090 if upwards then cur_v:=save_v-height(p) else cur_v:=save_v+depth(p); cur_h:=left_edge;
15091 end
15092
15093 @ @<Output a rule in a vlist...@>=
15094 if is_running(rule_wd) then rule_wd:=width(this_box);
15095 rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
15096 if upwards then cur_v:=cur_v-rule_ht else cur_v:=cur_v+rule_ht;
15097 if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
15098 begin if cur_dir=right_to_left then cur_h:=cur_h-rule_wd;
15099 synch_h; synch_v;
15100 dvi_out(put_rule); dvi_four(rule_ht); dvi_four(rule_wd);
15101 cur_h:=left_edge;
15102 end;
15103 goto next_p
15104
15105 @ @<Move down or output leaders@>=
15106 begin g:=glue_ptr(p); rule_ht:=width(g)-cur_g;
15107 if g_sign<>normal then
15108 begin if g_sign=stretching then
15109 begin if stretch_order(g)=g_order then
15110 begin cur_glue:=cur_glue+stretch(g);
15111 vet_glue(float(glue_set(this_box))*cur_glue);
15112 @^real multiplication@>
15113 cur_g:=round(glue_temp);
15114 end;
15115 end
15116 else if shrink_order(g)=g_order then
15117 begin cur_glue:=cur_glue-shrink(g);
15118 vet_glue(float(glue_set(this_box))*cur_glue);
15119 cur_g:=round(glue_temp);
15120 end;
15121 end;
15122 rule_ht:=rule_ht+cur_g;
15123 if subtype(p)>=a_leaders then
15124 @<Output leaders in a vlist, |goto fin_rule| if a rule
15125 or to |next_p| if done@>;
15126 goto move_past;
15127 end
15128
15129 @ @<Output leaders in a vlist...@>=
15130 begin leader_box:=leader_ptr(p);
15131 if type(leader_box)=rule_node then
15132 begin rule_wd:=width(leader_box); rule_dp:=0;
15133 goto fin_rule;
15134 end;
15135 leader_ht:=height(leader_box)+depth(leader_box);
15136 if (leader_ht>0)and(rule_ht>0) then
15137 begin rule_ht:=rule_ht+10; {compensate for floating-point rounding}
15138 edge:=cur_v+rule_ht; lx:=0;
15139 @<Let |cur_v| be the position of the first box, and set |leader_ht+lx|
15140 to the spacing between corresponding parts of boxes@>;
15141 while cur_v+leader_ht<=edge do
15142 @<Output a leader box at |cur_v|,
15143 then advance |cur_v| by |leader_ht+lx|@>;
15144 cur_v:=edge-10; goto next_p;
15145 end;
15146 end
15147
15148 @ @<Let |cur_v| be the position of the first box, ...@>=
15149 if subtype(p)=a_leaders then
15150 begin save_v:=cur_v;
15151 cur_v:=top_edge+leader_ht*((cur_v-top_edge)@!div leader_ht);
15152 if cur_v<save_v then cur_v:=cur_v+leader_ht;
15153 end
15154 else begin lq:=rule_ht div leader_ht; {the number of box copies}
15155 lr:=rule_ht mod leader_ht; {the remaining space}
15156 if subtype(p)=c_leaders then cur_v:=cur_v+(lr div 2)
15157 else begin lx:=lr div (lq+1);
15158 cur_v:=cur_v+((lr-(lq-1)*lx) div 2);
15159 end;
15160 end
15161
15162 @ When we reach this part of the program, |cur_v| indicates the top of a
15163 leader box, not its baseline.
15164
15165 @<Output a leader box at |cur_v|, ...@>=
15166 begin if cur_dir=right_to_left then
15167 cur_h:=left_edge-shift_amount(leader_box)
15168 else cur_h:=left_edge+shift_amount(leader_box);
15169 synch_h; save_h:=dvi_h;@/
15170 cur_v:=cur_v+height(leader_box); synch_v; save_v:=dvi_v;
15171 temp_ptr:=leader_box;
15172 outer_doing_leaders:=doing_leaders; doing_leaders:=true;
15173 if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
15174 doing_leaders:=outer_doing_leaders;
15175 dvi_v:=save_v; dvi_h:=save_h; cur_h:=left_edge;
15176 cur_v:=save_v-height(leader_box)+leader_ht+lx;
15177 end
15178
15179 @ The |hlist_out| and |vlist_out| procedures are now complete, so we are
15180 ready for the |ship_out| routine that gets them started in the first place.
15181
15182 @p procedure ship_out(@!p:pointer); {output the box |p|}
15183 label done;
15184 var page_loc:integer; {location of the current |bop|}
15185 @!j,@!k:0..9; {indices to first ten count registers}
15186 @!s:pool_pointer; {index into |str_pool|}
15187 @!old_setting:0..max_selector; {saved |selector| setting}
15188 begin
15189 if job_name=0 then open_log_file;
15190 if tracing_output>0 then
15191 begin print_nl(""); print_ln;
15192 print("Completed box being shipped out");
15193 @.Completed box...@>
15194 end;
15195 if term_offset>max_print_line-9 then print_ln
15196 else if (term_offset>0)or(file_offset>0) then print_char(" ");
15197 print_char("["); j:=9;
15198 while (count(j)=0)and(j>0) do decr(j);
15199 for k:=0 to j do
15200 begin print_int(count(k));
15201 if k<j then print_char(".");
15202 end;
15203 update_terminal;
15204 if tracing_output>0 then
15205 begin print_char("]");
15206 begin_diagnostic; show_box(p); end_diagnostic(true);
15207 end;
15208 @<Ship box |p| out@>;
15209 if eTeX_ex then @<Check for LR anomalies at the end of |ship_out|@>;
15210 if tracing_output<=0 then print_char("]");
15211 dead_cycles:=0;
15212 update_terminal; {progress report}
15213 @<Flush the box from memory, showing statistics if requested@>;
15214 end;
15215
15216 @ @<Flush the box from memory, showing statistics if requested@>=
15217 @!stat if tracing_stats>1 then
15218 begin print_nl("Memory usage before: ");
15219 @.Memory usage...@>
15220 print_int(var_used); print_char("&");
15221 print_int(dyn_used); print_char(";");
15222 end;
15223 tats@/
15224 flush_node_list(p);
15225 @!stat if tracing_stats>1 then
15226 begin print(" after: ");
15227 print_int(var_used); print_char("&");
15228 print_int(dyn_used); print("; still untouched: ");
15229 print_int(hi_mem_min-lo_mem_max-1); print_ln;
15230 end;
15231 tats
15232
15233 @ @<Ship box |p| out@>=
15234 @<Update the values of |max_h| and |max_v|; but if the page is too large,
15235 |goto done|@>;
15236 @<Initialize variables as |ship_out| begins@>;
15237 page_loc:=dvi_offset+dvi_ptr;
15238 dvi_out(bop);
15239 for k:=0 to 9 do dvi_four(count(k));
15240 dvi_four(last_bop); last_bop:=page_loc;
15241 { generate a pagesize special at start of page }
15242 old_setting:=selector; selector:=new_string;
15243 print("pdf:pagesize ");
15244 if (pdf_page_width > 0) and (pdf_page_height > 0) then begin
15245 print("width"); print(" ");
15246 print_scaled(pdf_page_width);
15247 print("pt"); print(" ");
15248 print("height"); print(" ");
15249 print_scaled(pdf_page_height);
15250 print("pt");
15251 end else
15252 print("default");
15253 selector:=old_setting;
15254 dvi_out(xxx1); dvi_out(cur_length);
15255 for s:=str_start_macro(str_ptr) to pool_ptr-1 do dvi_out(so(str_pool[s]));
15256 pool_ptr:=str_start_macro(str_ptr); {erase the string}
15257 cur_v:=height(p)+v_offset; { does this need changing for upwards mode ???? }
15258 temp_ptr:=p;
15259 if type(p)=vlist_node then vlist_out@+else hlist_out;
15260 dvi_out(eop); incr(total_pages); cur_s:=-1;
15261 if not no_pdf_output then fflush(dvi_file);
15262 done:
15263
15264 @ Sometimes the user will generate a huge page because other error messages
15265 are being ignored. Such pages are not output to the \.{dvi} file, since they
15266 may confuse the printing software.
15267
15268 @<Update the values of |max_h| and |max_v|; but if the page is too large...@>=
15269 if (height(p)>max_dimen)or@|(depth(p)>max_dimen)or@|
15270 (height(p)+depth(p)+v_offset>max_dimen)or@|
15271 (width(p)+h_offset>max_dimen) then
15272 begin print_err("Huge page cannot be shipped out");
15273 @.Huge page...@>
15274 help2("The page just created is more than 18 feet tall or")@/
15275 ("more than 18 feet wide, so I suspect something went wrong.");
15276 error;
15277 if tracing_output<=0 then
15278 begin begin_diagnostic;
15279 print_nl("The following box has been deleted:");
15280 @.The following...deleted@>
15281 show_box(p);
15282 end_diagnostic(true);
15283 end;
15284 goto done;
15285 end;
15286 if height(p)+depth(p)+v_offset>max_v then max_v:=height(p)+depth(p)+v_offset;
15287 if width(p)+h_offset>max_h then max_h:=width(p)+h_offset
15288
15289 @ At the end of the program, we must finish things off by writing the
15290 post\-amble. If |total_pages=0|, the \.{DVI} file was never opened.
15291 If |total_pages>=65536|, the \.{DVI} file will lie. And if
15292 |max_push>=65536|, the user deserves whatever chaos might ensue.
15293
15294 An integer variable |k| will be declared for use by this routine.
15295
15296 @<Finish the \.{DVI} file@>=
15297 while cur_s>-1 do
15298 begin if cur_s>0 then dvi_out(pop)
15299 else begin dvi_out(eop); incr(total_pages);
15300 end;
15301 decr(cur_s);
15302 end;
15303 if total_pages=0 then print_nl("No pages of output.")
15304 @.No pages of output@>
15305 else begin dvi_out(post); {beginning of the postamble}
15306 dvi_four(last_bop); last_bop:=dvi_offset+dvi_ptr-5; {|post| location}
15307 dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
15308 prepare_mag; dvi_four(mag); {magnification factor}
15309 dvi_four(max_v); dvi_four(max_h);@/
15310 dvi_out(max_push div 256); dvi_out(max_push mod 256);@/
15311 dvi_out((total_pages div 256) mod 256); dvi_out(total_pages mod 256);@/
15312 @<Output the font definitions for all fonts that were used@>;
15313 dvi_out(post_post); dvi_four(last_bop); dvi_out(id_byte);@/
15314 k:=4+((dvi_buf_size-dvi_ptr) mod 4); {the number of 223's}
15315 while k>0 do
15316 begin dvi_out(223); decr(k);
15317 end;
15318 @<Empty the last bytes out of |dvi_buf|@>;
15319 print_nl("Output written on "); slow_print(output_file_name);
15320 @.Output written on x@>
15321 print(" ("); print_int(total_pages); print(" page");
15322 if total_pages<>1 then print_char("s");
15323 print(", "); print_int(dvi_offset+dvi_ptr); print(" bytes).");
15324 b_close(dvi_file);
15325 end
15326
15327 @ @<Output the font definitions...@>=
15328 while font_ptr>font_base do
15329 begin if font_used[font_ptr] then dvi_font_def(font_ptr);
15330 decr(font_ptr);
15331 end
15332
15333 @* \[32b] \pdfTeX\ output low-level subroutines (equivalents).
15334
15335 @<Glob...@>=
15336 @!epochseconds: integer;
15337 @!microseconds: integer;
15338
15339 @* \[33] Packaging.
15340 We're essentially done with the parts of \TeX\ that are concerned with
15341 the input (|get_next|) and the output (|ship_out|). So it's time to
15342 get heavily into the remaining part, which does the real work of typesetting.
15343
15344 After lists are constructed, \TeX\ wraps them up and puts them into boxes.
15345 Two major subroutines are given the responsibility for this task: |hpack|
15346 applies to horizontal lists (hlists) and |vpack| applies to vertical lists
15347 (vlists). The main duty of |hpack| and |vpack| is to compute the dimensions
15348 of the resulting boxes, and to adjust the glue if one of those dimensions
15349 is pre-specified. The computed sizes normally enclose all of the material
15350 inside the new box; but some items may stick out if negative glue is used,
15351 if the box is overfull, or if a \.{\\vbox} includes other boxes that have
15352 been shifted left.
15353
15354 The subroutine call |hpack(p,w,m)| returns a pointer to an |hlist_node|
15355 for a box containing the hlist that starts at |p|. Parameter |w| specifies
15356 a width; and parameter |m| is either `|exactly|' or `|additional|'. Thus,
15357 |hpack(p,w,exactly)| produces a box whose width is exactly |w|, while
15358 |hpack(p,w,additional)| yields a box whose width is the natural width plus
15359 |w|. It is convenient to define a macro called `|natural|' to cover the
15360 most common case, so that we can say |hpack(p,natural)| to get a box that
15361 has the natural width of list |p|.
15362
15363 Similarly, |vpack(p,w,m)| returns a pointer to a |vlist_node| for a
15364 box containing the vlist that starts at |p|. In this case |w| represents
15365 a height instead of a width; the parameter |m| is interpreted as in |hpack|.
15366
15367 @d exactly=0 {a box dimension is pre-specified}
15368 @d additional=1 {a box dimension is increased from the natural one}
15369 @d natural==0,additional {shorthand for parameters to |hpack| and |vpack|}
15370
15371 @ The parameters to |hpack| and |vpack| correspond to \TeX's primitives
15372 like `\.{\\hbox} \.{to} \.{300pt}', `\.{\\hbox} \.{spread} \.{10pt}'; note
15373 that `\.{\\hbox}' with no dimension following it is equivalent to
15374 `\.{\\hbox} \.{spread} \.{0pt}'. The |scan_spec| subroutine scans such
15375 constructions in the user's input, including the mandatory left brace that
15376 follows them, and it puts the specification onto |save_stack| so that the
15377 desired box can later be obtained by executing the following code:
15378 $$\vbox{\halign{#\hfil\cr
15379 |save_ptr:=save_ptr-2;|\cr
15380 |hpack(p,saved(1),saved(0)).|\cr}}$$
15381 Special care is necessary to ensure that the special |save_stack| codes
15382 are placed just below the new group code, because scanning can change
15383 |save_stack| when \.{\\csname} appears.
15384
15385 @p procedure scan_spec(@!c:group_code;@!three_codes:boolean);
15386 {scans a box specification and left brace}
15387 label found;
15388 var @!s:integer; {temporarily saved value}
15389 @!spec_code:exactly..additional;
15390 begin if three_codes then s:=saved(0);
15391 if scan_keyword("to") then spec_code:=exactly
15392 @.to@>
15393 else if scan_keyword("spread") then spec_code:=additional
15394 @.spread@>
15395 else begin spec_code:=additional; cur_val:=0;
15396 goto found;
15397 end;
15398 scan_normal_dimen;
15399 found: if three_codes then
15400 begin saved(0):=s; incr(save_ptr);
15401 end;
15402 saved(0):=spec_code; saved(1):=cur_val; save_ptr:=save_ptr+2;
15403 new_save_level(c); scan_left_brace;
15404 end;
15405
15406 @ To figure out the glue setting, |hpack| and |vpack| determine how much
15407 stretchability and shrinkability are present, considering all four orders
15408 of infinity. The highest order of infinity that has a nonzero coefficient
15409 is then used as if no other orders were present.
15410
15411 For example, suppose that the given list contains six glue nodes with
15412 the respective stretchabilities 3pt, 8fill, 5fil, 6pt, $-3$fil, $-8$fill.
15413 Then the total is essentially 2fil; and if a total additional space of 6pt
15414 is to be achieved by stretching, the actual amounts of stretch will be
15415 0pt, 0pt, 15pt, 0pt, $-9$pt, and 0pt, since only `fil' glue will be
15416 considered. (The `fill' glue is therefore not really stretching infinitely
15417 with respect to `fil'; nobody would actually want that to happen.)
15418
15419 The arrays |total_stretch| and |total_shrink| are used to determine how much
15420 glue of each kind is present. A global variable |last_badness| is used
15421 to implement \.{\\badness}.
15422
15423 @<Glob...@>=
15424 @!total_stretch, @!total_shrink: array[glue_ord] of scaled;
15425 {glue found by |hpack| or |vpack|}
15426 @!last_badness:integer; {badness of the most recently packaged box}
15427
15428 @ If the global variable |adjust_tail| is non-null, the |hpack| routine
15429 also removes all occurrences of |ins_node|, |mark_node|, and |adjust_node|
15430 items and appends the resulting material onto the list that ends at
15431 location |adjust_tail|.
15432
15433 @<Glob...@>=
15434 @!adjust_tail:pointer; {tail of adjustment list}
15435
15436 @ @<Set init...@>=adjust_tail:=null; last_badness:=0;
15437
15438 @ Some stuff for character protrusion.
15439
15440 @d left_pw(#) == char_pw(#, left_side)
15441 @d right_pw(#) == char_pw(#, right_side)
15442
15443 @p
15444 function char_pw(p: pointer; side: small_number): scaled;
15445 var f: internal_font_number;
15446 c: integer;
15447 begin
15448 char_pw:=0;
15449 if side = left_side then
15450 last_leftmost_char:=null
15451 else
15452 last_rightmost_char:=null;
15453 if p = null then
15454 return;
15455
15456 { native word }
15457 if is_native_word_node(p) then begin
15458 if native_glyph_info_ptr(p) <> null_ptr then begin
15459 f:=native_font(p);
15460 char_pw:=round_xn_over_d(quad(f), get_native_word_cp(p, side), 1000);
15461 end;
15462 return;
15463 end;
15464
15465 { glyph node }
15466 if is_glyph_node(p) then begin
15467 f:=native_font(p);
15468 char_pw:=round_xn_over_d(quad(f), get_cp_code(f, native_glyph(p), side), 1000);
15469 return;
15470 end;
15471
15472 { char node or ligature; same like pdftex }
15473 if not is_char_node(p) then begin
15474 if type(p) = ligature_node then
15475 p:=lig_char(p)
15476 else
15477 return;
15478 end;
15479 f:=font(p);
15480 c:=get_cp_code(f, character(p), side);
15481 case side of
15482 left_side:
15483 last_leftmost_char:=p;
15484 right_side:
15485 last_rightmost_char:=p;
15486 endcases;
15487 if c = 0 then
15488 return;
15489 char_pw:=round_xn_over_d(quad(f), c, 1000);
15490 end;
15491
15492 function new_margin_kern(w: scaled; p: pointer; side: small_number): pointer;
15493 var k: pointer;
15494 begin
15495 k:=get_node(margin_kern_node_size);
15496 type(k):=margin_kern_node;
15497 subtype(k):=side;
15498 width(k):=w;
15499 new_margin_kern:=k;
15500 end;
15501
15502 @ Here now is |hpack|, which contains few if any surprises.
15503
15504 @p function hpack(@!p:pointer;@!w:scaled;@!m:small_number):pointer;
15505 label reswitch, common_ending, exit, restart;
15506 var r:pointer; {the box node that will be returned}
15507 @!q:pointer; {trails behind |p|}
15508 @!h,@!d,@!x:scaled; {height, depth, and natural width}
15509 @!s:scaled; {shift amount}
15510 @!g:pointer; {points to a glue specification}
15511 @!o:glue_ord; {order of infinity}
15512 @!f:internal_font_number; {the font in a |char_node|}
15513 @!i:four_quarters; {font information about a |char_node|}
15514 @!hd:eight_bits; {height and depth indices for a character}
15515 @!pp,@!ppp: pointer;
15516 @!total_chars, @!k: integer;
15517 begin last_badness:=0; r:=get_node(box_node_size); type(r):=hlist_node;
15518 subtype(r):=min_quarterword; shift_amount(r):=0;
15519 q:=r+list_offset; link(q):=p;@/
15520 h:=0; @<Clear dimensions to zero@>;
15521 if TeXXeT_en then @<Initialize the LR stack@>;
15522 while p<>null do @<Examine node |p| in the hlist, taking account of its effect
15523 on the dimensions of the new box, or moving it to the adjustment list;
15524 then advance |p| to the next node@>;
15525 if adjust_tail<>null then link(adjust_tail):=null;
15526 if pre_adjust_tail<>null then link(pre_adjust_tail):=null;
15527 height(r):=h; depth(r):=d;@/
15528 @<Determine the value of |width(r)| and the appropriate glue setting;
15529 then |return| or |goto common_ending|@>;
15530 common_ending: @<Finish issuing a diagnostic message
15531 for an overfull or underfull hbox@>;
15532 exit: if TeXXeT_en then @<Check for LR anomalies at the end of |hpack|@>;
15533 hpack:=r;
15534 end;
15535
15536 @ @<Clear dimensions to zero@>=
15537 d:=0; x:=0;
15538 total_stretch[normal]:=0; total_shrink[normal]:=0;
15539 total_stretch[fil]:=0; total_shrink[fil]:=0;
15540 total_stretch[fill]:=0; total_shrink[fill]:=0;
15541 total_stretch[filll]:=0; total_shrink[filll]:=0
15542
15543 @ @<Examine node |p| in the hlist, taking account of its effect...@>=
15544 @^inner loop@>
15545 begin reswitch: while is_char_node(p) do
15546 @<Incorporate character dimensions into the dimensions of
15547 the hbox that will contain~it, then move to the next node@>;
15548 if p<>null then
15549 begin case type(p) of
15550 hlist_node,vlist_node,rule_node,unset_node:
15551 @<Incorporate box dimensions into the dimensions of
15552 the hbox that will contain~it@>;
15553 ins_node,mark_node,adjust_node: if (adjust_tail<>null) or (pre_adjust_tail<> null) then
15554 @<Transfer node |p| to the adjustment list@>;
15555 whatsit_node:@<Incorporate a whatsit node into an hbox@>;
15556 glue_node:@<Incorporate glue into the horizontal totals@>;
15557 kern_node: x:=x+width(p);
15558 margin_kern_node: x:=x+width(p);
15559 math_node: begin x:=x+width(p);
15560 if TeXXeT_en then @<Adjust \(t)the LR stack for the |hpack| routine@>;
15561 end;
15562 ligature_node: @<Make node |p| look like a |char_node|
15563 and |goto reswitch|@>;
15564 othercases do_nothing
15565 endcases;@/
15566 p:=link(p);
15567 end;
15568 end
15569
15570
15571 @ @<Make node |p| look like a |char_node| and |goto reswitch|@>=
15572 begin mem[lig_trick]:=mem[lig_char(p)]; link(lig_trick):=link(p);
15573 p:=lig_trick; xtx_ligature_present:=true; goto reswitch;
15574 end
15575
15576 @ The code here implicitly uses the fact that running dimensions are
15577 indicated by |null_flag|, which will be ignored in the calculations
15578 because it is a highly negative number.
15579
15580 @<Incorporate box dimensions into the dimensions of the hbox...@>=
15581 begin x:=x+width(p);
15582 if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
15583 if height(p)-s>h then h:=height(p)-s;
15584 if depth(p)+s>d then d:=depth(p)+s;
15585 end
15586
15587 @ The following code is part of \TeX's inner loop; i.e., adding another
15588 character of text to the user's input will cause each of these instructions
15589 to be exercised one more time.
15590 @^inner loop@>
15591
15592 @<Incorporate character dimensions into the dimensions of the hbox...@>=
15593 begin f:=font(p); i:=char_info(f)(character(p)); hd:=height_depth(i);
15594 x:=x+char_width(f)(i);@/
15595 s:=char_height(f)(hd);@+if s>h then h:=s;
15596 s:=char_depth(f)(hd);@+if s>d then d:=s;
15597 p:=link(p);
15598 end
15599
15600 @ Although node |q| is not necessarily the immediate predecessor of node |p|,
15601 it always points to some node in the list preceding |p|. Thus, we can delete
15602 nodes by moving |q| when necessary. The algorithm takes linear time, and the
15603 extra computation does not intrude on the inner loop unless it is necessary
15604 to make a deletion.
15605 @^inner loop@>
15606
15607 @<Glob...@>=
15608 @!pre_adjust_tail: pointer;
15609
15610 @ @<Set init...@>=
15611 pre_adjust_tail:=null;
15612
15613 @ Materials in \.{\\vadjust} used with \.{pre} keyword will be appended to
15614 |pre_adjust_tail| instead of |adjust_tail|.
15615
15616 @d update_adjust_list(#) == begin
15617 if # = null then
15618 confusion("pre vadjust");
15619 link(#):=adjust_ptr(p);
15620 while link(#) <> null do
15621 #:=link(#);
15622 end
15623
15624 @<Transfer node |p| to the adjustment list@>=
15625 begin while link(q)<>p do q:=link(q);
15626 if type(p) = adjust_node then begin
15627 if adjust_pre(p) <> 0 then
15628 update_adjust_list(pre_adjust_tail)
15629 else
15630 update_adjust_list(adjust_tail);
15631 p:=link(p); free_node(link(q), small_node_size);
15632 end
15633 else begin link(adjust_tail):=p; adjust_tail:=p; p:=link(p);
15634 end;
15635 link(q):=p; p:=q;
15636 end
15637
15638 @ @<Incorporate glue into the horizontal totals@>=
15639 begin g:=glue_ptr(p); x:=x+width(g);@/
15640 o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
15641 o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
15642 if subtype(p)>=a_leaders then
15643 begin g:=leader_ptr(p);
15644 if height(g)>h then h:=height(g);
15645 if depth(g)>d then d:=depth(g);
15646 end;
15647 end
15648
15649 @ When we get to the present part of the program, |x| is the natural width
15650 of the box being packaged.
15651
15652 @<Determine the value of |width(r)| and the appropriate glue setting...@>=
15653 if m=additional then w:=x+w;
15654 width(r):=w; x:=w-x; {now |x| is the excess to be made up}
15655 if x=0 then
15656 begin glue_sign(r):=normal; glue_order(r):=normal;
15657 set_glue_ratio_zero(glue_set(r));
15658 return;
15659 end
15660 else if x>0 then @<Determine horizontal glue stretch setting, then |return|
15661 or \hbox{|goto common_ending|}@>
15662 else @<Determine horizontal glue shrink setting, then |return|
15663 or \hbox{|goto common_ending|}@>
15664
15665 @ @<Determine horizontal glue stretch setting...@>=
15666 begin @<Determine the stretch order@>;
15667 glue_order(r):=o; glue_sign(r):=stretching;
15668 if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
15669 @^real division@>
15670 else begin glue_sign(r):=normal;
15671 set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
15672 end;
15673 if o=normal then if list_ptr(r)<>null then
15674 @<Report an underfull hbox and |goto common_ending|, if this box
15675 is sufficiently bad@>;
15676 return;
15677 end
15678
15679 @ @<Determine the stretch order@>=
15680 if total_stretch[filll]<>0 then o:=filll
15681 else if total_stretch[fill]<>0 then o:=fill
15682 else if total_stretch[fil]<>0 then o:=fil
15683 else o:=normal
15684
15685 @ @<Report an underfull hbox and |goto common_ending|, if...@>=
15686 begin last_badness:=badness(x,total_stretch[normal]);
15687 if last_badness>hbadness then
15688 begin print_ln;
15689 if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
15690 print(" \hbox (badness "); print_int(last_badness);
15691 @.Underfull \\hbox...@>
15692 @.Loose \\hbox...@>
15693 goto common_ending;
15694 end;
15695 end
15696
15697 @ In order to provide a decent indication of where an overfull or underfull
15698 box originated, we use a global variable |pack_begin_line| that is
15699 set nonzero only when |hpack| is being called by the paragraph builder
15700 or the alignment finishing routine.
15701
15702 @<Glob...@>=
15703 @!pack_begin_line:integer; {source file line where the current paragraph
15704 or alignment began; a negative value denotes alignment}
15705
15706 @ @<Set init...@>=
15707 pack_begin_line:=0;
15708
15709 @ @<Finish issuing a diagnostic message for an overfull or underfull hbox@>=
15710 if output_active then print(") has occurred while \output is active")
15711 else begin if pack_begin_line<>0 then
15712 begin if pack_begin_line>0 then print(") in paragraph at lines ")
15713 else print(") in alignment at lines ");
15714 print_int(abs(pack_begin_line));
15715 print("--");
15716 end
15717 else print(") detected at line ");
15718 print_int(line);
15719 end;
15720 print_ln;@/
15721 font_in_short_display:=null_font; short_display(list_ptr(r)); print_ln;@/
15722 begin_diagnostic; show_box(r); end_diagnostic(true)
15723
15724 @ @<Determine horizontal glue shrink setting...@>=
15725 begin @<Determine the shrink order@>;
15726 glue_order(r):=o; glue_sign(r):=shrinking;
15727 if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
15728 @^real division@>
15729 else begin glue_sign(r):=normal;
15730 set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
15731 end;
15732 if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
15733 begin last_badness:=1000000;
15734 set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
15735 @<Report an overfull hbox and |goto common_ending|, if this box
15736 is sufficiently bad@>;
15737 end
15738 else if o=normal then if list_ptr(r)<>null then
15739 @<Report a tight hbox and |goto common_ending|, if this box
15740 is sufficiently bad@>;
15741 return;
15742 end
15743
15744 @ @<Determine the shrink order@>=
15745 if total_shrink[filll]<>0 then o:=filll
15746 else if total_shrink[fill]<>0 then o:=fill
15747 else if total_shrink[fil]<>0 then o:=fil
15748 else o:=normal
15749
15750 @ @<Report an overfull hbox and |goto common_ending|, if...@>=
15751 if (-x-total_shrink[normal]>hfuzz)or(hbadness<100) then
15752 begin if (overfull_rule>0)and(-x-total_shrink[normal]>hfuzz) then
15753 begin while link(q)<>null do q:=link(q);
15754 link(q):=new_rule;
15755 width(link(q)):=overfull_rule;
15756 end;
15757 print_ln; print_nl("Overfull \hbox (");
15758 @.Overfull \\hbox...@>
15759 print_scaled(-x-total_shrink[normal]); print("pt too wide");
15760 goto common_ending;
15761 end
15762
15763 @ @<Report a tight hbox and |goto common_ending|, if...@>=
15764 begin last_badness:=badness(-x,total_shrink[normal]);
15765 if last_badness>hbadness then
15766 begin print_ln; print_nl("Tight \hbox (badness "); print_int(last_badness);
15767 @.Tight \\hbox...@>
15768 goto common_ending;
15769 end;
15770 end
15771
15772 @ The |vpack| subroutine is actually a special case of a slightly more
15773 general routine called |vpackage|, which has four parameters. The fourth
15774 parameter, which is |max_dimen| in the case of |vpack|, specifies the
15775 maximum depth of the page box that is constructed. The depth is first
15776 computed by the normal rules; if it exceeds this limit, the reference
15777 point is simply moved down until the limiting depth is attained.
15778
15779 @d vpack(#)==vpackage(#,max_dimen) {special case of unconstrained depth}
15780
15781 @p function vpackage(@!p:pointer;@!h:scaled;@!m:small_number;@!l:scaled):
15782 pointer;
15783 label common_ending, exit;
15784 var r:pointer; {the box node that will be returned}
15785 @!w,@!d,@!x:scaled; {width, depth, and natural height}
15786 @!s:scaled; {shift amount}
15787 @!g:pointer; {points to a glue specification}
15788 @!o:glue_ord; {order of infinity}
15789 begin last_badness:=0; r:=get_node(box_node_size); type(r):=vlist_node;
15790 if XeTeX_upwards then subtype(r):=min_quarterword+1 else subtype(r):=min_quarterword;
15791 shift_amount(r):=0;
15792 list_ptr(r):=p;@/
15793 w:=0; @<Clear dimensions to zero@>;
15794 while p<>null do @<Examine node |p| in the vlist, taking account of its effect
15795 on the dimensions of the new box; then advance |p| to the next node@>;
15796 width(r):=w;
15797 if d>l then
15798 begin x:=x+d-l; depth(r):=l;
15799 end
15800 else depth(r):=d;
15801 @<Determine the value of |height(r)| and the appropriate glue setting;
15802 then |return| or |goto common_ending|@>;
15803 common_ending: @<Finish issuing a diagnostic message
15804 for an overfull or underfull vbox@>;
15805 exit: vpackage:=r;
15806 end;
15807
15808 @ @<Examine node |p| in the vlist, taking account of its effect...@>=
15809 begin if is_char_node(p) then confusion("vpack")
15810 @:this can't happen vpack}{\quad vpack@>
15811 else case type(p) of
15812 hlist_node,vlist_node,rule_node,unset_node:
15813 @<Incorporate box dimensions into the dimensions of
15814 the vbox that will contain~it@>;
15815 whatsit_node:@<Incorporate a whatsit node into a vbox@>;
15816 glue_node: @<Incorporate glue into the vertical totals@>;
15817 kern_node: begin x:=x+d+width(p); d:=0;
15818 end;
15819 othercases do_nothing
15820 endcases;
15821 p:=link(p);
15822 end
15823
15824 @ @<Incorporate box dimensions into the dimensions of the vbox...@>=
15825 begin x:=x+d+height(p); d:=depth(p);
15826 if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
15827 if width(p)+s>w then w:=width(p)+s;
15828 end
15829
15830 @ @<Incorporate glue into the vertical totals@>=
15831 begin x:=x+d; d:=0;@/
15832 g:=glue_ptr(p); x:=x+width(g);@/
15833 o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
15834 o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
15835 if subtype(p)>=a_leaders then
15836 begin g:=leader_ptr(p);
15837 if width(g)>w then w:=width(g);
15838 end;
15839 end
15840
15841 @ When we get to the present part of the program, |x| is the natural height
15842 of the box being packaged.
15843
15844 @<Determine the value of |height(r)| and the appropriate glue setting...@>=
15845 if m=additional then h:=x+h;
15846 height(r):=h; x:=h-x; {now |x| is the excess to be made up}
15847 if x=0 then
15848 begin glue_sign(r):=normal; glue_order(r):=normal;
15849 set_glue_ratio_zero(glue_set(r));
15850 return;
15851 end
15852 else if x>0 then @<Determine vertical glue stretch setting, then |return|
15853 or \hbox{|goto common_ending|}@>
15854 else @<Determine vertical glue shrink setting, then |return|
15855 or \hbox{|goto common_ending|}@>
15856
15857 @ @<Determine vertical glue stretch setting...@>=
15858 begin @<Determine the stretch order@>;
15859 glue_order(r):=o; glue_sign(r):=stretching;
15860 if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
15861 @^real division@>
15862 else begin glue_sign(r):=normal;
15863 set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
15864 end;
15865 if o=normal then if list_ptr(r)<>null then
15866 @<Report an underfull vbox and |goto common_ending|, if this box
15867 is sufficiently bad@>;
15868 return;
15869 end
15870
15871 @ @<Report an underfull vbox and |goto common_ending|, if...@>=
15872 begin last_badness:=badness(x,total_stretch[normal]);
15873 if last_badness>vbadness then
15874 begin print_ln;
15875 if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
15876 print(" \vbox (badness "); print_int(last_badness);
15877 @.Underfull \\vbox...@>
15878 @.Loose \\vbox...@>
15879 goto common_ending;
15880 end;
15881 end
15882
15883 @ @<Finish issuing a diagnostic message for an overfull or underfull vbox@>=
15884 if output_active then print(") has occurred while \output is active")
15885 else begin if pack_begin_line<>0 then {it's actually negative}
15886 begin print(") in alignment at lines ");
15887 print_int(abs(pack_begin_line));
15888 print("--");
15889 end
15890 else print(") detected at line ");
15891 print_int(line);
15892 print_ln;@/
15893 end;
15894 begin_diagnostic; show_box(r); end_diagnostic(true)
15895
15896 @ @<Determine vertical glue shrink setting...@>=
15897 begin @<Determine the shrink order@>;
15898 glue_order(r):=o; glue_sign(r):=shrinking;
15899 if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
15900 @^real division@>
15901 else begin glue_sign(r):=normal;
15902 set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
15903 end;
15904 if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
15905 begin last_badness:=1000000;
15906 set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
15907 @<Report an overfull vbox and |goto common_ending|, if this box
15908 is sufficiently bad@>;
15909 end
15910 else if o=normal then if list_ptr(r)<>null then
15911 @<Report a tight vbox and |goto common_ending|, if this box
15912 is sufficiently bad@>;
15913 return;
15914 end
15915
15916 @ @<Report an overfull vbox and |goto common_ending|, if...@>=
15917 if (-x-total_shrink[normal]>vfuzz)or(vbadness<100) then
15918 begin print_ln; print_nl("Overfull \vbox (");
15919 @.Overfull \\vbox...@>
15920 print_scaled(-x-total_shrink[normal]); print("pt too high");
15921 goto common_ending;
15922 end
15923
15924 @ @<Report a tight vbox and |goto common_ending|, if...@>=
15925 begin last_badness:=badness(-x,total_shrink[normal]);
15926 if last_badness>vbadness then
15927 begin print_ln; print_nl("Tight \vbox (badness "); print_int(last_badness);
15928 @.Tight \\vbox...@>
15929 goto common_ending;
15930 end;
15931 end
15932
15933 @ When a box is being appended to the current vertical list, the
15934 baselineskip calculation is handled by the |append_to_vlist| routine.
15935
15936 @p procedure append_to_vlist(@!b:pointer);
15937 var d:scaled; {deficiency of space between baselines}
15938 @!p:pointer; {a new glue node}
15939 @!upwards:boolean;
15940 begin upwards:=XeTeX_upwards;
15941 if prev_depth>ignore_depth then
15942 begin if upwards then d:=width(baseline_skip)-prev_depth-depth(b)
15943 else d:=width(baseline_skip)-prev_depth-height(b);
15944 if d<line_skip_limit then p:=new_param_glue(line_skip_code)
15945 else begin p:=new_skip_param(baseline_skip_code);
15946 width(temp_ptr):=d; {|temp_ptr=glue_ptr(p)|}
15947 end;
15948 link(tail):=p; tail:=p;
15949 end;
15950 link(tail):=b; tail:=b; if upwards then prev_depth:=height(b) else prev_depth:=depth(b);
15951 end;
15952
15953 @* \[34] Data structures for math mode.
15954 When \TeX\ reads a formula that is enclosed between \.\$'s, it constructs an
15955 {\sl mlist}, which is essentially a tree structure representing that
15956 formula. An mlist is a linear sequence of items, but we can regard it as
15957 a tree structure because mlists can appear within mlists. For example, many
15958 of the entries can be subscripted or superscripted, and such ``scripts''
15959 are mlists in their own right.
15960
15961 An entire formula is parsed into such a tree before any of the actual
15962 typesetting is done, because the current style of type is usually not
15963 known until the formula has been fully scanned. For example, when the
15964 formula `\.{\$a+b \\over c+d\$}' is being read, there is no way to tell
15965 that `\.{a+b}' will be in script size until `\.{\\over}' has appeared.
15966
15967 During the scanning process, each element of the mlist being built is
15968 classified as a relation, a binary operator, an open parenthesis, etc.,
15969 or as a construct like `\.{\\sqrt}' that must be built up. This classification
15970 appears in the mlist data structure.
15971
15972 After a formula has been fully scanned, the mlist is converted to an hlist
15973 so that it can be incorporated into the surrounding text. This conversion is
15974 controlled by a recursive procedure that decides all of the appropriate
15975 styles by a ``top-down'' process starting at the outermost level and working
15976 in towards the subformulas. The formula is ultimately pasted together using
15977 combinations of horizontal and vertical boxes, with glue and penalty nodes
15978 inserted as necessary.
15979
15980 An mlist is represented internally as a linked list consisting chiefly
15981 of ``noads'' (pronounced ``no-adds''), to distinguish them from the somewhat
15982 similar ``nodes'' in hlists and vlists. Certain kinds of ordinary nodes are
15983 allowed to appear in mlists together with the noads; \TeX\ tells the difference
15984 by means of the |type| field, since a noad's |type| is always greater than
15985 that of a node. An mlist does not contain character nodes, hlist nodes, vlist
15986 nodes, math nodes, ligature nodes,
15987 or unset nodes; in particular, each mlist item appears in the
15988 variable-size part of |mem|, so the |type| field is always present.
15989
15990 @ Each noad is four or more words long. The first word contains the |type|
15991 and |subtype| and |link| fields that are already so familiar to us; the
15992 second, third, and fourth words are called the noad's |nucleus|, |subscr|,
15993 and |supscr| fields.
15994
15995 Consider, for example, the simple formula `\.{\$x\^2\$}', which would be
15996 parsed into an mlist containing a single element called an |ord_noad|.
15997 The |nucleus| of this noad is a representation of `\.x', the |subscr| is
15998 empty, and the |supscr| is a representation of `\.2'.
15999
16000 The |nucleus|, |subscr|, and |supscr| fields are further broken into
16001 subfields. If |p| points to a noad, and if |q| is one of its principal
16002 fields (e.g., |q=subscr(p)|), there are several possibilities for the
16003 subfields, depending on the |math_type| of |q|.
16004
16005 \yskip\hang|math_type(q)=math_char| means that |fam(q)| refers to one of
16006 the sixteen font families, and |character(q)| is the number of a character
16007 within a font of that family, as in a character node.
16008
16009 \yskip\hang|math_type(q)=math_text_char| is similar, but the character is
16010 unsubscripted and unsuperscripted and it is followed immediately by another
16011 character from the same font. (This |math_type| setting appears only
16012 briefly during the processing; it is used to suppress unwanted italic
16013 corrections.)
16014
16015 \yskip\hang|math_type(q)=empty| indicates a field with no value (the
16016 corresponding attribute of noad |p| is not present).
16017
16018 \yskip\hang|math_type(q)=sub_box| means that |info(q)| points to a box
16019 node (either an |hlist_node| or a |vlist_node|) that should be used as the
16020 value of the field. The |shift_amount| in the subsidiary box node is the
16021 amount by which that box will be shifted downward.
16022
16023 \yskip\hang|math_type(q)=sub_mlist| means that |info(q)| points to
16024 an mlist; the mlist must be converted to an hlist in order to obtain
16025 the value of this field.
16026
16027 \yskip\noindent In the latter case, we might have |info(q)=null|. This
16028 is not the same as |math_type(q)=empty|; for example, `\.{\$P\_\{\}\$}'
16029 and `\.{\$P\$}' produce different results (the former will not have the
16030 ``italic correction'' added to the width of |P|, but the ``script skip''
16031 will be added).
16032
16033 The definitions of subfields given here are evidently wasteful of space,
16034 since a halfword is being used for the |math_type| although only three
16035 bits would be needed. However, there are hardly ever many noads present at
16036 once, since they are soon converted to nodes that take up even more space,
16037 so we can afford to represent them in whatever way simplifies the
16038 programming.
16039
16040 @d noad_size=4 {number of words in a normal noad}
16041 @d nucleus(#)==#+1 {the |nucleus| field of a noad}
16042 @d supscr(#)==#+2 {the |supscr| field of a noad}
16043 @d subscr(#)==#+3 {the |subscr| field of a noad}
16044 @d math_type==link {a |halfword| in |mem|}
16045 @d plane_and_fam_field==font {a |quarterword| in |mem|}
16046 @d fam(#) == (plane_and_fam_field(#) mod @"100)
16047 @d math_char=1 {|math_type| when the attribute is simple}
16048 @d sub_box=2 {|math_type| when the attribute is a box}
16049 @d sub_mlist=3 {|math_type| when the attribute is a formula}
16050 @d math_text_char=4 {|math_type| when italic correction is dubious}
16051
16052 @ Each portion of a formula is classified as Ord, Op, Bin, Rel, Open,
16053 Close, Punct, or Inner, for purposes of spacing and line breaking. An
16054 |ord_noad|, |op_noad|, |bin_noad|, |rel_noad|, |open_noad|, |close_noad|,
16055 |punct_noad|, or |inner_noad| is used to represent portions of the various
16056 types. For example, an `\.=' sign in a formula leads to the creation of a
16057 |rel_noad| whose |nucleus| field is a representation of an equals sign
16058 (usually |fam=0|, |character=@'75|). A formula preceded by \.{\\mathrel}
16059 also results in a |rel_noad|. When a |rel_noad| is followed by an
16060 |op_noad|, say, and possibly separated by one or more ordinary nodes (not
16061 noads), \TeX\ will insert a penalty node (with the current |rel_penalty|)
16062 just after the formula that corresponds to the |rel_noad|, unless there
16063 already was a penalty immediately following; and a ``thick space'' will be
16064 inserted just before the formula that corresponds to the |op_noad|.
16065
16066 A noad of type |ord_noad|, |op_noad|, \dots, |inner_noad| usually
16067 has a |subtype=normal|. The only exception is that an |op_noad| might
16068 have |subtype=limits| or |no_limits|, if the normal positioning of
16069 limits has been overridden for this operator.
16070
16071 @d ord_noad=unset_node+3 {|type| of a noad classified Ord}
16072 @d op_noad=ord_noad+1 {|type| of a noad classified Op}
16073 @d bin_noad=ord_noad+2 {|type| of a noad classified Bin}
16074 @d rel_noad=ord_noad+3 {|type| of a noad classified Rel}
16075 @d open_noad=ord_noad+4 {|type| of a noad classified Open}
16076 @d close_noad=ord_noad+5 {|type| of a noad classified Close}
16077 @d punct_noad=ord_noad+6 {|type| of a noad classified Punct}
16078 @d inner_noad=ord_noad+7 {|type| of a noad classified Inner}
16079 @d limits=1 {|subtype| of |op_noad| whose scripts are to be above, below}
16080 @d no_limits=2 {|subtype| of |op_noad| whose scripts are to be normal}
16081
16082 @ A |radical_noad| is five words long; the fifth word is the |left_delimiter|
16083 field, which usually represents a square root sign.
16084
16085 A |fraction_noad| is six words long; it has a |right_delimiter| field
16086 as well as a |left_delimiter|.
16087
16088 Delimiter fields are of type |four_quarters|, and they have four subfields
16089 called |small_fam|, |small_char|, |large_fam|, |large_char|. These subfields
16090 represent variable-size delimiters by giving the ``small'' and ``large''
16091 starting characters, as explained in Chapter~17 of {\sl The \TeX book}.
16092 @:TeXbook}{\sl The \TeX book@>
16093
16094 A |fraction_noad| is actually quite different from all other noads. Not
16095 only does it have six words, it has |thickness|, |denominator|, and
16096 |numerator| fields instead of |nucleus|, |subscr|, and |supscr|. The
16097 |thickness| is a scaled value that tells how thick to make a fraction
16098 rule; however, the special value |default_code| is used to stand for the
16099 |default_rule_thickness| of the current size. The |numerator| and
16100 |denominator| point to mlists that define a fraction; we always have
16101 $$\hbox{|math_type(numerator)=math_type(denominator)=sub_mlist|}.$$ The
16102 |left_delimiter| and |right_delimiter| fields specify delimiters that will
16103 be placed at the left and right of the fraction. In this way, a
16104 |fraction_noad| is able to represent all of \TeX's operators \.{\\over},
16105 \.{\\atop}, \.{\\above}, \.{\\overwithdelims}, \.{\\atopwithdelims}, and
16106 \.{\\abovewithdelims}.
16107
16108 @d left_delimiter(#)==#+4 {first delimiter field of a noad}
16109 @d right_delimiter(#)==#+5 {second delimiter field of a fraction noad}
16110 @d radical_noad=inner_noad+1 {|type| of a noad for square roots}
16111 @d radical_noad_size=5 {number of |mem| words in a radical noad}
16112 @d fraction_noad=radical_noad+1 {|type| of a noad for generalized fractions}
16113 @d fraction_noad_size=6 {number of |mem| words in a fraction noad}
16114 @d small_fam(#)==(mem[#].qqqq.b0 mod @"100) {|fam| for ``small'' delimiter}
16115 @d small_char(#)==(mem[#].qqqq.b1 + (mem[#].qqqq.b0 div @"100) * @"10000) {|character| for ``small'' delimiter}
16116 @d large_fam(#)==(mem[#].qqqq.b2 mod @"100) {|fam| for ``large'' delimiter}
16117 @d large_char(#)==(mem[#].qqqq.b3 + (mem[#].qqqq.b2 div @"100) * @"10000) {|character| for ``large'' delimiter}
16118 @d small_plane_and_fam_field(#)==mem[#].qqqq.b0
16119 @d small_char_field(#)==mem[#].qqqq.b1
16120 @d large_plane_and_fam_field(#)==mem[#].qqqq.b2
16121 @d large_char_field(#)==mem[#].qqqq.b3
16122 @d thickness==width {|thickness| field in a fraction noad}
16123 @d default_code==@'10000000000 {denotes |default_rule_thickness|}
16124 @d numerator==supscr {|numerator| field in a fraction noad}
16125 @d denominator==subscr {|denominator| field in a fraction noad}
16126
16127 @ The global variable |empty_field| is set up for initialization of empty
16128 fields in new noads. Similarly, |null_delimiter| is for the initialization
16129 of delimiter fields.
16130
16131 @<Glob...@>=
16132 @!empty_field:two_halves;
16133 @!null_delimiter:four_quarters;
16134
16135 @ @<Set init...@>=
16136 empty_field.rh:=empty; empty_field.lh:=null;@/
16137 null_delimiter.b0:=0; null_delimiter.b1:=min_quarterword;@/
16138 null_delimiter.b2:=0; null_delimiter.b3:=min_quarterword;
16139
16140 @ The |new_noad| function creates an |ord_noad| that is completely null.
16141
16142 @p function new_noad:pointer;
16143 var p:pointer;
16144 begin p:=get_node(noad_size);
16145 type(p):=ord_noad; subtype(p):=normal;
16146 mem[nucleus(p)].hh:=empty_field;
16147 mem[subscr(p)].hh:=empty_field;
16148 mem[supscr(p)].hh:=empty_field;
16149 new_noad:=p;
16150 end;
16151
16152 @ A few more kinds of noads will complete the set: An |under_noad| has its
16153 nucleus underlined; an |over_noad| has it overlined. An |accent_noad| places
16154 an accent over its nucleus; the accent character appears as
16155 |fam(accent_chr(p))| and |character(accent_chr(p))|. A |vcenter_noad|
16156 centers its nucleus vertically with respect to the axis of the formula;
16157 in such noads we always have |math_type(nucleus(p))=sub_box|.
16158
16159 And finally, we have |left_noad| and |right_noad| types, to implement
16160 \TeX's \.{\\left} and \.{\\right} as well as \eTeX's \.{\\middle}.
16161 The |nucleus| of such noads is
16162 replaced by a |delimiter| field; thus, for example, `\.{\\left(}' produces
16163 a |left_noad| such that |delimiter(p)| holds the family and character
16164 codes for all left parentheses. A |left_noad| never appears in an mlist
16165 except as the first element, and a |right_noad| never appears in an mlist
16166 except as the last element; furthermore, we either have both a |left_noad|
16167 and a |right_noad|, or neither one is present. The |subscr| and |supscr|
16168 fields are always |empty| in a |left_noad| and a |right_noad|.
16169
16170 @d under_noad=fraction_noad+1 {|type| of a noad for underlining}
16171 @d over_noad=under_noad+1 {|type| of a noad for overlining}
16172 @d accent_noad=over_noad+1 {|type| of a noad for accented subformulas}
16173 @d fixed_acc=1 {|subtype| for non growing math accents}
16174 @d bottom_acc=2 {|subtype| for bottom math accents}
16175 @d is_bottom_acc(#)==((subtype(#)=bottom_acc) or (subtype(#)=bottom_acc+fixed_acc))
16176 @d accent_noad_size=5 {number of |mem| words in an accent noad}
16177 @d accent_chr(#)==#+4 {the |accent_chr| field of an accent noad}
16178 @d vcenter_noad=accent_noad+1 {|type| of a noad for \.{\\vcenter}}
16179 @d left_noad=vcenter_noad+1 {|type| of a noad for \.{\\left}}
16180 @d right_noad=left_noad+1 {|type| of a noad for \.{\\right}}
16181 @d delimiter==nucleus {|delimiter| field in left and right noads}
16182 @d middle_noad==1 {|subtype| of right noad representing \.{\\middle}}
16183 @d scripts_allowed(#)==(type(#)>=ord_noad)and(type(#)<left_noad)
16184
16185 @ Math formulas can also contain instructions like \.{\\textstyle} that
16186 override \TeX's normal style rules. A |style_node| is inserted into the
16187 data structure to record such instructions; it is three words long, so it
16188 is considered a node instead of a noad. The |subtype| is either |display_style|
16189 or |text_style| or |script_style| or |script_script_style|. The
16190 second and third words of a |style_node| are not used, but they are
16191 present because a |choice_node| is converted to a |style_node|.
16192
16193 \TeX\ uses even numbers 0, 2, 4, 6 to encode the basic styles
16194 |display_style|, \dots, |script_script_style|, and adds~1 to get the
16195 ``cramped'' versions of these styles. This gives a numerical order that
16196 is backwards from the convention of Appendix~G in {\sl The \TeX book\/};
16197 i.e., a smaller style has a larger numerical value.
16198 @:TeXbook}{\sl The \TeX book@>
16199
16200 @d style_node=unset_node+1 {|type| of a style node}
16201 @d style_node_size=3 {number of words in a style node}
16202 @d display_style=0 {|subtype| for \.{\\displaystyle}}
16203 @d text_style=2 {|subtype| for \.{\\textstyle}}
16204 @d script_style=4 {|subtype| for \.{\\scriptstyle}}
16205 @d script_script_style=6 {|subtype| for \.{\\scriptscriptstyle}}
16206 @d cramped=1 {add this to an uncramped style if you want to cramp it}
16207
16208 @p function new_style(@!s:small_number):pointer; {create a style node}
16209 var p:pointer; {the new node}
16210 begin p:=get_node(style_node_size); type(p):=style_node;
16211 subtype(p):=s; width(p):=0; depth(p):=0; {the |width| and |depth| are not used}
16212 new_style:=p;
16213 end;
16214
16215 @ Finally, the \.{\\mathchoice} primitive creates a |choice_node|, which
16216 has special subfields |display_mlist|, |text_mlist|, |script_mlist|,
16217 and |script_script_mlist| pointing to the mlists for each style.
16218
16219 @d choice_node=unset_node+2 {|type| of a choice node}
16220 @d display_mlist(#)==info(#+1) {mlist to be used in display style}
16221 @d text_mlist(#)==link(#+1) {mlist to be used in text style}
16222 @d script_mlist(#)==info(#+2) {mlist to be used in script style}
16223 @d script_script_mlist(#)==link(#+2) {mlist to be used in scriptscript style}
16224
16225 @p function new_choice:pointer; {create a choice node}
16226 var p:pointer; {the new node}
16227 begin p:=get_node(style_node_size); type(p):=choice_node;
16228 subtype(p):=0; {the |subtype| is not used}
16229 display_mlist(p):=null; text_mlist(p):=null; script_mlist(p):=null;
16230 script_script_mlist(p):=null;
16231 new_choice:=p;
16232 end;
16233
16234 @ Let's consider now the previously unwritten part of |show_node_list|
16235 that displays the things that can only be present in mlists; this
16236 program illustrates how to access the data structures just defined.
16237
16238 In the context of the following program, |p| points to a node or noad that
16239 should be displayed, and the current string contains the ``recursion history''
16240 that leads to this point. The recursion history consists of a dot for each
16241 outer level in which |p| is subsidiary to some node, or in which |p| is
16242 subsidiary to the |nucleus| field of some noad; the dot is replaced by
16243 `\.\_' or `\.\^' or `\./' or `\.\\' if |p| is descended from the |subscr|
16244 or |supscr| or |denominator| or |numerator| fields of noads. For example,
16245 the current string would be `\.{.\^.\_/}' if |p| points to the |ord_noad| for
16246 |x| in the (ridiculous) formula
16247 `\.{\$\\sqrt\{a\^\{\\mathinner\{b\_\{c\\over x+y\}\}\}\}\$}'.
16248
16249 @<Cases of |show_node_list| that arise...@>=
16250 style_node:print_style(subtype(p));
16251 choice_node:@<Display choice node |p|@>;
16252 ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
16253 radical_noad,over_noad,under_noad,vcenter_noad,accent_noad,
16254 left_noad,right_noad:@<Display normal noad |p|@>;
16255 fraction_noad:@<Display fraction noad |p|@>;
16256
16257 @ Here are some simple routines used in the display of noads.
16258
16259 @<Declare procedures needed for displaying the elements of mlists@>=
16260 procedure print_fam_and_char(@!p:pointer); {prints family and character}
16261 var c:integer;
16262 begin print_esc("fam"); print_int(fam(p) mod @"100); print_char(" ");
16263 c:=(cast_to_ushort(character(p)) + ((plane_and_fam_field(p) div @"100) * @"10000));
16264 if c < @"10000 then print_ASCII(c)
16265 else print_char(c); {non-Plane 0 Unicodes can't be sent through |print_ASCII|}
16266 end;
16267 @#
16268 procedure print_delimiter(@!p:pointer); {prints a delimiter as 24-bit hex value}
16269 var a:integer; {accumulator}
16270 begin a:=small_fam(p)*256+qo(small_char(p));
16271 a:=a*@"1000+large_fam(p)*256+qo(large_char(p));
16272 if a<0 then print_int(a) {this should never happen}
16273 else print_hex(a);
16274 end;
16275
16276 @ The next subroutine will descend to another level of recursion when a
16277 subsidiary mlist needs to be displayed. The parameter |c| indicates what
16278 character is to become part of the recursion history. An empty mlist is
16279 distinguished from a field with |math_type(p)=empty|, because these are
16280 not equivalent (as explained above).
16281 @^recursion@>
16282
16283 @<Declare procedures needed for displaying...@>=
16284 procedure@?show_info; forward;@t\2@>@?{|show_node_list(info(temp_ptr))|}
16285 procedure print_subsidiary_data(@!p:pointer;@!c:ASCII_code);
16286 {display a noad field}
16287 begin if cur_length>=depth_threshold then
16288 begin if math_type(p)<>empty then print(" []");
16289 end
16290 else begin append_char(c); {include |c| in the recursion history}
16291 temp_ptr:=p; {prepare for |show_info| if recursion is needed}
16292 case math_type(p) of
16293 math_char: begin print_ln; print_current_string; print_fam_and_char(p);
16294 end;
16295 sub_box: show_info; {recursive call}
16296 sub_mlist: if info(p)=null then
16297 begin print_ln; print_current_string; print("{}");
16298 end
16299 else show_info; {recursive call}
16300 othercases do_nothing {|empty|}
16301 endcases;@/
16302 flush_char; {remove |c| from the recursion history}
16303 end;
16304 end;
16305
16306 @ The inelegant introduction of |show_info| in the code above seems better
16307 than the alternative of using \PASCAL's strange |forward| declaration for a
16308 procedure with parameters. The \PASCAL\ convention about dropping parameters
16309 from a post-|forward| procedure is, frankly, so intolerable to the author
16310 of \TeX\ that he would rather stoop to communication via a global temporary
16311 variable. (A similar stoopidity occurred with respect to |hlist_out| and
16312 |vlist_out| above, and it will occur with respect to |mlist_to_hlist| below.)
16313 @^Knuth, Donald Ervin@>
16314 @:PASCAL}{\PASCAL@>
16315
16316 @p procedure show_info; {the reader will kindly forgive this}
16317 begin show_node_list(info(temp_ptr));
16318 end;
16319
16320 @ @<Declare procedures needed for displaying...@>=
16321 procedure print_style(@!c:integer);
16322 begin case c div 2 of
16323 0: print_esc("displaystyle"); {|display_style=0|}
16324 1: print_esc("textstyle"); {|text_style=2|}
16325 2: print_esc("scriptstyle"); {|script_style=4|}
16326 3: print_esc("scriptscriptstyle"); {|script_script_style=6|}
16327 othercases print("Unknown style!")
16328 endcases;
16329 end;
16330
16331 @ @<Display choice node |p|@>=
16332 begin print_esc("mathchoice");
16333 append_char("D"); show_node_list(display_mlist(p)); flush_char;
16334 append_char("T"); show_node_list(text_mlist(p)); flush_char;
16335 append_char("S"); show_node_list(script_mlist(p)); flush_char;
16336 append_char("s"); show_node_list(script_script_mlist(p)); flush_char;
16337 end
16338
16339 @ @<Display normal noad |p|@>=
16340 begin case type(p) of
16341 ord_noad: print_esc("mathord");
16342 op_noad: print_esc("mathop");
16343 bin_noad: print_esc("mathbin");
16344 rel_noad: print_esc("mathrel");
16345 open_noad: print_esc("mathopen");
16346 close_noad: print_esc("mathclose");
16347 punct_noad: print_esc("mathpunct");
16348 inner_noad: print_esc("mathinner");
16349 over_noad: print_esc("overline");
16350 under_noad: print_esc("underline");
16351 vcenter_noad: print_esc("vcenter");
16352 radical_noad: begin print_esc("radical"); print_delimiter(left_delimiter(p));
16353 end;
16354 accent_noad: begin print_esc("accent"); print_fam_and_char(accent_chr(p));
16355 end;
16356 left_noad: begin print_esc("left"); print_delimiter(delimiter(p));
16357 end;
16358 right_noad: begin if subtype(p)=normal then print_esc("right")
16359 else print_esc("middle");
16360 print_delimiter(delimiter(p));
16361 end;
16362 end;
16363 if type(p)<left_noad then
16364 begin if subtype(p)<>normal then
16365 if subtype(p)=limits then print_esc("limits")
16366 else print_esc("nolimits");
16367 print_subsidiary_data(nucleus(p),".");
16368 end;
16369 print_subsidiary_data(supscr(p),"^");
16370 print_subsidiary_data(subscr(p),"_");
16371 end
16372
16373 @ @<Display fraction noad |p|@>=
16374 begin print_esc("fraction, thickness ");
16375 if thickness(p)=default_code then print("= default")
16376 else print_scaled(thickness(p));
16377 if (small_fam(left_delimiter(p))<>0)or@+
16378 (small_char(left_delimiter(p))<>min_quarterword)or@|
16379 (large_fam(left_delimiter(p))<>0)or@|
16380 (large_char(left_delimiter(p))<>min_quarterword) then
16381 begin print(", left-delimiter "); print_delimiter(left_delimiter(p));
16382 end;
16383 if (small_fam(right_delimiter(p))<>0)or@|
16384 (small_char(right_delimiter(p))<>min_quarterword)or@|
16385 (large_fam(right_delimiter(p))<>0)or@|
16386 (large_char(right_delimiter(p))<>min_quarterword) then
16387 begin print(", right-delimiter "); print_delimiter(right_delimiter(p));
16388 end;
16389 print_subsidiary_data(numerator(p),"\");
16390 print_subsidiary_data(denominator(p),"/");
16391 end
16392
16393 @ That which can be displayed can also be destroyed.
16394
16395 @<Cases of |flush_node_list| that arise...@>=
16396 style_node: begin free_node(p,style_node_size); goto done;
16397 end;
16398 choice_node:begin flush_node_list(display_mlist(p));
16399 flush_node_list(text_mlist(p));
16400 flush_node_list(script_mlist(p));
16401 flush_node_list(script_script_mlist(p));
16402 free_node(p,style_node_size); goto done;
16403 end;
16404 ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
16405 radical_noad,over_noad,under_noad,vcenter_noad,accent_noad:@t@>@;@/
16406 begin if math_type(nucleus(p))>=sub_box then
16407 flush_node_list(info(nucleus(p)));
16408 if math_type(supscr(p))>=sub_box then
16409 flush_node_list(info(supscr(p)));
16410 if math_type(subscr(p))>=sub_box then
16411 flush_node_list(info(subscr(p)));
16412 if type(p)=radical_noad then free_node(p,radical_noad_size)
16413 else if type(p)=accent_noad then free_node(p,accent_noad_size)
16414 else free_node(p,noad_size);
16415 goto done;
16416 end;
16417 left_noad,right_noad: begin free_node(p,noad_size); goto done;
16418 end;
16419 fraction_noad: begin flush_node_list(info(numerator(p)));
16420 flush_node_list(info(denominator(p)));
16421 free_node(p,fraction_noad_size); goto done;
16422 end;
16423
16424 @* \[35] Subroutines for math mode.
16425 In order to convert mlists to hlists, i.e., noads to nodes, we need several
16426 subroutines that are conveniently dealt with now.
16427
16428 Let us first introduce the macros that make it easy to get at the parameters and
16429 other font information. A size code, which is a multiple of 16, is added to a
16430 family number to get an index into the table of internal font numbers
16431 for each combination of family and size. (Be alert: Size codes get
16432 larger as the type gets smaller.)
16433
16434 @<Basic printing procedures@>=
16435 procedure print_size(@!s:integer);
16436 begin if s=text_size then print_esc("textfont")
16437 else if s=script_size then print_esc("scriptfont")
16438 else print_esc("scriptscriptfont");
16439 end;
16440
16441 @ Before an mlist is converted to an hlist, \TeX\ makes sure that
16442 the fonts in family~2 have enough parameters to be math-symbol
16443 fonts, and that the fonts in family~3 have enough parameters to be
16444 math-extension fonts. The math-symbol parameters are referred to by using the
16445 following macros, which take a size code as their parameter; for example,
16446 |num1(cur_size)| gives the value of the |num1| parameter for the current size.
16447 @^parameters for symbols@>
16448 @^font parameters@>
16449
16450 NB: the access functions here must all put the font \# into /f/ for mathsy().
16451
16452 The accessors are defined with
16453 |define_mathsy_accessor(NAME)(fontdimen-number)(NAME)|
16454 because I can't see how to only give the name once, with WEB's limited
16455 macro capabilities. This seems a bit ugly, but it works.
16456
16457 @d total_mathsy_params=22
16458
16459 {the following are OpenType MATH constant indices for use with OT math fonts}
16460 @d scriptPercentScaleDown = 0
16461 @d scriptScriptPercentScaleDown = 1
16462 @d delimitedSubFormulaMinHeight = 2
16463 @d displayOperatorMinHeight = 3
16464 @d mathLeading = 4
16465 @d firstMathValueRecord = mathLeading
16466 @d axisHeight = 5
16467 @d accentBaseHeight = 6
16468 @d flattenedAccentBaseHeight = 7
16469 @d subscriptShiftDown = 8
16470 @d subscriptTopMax = 9
16471 @d subscriptBaselineDropMin = 10
16472 @d superscriptShiftUp = 11
16473 @d superscriptShiftUpCramped = 12
16474 @d superscriptBottomMin = 13
16475 @d superscriptBaselineDropMax = 14
16476 @d subSuperscriptGapMin = 15
16477 @d superscriptBottomMaxWithSubscript = 16
16478 @d spaceAfterScript = 17
16479 @d upperLimitGapMin = 18
16480 @d upperLimitBaselineRiseMin = 19
16481 @d lowerLimitGapMin = 20
16482 @d lowerLimitBaselineDropMin = 21
16483 @d stackTopShiftUp = 22
16484 @d stackTopDisplayStyleShiftUp = 23
16485 @d stackBottomShiftDown = 24
16486 @d stackBottomDisplayStyleShiftDown = 25
16487 @d stackGapMin = 26
16488 @d stackDisplayStyleGapMin = 27
16489 @d stretchStackTopShiftUp = 28
16490 @d stretchStackBottomShiftDown = 29
16491 @d stretchStackGapAboveMin = 30
16492 @d stretchStackGapBelowMin = 31
16493 @d fractionNumeratorShiftUp = 32
16494 @d fractionNumeratorDisplayStyleShiftUp = 33
16495 @d fractionDenominatorShiftDown = 34
16496 @d fractionDenominatorDisplayStyleShiftDown = 35
16497 @d fractionNumeratorGapMin = 36
16498 @d fractionNumDisplayStyleGapMin = 37
16499 @d fractionRuleThickness = 38
16500 @d fractionDenominatorGapMin = 39
16501 @d fractionDenomDisplayStyleGapMin = 40
16502 @d skewedFractionHorizontalGap = 41
16503 @d skewedFractionVerticalGap = 42
16504 @d overbarVerticalGap = 43
16505 @d overbarRuleThickness = 44
16506 @d overbarExtraAscender = 45
16507 @d underbarVerticalGap = 46
16508 @d underbarRuleThickness = 47
16509 @d underbarExtraDescender = 48
16510 @d radicalVerticalGap = 49
16511 @d radicalDisplayStyleVerticalGap = 50
16512 @d radicalRuleThickness = 51
16513 @d radicalExtraAscender = 52
16514 @d radicalKernBeforeDegree = 53
16515 @d radicalKernAfterDegree = 54
16516 @d lastMathValueRecord = radicalKernAfterDegree
16517 @d radicalDegreeBottomRaisePercent = 55
16518 @d lastMathConstant = radicalDegreeBottomRaisePercent
16519
16520
16521 @d mathsy(#)==font_info[#+param_base[f]].sc
16522
16523 @d define_mathsy_end(#)==
16524 #:=rval;
16525 end
16526 @d define_mathsy_body(#)==
16527 var
16528 f: integer;
16529 rval: scaled;
16530 begin
16531 f:=fam_fnt(2 + size_code);
16532 if is_new_mathfont(f) then
16533 rval:=get_native_mathsy_param(f, #)
16534 else
16535 rval:=mathsy(#);
16536 define_mathsy_end
16537 @d define_mathsy_accessor(#)==function #(size_code: integer): scaled; define_mathsy_body
16538
16539 @p define_mathsy_accessor(math_x_height)(5)(math_x_height);
16540 define_mathsy_accessor(math_quad)(6)(math_quad);
16541 define_mathsy_accessor(num1)(8)(num1);
16542 define_mathsy_accessor(num2)(9)(num2);
16543 define_mathsy_accessor(num3)(10)(num3);
16544 define_mathsy_accessor(denom1)(11)(denom1);
16545 define_mathsy_accessor(denom2)(12)(denom2);
16546 define_mathsy_accessor(sup1)(13)(sup1);
16547 define_mathsy_accessor(sup2)(14)(sup2);
16548 define_mathsy_accessor(sup3)(15)(sup3);
16549 define_mathsy_accessor(sub1)(16)(sub1);
16550 define_mathsy_accessor(sub2)(17)(sub2);
16551 define_mathsy_accessor(sup_drop)(18)(sup_drop);
16552 define_mathsy_accessor(sub_drop)(19)(sub_drop);
16553 define_mathsy_accessor(delim1)(20)(delim1);
16554 define_mathsy_accessor(delim2)(21)(delim2);
16555 define_mathsy_accessor(axis_height)(22)(axis_height);
16556
16557 @ The math-extension parameters have similar macros, but the size code is
16558 omitted (since it is always |cur_size| when we refer to such parameters).
16559 @^parameters for symbols@>
16560 @^font parameters@>
16561
16562 @d total_mathex_params=13
16563
16564 @d mathex(#)==font_info[#+param_base[f]].sc
16565
16566 @d define_mathex_end(#)==
16567 #:=rval;
16568 end
16569 @d define_mathex_body(#)==
16570 var
16571 f: integer;
16572 rval: scaled;
16573 begin
16574 f:=fam_fnt(3 + cur_size);
16575 if is_new_mathfont(f) then
16576 rval:=get_native_mathex_param(f, #)
16577 else
16578 rval:=mathex(#);
16579 define_mathex_end
16580 @d define_mathex_accessor(#)==function #:scaled; define_mathex_body
16581
16582 @p define_mathex_accessor(default_rule_thickness)(8)(default_rule_thickness);
16583 define_mathex_accessor(big_op_spacing1)(9)(big_op_spacing1);
16584 define_mathex_accessor(big_op_spacing2)(10)(big_op_spacing2);
16585 define_mathex_accessor(big_op_spacing3)(11)(big_op_spacing3);
16586 define_mathex_accessor(big_op_spacing4)(12)(big_op_spacing4);
16587 define_mathex_accessor(big_op_spacing5)(13)(big_op_spacing5);
16588
16589 @ Native font support requires these additional subroutines.
16590
16591 |new_native_word_node| creates the node, but does not actually set its metrics;
16592 call |set_native_metrics(node)| if that is required.
16593
16594 @<Declare subroutines for |new_character|@>=
16595 function new_native_word_node(@!f:internal_font_number;@!n:integer):pointer;
16596 var
16597 l: integer;
16598 q: pointer;
16599 begin
16600 l:=native_node_size + (n * sizeof(UTF16_code) + sizeof(memory_word) - 1) div sizeof(memory_word);
16601
16602 q:=get_node(l);
16603 type(q):=whatsit_node;
16604 if XeTeX_generate_actual_text_en then subtype(q):=native_word_node_AT
16605 else subtype(q):=native_word_node;
16606
16607 native_size(q):=l;
16608 native_font(q):=f;
16609 native_length(q):=n;
16610
16611 native_glyph_count(q):=0;
16612 native_glyph_info_ptr(q):=null_ptr;
16613
16614 new_native_word_node:=q;
16615 end;
16616
16617 function new_native_character(@!f:internal_font_number;@!c:UnicodeScalar):pointer;
16618 var
16619 p: pointer;
16620 i, len: integer;
16621 begin
16622 if font_mapping[f] <> 0 then begin
16623 if (c>@"FFFF) then str_room(2)
16624 else str_room(1);
16625 append_char(c);
16626 len:=apply_mapping(font_mapping[f], addressof(str_pool[str_start_macro(str_ptr)]), cur_length);
16627 pool_ptr:=str_start_macro(str_ptr); { flush the string, as we'll be using the mapped text instead }
16628
16629 i:=0;
16630 while i < len do begin
16631 if (mapped_text[i] >= @"D800) and (mapped_text[i] < @"DC00) then begin
16632 c:=(mapped_text[i] - @"D800) * 1024 + mapped_text[i+1] - @"DC00 + @"10000;
16633 if map_char_to_glyph(f, c) = 0 then begin
16634 char_warning(f, c);
16635 end;
16636 i:=i + 2;
16637 end
16638 else begin
16639 if map_char_to_glyph(f, mapped_text[i]) = 0 then begin
16640 char_warning(f, mapped_text[i]);
16641 end;
16642 i:=i + 1;
16643 end;
16644 end;
16645
16646 p:=new_native_word_node(f, len);
16647 for i:=0 to len-1 do begin
16648 set_native_char(p, i, mapped_text[i]);
16649 end
16650 end
16651 else begin
16652 if tracing_lost_chars > 0 then
16653 if map_char_to_glyph(f, c) = 0 then begin
16654 char_warning(f, c);
16655 end;
16656
16657 p:=get_node(native_node_size + 1);
16658 type(p):=whatsit_node;
16659 subtype(p):=native_word_node;
16660
16661 native_size(p):=native_node_size + 1;
16662 native_glyph_count(p):=0;
16663 native_glyph_info_ptr(p):=null_ptr;
16664 native_font(p):=f;
16665
16666 if c > @"FFFF then begin
16667 native_length(p):=2;
16668 set_native_char(p, 0, (c - @"10000) div 1024 + @"D800);
16669 set_native_char(p, 1, (c - @"10000) mod 1024 + @"DC00);
16670 end
16671 else begin
16672 native_length(p):=1;
16673 set_native_char(p, 0, c);
16674 end;
16675 end;
16676
16677 set_native_metrics(p, XeTeX_use_glyph_metrics);
16678
16679 new_native_character:=p;
16680 end;
16681
16682 procedure font_feature_warning(featureNameP:void_pointer; featLen:integer;
16683 settingNameP:void_pointer; setLen:integer);
16684 var
16685 i: integer;
16686 begin
16687 begin_diagnostic;
16688 print_nl("Unknown ");
16689 if setLen > 0 then begin
16690 print("selector `");
16691 print_utf8_str(settingNameP, setLen);
16692 print("' for ");
16693 end;
16694 print("feature `");
16695 print_utf8_str(featureNameP, featLen);
16696 print("' in font `");
16697 i:=1;
16698 while ord(name_of_file[i]) <> 0 do begin
16699 print_visible_char(name_of_file[i]); { this is already UTF-8 }
16700 incr(i);
16701 end;
16702 print("'.");
16703 end_diagnostic(false);
16704 end;
16705
16706 procedure font_mapping_warning(mappingNameP:void_pointer;
16707 mappingNameLen:integer;
16708 warningType:integer); { 0: just logging; 1: file not found; 2: can't load }
16709 var
16710 i: integer;
16711 begin
16712 begin_diagnostic;
16713 if warningType=0 then print_nl("Loaded mapping `")
16714 else print_nl("Font mapping `");
16715 print_utf8_str(mappingNameP, mappingNameLen);
16716 print("' for font `");
16717 i:=1;
16718 while ord(name_of_file[i]) <> 0 do begin
16719 print_visible_char(name_of_file[i]); { this is already UTF-8 }
16720 incr(i);
16721 end;
16722 case warningType of
16723 1: print("' not found.");
16724 2: begin print("' not usable;");
16725 print_nl("bad mapping file or incorrect mapping type.");
16726 end;
16727 othercases print("'.")
16728 endcases;
16729 end_diagnostic(false);
16730 end;
16731
16732 procedure graphite_warning;
16733 var
16734 i: integer;
16735 begin
16736 begin_diagnostic;
16737 print_nl("Font `");
16738 i:=1;
16739 while ord(name_of_file[i]) <> 0 do begin
16740 print_visible_char(name_of_file[i]); { this is already UTF-8 }
16741 incr(i);
16742 end;
16743 print("' does not support Graphite. Trying OpenType layout instead.");
16744 end_diagnostic(false);
16745 end;
16746
16747 function load_native_font(u: pointer; nom, aire:str_number; s: scaled): internal_font_number;
16748 label
16749 done;
16750 const
16751 first_math_fontdimen = 10;
16752 var
16753 k, num_font_dimens: integer;
16754 font_engine: void_pointer; {really an CFDictionaryRef or XeTeXLayoutEngine}
16755 actual_size: scaled; {|s| converted to real size, if it was negative}
16756 p: pointer; {for temporary |native_char| node we'll create}
16757 ascent, descent, font_slant, x_ht, cap_ht: scaled;
16758 f: internal_font_number;
16759 full_name: str_number;
16760 begin
16761 { on entry here, the full name is packed into |name_of_file| in UTF8 form }
16762
16763 load_native_font:=null_font;
16764
16765 font_engine:=find_native_font(name_of_file + 1, s);
16766 if font_engine = 0 then goto done;
16767
16768 if s>=0 then
16769 actual_size:=s
16770 else begin
16771 if (s <> -1000) then
16772 actual_size:=xn_over_d(loaded_font_design_size,-s,1000)
16773 else
16774 actual_size:=loaded_font_design_size;
16775 end;
16776
16777 { look again to see if the font is already loaded, now that we know its canonical name }
16778 str_room(name_length);
16779 for k:=1 to name_length do
16780 append_char(name_of_file[k]);
16781 full_name:=make_string; { not |slow_make_string| because we'll flush it if the font was already loaded }
16782
16783 for f:=font_base+1 to font_ptr do
16784 if (font_area[f] = native_font_type_flag) and str_eq_str(font_name[f], full_name) and (font_size[f] = actual_size) then begin
16785 release_font_engine(font_engine, native_font_type_flag);
16786 flush_string;
16787 load_native_font:=f;
16788 goto done;
16789 end;
16790
16791 if (native_font_type_flag = otgr_font_flag) and isOpenTypeMathFont(font_engine) then
16792 num_font_dimens:=first_math_fontdimen + lastMathConstant
16793 else
16794 num_font_dimens:=8;
16795
16796 if (font_ptr = font_max) or (fmem_ptr + num_font_dimens > font_mem_size) then begin
16797 @<Apologize for not loading the font, |goto done|@>;
16798 end;
16799
16800 { we've found a valid installed font, and have room }
16801 incr(font_ptr);
16802 font_area[font_ptr]:=native_font_type_flag; { set by |find_native_font| to either |aat_font_flag| or |ot_font_flag| }
16803
16804 { store the canonical name }
16805 font_name[font_ptr]:=full_name;
16806
16807 font_check[font_ptr].b0:=0;
16808 font_check[font_ptr].b1:=0;
16809 font_check[font_ptr].b2:=0;
16810 font_check[font_ptr].b3:=0;
16811 font_glue[font_ptr]:=null;
16812 font_dsize[font_ptr]:=loaded_font_design_size;
16813 font_size[font_ptr]:=actual_size;
16814
16815 if (native_font_type_flag = aat_font_flag) then begin
16816 aat_get_font_metrics(font_engine, addressof(ascent), addressof(descent),
16817 addressof(x_ht), addressof(cap_ht), addressof(font_slant))
16818 end else begin
16819 ot_get_font_metrics(font_engine, addressof(ascent), addressof(descent),
16820 addressof(x_ht), addressof(cap_ht), addressof(font_slant));
16821 end;
16822
16823 height_base[font_ptr]:=ascent;
16824 depth_base[font_ptr]:=-descent;
16825
16826 font_params[font_ptr]:=num_font_dimens; {we add an extra \.{\\fontdimen8} |:= cap_height|; then OT math fonts have a bunch more}
16827 font_bc[font_ptr]:=0;
16828 font_ec[font_ptr]:=65535;
16829 font_used[font_ptr]:=false;
16830 hyphen_char[font_ptr]:=default_hyphen_char;
16831 skew_char[font_ptr]:=default_skew_char;
16832 param_base[font_ptr]:=fmem_ptr-1;
16833
16834 font_layout_engine[font_ptr]:=font_engine;
16835 font_mapping[font_ptr]:=0; {don't use the mapping, if any, when measuring space here}
16836 font_letter_space[font_ptr]:=loaded_font_letter_space;
16837
16838 @# {measure the width of the space character and set up font parameters}
16839 p:=new_native_character(font_ptr, " ");
16840 s:=width(p) + loaded_font_letter_space;
16841 free_node(p, native_size(p));
16842
16843 font_info[fmem_ptr].sc:=font_slant; {|slant|}
16844 incr(fmem_ptr);
16845 font_info[fmem_ptr].sc:=s; {|space| = width of space character}
16846 incr(fmem_ptr);
16847 font_info[fmem_ptr].sc:=s div 2; {|space_stretch| = 1/2 * space}
16848 incr(fmem_ptr);
16849 font_info[fmem_ptr].sc:=s div 3; {|space_shrink| = 1/3 * space}
16850 incr(fmem_ptr);
16851 font_info[fmem_ptr].sc:=x_ht; {|x_height|}
16852 incr(fmem_ptr);
16853 font_info[fmem_ptr].sc:=font_size[font_ptr]; {|quad| = font size}
16854 incr(fmem_ptr);
16855 font_info[fmem_ptr].sc:=s div 3; {|extra_space| = 1/3 * space}
16856 incr(fmem_ptr);
16857 font_info[fmem_ptr].sc:=cap_ht; {|cap_height|}
16858 incr(fmem_ptr);
16859
16860 if num_font_dimens = first_math_fontdimen + lastMathConstant then begin
16861 font_info[fmem_ptr].int:=num_font_dimens; { \.{\\fontdimen9} |:=| number of assigned fontdimens }
16862 incr(fmem_ptr);
16863 for k:=0 to lastMathConstant do begin
16864 font_info[fmem_ptr].sc:=get_ot_math_constant(font_ptr, k);
16865 incr(fmem_ptr);
16866 end;
16867 end;
16868
16869 font_mapping[font_ptr]:=loaded_font_mapping;
16870 font_flags[font_ptr]:=loaded_font_flags;
16871
16872 load_native_font:=font_ptr;
16873 done:
16874 end;
16875
16876 procedure do_locale_linebreaks(s: integer; len: integer);
16877 var
16878 offs, prevOffs, i: integer;
16879 use_penalty, use_skip: boolean;
16880 begin
16881 if (XeTeX_linebreak_locale = 0) or (len = 1) then begin
16882 link(tail):=new_native_word_node(main_f, len);
16883 tail:=link(tail);
16884 for i:=0 to len - 1 do
16885 set_native_char(tail, i, native_text[s + i]);
16886 set_native_metrics(tail, XeTeX_use_glyph_metrics);
16887 end else begin
16888 use_skip:=XeTeX_linebreak_skip <> zero_glue;
16889 use_penalty:=XeTeX_linebreak_penalty <> 0 or not use_skip;
16890 linebreak_start(main_f, XeTeX_linebreak_locale, native_text + s, len);
16891 offs:=0;
16892 repeat
16893 prevOffs:=offs;
16894 offs:=linebreak_next;
16895 if offs > 0 then begin
16896 if prevOffs <> 0 then begin
16897 if use_penalty then
16898 tail_append(new_penalty(XeTeX_linebreak_penalty));
16899 if use_skip then
16900 tail_append(new_param_glue(XeTeX_linebreak_skip_code));
16901 end;
16902 link(tail):=new_native_word_node(main_f, offs - prevOffs);
16903 tail:=link(tail);
16904 for i:=prevOffs to offs - 1 do
16905 set_native_char(tail, i - prevOffs, native_text[s + i]);
16906 set_native_metrics(tail, XeTeX_use_glyph_metrics);
16907 end;
16908 until offs < 0;
16909 end
16910 end;
16911
16912 procedure bad_utf8_warning;
16913 begin
16914 begin_diagnostic;
16915 print_nl("Invalid UTF-8 byte or sequence");
16916 if terminal_input then print(" in terminal input")
16917 else begin
16918 print(" at line ");
16919 print_int(line);
16920 end;
16921 print(" replaced by U+FFFD.");
16922 end_diagnostic(false);
16923 end;
16924
16925 function get_input_normalization_state: integer;
16926 begin
16927 if eqtb=nil then get_input_normalization_state:=0 { may be called before eqtb is initialized }
16928 else get_input_normalization_state:=XeTeX_input_normalization_state;
16929 end;
16930
16931 function get_tracing_fonts_state: integer;
16932 begin
16933 get_tracing_fonts_state:=XeTeX_tracing_fonts_state;
16934 end;
16935
16936 @ We also need to compute the change in style between mlists and their
16937 subsidiaries. The following macros define the subsidiary style for
16938 an overlined nucleus (|cramped_style|), for a subscript or a superscript
16939 (|sub_style| or |sup_style|), or for a numerator or denominator (|num_style|
16940 or |denom_style|).
16941
16942 @d cramped_style(#)==2*(# div 2)+cramped {cramp the style}
16943 @d sub_style(#)==2*(# div 4)+script_style+cramped {smaller and cramped}
16944 @d sup_style(#)==2*(# div 4)+script_style+(# mod 2) {smaller}
16945 @d num_style(#)==#+2-2*(# div 6) {smaller unless already script-script}
16946 @d denom_style(#)==2*(# div 2)+cramped+2-2*(# div 6) {smaller, cramped}
16947
16948 @ When the style changes, the following piece of program computes associated
16949 information:
16950
16951 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>=
16952 begin if cur_style<script_style then cur_size:=text_size
16953 else cur_size:=script_size*((cur_style-text_style) div 2);
16954 cur_mu:=x_over_n(math_quad(cur_size),18);
16955 end
16956
16957 @ Here is a function that returns a pointer to a rule node having a given
16958 thickness |t|. The rule will extend horizontally to the boundary of the vlist
16959 that eventually contains it.
16960
16961 @p function fraction_rule(@!t:scaled):pointer;
16962 {construct the bar for a fraction}
16963 var p:pointer; {the new node}
16964 begin p:=new_rule; height(p):=t; depth(p):=0; fraction_rule:=p;
16965 end;
16966
16967 @ The |overbar| function returns a pointer to a vlist box that consists of
16968 a given box |b|, above which has been placed a kern of height |k| under a
16969 fraction rule of thickness |t| under additional space of height |t|.
16970
16971 @p function overbar(@!b:pointer;@!k,@!t:scaled):pointer;
16972 var p,@!q:pointer; {nodes being constructed}
16973 begin p:=new_kern(k); link(p):=b; q:=fraction_rule(t); link(q):=p;
16974 p:=new_kern(t); link(p):=q; overbar:=vpack(p,natural);
16975 end;
16976
16977 @ The |var_delimiter| function, which finds or constructs a sufficiently
16978 large delimiter, is the most interesting of the auxiliary functions that
16979 currently concern us. Given a pointer |d| to a delimiter field in some noad,
16980 together with a size code |s| and a vertical distance |v|, this function
16981 returns a pointer to a box that contains the smallest variant of |d| whose
16982 height plus depth is |v| or more. (And if no variant is large enough, it
16983 returns the largest available variant.) In particular, this routine will
16984 construct arbitrarily large delimiters from extensible components, if
16985 |d| leads to such characters.
16986
16987 The value returned is a box whose |shift_amount| has been set so that
16988 the box is vertically centered with respect to the axis in the given size.
16989 If a built-up symbol is returned, the height of the box before shifting
16990 will be the height of its topmost component.
16991
16992 @p@t\4@>@<Declare subprocedures for |var_delimiter|@>
16993 procedure stack_glyph_into_box(@!b:pointer;@!f:internal_font_number;@!g:integer);
16994 var p,q:pointer;
16995 begin
16996 p:=get_node(glyph_node_size);
16997 type(p):=whatsit_node; subtype(p):=glyph_node;
16998 native_font(p):=f; native_glyph(p):=g;
16999 set_native_glyph_metrics(p, 1);
17000 if type(b)=hlist_node then begin
17001 q:=list_ptr(b);
17002 if q=null then list_ptr(b):=p else begin
17003 while link(q)<>null do q:=link(q);
17004 link(q):=p;
17005 if (height(b) < height(p)) then height(b):=height(p);
17006 if (depth(b) < depth(p)) then depth(b):=depth(p);
17007 end;
17008 end else begin
17009 link(p):=list_ptr(b); list_ptr(b):=p;
17010 height(b):=height(p);
17011 if (width(b) < width(p)) then width(b):=width(p);
17012 end;
17013 end;
17014
17015 procedure stack_glue_into_box(@!b:pointer;@!min,max:scaled);
17016 var p,q:pointer;
17017 begin
17018 q:=new_spec(zero_glue);
17019 width(q):=min;
17020 stretch(q):=max-min;
17021 p:=new_glue(q);
17022 if type(b)=hlist_node then begin
17023 q:=list_ptr(b);
17024 if q=null then list_ptr(b):=p else begin
17025 while link(q)<>null do q:=link(q);
17026 link(q):=p;
17027 end;
17028 end else begin
17029 link(p):=list_ptr(b); list_ptr(b):=p;
17030 height(b):=height(p); width(b):=width(p);
17031 end;
17032 end;
17033
17034 function build_opentype_assembly(@!f:internal_font_number;@!a:void_pointer;@!s:scaled;@!horiz:boolean):pointer;
17035 {return a box with height/width at least |s|, using font |f|, with glyph assembly info from |a|}
17036 var
17037 b:pointer; {the box we're constructing}
17038 n:integer; {the number of repetitions of each extender}
17039 i,j:integer; {indexes}
17040 g:integer; {glyph code}
17041 p:pointer; {temp pointer}
17042 s_max,o,oo,prev_o,min_o:scaled;
17043 no_extenders: boolean;
17044 nat,str:scaled; {natural size, stretch}
17045 begin
17046 b:=new_null_box;
17047 if horiz then
17048 type(b):=hlist_node
17049 else
17050 type(b):=vlist_node;
17051
17052 {figure out how many repeats of each extender to use}
17053 n:=-1;
17054 no_extenders:=true;
17055 min_o:=ot_min_connector_overlap(f);
17056 repeat
17057 n:=n+1;
17058 {calc max possible size with this number of extenders}
17059 s_max:=0;
17060 prev_o:=0;
17061 for i:=0 to ot_part_count(a)-1 do begin
17062 if ot_part_is_extender(a, i) then begin
17063 no_extenders:=false;
17064 for j:=1 to n do begin
17065 o:=ot_part_start_connector(f, a, i);
17066 if min_o<o then o:=min_o;
17067 if prev_o<o then o:=prev_o;
17068 s_max:=s_max-o+ot_part_full_advance(f, a, i);
17069 prev_o:=ot_part_end_connector(f, a, i);
17070 end
17071 end else begin
17072 o:=ot_part_start_connector(f, a, i);
17073 if min_o<o then o:=min_o;
17074 if prev_o<o then o:=prev_o;
17075 s_max:=s_max-o+ot_part_full_advance(f, a, i);
17076 prev_o:=ot_part_end_connector(f, a, i);
17077 end;
17078 end;
17079 until (s_max>=s) or no_extenders;
17080
17081 {assemble box using |n| copies of each extender,
17082 with appropriate glue wherever an overlap occurs}
17083 prev_o:=0;
17084 for i:=0 to ot_part_count(a)-1 do begin
17085 if ot_part_is_extender(a, i) then begin
17086 for j:=1 to n do begin
17087 o:=ot_part_start_connector(f, a, i);
17088 if prev_o<o then o:=prev_o;
17089 oo:=o; {max overlap}
17090 if min_o<o then o:=min_o;
17091 if oo>0 then stack_glue_into_box(b, -oo, -o);
17092 g:=ot_part_glyph(a, i);
17093 stack_glyph_into_box(b, f, g);
17094 prev_o:=ot_part_end_connector(f, a, i);
17095 end
17096 end else begin
17097 o:=ot_part_start_connector(f, a, i);
17098 if prev_o<o then o:=prev_o;
17099 oo:=o; {max overlap}
17100 if min_o<o then o:=min_o;
17101 if oo>0 then stack_glue_into_box(b, -oo, -o);
17102 g:=ot_part_glyph(a, i);
17103 stack_glyph_into_box(b, f, g);
17104 prev_o:=ot_part_end_connector(f, a, i);
17105 end;
17106 end;
17107
17108 {find natural size and total stretch of the box}
17109 p:=list_ptr(b); nat:=0; str:=0;
17110 while p<>null do begin
17111 if type(p)=whatsit_node then begin
17112 if horiz then
17113 nat:=nat+width(p)
17114 else
17115 nat:=nat+height(p)+depth(p);
17116 end else if type(p)=glue_node then begin
17117 nat:=nat+width(glue_ptr(p));
17118 str:=str+stretch(glue_ptr(p));
17119 end;
17120 p:=link(p);
17121 end;
17122
17123 {set glue so as to stretch the connections if needed}
17124 o:=0;
17125 if (s>nat) and (str>0) then begin
17126 o:=(s-nat);
17127 {don't stretch more than |str|}
17128 if (o>str) then o:=str;
17129 glue_order(b):=normal; glue_sign(b):=stretching;
17130 glue_set(b):=unfloat(o/str);
17131 if horiz then
17132 width(b):= nat+round(str*float(glue_set(b)))
17133 else
17134 height(b):=nat+round(str*float(glue_set(b)));
17135 end else
17136 if horiz then
17137 width(b):=nat
17138 else
17139 height(b):=nat;
17140
17141 build_opentype_assembly:=b;
17142 end;
17143
17144 function var_delimiter(@!d:pointer;@!s:integer;@!v:scaled):pointer;
17145 label found,continue;
17146 var b:pointer; {the box that will be constructed}
17147 ot_assembly_ptr:void_pointer;
17148 @!f,@!g: internal_font_number; {best-so-far and tentative font codes}
17149 @!c,@!x,@!y: quarterword; {best-so-far and tentative character codes}
17150 @!m,@!n: integer; {the number of extensible pieces}
17151 @!u: scaled; {height-plus-depth of a tentative character}
17152 @!w: scaled; {largest height-plus-depth so far}
17153 @!q: four_quarters; {character info}
17154 @!hd: eight_bits; {height-depth byte}
17155 @!r: four_quarters; {extensible pieces}
17156 @!z: integer; {runs through font family members}
17157 @!large_attempt: boolean; {are we trying the ``large'' variant?}
17158 begin f:=null_font; w:=0; large_attempt:=false;
17159 z:=small_fam(d); x:=small_char(d);
17160 ot_assembly_ptr:=nil;
17161 loop@+ begin @<Look at the variants of |(z,x)|; set |f| and |c| whenever
17162 a better character is found; |goto found| as soon as a
17163 large enough variant is encountered@>;
17164 if large_attempt then goto found; {there were none large enough}
17165 large_attempt:=true; z:=large_fam(d); x:=large_char(d);
17166 end;
17167 found: if f<>null_font then begin
17168 if not is_ot_font(f) then
17169 @<Make variable |b| point to a box for |(f,c)|@>
17170 else begin
17171 {for OT fonts, c is the glyph ID to use}
17172 if ot_assembly_ptr<>nil then
17173 b:=build_opentype_assembly(f, ot_assembly_ptr, v, 0)
17174 else begin
17175 b:=new_null_box; type(b):=vlist_node; list_ptr(b):=get_node(glyph_node_size);
17176 type(list_ptr(b)):=whatsit_node; subtype(list_ptr(b)):=glyph_node;
17177 native_font(list_ptr(b)):=f; native_glyph(list_ptr(b)):=c;
17178 set_native_glyph_metrics(list_ptr(b), 1);
17179 width(b):=width(list_ptr(b));
17180 height(b):=height(list_ptr(b));
17181 depth(b):=depth(list_ptr(b));
17182 end
17183 end
17184 end else begin b:=new_null_box;
17185 width(b):=null_delimiter_space; {use this width if no delimiter was found}
17186 end;
17187 shift_amount(b):=half(height(b)-depth(b)) - axis_height(s);
17188 free_ot_assembly(ot_assembly_ptr);
17189 var_delimiter:=b;
17190 end;
17191
17192 @ The search process is complicated slightly by the facts that some of the
17193 characters might not be present in some of the fonts, and they might not
17194 be probed in increasing order of height.
17195
17196 @<Look at the variants of |(z,x)|; set |f| and |c|...@>=
17197 if (z<>0)or(x<>min_quarterword) then
17198 begin z:=z+s+script_size;
17199 repeat z:=z-script_size; g:=fam_fnt(z);
17200 if g<>null_font then
17201 @<Look at the list of characters starting with |x| in
17202 font |g|; set |f| and |c| whenever
17203 a better character is found; |goto found| as soon as a
17204 large enough variant is encountered@>;
17205 until z<script_size;
17206 end
17207
17208 @ @<Look at the list of characters starting with |x|...@>=
17209 if is_ot_font(g) then begin
17210 x:=map_char_to_glyph(g, x);
17211 f:=g; c:=x; w:=0; n:=0;
17212 repeat
17213 y:=get_ot_math_variant(g, x, n, addressof(u), 0);
17214 if u>w then begin
17215 c:=y; w:=u;
17216 if u>=v then goto found;
17217 end;
17218 n:=n+1;
17219 until u<0;
17220 {if we get here, then we didn't find a big enough glyph; check if the char is extensible}
17221 ot_assembly_ptr:=get_ot_assembly_ptr(g, x, 0);
17222 if ot_assembly_ptr<>nil then goto found;
17223 end else
17224 begin y:=x;
17225 if (qo(y)>=font_bc[g])and(qo(y)<=font_ec[g]) then
17226 begin continue: q:=char_info(g)(y);
17227 if char_exists(q) then
17228 begin if char_tag(q)=ext_tag then
17229 begin f:=g; c:=y; goto found;
17230 end;
17231 hd:=height_depth(q);
17232 u:=char_height(g)(hd)+char_depth(g)(hd);
17233 if u>w then
17234 begin f:=g; c:=y; w:=u;
17235 if u>=v then goto found;
17236 end;
17237 if char_tag(q)=list_tag then
17238 begin y:=rem_byte(q); goto continue;
17239 end;
17240 end;
17241 end;
17242 end
17243
17244 @ Here is a subroutine that creates a new box, whose list contains a
17245 single character, and whose width includes the italic correction for
17246 that character. The height or depth of the box will be negative, if
17247 the height or depth of the character is negative; thus, this routine
17248 may deliver a slightly different result than |hpack| would produce.
17249
17250 @<Declare subprocedures for |var_delimiter|@>=
17251 function char_box(@!f:internal_font_number;@!c:integer):pointer;
17252 var q:four_quarters;
17253 @!hd:eight_bits; {|height_depth| byte}
17254 @!b,@!p:pointer; {the new box and its character node}
17255 begin
17256 if is_native_font(f) then begin
17257 b:=new_null_box;
17258 p:=new_native_character(f, c);
17259 list_ptr(b):=p;
17260 height(b):=height(p); width(b):=width(p);
17261 if depth(p)<0 then depth(b):=0 else depth(b):=depth(p);
17262 end
17263 else begin
17264 q:=char_info(f)(c); hd:=height_depth(q);
17265 b:=new_null_box; width(b):=char_width(f)(q)+char_italic(f)(q);
17266 height(b):=char_height(f)(hd); depth(b):=char_depth(f)(hd);
17267 p:=get_avail; character(p):=c; font(p):=f;
17268 end;
17269 list_ptr(b):=p; char_box:=b;
17270 end;
17271
17272 @ When the following code is executed, |char_tag(q)| will be equal to
17273 |ext_tag| if and only if a built-up symbol is supposed to be returned.
17274
17275 @<Make variable |b| point to a box for |(f,c)|@>=
17276 if char_tag(q)=ext_tag then
17277 @<Construct an extensible character in a new box |b|,
17278 using recipe |rem_byte(q)| and font |f|@>
17279 else b:=char_box(f,c)
17280
17281 @ When we build an extensible character, it's handy to have the
17282 following subroutine, which puts a given character on top
17283 of the characters already in box |b|:
17284
17285 @<Declare subprocedures for |var_delimiter|@>=
17286 procedure stack_into_box(@!b:pointer;@!f:internal_font_number;
17287 @!c:quarterword);
17288 var p:pointer; {new node placed into |b|}
17289 begin p:=char_box(f,c); link(p):=list_ptr(b); list_ptr(b):=p;
17290 height(b):=height(p);
17291 end;
17292
17293 @ Another handy subroutine computes the height plus depth of
17294 a given character:
17295
17296 @<Declare subprocedures for |var_delimiter|@>=
17297 function height_plus_depth(@!f:internal_font_number;@!c:quarterword):scaled;
17298 var q:four_quarters;
17299 @!hd:eight_bits; {|height_depth| byte}
17300 begin q:=char_info(f)(c); hd:=height_depth(q);
17301 height_plus_depth:=char_height(f)(hd)+char_depth(f)(hd);
17302 end;
17303
17304 @ @<Construct an extensible...@>=
17305 begin b:=new_null_box;
17306 type(b):=vlist_node;
17307 r:=font_info[exten_base[f]+rem_byte(q)].qqqq;@/
17308 @<Compute the minimum suitable height, |w|, and the corresponding
17309 number of extension steps, |n|; also set |width(b)|@>;
17310 c:=ext_bot(r);
17311 if c<>min_quarterword then stack_into_box(b,f,c);
17312 c:=ext_rep(r);
17313 for m:=1 to n do stack_into_box(b,f,c);
17314 c:=ext_mid(r);
17315 if c<>min_quarterword then
17316 begin stack_into_box(b,f,c); c:=ext_rep(r);
17317 for m:=1 to n do stack_into_box(b,f,c);
17318 end;
17319 c:=ext_top(r);
17320 if c<>min_quarterword then stack_into_box(b,f,c);
17321 depth(b):=w-height(b);
17322 end
17323
17324 @ The width of an extensible character is the width of the repeatable
17325 module. If this module does not have positive height plus depth,
17326 we don't use any copies of it, otherwise we use as few as possible
17327 (in groups of two if there is a middle part).
17328
17329 @<Compute the minimum suitable height, |w|, and...@>=
17330 c:=ext_rep(r); u:=height_plus_depth(f,c);
17331 w:=0; q:=char_info(f)(c); width(b):=char_width(f)(q)+char_italic(f)(q);@/
17332 c:=ext_bot(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
17333 c:=ext_mid(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
17334 c:=ext_top(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
17335 n:=0;
17336 if u>0 then while w<v do
17337 begin w:=w+u; incr(n);
17338 if ext_mid(r)<>min_quarterword then w:=w+u;
17339 end
17340
17341 @ The next subroutine is much simpler; it is used for numerators and
17342 denominators of fractions as well as for displayed operators and
17343 their limits above and below. It takes a given box~|b| and
17344 changes it so that the new box is centered in a box of width~|w|.
17345 The centering is done by putting \.{\\hss} glue at the left and right
17346 of the list inside |b|, then packaging the new box; thus, the
17347 actual box might not really be centered, if it already contains
17348 infinite glue.
17349
17350 The given box might contain a single character whose italic correction
17351 has been added to the width of the box; in this case a compensating
17352 kern is inserted.
17353
17354 @p function rebox(@!b:pointer;@!w:scaled):pointer;
17355 var p:pointer; {temporary register for list manipulation}
17356 @!f:internal_font_number; {font in a one-character box}
17357 @!v:scaled; {width of a character without italic correction}
17358 begin if (width(b)<>w)and(list_ptr(b)<>null) then
17359 begin if type(b)=vlist_node then b:=hpack(b,natural);
17360 p:=list_ptr(b);
17361 if (is_char_node(p))and(link(p)=null) then
17362 begin f:=font(p); v:=char_width(f)(char_info(f)(character(p)));
17363 if v<>width(b) then link(p):=new_kern(width(b)-v);
17364 end;
17365 free_node(b,box_node_size);
17366 b:=new_glue(ss_glue); link(b):=p;
17367 while link(p)<>null do p:=link(p);
17368 link(p):=new_glue(ss_glue);
17369 rebox:=hpack(b,w,exactly);
17370 end
17371 else begin width(b):=w; rebox:=b;
17372 end;
17373 end;
17374
17375 @ Here is a subroutine that creates a new glue specification from another
17376 one that is expressed in `\.{mu}', given the value of the math unit.
17377
17378 @d mu_mult(#)==nx_plus_y(n,#,xn_over_d(#,f,@'200000))
17379
17380 @p function math_glue(@!g:pointer;@!m:scaled):pointer;
17381 var p:pointer; {the new glue specification}
17382 @!n:integer; {integer part of |m|}
17383 @!f:scaled; {fraction part of |m|}
17384 begin n:=x_over_n(m,@'200000); f:=remainder;@/
17385 if f<0 then
17386 begin decr(n); f:=f+@'200000;
17387 end;
17388 p:=get_node(glue_spec_size);
17389 width(p):=mu_mult(width(g)); {convert \.{mu} to \.{pt}}
17390 stretch_order(p):=stretch_order(g);
17391 if stretch_order(p)=normal then stretch(p):=mu_mult(stretch(g))
17392 else stretch(p):=stretch(g);
17393 shrink_order(p):=shrink_order(g);
17394 if shrink_order(p)=normal then shrink(p):=mu_mult(shrink(g))
17395 else shrink(p):=shrink(g);
17396 math_glue:=p;
17397 end;
17398
17399 @ The |math_kern| subroutine removes |mu_glue| from a kern node, given
17400 the value of the math unit.
17401
17402 @p procedure math_kern(@!p:pointer;@!m:scaled);
17403 var @!n:integer; {integer part of |m|}
17404 @!f:scaled; {fraction part of |m|}
17405 begin if subtype(p)=mu_glue then
17406 begin n:=x_over_n(m,@'200000); f:=remainder;@/
17407 if f<0 then
17408 begin decr(n); f:=f+@'200000;
17409 end;
17410 width(p):=mu_mult(width(p)); subtype(p):=explicit;
17411 end;
17412 end;
17413
17414 @ Sometimes it is necessary to destroy an mlist. The following
17415 subroutine empties the current list, assuming that |abs(mode)=mmode|.
17416
17417 @p procedure flush_math;
17418 begin flush_node_list(link(head)); flush_node_list(incompleat_noad);
17419 link(head):=null; tail:=head; incompleat_noad:=null;
17420 end;
17421
17422 @* \[36] Typesetting math formulas.
17423 \TeX's most important routine for dealing with formulas is called
17424 |mlist_to_hlist|. After a formula has been scanned and represented as an
17425 mlist, this routine converts it to an hlist that can be placed into a box
17426 or incorporated into the text of a paragraph. There are three implicit
17427 parameters, passed in global variables: |cur_mlist| points to the first
17428 node or noad in the given mlist (and it might be |null|); |cur_style| is a
17429 style code; and |mlist_penalties| is |true| if penalty nodes for potential
17430 line breaks are to be inserted into the resulting hlist. After
17431 |mlist_to_hlist| has acted, |link(temp_head)| points to the translated hlist.
17432
17433 Since mlists can be inside mlists, the procedure is recursive. And since this
17434 is not part of \TeX's inner loop, the program has been written in a manner
17435 that stresses compactness over efficiency.
17436 @^recursion@>
17437
17438 @<Glob...@>=
17439 @!cur_mlist:pointer; {beginning of mlist to be translated}
17440 @!cur_style:small_number; {style code at current place in the list}
17441 @!cur_size:integer; {size code corresponding to |cur_style|}
17442 @!cur_mu:scaled; {the math unit width corresponding to |cur_size|}
17443 @!mlist_penalties:boolean; {should |mlist_to_hlist| insert penalties?}
17444
17445 @ The recursion in |mlist_to_hlist| is due primarily to a subroutine
17446 called |clean_box| that puts a given noad field into a box using a given
17447 math style; |mlist_to_hlist| can call |clean_box|, which can call
17448 |mlist_to_hlist|.
17449 @^recursion@>
17450
17451 The box returned by |clean_box| is ``clean'' in the
17452 sense that its |shift_amount| is zero.
17453
17454 @p procedure@?mlist_to_hlist; forward;@t\2@>@/
17455 function clean_box(@!p:pointer;@!s:small_number):pointer;
17456 label found;
17457 var q:pointer; {beginning of a list to be boxed}
17458 @!save_style:small_number; {|cur_style| to be restored}
17459 @!x:pointer; {box to be returned}
17460 @!r:pointer; {temporary pointer}
17461 begin case math_type(p) of
17462 math_char: begin cur_mlist:=new_noad; mem[nucleus(cur_mlist)]:=mem[p];
17463 end;
17464 sub_box: begin q:=info(p); goto found;
17465 end;
17466 sub_mlist: cur_mlist:=info(p);
17467 othercases begin q:=new_null_box; goto found;
17468 end
17469 endcases;@/
17470 save_style:=cur_style; cur_style:=s; mlist_penalties:=false;@/
17471 mlist_to_hlist; q:=link(temp_head); {recursive call}
17472 cur_style:=save_style; {restore the style}
17473 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
17474 found: if is_char_node(q)or(q=null) then x:=hpack(q,natural)
17475 else if (link(q)=null)and(type(q)<=vlist_node)and(shift_amount(q)=0) then
17476 x:=q {it's already clean}
17477 else x:=hpack(q,natural);
17478 @<Simplify a trivial box@>;
17479 clean_box:=x;
17480 end;
17481
17482 @ Here we save memory space in a common case.
17483
17484 @<Simplify a trivial box@>=
17485 q:=list_ptr(x);
17486 if is_char_node(q) then
17487 begin r:=link(q);
17488 if r<>null then if link(r)=null then if not is_char_node(r) then
17489 if type(r)=kern_node then {unneeded italic correction}
17490 begin free_node(r,small_node_size); link(q):=null;
17491 end;
17492 end
17493
17494 @ It is convenient to have a procedure that converts a |math_char|
17495 field to an ``unpacked'' form. The |fetch| routine sets |cur_f|, |cur_c|,
17496 and |cur_i| to the font code, character code, and character information bytes of
17497 a given noad field. It also takes care of issuing error messages for
17498 nonexistent characters; in such cases, |char_exists(cur_i)| will be |false|
17499 after |fetch| has acted, and the field will also have been reset to |empty|.
17500
17501 @p procedure fetch(@!a:pointer); {unpack the |math_char| field |a|}
17502 begin cur_c:=cast_to_ushort(character(a)); cur_f:=fam_fnt(fam(a)+cur_size);
17503 cur_c:=cur_c + (plane_and_fam_field(a) div @"100) * @"10000;
17504 if cur_f=null_font then
17505 @<Complain about an undefined family and set |cur_i| null@>
17506 else if is_native_font(cur_f) then begin
17507 cur_i:=null_character;
17508 end else begin if (qo(cur_c)>=font_bc[cur_f])and(qo(cur_c)<=font_ec[cur_f]) then
17509 cur_i:=char_info(cur_f)(cur_c)
17510 else cur_i:=null_character;
17511 if not(char_exists(cur_i)) then
17512 begin char_warning(cur_f,qo(cur_c));
17513 math_type(a):=empty; cur_i:=null_character;
17514 end;
17515 end;
17516 end;
17517
17518 @ @<Complain about an undefined family...@>=
17519 begin print_err(""); print_size(cur_size); print_char(" ");
17520 print_int(fam(a)); print(" is undefined (character ");
17521 print_ASCII(qo(cur_c)); print_char(")");
17522 help4("Somewhere in the math formula just ended, you used the")@/
17523 ("stated character from an undefined font family. For example,")@/
17524 ("plain TeX doesn't allow \it or \sl in subscripts. Proceed,")@/
17525 ("and I'll try to forget that I needed that character.");
17526 error; cur_i:=null_character; math_type(a):=empty;
17527 end
17528
17529 @ The outputs of |fetch| are placed in global variables.
17530
17531 @<Glob...@>=
17532 @!cur_f:internal_font_number; {the |font| field of a |math_char|}
17533 @!cur_c:integer; {the |character| field of a |math_char|}
17534 @!cur_i:four_quarters; {the |char_info| of a |math_char|,
17535 or a lig/kern instruction}
17536
17537 @ We need to do a lot of different things, so |mlist_to_hlist| makes two
17538 passes over the given mlist.
17539
17540 The first pass does most of the processing: It removes ``mu'' spacing from
17541 glue, it recursively evaluates all subsidiary mlists so that only the
17542 top-level mlist remains to be handled, it puts fractions and square roots
17543 and such things into boxes, it attaches subscripts and superscripts, and
17544 it computes the overall height and depth of the top-level mlist so that
17545 the size of delimiters for a |left_noad| and a |right_noad| will be known.
17546 The hlist resulting from each noad is recorded in that noad's |new_hlist|
17547 field, an integer field that replaces the |nucleus| or |thickness|.
17548 @^recursion@>
17549
17550 The second pass eliminates all noads and inserts the correct glue and
17551 penalties between nodes.
17552
17553 @d new_hlist(#)==mem[nucleus(#)].int {the translation of an mlist}
17554
17555 @ Here is the overall plan of |mlist_to_hlist|, and the list of its
17556 local variables.
17557
17558 @d done_with_noad=80 {go here when a noad has been fully translated}
17559 @d done_with_node=81 {go here when a node has been fully converted}
17560 @d check_dimensions=82 {go here to update |max_h| and |max_d|}
17561 @d delete_q=83 {go here to delete |q| and move to the next node}
17562
17563 @p@t\4@>@<Declare math construction procedures@>
17564 procedure mlist_to_hlist;
17565 label reswitch, check_dimensions, done_with_noad, done_with_node, delete_q,
17566 done;
17567 var mlist:pointer; {beginning of the given list}
17568 @!penalties:boolean; {should penalty nodes be inserted?}
17569 @!style:small_number; {the given style}
17570 @!save_style:small_number; {holds |cur_style| during recursion}
17571 @!q:pointer; {runs through the mlist}
17572 @!r:pointer; {the most recent noad preceding |q|}
17573 @!r_type:small_number; {the |type| of noad |r|, or |op_noad| if |r=null|}
17574 @!t:small_number; {the effective |type| of noad |q| during the second pass}
17575 @!p,@!x,@!y,@!z: pointer; {temporary registers for list construction}
17576 @!pen:integer; {a penalty to be inserted}
17577 @!s:small_number; {the size of a noad to be deleted}
17578 @!max_h,@!max_d:scaled; {maximum height and depth of the list translated so far}
17579 @!delta:scaled; {offset between subscript and superscript}
17580 begin mlist:=cur_mlist; penalties:=mlist_penalties;
17581 style:=cur_style; {tuck global parameters away as local variables}
17582 q:=mlist; r:=null; r_type:=op_noad; max_h:=0; max_d:=0;
17583 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
17584 while q<>null do @<Process node-or-noad |q| as much as possible in preparation
17585 for the second pass of |mlist_to_hlist|, then move to the next
17586 item in the mlist@>;
17587 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
17588 @<Make a second pass over the mlist, removing all noads and inserting the
17589 proper spacing and penalties@>;
17590 end;
17591
17592 @ We use the fact that no character nodes appear in an mlist, hence
17593 the field |type(q)| is always present.
17594
17595 @<Process node-or-noad...@>=
17596 begin @<Do first-pass processing based on |type(q)|; |goto done_with_noad|
17597 if a noad has been fully processed, |goto check_dimensions| if it
17598 has been translated into |new_hlist(q)|, or |goto done_with_node|
17599 if a node has been fully processed@>;
17600 check_dimensions: z:=hpack(new_hlist(q),natural);
17601 if height(z)>max_h then max_h:=height(z);
17602 if depth(z)>max_d then max_d:=depth(z);
17603 free_node(z,box_node_size);
17604 done_with_noad: r:=q; r_type:=type(r);
17605 if r_type=right_noad then
17606 begin r_type:=left_noad; cur_style:=style; @<Set up the values...@>;
17607 end;
17608 done_with_node: q:=link(q);
17609 end
17610
17611 @ One of the things we must do on the first pass is change a |bin_noad| to
17612 an |ord_noad| if the |bin_noad| is not in the context of a binary operator.
17613 The values of |r| and |r_type| make this fairly easy.
17614
17615 @<Do first-pass processing...@>=
17616 reswitch: delta:=0;
17617 case type(q) of
17618 bin_noad: case r_type of
17619 bin_noad,op_noad,rel_noad,open_noad,punct_noad,left_noad:
17620 begin type(q):=ord_noad; goto reswitch;
17621 end;
17622 othercases do_nothing
17623 endcases;
17624 rel_noad,close_noad,punct_noad,right_noad: begin@t@>@;@/
17625 @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
17626 if type(q)=right_noad then goto done_with_noad;
17627 end;
17628 @t\4@>@<Cases for noads that can follow a |bin_noad|@>@;
17629 @t\4@>@<Cases for nodes that can appear in an mlist, after which we
17630 |goto done_with_node|@>@;
17631 othercases confusion("mlist1")
17632 @:this can't happen mlist1}{\quad mlist1@>
17633 endcases;@/
17634 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>
17635
17636 @ @<Convert \(a)a final |bin_noad| to an |ord_noad|@>=
17637 if r_type=bin_noad then type(r):=ord_noad
17638
17639 @ @<Cases for nodes that can appear in an mlist...@>=
17640 style_node: begin cur_style:=subtype(q);
17641 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
17642 goto done_with_node;
17643 end;
17644 choice_node: @<Change this node to a style node followed by the correct choice,
17645 then |goto done_with_node|@>;
17646 ins_node,mark_node,adjust_node,
17647 whatsit_node,penalty_node,disc_node: goto done_with_node;
17648 rule_node: begin if height(q)>max_h then max_h:=height(q);
17649 if depth(q)>max_d then max_d:=depth(q); goto done_with_node;
17650 end;
17651 glue_node: begin @<Convert \(m)math glue to ordinary glue@>;
17652 goto done_with_node;
17653 end;
17654 kern_node: begin math_kern(q,cur_mu); goto done_with_node;
17655 end;
17656
17657 @ @d choose_mlist(#)==begin p:=#(q); #(q):=null;@+end
17658
17659 @<Change this node to a style node...@>=
17660 begin case cur_style div 2 of
17661 0: choose_mlist(display_mlist); {|display_style=0|}
17662 1: choose_mlist(text_mlist); {|text_style=2|}
17663 2: choose_mlist(script_mlist); {|script_style=4|}
17664 3: choose_mlist(script_script_mlist); {|script_script_style=6|}
17665 end; {there are no other cases}
17666 flush_node_list(display_mlist(q));
17667 flush_node_list(text_mlist(q));
17668 flush_node_list(script_mlist(q));
17669 flush_node_list(script_script_mlist(q));@/
17670 type(q):=style_node; subtype(q):=cur_style; width(q):=0; depth(q):=0;
17671 if p<>null then
17672 begin z:=link(q); link(q):=p;
17673 while link(p)<>null do p:=link(p);
17674 link(p):=z;
17675 end;
17676 goto done_with_node;
17677 end
17678
17679 @ Conditional math glue (`\.{\\nonscript}') results in a |glue_node|
17680 pointing to |zero_glue|, with |subtype(q)=cond_math_glue|; in such a case
17681 the node following will be eliminated if it is a glue or kern node and if the
17682 current size is different from |text_size|. Unconditional math glue
17683 (`\.{\\muskip}') is converted to normal glue by multiplying the dimensions
17684 by |cur_mu|.
17685 @!@:non_script_}{\.{\\nonscript} primitive@>
17686
17687 @<Convert \(m)math glue to ordinary glue@>=
17688 if subtype(q)=mu_glue then
17689 begin x:=glue_ptr(q);
17690 y:=math_glue(x,cur_mu); delete_glue_ref(x); glue_ptr(q):=y;
17691 subtype(q):=normal;
17692 end
17693 else if (cur_size<>text_size)and(subtype(q)=cond_math_glue) then
17694 begin p:=link(q);
17695 if p<>null then if (type(p)=glue_node)or(type(p)=kern_node) then
17696 begin link(q):=link(p); link(p):=null; flush_node_list(p);
17697 end;
17698 end
17699
17700 @ @<Cases for noads that can follow a |bin_noad|@>=
17701 left_noad: goto done_with_noad;
17702 fraction_noad: begin make_fraction(q); goto check_dimensions;
17703 end;
17704 op_noad: begin delta:=make_op(q);
17705 if subtype(q)=limits then goto check_dimensions;
17706 end;
17707 ord_noad: make_ord(q);
17708 open_noad,inner_noad: do_nothing;
17709 radical_noad: make_radical(q);
17710 over_noad: make_over(q);
17711 under_noad: make_under(q);
17712 accent_noad: make_math_accent(q);
17713 vcenter_noad: make_vcenter(q);
17714
17715 @ Most of the actual construction work of |mlist_to_hlist| is done
17716 by procedures with names
17717 like |make_fraction|, |make_radical|, etc. To illustrate
17718 the general setup of such procedures, let's begin with a couple of
17719 simple ones.
17720
17721 @<Declare math...@>=
17722 procedure make_over(@!q:pointer);
17723 begin info(nucleus(q)):=@|
17724 overbar(clean_box(nucleus(q),cramped_style(cur_style)),@|
17725 3*default_rule_thickness,default_rule_thickness);
17726 math_type(nucleus(q)):=sub_box;
17727 end;
17728
17729 @ @<Declare math...@>=
17730 procedure make_under(@!q:pointer);
17731 var p,@!x,@!y: pointer; {temporary registers for box construction}
17732 @!delta:scaled; {overall height plus depth}
17733 begin x:=clean_box(nucleus(q),cur_style);
17734 p:=new_kern(3*default_rule_thickness); link(x):=p;
17735 link(p):=fraction_rule(default_rule_thickness);
17736 y:=vpack(x,natural);
17737 delta:=height(y)+depth(y)+default_rule_thickness;
17738 height(y):=height(x); depth(y):=delta-height(y);
17739 info(nucleus(q)):=y; math_type(nucleus(q)):=sub_box;
17740 end;
17741
17742 @ @<Declare math...@>=
17743 procedure make_vcenter(@!q:pointer);
17744 var v:pointer; {the box that should be centered vertically}
17745 @!delta:scaled; {its height plus depth}
17746 begin v:=info(nucleus(q));
17747 if type(v)<>vlist_node then confusion("vcenter");
17748 @:this can't happen vcenter}{\quad vcenter@>
17749 delta:=height(v)+depth(v);
17750 height(v):=axis_height(cur_size)+half(delta);
17751 depth(v):=delta-height(v);
17752 end;
17753
17754 @ According to the rules in the \.{DVI} file specifications, we ensure alignment
17755 @^square roots@>
17756 between a square root sign and the rule above its nucleus by assuming that the
17757 baseline of the square-root symbol is the same as the bottom of the rule. The
17758 height of the square-root symbol will be the thickness of the rule, and the
17759 depth of the square-root symbol should exceed or equal the height-plus-depth
17760 of the nucleus plus a certain minimum clearance~|clr|. The symbol will be
17761 placed so that the actual clearance is |clr| plus half the excess.
17762
17763 @<Declare math...@>=
17764 procedure make_radical(@!q:pointer);
17765 var x,@!y:pointer; {temporary registers for box construction}
17766 f:internal_font_number;
17767 rule_thickness:scaled; {rule thickness}
17768 @!delta,@!clr:scaled; {dimensions involved in the calculation}
17769 begin f:=fam_fnt(small_fam(left_delimiter(q)) + cur_size);
17770 if is_new_mathfont(f) then rule_thickness:=get_ot_math_constant(f,radicalRuleThickness)
17771 else rule_thickness:=default_rule_thickness;
17772 x:=clean_box(nucleus(q),cramped_style(cur_style));
17773 if is_new_mathfont(f) then begin
17774 if cur_style<text_style then {display style}
17775 clr:=get_ot_math_constant(f,radicalDisplayStyleVerticalGap)
17776 else clr:=get_ot_math_constant(f,radicalVerticalGap);
17777 end else begin
17778 if cur_style<text_style then {display style}
17779 clr:=rule_thickness+(abs(math_x_height(cur_size)) div 4)
17780 else begin clr:=rule_thickness; clr:=clr + (abs(clr) div 4);
17781 end;
17782 end;
17783 y:=var_delimiter(left_delimiter(q),cur_size,height(x)+depth(x)+clr+rule_thickness);
17784 if is_new_mathfont(f) then begin
17785 depth(y):=height(y)+depth(y)-rule_thickness;
17786 height(y):=rule_thickness;
17787 end;
17788 delta:=depth(y)-(height(x)+depth(x)+clr);
17789 if delta>0 then clr:=clr+half(delta); {increase the actual clearance}
17790 shift_amount(y):=-(height(x)+clr);
17791 link(y):=overbar(x,clr,height(y));
17792 info(nucleus(q)):=hpack(y,natural); math_type(nucleus(q)):=sub_box;
17793 end;
17794
17795 @ Slants are not considered when placing accents in math mode. The accenter is
17796 centered over the accentee, and the accent width is treated as zero with
17797 respect to the size of the final box.
17798
17799 @<Declare math...@>=
17800 function compute_ot_math_accent_pos(@!p:pointer):scaled;
17801 var
17802 @!q,@!r:pointer;
17803 @!s,@!g:scaled;
17804 begin
17805 if (math_type(nucleus(p))=math_char) then begin
17806 fetch(nucleus(p));
17807 q:=new_native_character(cur_f, qo(cur_c));
17808 g:=get_native_glyph(q, 0);
17809 s:=get_ot_math_accent_pos(cur_f, g);
17810 end else begin
17811 if (math_type(nucleus(p))=sub_mlist) then begin
17812 r:=info(nucleus(p));
17813 if (r<>null) and (type(r)=accent_noad) then
17814 s:=compute_ot_math_accent_pos(r)
17815 else
17816 s:=@"7FFFFFFF;
17817 end else
17818 s:=@"7FFFFFFF;
17819 end;
17820 compute_ot_math_accent_pos:=s;
17821 end;
17822
17823 procedure make_math_accent(@!q:pointer);
17824 label done,done1;
17825 var p,@!x,@!y:pointer; {temporary registers for box construction}
17826 @!a:integer; {address of lig/kern instruction}
17827 @!c,@!g:integer; {accent character}
17828 @!f:internal_font_number; {its font}
17829 @!i:four_quarters; {its |char_info|}
17830 @!s,@!sa:scaled; {amount to skew the accent to the right}
17831 @!h:scaled; {height of character being accented}
17832 @!delta:scaled; {space to remove between accent and accentee}
17833 @!w,@!w2:scaled; {width of the accentee, not including sub/superscripts}
17834 @!ot_assembly_ptr:void_pointer;
17835 begin fetch(accent_chr(q));
17836 x:=null;
17837 ot_assembly_ptr:=nil;
17838 if is_native_font(cur_f) then
17839 begin c:=cur_c; f:=cur_f;
17840 if not is_bottom_acc(q) then s:=compute_ot_math_accent_pos(q) else s:=0;
17841 x:=clean_box(nucleus(q),cramped_style(cur_style)); w:=width(x); h:=height(x);
17842 end
17843 else if char_exists(cur_i) then
17844 begin i:=cur_i; c:=cur_c; f:=cur_f;@/
17845 @<Compute the amount of skew@>;
17846 x:=clean_box(nucleus(q),cramped_style(cur_style)); w:=width(x); h:=height(x);
17847 @<Switch to a larger accent if available and appropriate@>;
17848 end;
17849 if x<>null then begin
17850 if is_new_mathfont(f) then
17851 if is_bottom_acc(q) then delta:=0
17852 else if h<get_ot_math_constant(f, accentBaseHeight) then delta:=h@+else delta:=get_ot_math_constant(f, accentBaseHeight)
17853 else
17854 if h<x_height(f) then delta:=h@+else delta:=x_height(f);
17855 if (math_type(supscr(q))<>empty)or(math_type(subscr(q))<>empty) then
17856 if math_type(nucleus(q))=math_char then
17857 @<Swap the subscript and superscript into box |x|@>;
17858 y:=char_box(f,c);
17859 if is_native_font(f) then begin
17860 {turn the |native_word| node into a |native_glyph| one}
17861 p:=get_node(glyph_node_size);
17862 type(p):=whatsit_node; subtype(p):=glyph_node;
17863 native_font(p):=f; native_glyph(p):=get_native_glyph(list_ptr(y), 0);
17864 set_native_glyph_metrics(p, 1);
17865 free_node(list_ptr(y), native_size(list_ptr(y)));
17866 list_ptr(y):=p;
17867
17868 @<Switch to a larger native-font accent if available and appropriate@>;
17869
17870 {determine horiz positioning}
17871 if is_glyph_node(p) then
17872 begin sa:=get_ot_math_accent_pos(f,native_glyph(p));
17873 if sa=@"7FFFFFFF then sa:=half(width(y));
17874 end
17875 else sa:=half(width(y));
17876 if is_bottom_acc(q) or (s=@"7FFFFFFF) then s:=half(w);
17877 shift_amount(y):=s-sa;
17878 end else
17879 shift_amount(y):=s+half(w-width(y));
17880 width(y):=0;
17881 if is_bottom_acc(q) then begin
17882 link(x):=y; y:=vpack(x,natural); shift_amount(y):=-(h - height(y));
17883 end else begin
17884 p:=new_kern(-delta); link(p):=x; link(y):=p; y:=vpack(y,natural);
17885 if height(y)<h then @<Make the height of box |y| equal to |h|@>;
17886 end;
17887 width(y):=width(x);
17888 info(nucleus(q)):=y;
17889 math_type(nucleus(q)):=sub_box;
17890 end;
17891 free_ot_assembly(ot_assembly_ptr);
17892 end;
17893
17894 @ @<Make the height of box |y|...@>=
17895 begin p:=new_kern(h-height(y)); link(p):=list_ptr(y); list_ptr(y):=p;
17896 height(y):=h;
17897 end
17898
17899 @ @<Switch to a larger native-font accent if available and appropriate@>=
17900 if odd(subtype(q)) then {non growing accent}
17901 set_native_glyph_metrics(p, 1)
17902 else begin
17903 c:=native_glyph(p);
17904 a:=0;
17905 repeat
17906 g:=get_ot_math_variant(f, c, a, addressof(w2), 1);
17907 if (w2>0) and (w2<=w) then begin
17908 native_glyph(p):=g;
17909 set_native_glyph_metrics(p, 1);
17910 incr(a);
17911 end;
17912 until (w2<0) or (w2>=w);
17913 if (w2<0) then begin
17914 ot_assembly_ptr:=get_ot_assembly_ptr(f, c, 1);
17915 if ot_assembly_ptr<>nil then begin
17916 free_node(p,glyph_node_size);
17917 p:=build_opentype_assembly(f, ot_assembly_ptr, w, 1);
17918 list_ptr(y):=p;
17919 goto found;
17920 end;
17921 end else
17922 set_native_glyph_metrics(p, 1);
17923 end;
17924 found:
17925 width(y):=width(p); height(y):=height(p); depth(y):=depth(p);
17926 if is_bottom_acc(q) then begin
17927 if height(y)<0 then height(y):=0
17928 end else if depth(y)<0 then depth(y):=0;
17929
17930 @ @<Switch to a larger accent if available and appropriate@>=
17931 loop@+ begin if char_tag(i)<>list_tag then goto done;
17932 y:=rem_byte(i);
17933 i:=char_info(f)(y);
17934 if not char_exists(i) then goto done;
17935 if char_width(f)(i)>w then goto done;
17936 c:=y;
17937 end;
17938 done:
17939
17940 @ @<Compute the amount of skew@>=
17941 s:=0;
17942 if math_type(nucleus(q))=math_char then
17943 begin fetch(nucleus(q));
17944 if char_tag(cur_i)=lig_tag then
17945 begin a:=lig_kern_start(cur_f)(cur_i);
17946 cur_i:=font_info[a].qqqq;
17947 if skip_byte(cur_i)>stop_flag then
17948 begin a:=lig_kern_restart(cur_f)(cur_i);
17949 cur_i:=font_info[a].qqqq;
17950 end;
17951 loop@+ begin if qo(next_char(cur_i))=skew_char[cur_f] then
17952 begin if op_byte(cur_i)>=kern_flag then
17953 if skip_byte(cur_i)<=stop_flag then s:=char_kern(cur_f)(cur_i);
17954 goto done1;
17955 end;
17956 if skip_byte(cur_i)>=stop_flag then goto done1;
17957 a:=a+qo(skip_byte(cur_i))+1;
17958 cur_i:=font_info[a].qqqq;
17959 end;
17960 end;
17961 end;
17962 done1:
17963
17964 @ @<Swap the subscript and superscript into box |x|@>=
17965 begin flush_node_list(x); x:=new_noad;
17966 mem[nucleus(x)]:=mem[nucleus(q)];
17967 mem[supscr(x)]:=mem[supscr(q)];
17968 mem[subscr(x)]:=mem[subscr(q)];@/
17969 mem[supscr(q)].hh:=empty_field;
17970 mem[subscr(q)].hh:=empty_field;@/
17971 math_type(nucleus(q)):=sub_mlist; info(nucleus(q)):=x;
17972 x:=clean_box(nucleus(q),cur_style); delta:=delta+height(x)-h; h:=height(x);
17973 end
17974
17975 @ The |make_fraction| procedure is a bit different because it sets
17976 |new_hlist(q)| directly rather than making a sub-box.
17977
17978 @<Declare math...@>=
17979 procedure make_fraction(@!q:pointer);
17980 var p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
17981 @!delta,@!delta1,@!delta2,@!shift_up,@!shift_down,@!clr:scaled;
17982 {dimensions for box calculations}
17983 begin if thickness(q)=default_code then thickness(q):=default_rule_thickness;
17984 @<Create equal-width boxes |x| and |z| for the numerator and denominator,
17985 and compute the default amounts |shift_up| and |shift_down| by which they
17986 are displaced from the baseline@>;
17987 if thickness(q)=0 then @<Adjust \(s)|shift_up| and |shift_down| for the case
17988 of no fraction line@>
17989 else @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>;
17990 @<Construct a vlist box for the fraction, according to |shift_up| and
17991 |shift_down|@>;
17992 @<Put the \(f)fraction into a box with its delimiters, and make |new_hlist(q)|
17993 point to it@>;
17994 end;
17995
17996 @ @<Create equal-width boxes |x| and |z| for the numerator and denom...@>=
17997 x:=clean_box(numerator(q),num_style(cur_style));
17998 z:=clean_box(denominator(q),denom_style(cur_style));
17999 if width(x)<width(z) then x:=rebox(x,width(z))
18000 else z:=rebox(z,width(x));
18001 if cur_style<text_style then {display style}
18002 begin shift_up:=num1(cur_size); shift_down:=denom1(cur_size);
18003 end
18004 else begin shift_down:=denom2(cur_size);
18005 if thickness(q)<>0 then shift_up:=num2(cur_size)
18006 else shift_up:=num3(cur_size);
18007 end
18008
18009 @ The numerator and denominator must be separated by a certain minimum
18010 clearance, called |clr| in the following program. The difference between
18011 |clr| and the actual clearance is twice |delta|.
18012
18013 @<Adjust \(s)|shift_up| and |shift_down| for the case of no fraction line@>=
18014 begin if is_new_mathfont(cur_f) then begin
18015 if cur_style<text_style then clr:=get_ot_math_constant(cur_f, stackDisplayStyleGapMin)
18016 else clr:=get_ot_math_constant(cur_f, stackGapMin);
18017 end else begin
18018 if cur_style<text_style then clr:=7*default_rule_thickness
18019 else clr:=3*default_rule_thickness;
18020 end;
18021 delta:=half(clr-((shift_up-depth(x))-(height(z)-shift_down)));
18022 if delta>0 then
18023 begin shift_up:=shift_up+delta;
18024 shift_down:=shift_down+delta;
18025 end;
18026 end
18027
18028 @ In the case of a fraction line, the minimum clearance depends on the actual
18029 thickness of the line.
18030
18031 @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>=
18032 begin if is_new_mathfont(cur_f) then begin
18033 delta:=half(thickness(q));
18034 if cur_style<text_style then clr:=get_ot_math_constant(cur_f, fractionNumDisplayStyleGapMin)
18035 else clr:=get_ot_math_constant(cur_f, fractionNumeratorGapMin);
18036 delta1:=clr-((shift_up-depth(x))-(axis_height(cur_size)+delta));
18037 if cur_style<text_style then clr:=get_ot_math_constant(cur_f, fractionDenomDisplayStyleGapMin)
18038 else clr:=get_ot_math_constant(cur_f, fractionDenominatorGapMin);
18039 delta2:=clr-((axis_height(cur_size)-delta)-(height(z)-shift_down));
18040 end else begin
18041 if cur_style<text_style then clr:=3*thickness(q)
18042 else clr:=thickness(q);
18043 delta:=half(thickness(q));
18044 delta1:=clr-((shift_up-depth(x))-(axis_height(cur_size)+delta));
18045 delta2:=clr-((axis_height(cur_size)-delta)-(height(z)-shift_down));
18046 end;
18047 if delta1>0 then shift_up:=shift_up+delta1;
18048 if delta2>0 then shift_down:=shift_down+delta2;
18049 end
18050
18051 @ @<Construct a vlist box for the fraction...@>=
18052 v:=new_null_box; type(v):=vlist_node;
18053 height(v):=shift_up+height(x); depth(v):=depth(z)+shift_down;
18054 width(v):=width(x); {this also equals |width(z)|}
18055 if thickness(q)=0 then
18056 begin p:=new_kern((shift_up-depth(x))-(height(z)-shift_down));
18057 link(p):=z;
18058 end
18059 else begin y:=fraction_rule(thickness(q));@/
18060 p:=new_kern((axis_height(cur_size)-delta)-@|(height(z)-shift_down));@/
18061 link(y):=p; link(p):=z;@/
18062 p:=new_kern((shift_up-depth(x))-(axis_height(cur_size)+delta));
18063 link(p):=y;
18064 end;
18065 link(x):=p; list_ptr(v):=x
18066
18067 @ @<Put the \(f)fraction into a box with its delimiters...@>=
18068 if cur_style<text_style then delta:=delim1(cur_size)
18069 else delta:=delim2(cur_size);
18070 x:=var_delimiter(left_delimiter(q), cur_size, delta); link(x):=v;@/
18071 z:=var_delimiter(right_delimiter(q), cur_size, delta); link(v):=z;@/
18072 new_hlist(q):=hpack(x,natural)
18073
18074 @ If the nucleus of an |op_noad| is a single character, it is to be
18075 centered vertically with respect to the axis, after first being enlarged
18076 (via a character list in the font) if we are in display style. The normal
18077 convention for placing displayed limits is to put them above and below the
18078 operator in display style.
18079
18080 The italic correction is removed from the character if there is a subscript
18081 and the limits are not being displayed. The |make_op|
18082 routine returns the value that should be used as an offset between
18083 subscript and superscript.
18084
18085 After |make_op| has acted, |subtype(q)| will be |limits| if and only if
18086 the limits have been set above and below the operator. In that case,
18087 |new_hlist(q)| will already contain the desired final box.
18088
18089 @<Declare math...@>=
18090 function make_op(@!q:pointer):scaled;
18091 label found;
18092 var delta:scaled; {offset between subscript and superscript}
18093 @!p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
18094 @!c:quarterword;@+@!i:four_quarters; {registers for character examination}
18095 @!shift_up,@!shift_down:scaled; {dimensions for box calculation}
18096 @!h1,@!h2:scaled; {height of original text-style symbol and possible replacement}
18097 @!n,@!g:integer; {potential variant index and glyph code}
18098 @!ot_assembly_ptr:void_pointer;
18099 @!save_f:internal_font_number;
18100 begin if (subtype(q)=normal)and(cur_style<text_style) then
18101 subtype(q):=limits;
18102 delta:=0;
18103 ot_assembly_ptr:=nil;
18104 if math_type(nucleus(q))=math_char then
18105 begin fetch(nucleus(q));
18106 if not is_ot_font(cur_f) then begin
18107 if (cur_style<text_style)and(char_tag(cur_i)=list_tag) then {make it larger}
18108 begin c:=rem_byte(cur_i); i:=char_info(cur_f)(c);
18109 if char_exists(i) then
18110 begin cur_c:=c; cur_i:=i; character(nucleus(q)):=c;
18111 end;
18112 end;
18113 delta:=char_italic(cur_f)(cur_i);
18114 end;
18115 x:=clean_box(nucleus(q),cur_style);
18116 if is_new_mathfont(cur_f) then begin
18117 p:=list_ptr(x);
18118 if is_glyph_node(p) then begin
18119 if cur_style<text_style then begin
18120 {try to replace the operator glyph with a display-size variant,
18121 ensuring it is larger than the text size}
18122 h1:=get_ot_math_constant(cur_f,displayOperatorMinHeight);
18123 if h1<(height(p)+depth(p))*5/4 then h1:=(height(p)+depth(p))*5/4;
18124 c:=native_glyph(p);
18125 n:=0;
18126 repeat
18127 g:=get_ot_math_variant(cur_f, c, n, addressof(h2), 0);
18128 if h2>0 then begin
18129 native_glyph(p):=g;
18130 set_native_glyph_metrics(p, 1);
18131 end;
18132 incr(n);
18133 until (h2<0) or (h2>=h1);
18134 if (h2<0) then begin
18135 {if we get here, then we didn't find a big enough glyph; check if the char is extensible}
18136 ot_assembly_ptr:=get_ot_assembly_ptr(cur_f, c, 0);
18137 if ot_assembly_ptr<>nil then begin
18138 free_node(p,glyph_node_size);
18139 p:=build_opentype_assembly(cur_f, ot_assembly_ptr, h1, 0);
18140 list_ptr(x):=p;
18141 delta:=0;
18142 goto found;
18143 end;
18144 end else
18145 set_native_glyph_metrics(p, 1);
18146 end;
18147 delta:=get_ot_math_ital_corr(cur_f, native_glyph(p));
18148 found:
18149 width(x):=width(p); height(x):=height(p); depth(x):=depth(p);
18150 end
18151 end;
18152 if (math_type(subscr(q))<>empty)and(subtype(q)<>limits) then
18153 width(x):=width(x)-delta; {remove italic correction}
18154 shift_amount(x):=half(height(x)-depth(x)) - axis_height(cur_size);
18155 {center vertically}
18156 math_type(nucleus(q)):=sub_box; info(nucleus(q)):=x;
18157 end;
18158 save_f:=cur_f;
18159 if subtype(q)=limits then
18160 @<Construct a box with limits above and below it, skewed by |delta|@>;
18161 free_ot_assembly(ot_assembly_ptr);
18162 make_op:=delta;
18163 end;
18164
18165 @ The following program builds a vlist box |v| for displayed limits. The
18166 width of the box is not affected by the fact that the limits may be skewed.
18167
18168 @<Construct a box with limits above and below it...@>=
18169 begin x:=clean_box(supscr(q),sup_style(cur_style));
18170 y:=clean_box(nucleus(q),cur_style);
18171 z:=clean_box(subscr(q),sub_style(cur_style));
18172 v:=new_null_box; type(v):=vlist_node; width(v):=width(y);
18173 if width(x)>width(v) then width(v):=width(x);
18174 if width(z)>width(v) then width(v):=width(z);
18175 x:=rebox(x,width(v)); y:=rebox(y,width(v)); z:=rebox(z,width(v));@/
18176 shift_amount(x):=half(delta); shift_amount(z):=-shift_amount(x);
18177 height(v):=height(y); depth(v):=depth(y);
18178 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)| to
18179 account for their presence@>;
18180 new_hlist(q):=v;
18181 end
18182
18183 @ We use |shift_up| and |shift_down| in the following program for the
18184 amount of glue between the displayed operator |y| and its limits |x| and
18185 |z|. The vlist inside box |v| will consist of |x| followed by |y| followed
18186 by |z|, with kern nodes for the spaces between and around them.
18187
18188 @<Attach the limits to |y| and adjust |height(v)|, |depth(v)|...@>=
18189 cur_f:=save_f;
18190 if math_type(supscr(q))=empty then
18191 begin free_node(x,box_node_size); list_ptr(v):=y;
18192 end
18193 else begin shift_up:=big_op_spacing3-depth(x);
18194 if shift_up<big_op_spacing1 then shift_up:=big_op_spacing1;
18195 p:=new_kern(shift_up); link(p):=y; link(x):=p;@/
18196 p:=new_kern(big_op_spacing5); link(p):=x; list_ptr(v):=p;
18197 height(v):=height(v)+big_op_spacing5+height(x)+depth(x)+shift_up;
18198 end;
18199 if math_type(subscr(q))=empty then free_node(z,box_node_size)
18200 else begin shift_down:=big_op_spacing4-height(z);
18201 if shift_down<big_op_spacing2 then shift_down:=big_op_spacing2;
18202 p:=new_kern(shift_down); link(y):=p; link(p):=z;@/
18203 p:=new_kern(big_op_spacing5); link(z):=p;
18204 depth(v):=depth(v)+big_op_spacing5+height(z)+depth(z)+shift_down;
18205 end
18206
18207 @ A ligature found in a math formula does not create a |ligature_node|, because
18208 there is no question of hyphenation afterwards; the ligature will simply be
18209 stored in an ordinary |char_node|, after residing in an |ord_noad|.
18210
18211 The |math_type| is converted to |math_text_char| here if we would not want to
18212 apply an italic correction to the current character unless it belongs
18213 to a math font (i.e., a font with |space=0|).
18214
18215 No boundary characters enter into these ligatures.
18216
18217 @<Declare math...@>=
18218 procedure make_ord(@!q:pointer);
18219 label restart,exit;
18220 var a:integer; {address of lig/kern instruction}
18221 @!p,@!r:pointer; {temporary registers for list manipulation}
18222 begin restart:@t@>@;@/
18223 if math_type(subscr(q))=empty then if math_type(supscr(q))=empty then
18224 if math_type(nucleus(q))=math_char then
18225 begin p:=link(q);
18226 if p<>null then if (type(p)>=ord_noad)and(type(p)<=punct_noad) then
18227 if math_type(nucleus(p))=math_char then
18228 if fam(nucleus(p))=fam(nucleus(q)) then
18229 begin math_type(nucleus(q)):=math_text_char;
18230 fetch(nucleus(q));
18231 if char_tag(cur_i)=lig_tag then
18232 begin a:=lig_kern_start(cur_f)(cur_i);
18233 cur_c:=character(nucleus(p));
18234 cur_i:=font_info[a].qqqq;
18235 if skip_byte(cur_i)>stop_flag then
18236 begin a:=lig_kern_restart(cur_f)(cur_i);
18237 cur_i:=font_info[a].qqqq;
18238 end;
18239 loop@+ begin @<If instruction |cur_i| is a kern with |cur_c|, attach
18240 the kern after~|q|; or if it is a ligature with |cur_c|, combine
18241 noads |q| and~|p| appropriately; then |return| if the cursor has
18242 moved past a noad, or |goto restart|@>;
18243 if skip_byte(cur_i)>=stop_flag then return;
18244 a:=a+qo(skip_byte(cur_i))+1;
18245 cur_i:=font_info[a].qqqq;
18246 end;
18247 end;
18248 end;
18249 end;
18250 exit:end;
18251
18252 @ Note that a ligature between an |ord_noad| and another kind of noad
18253 is replaced by an |ord_noad|, when the two noads collapse into one.
18254 But we could make a parenthesis (say) change shape when it follows
18255 certain letters. Presumably a font designer will define such
18256 ligatures only when this convention makes sense.
18257
18258 \chardef\?='174 % vertical line to indicate character retention
18259
18260 @<If instruction |cur_i| is a kern with |cur_c|, ...@>=
18261 if next_char(cur_i)=cur_c then if skip_byte(cur_i)<=stop_flag then
18262 if op_byte(cur_i)>=kern_flag then
18263 begin p:=new_kern(char_kern(cur_f)(cur_i));
18264 link(p):=link(q); link(q):=p; return;
18265 end
18266 else begin check_interrupt; {allow a way out of infinite ligature loop}
18267 case op_byte(cur_i) of
18268 qi(1),qi(5): character(nucleus(q)):=rem_byte(cur_i); {\.{=:\?}, \.{=:\?>}}
18269 qi(2),qi(6): character(nucleus(p)):=rem_byte(cur_i); {\.{\?=:}, \.{\?=:>}}
18270 qi(3),qi(7),qi(11):begin r:=new_noad; {\.{\?=:\?}, \.{\?=:\?>}, \.{\?=:\?>>}}
18271 character(nucleus(r)):=rem_byte(cur_i);
18272 plane_and_fam_field(nucleus(r)):=fam(nucleus(q));@/
18273 link(q):=r; link(r):=p;
18274 if op_byte(cur_i)<qi(11) then math_type(nucleus(r)):=math_char
18275 else math_type(nucleus(r)):=math_text_char; {prevent combination}
18276 end;
18277 othercases begin link(q):=link(p);
18278 character(nucleus(q)):=rem_byte(cur_i); {\.{=:}}
18279 mem[subscr(q)]:=mem[subscr(p)]; mem[supscr(q)]:=mem[supscr(p)];@/
18280 free_node(p,noad_size);
18281 end
18282 endcases;
18283 if op_byte(cur_i)>qi(3) then return;
18284 math_type(nucleus(q)):=math_char; goto restart;
18285 end
18286
18287 @ When we get to the following part of the program, we have ``fallen through''
18288 from cases that did not lead to |check_dimensions| or |done_with_noad| or
18289 |done_with_node|. Thus, |q|~points to a noad whose nucleus may need to be
18290 converted to an hlist, and whose subscripts and superscripts need to be
18291 appended if they are present.
18292
18293 If |nucleus(q)| is not a |math_char|, the variable |delta| is the amount
18294 by which a superscript should be moved right with respect to a subscript
18295 when both are present.
18296 @^subscripts@>
18297 @^superscripts@>
18298
18299 @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>=
18300 case math_type(nucleus(q)) of
18301 math_char, math_text_char:
18302 @<Create a character node |p| for |nucleus(q)|, possibly followed
18303 by a kern node for the italic correction, and set |delta| to the
18304 italic correction if a subscript is present@>;
18305 empty: p:=null;
18306 sub_box: p:=info(nucleus(q));
18307 sub_mlist: begin cur_mlist:=info(nucleus(q)); save_style:=cur_style;
18308 mlist_penalties:=false; mlist_to_hlist; {recursive call}
18309 @^recursion@>
18310 cur_style:=save_style; @<Set up the values...@>;
18311 p:=hpack(link(temp_head),natural);
18312 end;
18313 othercases confusion("mlist2")
18314 @:this can't happen mlist2}{\quad mlist2@>
18315 endcases;@/
18316 new_hlist(q):=p;
18317 if (math_type(subscr(q))=empty)and(math_type(supscr(q))=empty) then
18318 goto check_dimensions;
18319 make_scripts(q,delta)
18320
18321 @ @<Create a character node |p| for |nucleus(q)|...@>=
18322 begin fetch(nucleus(q));
18323 if is_native_font(cur_f) then begin
18324 z:=new_native_character(cur_f, qo(cur_c));
18325 p:=get_node(glyph_node_size);
18326 type(p):=whatsit_node; subtype(p):=glyph_node;
18327 native_font(p):=cur_f; native_glyph(p):=get_native_glyph(z, 0);
18328 set_native_glyph_metrics(p, 1);
18329 free_node(z, native_size(z));
18330 delta:=get_ot_math_ital_corr(cur_f, native_glyph(p));
18331 if (math_type(nucleus(q))=math_text_char)and(not is_new_mathfont(cur_f)<>0) then
18332 delta:=0; {no italic correction in mid-word of text font}
18333 if (math_type(subscr(q))=empty)and(delta<>0) then
18334 begin link(p):=new_kern(delta); delta:=0;
18335 end;
18336 end else if char_exists(cur_i) then
18337 begin delta:=char_italic(cur_f)(cur_i); p:=new_character(cur_f,qo(cur_c));
18338 if (math_type(nucleus(q))=math_text_char)and(space(cur_f)<>0) then
18339 delta:=0; {no italic correction in mid-word of text font}
18340 if (math_type(subscr(q))=empty)and(delta<>0) then
18341 begin link(p):=new_kern(delta); delta:=0;
18342 end;
18343 end
18344 else p:=null;
18345 end
18346
18347 @ The purpose of |make_scripts(q,delta)| is to attach the subscript and/or
18348 superscript of noad |q| to the list that starts at |new_hlist(q)|,
18349 given that the subscript and superscript aren't both empty. The superscript
18350 will appear to the right of the subscript by a given distance |delta|.
18351
18352 We set |shift_down| and |shift_up| to the minimum amounts to shift the
18353 baseline of subscripts and superscripts based on the given nucleus.
18354
18355 @<Declare math...@>=
18356 function attach_hkern_to_new_hlist(@!q:pointer;@!delta:scaled):pointer;
18357 var y,@!z:pointer; {temporary registers for box construction}
18358 begin z:=new_kern(delta);
18359 if new_hlist(q)=null then new_hlist(q):=z
18360 else begin y:=new_hlist(q);
18361 while link(y)<>null do y:=link(y);
18362 link(y):=z;
18363 end;
18364 attach_hkern_to_new_hlist:=new_hlist(q);
18365 end;
18366
18367 procedure make_scripts(@!q:pointer;@!delta:scaled);
18368 var p,@!x,@!y,@!z:pointer; {temporary registers for box construction}
18369 @!shift_up,@!shift_down,@!clr,@!sub_kern,@!sup_kern:scaled; {dimensions in the calculation}
18370 @!script_c:pointer; {temprary native character for sub/superscript}
18371 @!script_g:quarterword; {temporary register for sub/superscript native glyph id}
18372 @!script_f:internal_font_number; {temporary register for sub/superscript font}
18373 @!sup_g:quarterword; {superscript native glyph id}
18374 @!sup_f:internal_font_number; {superscript font}
18375 @!sub_g:quarterword; {subscript native glyph id}
18376 @!sub_f:internal_font_number; {subscript font}
18377 @!t:integer; {subsidiary size code}
18378 @!save_f:internal_font_number;
18379 @!script_head:pointer; {scratch var for OpenType s*scripts}
18380 @!script_ptr:pointer; {scratch var for OpenType s*scripts}
18381 @!saved_math_style:small_number; {scratch var for OpenType s*scripts}
18382 @!this_math_style:small_number; {scratch var for OpenType s*scripts}
18383 begin p:=new_hlist(q);
18384 script_c:=null; script_g:=0; script_f:=0; sup_kern:=0; sub_kern:=0;
18385 if is_char_node(p) or is_glyph_node(p) then
18386 begin shift_up:=0; shift_down:=0;
18387 end
18388 else begin z:=hpack(p,natural);
18389 if cur_style<script_style then t:=script_size@+else t:=script_script_size;
18390 shift_up:=height(z)-sup_drop(t);
18391 shift_down:=depth(z)+sub_drop(t);
18392 free_node(z,box_node_size);
18393 end;
18394 if math_type(supscr(q))=empty then
18395 @<Construct a subscript box |x| when there is no superscript@>
18396 else begin @<Construct a superscript box |x|@>;
18397 if math_type(subscr(q))=empty then shift_amount(x):=-shift_up
18398 else @<Construct a sub/superscript combination box |x|, with the
18399 superscript offset by |delta|@>;
18400 end;
18401 if new_hlist(q)=null then new_hlist(q):=x
18402 else begin p:=new_hlist(q);
18403 while link(p)<>null do p:=link(p);
18404 link(p):=x;
18405 end;
18406 end;
18407
18408 @ When there is a subscript without a superscript, the top of the subscript
18409 should not exceed the baseline plus four-fifths of the x-height.
18410
18411 @<Construct a subscript box |x| when there is no superscript@>=
18412 begin
18413 script_head:=subscr(q);
18414 @<Fetch first character of a sub/superscript@>;
18415 sub_g:=script_g;
18416 sub_f:=script_f;
18417 save_f:=cur_f;
18418 x:=clean_box(subscr(q),sub_style(cur_style));
18419 cur_f:=save_f;
18420 width(x):=width(x)+script_space;
18421 if shift_down<sub1(cur_size) then shift_down:=sub1(cur_size);
18422 if is_new_mathfont(cur_f) then
18423 clr:=height(x)-get_ot_math_constant(cur_f, subscriptTopMax)
18424 else
18425 clr:=height(x)-(abs(math_x_height(cur_size)*4) div 5);
18426 if shift_down<clr then shift_down:=clr;
18427 shift_amount(x):=shift_down;
18428 if is_new_mathfont(cur_f) then @<Attach subscript OpenType math kerning@>
18429 end
18430
18431 @ The bottom of a superscript should never descend below the baseline plus
18432 one-fourth of the x-height.
18433
18434 @<Construct a superscript box |x|@>=
18435 begin
18436 script_head:=supscr(q);
18437 @<Fetch first character of a sub/superscript@>;
18438 sup_g:=script_g;
18439 sup_f:=script_f;
18440 save_f:=cur_f;
18441 x:=clean_box(supscr(q),sup_style(cur_style));
18442 cur_f:=save_f;
18443 width(x):=width(x)+script_space;
18444 if odd(cur_style) then clr:=sup3(cur_size)
18445 else if cur_style<text_style then clr:=sup1(cur_size)
18446 else clr:=sup2(cur_size);
18447 if shift_up<clr then shift_up:=clr;
18448 if is_new_mathfont(cur_f) then
18449 clr:=depth(x)+get_ot_math_constant(cur_f, superscriptBottomMin)
18450 else
18451 clr:=depth(x)+(abs(math_x_height(cur_size)) div 4);
18452 if shift_up<clr then shift_up:=clr;
18453 if is_new_mathfont(cur_f) then @<Attach superscript OpenType math kerning@>
18454 end
18455
18456 @ When both subscript and superscript are present, the subscript must be
18457 separated from the superscript by at least four times |default_rule_thickness|.
18458 If this condition would be violated, the subscript moves down, after which
18459 both subscript and superscript move up so that the bottom of the superscript
18460 is at least as high as the baseline plus four-fifths of the x-height.
18461
18462 @<Construct a sub/superscript combination box |x|...@>=
18463 begin
18464 save_f:=cur_f;
18465 script_head:=subscr(q);
18466 @<Fetch first character of a sub/superscript@>;
18467 sub_g:=script_g;
18468 sub_f:=script_f;
18469 y:=clean_box(subscr(q),sub_style(cur_style));
18470 cur_f:=save_f;
18471 width(y):=width(y)+script_space;
18472 if shift_down<sub2(cur_size) then shift_down:=sub2(cur_size);
18473 if is_new_mathfont(cur_f) then
18474 clr:=get_ot_math_constant(cur_f, subSuperscriptGapMin)-((shift_up-depth(x))-(height(y)-shift_down))
18475 else
18476 clr:=4*default_rule_thickness-((shift_up-depth(x))-(height(y)-shift_down));
18477 if clr>0 then
18478 begin shift_down:=shift_down+clr;
18479 if is_new_mathfont(cur_f) then
18480 clr:=get_ot_math_constant(cur_f, superscriptBottomMaxWithSubscript)-(shift_up-depth(x))
18481 else
18482 clr:=(abs(math_x_height(cur_size)*4) div 5)-(shift_up-depth(x));
18483 if clr>0 then
18484 begin shift_up:=shift_up+clr;
18485 shift_down:=shift_down-clr;
18486 end;
18487 end;
18488 if is_new_mathfont(cur_f) then begin
18489 @<Attach subscript OpenType math kerning@>@/
18490 @<Attach superscript OpenType math kerning@>
18491 end
18492 else
18493 begin sup_kern:=0; sub_kern:=0;
18494 end;
18495 shift_amount(x):=sup_kern+delta-sub_kern; {superscript is |delta| to the right of the subscript}
18496 p:=new_kern((shift_up-depth(x))-(height(y)-shift_down)); link(x):=p; link(p):=y;
18497 x:=vpack(x,natural); shift_amount(x):=shift_down;
18498 end
18499
18500 @ OpenType math fonts provide an additional adjustment for the horizontal
18501 position of sub/superscripts called math kerning.
18502
18503 The following definitions should be kept in sync with \.{XeTeXOTMath.cpp}.
18504
18505 @d sup_cmd=0 {superscript kern type for |get_ot_math_kern|}
18506 @d sub_cmd=1 {subscript kern type for |get_ot_math_kern|}
18507
18508 @d is_valid_pointer(#) == ((# >= mem_min) and (# <= mem_end))
18509
18510 @ @<Fetch first character of a sub/superscript@> =
18511 script_c:=null;
18512 script_g:=qi(0);
18513 script_f:=null_font;
18514 this_math_style:=sub_style(cur_style);
18515
18516 { Loop through the |sub_mlist| looking for the first character-like
18517 thing. Ignore kerns or glue so that, for example, changing
18518 $P_j$ to $P_{\!j}$ will have a predictable effect. Intercept
18519 |style_node|s and execute them. If we encounter a |choice_node|,
18520 follow the appropriate branch. Anything else halts the search
18521 and inhibits OpenType kerning. }
18522
18523 { Don't try to do anything clever if the nucleus of the
18524 |script_head| is empty, e.g., $P_{^j}$ and the such. }
18525
18526 if math_type(script_head)=sub_mlist then
18527 begin
18528 script_ptr:=info(script_head);
18529 script_head:=null;
18530
18531 while is_valid_pointer(script_ptr) do
18532 begin
18533 case type(script_ptr) of
18534 kern_node, glue_node: do_nothing;
18535 style_node: begin this_math_style:=subtype(script_ptr);
18536 end;
18537 choice_node: do_nothing; {see below}
18538 ord_noad, op_noad, bin_noad, rel_noad, open_noad,
18539 close_noad, punct_noad: begin script_head:=nucleus(script_ptr);
18540 script_ptr:=null;
18541 end;
18542 othercases script_ptr:=null {end the search}
18543 endcases;
18544
18545 if is_valid_pointer(script_ptr) then
18546 if type(script_ptr)=choice_node then
18547 case this_math_style div 2 of
18548 0: script_ptr:=display_mlist(script_ptr);
18549 1: script_ptr:=text_mlist(script_ptr);
18550 2: script_ptr:=script_mlist(script_ptr);
18551 3: script_ptr:=script_script_mlist(script_ptr);
18552 end
18553 else
18554 script_ptr:=link(script_ptr);
18555 end;
18556 end;
18557
18558 if is_valid_pointer(script_head) and math_type(script_head)=math_char then
18559 begin
18560 save_f:=cur_f;
18561 saved_math_style:=cur_style;
18562 cur_style:=this_math_style;
18563 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
18564 fetch(script_head);
18565
18566 if is_new_mathfont(cur_f) then
18567 begin
18568 script_c:=new_native_character(cur_f,qo(cur_c));
18569 script_g:=get_native_glyph(script_c,0);
18570 script_f:=cur_f; {script font}
18571 end;
18572
18573 cur_f:=save_f;
18574 cur_style:=saved_math_style;
18575 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
18576 end;
18577
18578 { The remaining case is |math_type(script_head) = sub_box|.
18579 Although it would be possible to deconstruct the box node to
18580 find the first glyph, it will most likely be from a text font
18581 without MATH kerning, so there's probably no point. }
18582
18583 @ @<Attach subscript OpenType math kerning@> =
18584 begin
18585 if is_glyph_node(p) then
18586 begin
18587 sub_kern:=get_ot_math_kern(native_font(p),native_glyph(p),sub_f,sub_g,sub_cmd,shift_down);
18588 if sub_kern<>0 then p:=attach_hkern_to_new_hlist(q,sub_kern);
18589 end;
18590 end;
18591
18592 @ @<Attach superscript OpenType math kerning@> =
18593 begin
18594 { if there is a superscript the kern will be added to |shift_amount(x)| }
18595
18596 if math_type(subscr(q))=empty then
18597 if is_glyph_node(p) then
18598 begin
18599 sup_kern:=get_ot_math_kern(native_font(p),native_glyph(p),sup_f,sup_g,sup_cmd,shift_up);
18600 if sup_kern<>0 then p:=attach_hkern_to_new_hlist(q,sup_kern);
18601 end;
18602 end;
18603
18604 @ We have now tied up all the loose ends of the first pass of |mlist_to_hlist|.
18605 The second pass simply goes through and hooks everything together with the
18606 proper glue and penalties. It also handles the |left_noad| and |right_noad| that
18607 might be present, since |max_h| and |max_d| are now known. Variable |p| points
18608 to a node at the current end of the final hlist.
18609
18610 @<Make a second pass over the mlist, ...@>=
18611 p:=temp_head; link(p):=null; q:=mlist; r_type:=0; cur_style:=style;
18612 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
18613 while q<>null do
18614 begin @<If node |q| is a style node, change the style and |goto delete_q|;
18615 otherwise if it is not a noad, put it into the hlist,
18616 advance |q|, and |goto done|; otherwise set |s| to the size
18617 of noad |q|, set |t| to the associated type (|ord_noad..
18618 inner_noad|), and set |pen| to the associated penalty@>;
18619 @<Append inter-element spacing based on |r_type| and |t|@>;
18620 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>;
18621 if type(q)=right_noad then t:=open_noad;
18622 r_type:=t;
18623 delete_q: r:=q; q:=link(q); free_node(r,s);
18624 done: end
18625
18626 @ Just before doing the big |case| switch in the second pass, the program
18627 sets up default values so that most of the branches are short.
18628
18629 @<If node |q| is a style node, change the style...@>=
18630 t:=ord_noad; s:=noad_size; pen:=inf_penalty;
18631 case type(q) of
18632 op_noad,open_noad,close_noad,punct_noad,inner_noad: t:=type(q);
18633 bin_noad: begin t:=bin_noad; pen:=bin_op_penalty;
18634 end;
18635 rel_noad: begin t:=rel_noad; pen:=rel_penalty;
18636 end;
18637 ord_noad,vcenter_noad,over_noad,under_noad: do_nothing;
18638 radical_noad: s:=radical_noad_size;
18639 accent_noad: s:=accent_noad_size;
18640 fraction_noad: s:=fraction_noad_size;
18641 left_noad,right_noad: t:=make_left_right(q,style,max_d,max_h);
18642 style_node: @<Change the current style and |goto delete_q|@>;
18643 whatsit_node,penalty_node,rule_node,disc_node,adjust_node,ins_node,mark_node,
18644 glue_node,kern_node:@t@>@;@/
18645 begin link(p):=q; p:=q; q:=link(q); link(p):=null; goto done;
18646 end;
18647 othercases confusion("mlist3")
18648 @:this can't happen mlist3}{\quad mlist3@>
18649 endcases
18650
18651 @ The |make_left_right| function constructs a left or right delimiter of
18652 the required size and returns the value |open_noad| or |close_noad|. The
18653 |right_noad| and |left_noad| will both be based on the original |style|,
18654 so they will have consistent sizes.
18655
18656 We use the fact that |right_noad-left_noad=close_noad-open_noad|.
18657
18658 @<Declare math...@>=
18659 function make_left_right(@!q:pointer;@!style:small_number;
18660 @!max_d,@!max_h:scaled):small_number;
18661 var delta,@!delta1,@!delta2:scaled; {dimensions used in the calculation}
18662 begin cur_style:=style; @<Set up the values...@>;
18663 delta2:=max_d+axis_height(cur_size);
18664 delta1:=max_h+max_d-delta2;
18665 if delta2>delta1 then delta1:=delta2; {|delta1| is max distance from axis}
18666 delta:=(delta1 div 500)*delimiter_factor;
18667 delta2:=delta1+delta1-delimiter_shortfall;
18668 if delta<delta2 then delta:=delta2;
18669 new_hlist(q):=var_delimiter(delimiter(q),cur_size,delta);
18670 make_left_right:=type(q)-(left_noad-open_noad); {|open_noad| or |close_noad|}
18671 end;
18672
18673 @ @<Change the current style and |goto delete_q|@>=
18674 begin cur_style:=subtype(q); s:=style_node_size;
18675 @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
18676 goto delete_q;
18677 end
18678
18679 @ The inter-element spacing in math formulas depends on an $8\times8$ table that
18680 \TeX\ preloads as a 64-digit string. The elements of this string have the
18681 following significance:
18682 $$\vbox{\halign{#\hfil\cr
18683 \.0 means no space;\cr
18684 \.1 means a conditional thin space (\.{\\nonscript\\mskip\\thinmuskip});\cr
18685 \.2 means a thin space (\.{\\mskip\\thinmuskip});\cr
18686 \.3 means a conditional medium space
18687 (\.{\\nonscript\\mskip\\medmuskip});\cr
18688 \.4 means a conditional thick space
18689 (\.{\\nonscript\\mskip\\thickmuskip});\cr
18690 \.* means an impossible case.\cr}}$$
18691 This is all pretty cryptic, but {\sl The \TeX book\/} explains what is
18692 supposed to happen, and the string makes it happen.
18693 @:TeXbook}{\sl The \TeX book@>
18694
18695 A global variable |magic_offset| is computed so that if |a| and |b| are
18696 in the range |ord_noad..inner_noad|, then |str_pool[a*8+b+magic_offset]|
18697 is the digit for spacing between noad types |a| and |b|.
18698
18699 If \PASCAL\ had provided a good way to preload constant arrays, this part of
18700 the program would not have been so strange.
18701 @:PASCAL}{\PASCAL@>
18702
18703 @d math_spacing=@;@/
18704 @t\hskip-35pt@>
18705 "0234000122*4000133**3**344*0400400*000000234000111*1111112341011"
18706 @t$ \hskip-35pt$@>
18707
18708 @<Glob...@>=
18709 @!magic_offset:integer; {used to find inter-element spacing}
18710
18711 @ @<Compute the magic offset@>=
18712 magic_offset:=str_start_macro(math_spacing)-9*ord_noad
18713
18714 @ @<Append inter-element spacing based on |r_type| and |t|@>=
18715 if r_type>0 then {not the first noad}
18716 begin case so(str_pool[r_type*8+t+magic_offset]) of
18717 "0": x:=0;
18718 "1": if cur_style<script_style then x:=thin_mu_skip_code@+else x:=0;
18719 "2": x:=thin_mu_skip_code;
18720 "3": if cur_style<script_style then x:=med_mu_skip_code@+else x:=0;
18721 "4": if cur_style<script_style then x:=thick_mu_skip_code@+else x:=0;
18722 othercases confusion("mlist4")
18723 @:this can't happen mlist4}{\quad mlist4@>
18724 endcases;
18725 if x<>0 then
18726 begin y:=math_glue(glue_par(x),cur_mu);
18727 z:=new_glue(y); glue_ref_count(y):=null; link(p):=z; p:=z;@/
18728 subtype(z):=x+1; {store a symbolic subtype}
18729 end;
18730 end
18731
18732 @ We insert a penalty node after the hlist entries of noad |q| if |pen|
18733 is not an ``infinite'' penalty, and if the node immediately following |q|
18734 is not a penalty node or a |rel_noad| or absent entirely.
18735
18736 @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>=
18737 if new_hlist(q)<>null then
18738 begin link(p):=new_hlist(q);
18739 repeat p:=link(p);
18740 until link(p)=null;
18741 end;
18742 if penalties then if link(q)<>null then if pen<inf_penalty then
18743 begin r_type:=type(link(q));
18744 if r_type<>penalty_node then if r_type<>rel_noad then
18745 begin z:=new_penalty(pen); link(p):=z; p:=z;
18746 end;
18747 end
18748
18749 @* \[37] Alignment.
18750 It's sort of a miracle whenever \.{\\halign} and \.{\\valign} work, because
18751 they cut across so many of the control structures of \TeX.
18752
18753 Therefore the
18754 present page is probably not the best place for a beginner to start reading
18755 this program; it is better to master everything else first.
18756
18757 Let us focus our thoughts on an example of what the input might be, in order
18758 to get some idea about how the alignment miracle happens. The example doesn't
18759 do anything useful, but it is sufficiently general to indicate all of the
18760 special cases that must be dealt with; please do not be disturbed by its
18761 apparent complexity and meaninglessness.
18762 $$\vbox{\halign{\.{#}\hfil\cr
18763 {}\\tabskip 2pt plus 3pt\cr
18764 {}\\halign to 300pt\{u1\#v1\&\cr
18765 \hskip 50pt\\tabskip 1pt plus 1fil u2\#v2\&\cr
18766 \hskip 50pt u3\#v3\\cr\cr
18767 \hskip 25pt a1\&\\omit a2\&\\vrule\\cr\cr
18768 \hskip 25pt \\noalign\{\\vskip 3pt\}\cr
18769 \hskip 25pt b1\\span b2\\cr\cr
18770 \hskip 25pt \\omit\&c2\\span\\omit\\cr\}\cr}}$$
18771 Here's what happens:
18772
18773 \yskip
18774 (0) When `\.{\\halign to 300pt\{}' is scanned, the |scan_spec| routine
18775 places the 300pt dimension onto the |save_stack|, and an |align_group|
18776 code is placed above it. This will make it possible to complete the alignment
18777 when the matching `\.\}' is found.
18778
18779 (1) The preamble is scanned next. Macros in the preamble are not expanded,
18780 @^preamble@>
18781 except as part of a tabskip specification. For example, if \.{u2} had been
18782 a macro in the preamble above, it would have been expanded, since \TeX\
18783 must look for `\.{minus...}' as part of the tabskip glue. A ``preamble list''
18784 is constructed based on the user's preamble; in our case it contains the
18785 following seven items:
18786 $$\vbox{\halign{\.{#}\hfil\qquad&(#)\hfil\cr
18787 {}\\glue 2pt plus 3pt&the tabskip preceding column 1\cr
18788 {}\\alignrecord, width $-\infty$&preamble info for column 1\cr
18789 {}\\glue 2pt plus 3pt&the tabskip between columns 1 and 2\cr
18790 {}\\alignrecord, width $-\infty$&preamble info for column 2\cr
18791 {}\\glue 1pt plus 1fil&the tabskip between columns 2 and 3\cr
18792 {}\\alignrecord, width $-\infty$&preamble info for column 3\cr
18793 {}\\glue 1pt plus 1fil&the tabskip following column 3\cr}}$$
18794 These ``alignrecord'' entries have the same size as an |unset_node|,
18795 since they will later be converted into such nodes. However, at the
18796 moment they have no |type| or |subtype| fields; they have |info| fields
18797 instead, and these |info| fields are initially set to the value |end_span|,
18798 for reasons explained below. Furthermore, the alignrecord nodes have no
18799 |height| or |depth| fields; these are renamed |u_part| and |v_part|,
18800 and they point to token lists for the templates of the alignment.
18801 For example, the |u_part| field in the first alignrecord points to the
18802 token list `\.{u1}', i.e., the template preceding the `\.\#' for column~1.
18803
18804 (2) \TeX\ now looks at what follows the \.{\\cr} that ended the preamble.
18805 It is not `\.{\\noalign}' or `\.{\\omit}', so this input is put back to
18806 be read again, and the template `\.{u1}' is fed to the scanner. Just
18807 before reading `\.{u1}', \TeX\ goes into restricted horizontal mode.
18808 Just after reading `\.{u1}', \TeX\ will see `\.{a1}', and then (when the
18809 {\.\&} is sensed) \TeX\ will see `\.{v1}'. Then \TeX\ scans an |endv|
18810 token, indicating the end of a column. At this point an |unset_node| is
18811 created, containing the contents of the current hlist (i.e., `\.{u1a1v1}').
18812 The natural width of this unset node replaces the |width| field of the
18813 alignrecord for column~1; in general, the alignrecords will record the
18814 maximum natural width that has occurred so far in a given column.
18815
18816 (3) Since `\.{\\omit}' follows the `\.\&', the templates for column~2
18817 are now bypassed. Again \TeX\ goes into restricted horizontal mode and
18818 makes an |unset_node| from the resulting hlist; but this time the
18819 hlist contains simply `\.{a2}'. The natural width of the new unset box
18820 is remembered in the |width| field of the alignrecord for column~2.
18821
18822 (4) A third |unset_node| is created for column 3, using essentially the
18823 mechanism that worked for column~1; this unset box contains `\.{u3\\vrule
18824 v3}'. The vertical rule in this case has running dimensions that will later
18825 extend to the height and depth of the whole first row, since each |unset_node|
18826 in a row will eventually inherit the height and depth of its enclosing box.
18827
18828 (5) The first row has now ended; it is made into a single unset box
18829 comprising the following seven items:
18830 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
18831 {}\\glue 2pt plus 3pt\cr
18832 {}\\unsetbox for 1 column: u1a1v1\cr
18833 {}\\glue 2pt plus 3pt\cr
18834 {}\\unsetbox for 1 column: a2\cr
18835 {}\\glue 1pt plus 1fil\cr
18836 {}\\unsetbox for 1 column: u3\\vrule v3\cr
18837 {}\\glue 1pt plus 1fil\cr}}$$
18838 The width of this unset row is unimportant, but it has the correct height
18839 and depth, so the correct baselineskip glue will be computed as the row
18840 is inserted into a vertical list.
18841
18842 (6) Since `\.{\\noalign}' follows the current \.{\\cr}, \TeX\ appends
18843 additional material (in this case \.{\\vskip 3pt}) to the vertical list.
18844 While processing this material, \TeX\ will be in internal vertical
18845 mode, and |no_align_group| will be on |save_stack|.
18846
18847 (7) The next row produces an unset box that looks like this:
18848 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
18849 {}\\glue 2pt plus 3pt\cr
18850 {}\\unsetbox for 2 columns: u1b1v1u2b2v2\cr
18851 {}\\glue 1pt plus 1fil\cr
18852 {}\\unsetbox for 1 column: {\rm(empty)}\cr
18853 {}\\glue 1pt plus 1fil\cr}}$$
18854 The natural width of the unset box that spans columns 1~and~2 is stored
18855 in a ``span node,'' which we will explain later; the |info| field of the
18856 alignrecord for column~1 now points to the new span node, and the |info|
18857 of the span node points to |end_span|.
18858
18859 (8) The final row produces the unset box
18860 $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
18861 {}\\glue 2pt plus 3pt\cr
18862 {}\\unsetbox for 1 column: {\rm(empty)}\cr
18863 {}\\glue 2pt plus 3pt\cr
18864 {}\\unsetbox for 2 columns: u2c2v2\cr
18865 {}\\glue 1pt plus 1fil\cr}}$$
18866 A new span node is attached to the alignrecord for column 2.
18867
18868 (9) The last step is to compute the true column widths and to change all the
18869 unset boxes to hboxes, appending the whole works to the vertical list that
18870 encloses the \.{\\halign}. The rules for deciding on the final widths of
18871 each unset column box will be explained below.
18872
18873 \yskip\noindent
18874 Note that as \.{\\halign} is being processed, we fearlessly give up control
18875 to the rest of \TeX. At critical junctures, an alignment routine is
18876 called upon to step in and do some little action, but most of the time
18877 these routines just lurk in the background. It's something like
18878 post-hypnotic suggestion.
18879
18880 @ We have mentioned that alignrecords contain no |height| or |depth| fields.
18881 Their |glue_sign| and |glue_order| are pre-empted as well, since it
18882 is necessary to store information about what to do when a template ends.
18883 This information is called the |extra_info| field.
18884
18885 @d u_part(#)==mem[#+height_offset].int {pointer to \<u_j> token list}
18886 @d v_part(#)==mem[#+depth_offset].int {pointer to \<v_j> token list}
18887 @d extra_info(#)==info(#+list_offset) {info to remember during template}
18888
18889 @ Alignments can occur within alignments, so a small stack is used to access
18890 the alignrecord information. At each level we have a |preamble| pointer,
18891 indicating the beginning of the preamble list; a |cur_align| pointer,
18892 indicating the current position in the preamble list; a |cur_span| pointer,
18893 indicating the value of |cur_align| at the beginning of a sequence of
18894 spanned columns; a |cur_loop| pointer, indicating the tabskip glue before
18895 an alignrecord that should be copied next if the current list is extended;
18896 and the |align_state| variable, which indicates the nesting of braces so
18897 that \.{\\cr} and \.{\\span} and tab marks are properly intercepted.
18898 There also are pointers |cur_head| and |cur_tail| to the head and tail
18899 of a list of adjustments being moved out from horizontal mode to
18900 vertical~mode.
18901
18902 The current values of these seven quantities appear in global variables;
18903 when they have to be pushed down, they are stored in 5-word nodes, and
18904 |align_ptr| points to the topmost such node.
18905
18906 @d preamble==link(align_head) {the current preamble list}
18907 @d align_stack_node_size=6 {number of |mem| words to save alignment states}
18908
18909 @<Glob...@>=
18910 @!cur_align:pointer; {current position in preamble list}
18911 @!cur_span:pointer; {start of currently spanned columns in preamble list}
18912 @!cur_loop:pointer; {place to copy when extending a periodic preamble}
18913 @!align_ptr:pointer; {most recently pushed-down alignment stack node}
18914 @!cur_head,@!cur_tail:pointer; {adjustment list pointers}
18915 @!cur_pre_head,@!cur_pre_tail:pointer; {pre-adjustment list pointers}
18916
18917 @ The |align_state| and |preamble| variables are initialized elsewhere.
18918
18919 @<Set init...@>=
18920 align_ptr:=null; cur_align:=null; cur_span:=null; cur_loop:=null;
18921 cur_head:=null; cur_tail:=null;
18922 cur_pre_head:=null; cur_pre_tail:=null;
18923
18924 @ Alignment stack maintenance is handled by a pair of trivial routines
18925 called |push_alignment| and |pop_alignment|.
18926
18927 @p procedure push_alignment;
18928 var p:pointer; {the new alignment stack node}
18929 begin p:=get_node(align_stack_node_size);
18930 link(p):=align_ptr; info(p):=cur_align;
18931 llink(p):=preamble; rlink(p):=cur_span;
18932 mem[p+2].int:=cur_loop; mem[p+3].int:=align_state;
18933 info(p+4):=cur_head; link(p+4):=cur_tail;
18934 info(p+5):=cur_pre_head; link(p+5):=cur_pre_tail;
18935 align_ptr:=p;
18936 cur_head:=get_avail;
18937 cur_pre_head:=get_avail;
18938 end;
18939 @#
18940 procedure pop_alignment;
18941 var p:pointer; {the top alignment stack node}
18942 begin free_avail(cur_head);
18943 free_avail(cur_pre_head);
18944 p:=align_ptr;
18945 cur_tail:=link(p+4); cur_head:=info(p+4);
18946 cur_pre_tail:=link(p+5); cur_pre_head:=info(p+5);
18947 align_state:=mem[p+3].int; cur_loop:=mem[p+2].int;
18948 cur_span:=rlink(p); preamble:=llink(p);
18949 cur_align:=info(p); align_ptr:=link(p);
18950 free_node(p,align_stack_node_size);
18951 end;
18952
18953 @ \TeX\ has eight procedures that govern alignments: |init_align| and
18954 |fin_align| are used at the very beginning and the very end; |init_row| and
18955 |fin_row| are used at the beginning and end of individual rows; |init_span|
18956 is used at the beginning of a sequence of spanned columns (possibly involving
18957 only one column); |init_col| and |fin_col| are used at the beginning and
18958 end of individual columns; and |align_peek| is used after \.{\\cr} to see
18959 whether the next item is \.{\\noalign}.
18960
18961 We shall consider these routines in the order they are first used during
18962 the course of a complete \.{\\halign}, namely |init_align|, |align_peek|,
18963 |init_row|, |init_span|, |init_col|, |fin_col|, |fin_row|, |fin_align|.
18964
18965 @ When \.{\\halign} or \.{\\valign} has been scanned in an appropriate
18966 mode, \TeX\ calls |init_align|, whose task is to get everything off to a
18967 good start. This mostly involves scanning the preamble and putting its
18968 information into the preamble list.
18969 @^preamble@>
18970
18971 @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/
18972 procedure@?align_peek; forward;@t\2@>@/
18973 procedure@?normal_paragraph; forward;@t\2@>@/
18974 procedure init_align;
18975 label done, done1, done2, continue;
18976 var save_cs_ptr:pointer; {|warning_index| value for error messages}
18977 @!p:pointer; {for short-term temporary use}
18978 begin save_cs_ptr:=cur_cs; {\.{\\halign} or \.{\\valign}, usually}
18979 push_alignment; align_state:=-1000000; {enter a new alignment level}
18980 @<Check for improper alignment in displayed math@>;
18981 push_nest; {enter a new semantic level}
18982 @<Change current mode to |-vmode| for \.{\\halign}, |-hmode| for \.{\\valign}@>;
18983 scan_spec(align_group,false);@/
18984 @<Scan the preamble and record it in the |preamble| list@>;
18985 new_save_level(align_group);
18986 if every_cr<>null then begin_token_list(every_cr,every_cr_text);
18987 align_peek; {look for \.{\\noalign} or \.{\\omit}}
18988 end;
18989
18990 @ In vertical modes, |prev_depth| already has the correct value. But
18991 if we are in |mmode| (displayed formula mode), we reach out to the
18992 enclosing vertical mode for the |prev_depth| value that produces the
18993 correct baseline calculations.
18994
18995 @<Change current mode...@>=
18996 if mode=mmode then
18997 begin mode:=-vmode; prev_depth:=nest[nest_ptr-2].aux_field.sc;
18998 end
18999 else if mode>0 then negate(mode)
19000
19001 @ When \.{\\halign} is used as a displayed formula, there should be
19002 no other pieces of mlists present.
19003
19004 @<Check for improper alignment in displayed math@>=
19005 if (mode=mmode)and((tail<>head)or(incompleat_noad<>null)) then
19006 begin print_err("Improper "); print_esc("halign"); print(" inside $$'s");
19007 @.Improper \\halign...@>
19008 help3("Displays can use special alignments (like \eqalignno)")@/
19009 ("only if nothing but the alignment itself is between $$'s.")@/
19010 ("So I've deleted the formulas that preceded this alignment.");
19011 error; flush_math;
19012 end
19013
19014 @ @<Scan the preamble and record it in the |preamble| list@>=
19015 preamble:=null; cur_align:=align_head; cur_loop:=null; scanner_status:=aligning;
19016 warning_index:=save_cs_ptr; align_state:=-1000000;
19017 {at this point, |cur_cmd=left_brace|}
19018 loop@+ begin @<Append the current tabskip glue to the preamble list@>;
19019 if cur_cmd=car_ret then goto done; {\.{\\cr} ends the preamble}
19020 @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|,
19021 looking for changes in the tabskip glue; append an
19022 alignrecord to the preamble list@>;
19023 end;
19024 done: scanner_status:=normal
19025
19026 @ @<Append the current tabskip glue to the preamble list@>=
19027 link(cur_align):=new_param_glue(tab_skip_code);
19028 cur_align:=link(cur_align)
19029
19030 @ @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|...@>=
19031 @<Scan the template \<u_j>, putting the resulting token list in |hold_head|@>;
19032 link(cur_align):=new_null_box; cur_align:=link(cur_align); {a new alignrecord}
19033 info(cur_align):=end_span; width(cur_align):=null_flag;
19034 u_part(cur_align):=link(hold_head);
19035 @<Scan the template \<v_j>, putting the resulting token list in |hold_head|@>;
19036 v_part(cur_align):=link(hold_head)
19037
19038 @ We enter `\.{\\span}' into |eqtb| with |tab_mark| as its command code,
19039 and with |span_code| as the command modifier. This makes \TeX\ interpret it
19040 essentially the same as an alignment delimiter like `\.\&', yet it is
19041 recognizably different when we need to distinguish it from a normal delimiter.
19042 It also turns out to be useful to give a special |cr_code| to `\.{\\cr}',
19043 and an even larger |cr_cr_code| to `\.{\\crcr}'.
19044
19045 The end of a template is represented by two ``frozen'' control sequences
19046 called \.{\\endtemplate}. The first has the command code |end_template|, which
19047 is |>outer_call|, so it will not easily disappear in the presence of errors.
19048 The |get_x_token| routine converts the first into the second, which has |endv|
19049 as its command code.
19050
19051 @d span_code=special_char {distinct from any character}
19052 @d cr_code=span_code+1 {distinct from |span_code| and from any character}
19053 @d cr_cr_code=cr_code+1 {this distinguishes \.{\\crcr} from \.{\\cr}}
19054 @d end_template_token==cs_token_flag+frozen_end_template
19055
19056 @<Put each of \TeX's primitives into the hash table@>=
19057 primitive("span",tab_mark,span_code);@/
19058 @!@:span_}{\.{\\span} primitive@>
19059 primitive("cr",car_ret,cr_code);
19060 @!@:cr_}{\.{\\cr} primitive@>
19061 text(frozen_cr):="cr"; eqtb[frozen_cr]:=eqtb[cur_val];@/
19062 primitive("crcr",car_ret,cr_cr_code);
19063 @!@:cr_cr_}{\.{\\crcr} primitive@>
19064 text(frozen_end_template):="endtemplate"; text(frozen_endv):="endtemplate";
19065 @.endtemplate@>
19066 eq_type(frozen_endv):=endv; equiv(frozen_endv):=null_list;
19067 eq_level(frozen_endv):=level_one;@/
19068 eqtb[frozen_end_template]:=eqtb[frozen_endv];
19069 eq_type(frozen_end_template):=end_template;
19070
19071 @ @<Cases of |print_cmd_chr|...@>=
19072 tab_mark: if chr_code=span_code then print_esc("span")
19073 else chr_cmd("alignment tab character ");
19074 car_ret: if chr_code=cr_code then print_esc("cr")
19075 else print_esc("crcr");
19076
19077 @ The preamble is copied directly, except that \.{\\tabskip} causes a change
19078 to the tabskip glue, thereby possibly expanding macros that immediately
19079 follow it. An appearance of \.{\\span} also causes such an expansion.
19080
19081 Note that if the preamble contains `\.{\\global\\tabskip}', the `\.{\\global}'
19082 token survives in the preamble and the `\.{\\tabskip}' defines new
19083 tabskip glue (locally).
19084
19085 @<Declare the procedure called |get_preamble_token|@>=
19086 procedure get_preamble_token;
19087 label restart;
19088 begin restart: get_token;
19089 while (cur_chr=span_code)and(cur_cmd=tab_mark) do
19090 begin get_token; {this token will be expanded once}
19091 if cur_cmd>max_command then
19092 begin expand; get_token;
19093 end;
19094 end;
19095 if cur_cmd=endv then
19096 fatal_error("(interwoven alignment preambles are not allowed)");
19097 @.interwoven alignment preambles...@>
19098 if (cur_cmd=assign_glue)and(cur_chr=glue_base+tab_skip_code) then
19099 begin scan_optional_equals; scan_glue(glue_val);
19100 if global_defs>0 then geq_define(glue_base+tab_skip_code,glue_ref,cur_val)
19101 else eq_define(glue_base+tab_skip_code,glue_ref,cur_val);
19102 goto restart;
19103 end;
19104 end;
19105
19106 @ Spaces are eliminated from the beginning of a template.
19107
19108 @<Scan the template \<u_j>...@>=
19109 p:=hold_head; link(p):=null;
19110 loop@+ begin get_preamble_token;
19111 if cur_cmd=mac_param then goto done1;
19112 if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
19113 if (p=hold_head)and(cur_loop=null)and(cur_cmd=tab_mark)
19114 then cur_loop:=cur_align
19115 else begin print_err("Missing # inserted in alignment preamble");
19116 @.Missing \# inserted...@>
19117 help3("There should be exactly one # between &'s, when an")@/
19118 ("\halign or \valign is being set up. In this case you had")@/
19119 ("none, so I've put one in; maybe that will work.");
19120 back_error; goto done1;
19121 end
19122 else if (cur_cmd<>spacer)or(p<>hold_head) then
19123 begin link(p):=get_avail; p:=link(p); info(p):=cur_tok;
19124 end;
19125 end;
19126 done1:
19127
19128 @ @<Scan the template \<v_j>...@>=
19129 p:=hold_head; link(p):=null;
19130 loop@+ begin continue: get_preamble_token;
19131 if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
19132 goto done2;
19133 if cur_cmd=mac_param then
19134 begin print_err("Only one # is allowed per tab");
19135 @.Only one \# is allowed...@>
19136 help3("There should be exactly one # between &'s, when an")@/
19137 ("\halign or \valign is being set up. In this case you had")@/
19138 ("more than one, so I'm ignoring all but the first.");
19139 error; goto continue;
19140 end;
19141 link(p):=get_avail; p:=link(p); info(p):=cur_tok;
19142 end;
19143 done2: link(p):=get_avail; p:=link(p);
19144 info(p):=end_template_token {put \.{\\endtemplate} at the end}
19145
19146 @ The tricky part about alignments is getting the templates into the
19147 scanner at the right time, and recovering control when a row or column
19148 is finished.
19149
19150 We usually begin a row after each \.{\\cr} has been sensed, unless that
19151 \.{\\cr} is followed by \.{\\noalign} or by the right brace that terminates
19152 the alignment. The |align_peek| routine is used to look ahead and do
19153 the right thing; it either gets a new row started, or gets a \.{\\noalign}
19154 started, or finishes off the alignment.
19155
19156 @<Declare the procedure called |align_peek|@>=
19157 procedure align_peek;
19158 label restart;
19159 begin restart: align_state:=1000000;
19160 repeat get_x_or_protected;
19161 until cur_cmd<>spacer;
19162 if cur_cmd=no_align then
19163 begin scan_left_brace; new_save_level(no_align_group);
19164 if mode=-vmode then normal_paragraph;
19165 end
19166 else if cur_cmd=right_brace then fin_align
19167 else if (cur_cmd=car_ret)and(cur_chr=cr_cr_code) then
19168 goto restart {ignore \.{\\crcr}}
19169 else begin init_row; {start a new row}
19170 init_col; {start a new column and replace what we peeked at}
19171 end;
19172 end;
19173
19174 @ To start a row (i.e., a `row' that rhymes with `dough' but not with `bough'),
19175 we enter a new semantic level, copy the first tabskip glue, and change
19176 from internal vertical mode to restricted horizontal mode or vice versa.
19177 The |space_factor| and |prev_depth| are not used on this semantic level,
19178 but we clear them to zero just to be tidy.
19179
19180 @p @t\4@>@<Declare the procedure called |init_span|@>@t@>@/
19181 procedure init_row;
19182 begin push_nest; mode:=(-hmode-vmode)-mode;
19183 if mode=-hmode then space_factor:=0 @+else prev_depth:=0;
19184 tail_append(new_glue(glue_ptr(preamble)));
19185 subtype(tail):=tab_skip_code+1;@/
19186 cur_align:=link(preamble); cur_tail:=cur_head; cur_pre_tail:=cur_pre_head;
19187 init_span(cur_align);
19188 end;
19189
19190 @ The parameter to |init_span| is a pointer to the alignrecord where the
19191 next column or group of columns will begin. A new semantic level is
19192 entered, so that the columns will generate a list for subsequent packaging.
19193
19194 @<Declare the procedure called |init_span|@>=
19195 procedure init_span(@!p:pointer);
19196 begin push_nest;
19197 if mode=-hmode then space_factor:=1000
19198 else begin prev_depth:=ignore_depth; normal_paragraph;
19199 end;
19200 cur_span:=p;
19201 end;
19202
19203 @ When a column begins, we assume that |cur_cmd| is either |omit| or else
19204 the current token should be put back into the input until the \<u_j>
19205 template has been scanned. (Note that |cur_cmd| might be |tab_mark| or
19206 |car_ret|.) We also assume that |align_state| is approximately 1000000 at
19207 this time. We remain in the same mode, and start the template if it is
19208 called for.
19209
19210 @p procedure init_col;
19211 begin extra_info(cur_align):=cur_cmd;
19212 if cur_cmd=omit then align_state:=0
19213 else begin back_input; begin_token_list(u_part(cur_align),u_template);
19214 end; {now |align_state=1000000|}
19215 end;
19216
19217 @ The scanner sets |align_state| to zero when the \<u_j> template ends. When
19218 a subsequent \.{\\cr} or \.{\\span} or tab mark occurs with |align_state=0|,
19219 the scanner activates the following code, which fires up the \<v_j> template.
19220 We need to remember the |cur_chr|, which is either |cr_cr_code|, |cr_code|,
19221 |span_code|, or a character code, depending on how the column text has ended.
19222
19223 This part of the program had better not be activated when the preamble
19224 to another alignment is being scanned, or when no alignment preamble is active.
19225
19226 @<Insert the \(v)\<v_j>...@>=
19227 begin if (scanner_status=aligning) or (cur_align=null) then
19228 fatal_error("(interwoven alignment preambles are not allowed)");
19229 @.interwoven alignment preambles...@>
19230 cur_cmd:=extra_info(cur_align); extra_info(cur_align):=cur_chr;
19231 if cur_cmd=omit then begin_token_list(omit_template,v_template)
19232 else begin_token_list(v_part(cur_align),v_template);
19233 align_state:=1000000; goto restart;
19234 end
19235
19236 @ The token list |omit_template| just referred to is a constant token
19237 list that contains the special control sequence \.{\\endtemplate} only.
19238
19239 @<Initialize the special...@>=
19240 info(omit_template):=end_template_token; {|link(omit_template)=null|}
19241
19242 @ When the |endv| command at the end of a \<v_j> template comes through the
19243 scanner, things really start to happen; and it is the |fin_col| routine
19244 that makes them happen. This routine returns |true| if a row as well as a
19245 column has been finished.
19246
19247 @p function fin_col:boolean;
19248 label exit;
19249 var p:pointer; {the alignrecord after the current one}
19250 @!q,@!r:pointer; {temporary pointers for list manipulation}
19251 @!s:pointer; {a new span node}
19252 @!u:pointer; {a new unset box}
19253 @!w:scaled; {natural width}
19254 @!o:glue_ord; {order of infinity}
19255 @!n:halfword; {span counter}
19256 begin if cur_align=null then confusion("endv");
19257 q:=link(cur_align);@+if q=null then confusion("endv");
19258 @:this can't happen endv}{\quad endv@>
19259 if align_state<500000 then
19260 fatal_error("(interwoven alignment preambles are not allowed)");
19261 @.interwoven alignment preambles...@>
19262 p:=link(q);
19263 @<If the preamble list has been traversed, check that the row has ended@>;
19264 if extra_info(cur_align)<>span_code then
19265 begin unsave; new_save_level(align_group);@/
19266 @<Package an unset box for the current column and record its width@>;
19267 @<Copy the tabskip glue between columns@>;
19268 if extra_info(cur_align)>=cr_code then
19269 begin fin_col:=true; return;
19270 end;
19271 init_span(p);
19272 end;
19273 align_state:=1000000;
19274 repeat get_x_or_protected;
19275 until cur_cmd<>spacer;
19276 cur_align:=p;
19277 init_col; fin_col:=false;
19278 exit: end;
19279
19280 @ @<If the preamble list has been traversed, check that the row has ended@>=
19281 if (p=null)and(extra_info(cur_align)<cr_code) then
19282 if cur_loop<>null then @<Lengthen the preamble periodically@>
19283 else begin print_err("Extra alignment tab has been changed to ");
19284 @.Extra alignment tab...@>
19285 print_esc("cr");
19286 help3("You have given more \span or & marks than there were")@/
19287 ("in the preamble to the \halign or \valign now in progress.")@/
19288 ("So I'll assume that you meant to type \cr instead.");
19289 extra_info(cur_align):=cr_code; error;
19290 end
19291
19292 @ @<Lengthen the preamble...@>=
19293 begin link(q):=new_null_box; p:=link(q); {a new alignrecord}
19294 info(p):=end_span; width(p):=null_flag; cur_loop:=link(cur_loop);
19295 @<Copy the templates from node |cur_loop| into node |p|@>;
19296 cur_loop:=link(cur_loop);
19297 link(p):=new_glue(glue_ptr(cur_loop));
19298 subtype(link(p)):=tab_skip_code+1;
19299 end
19300
19301 @ @<Copy the templates from node |cur_loop| into node |p|@>=
19302 q:=hold_head; r:=u_part(cur_loop);
19303 while r<>null do
19304 begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
19305 end;
19306 link(q):=null; u_part(p):=link(hold_head);
19307 q:=hold_head; r:=v_part(cur_loop);
19308 while r<>null do
19309 begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
19310 end;
19311 link(q):=null; v_part(p):=link(hold_head)
19312
19313 @ @<Copy the tabskip glue...@>=
19314 tail_append(new_glue(glue_ptr(link(cur_align))));
19315 subtype(tail):=tab_skip_code+1
19316
19317 @ @<Package an unset...@>=
19318 begin if mode=-hmode then
19319 begin adjust_tail:=cur_tail; pre_adjust_tail:=cur_pre_tail;
19320 u:=hpack(link(head),natural); w:=width(u);
19321 cur_tail:=adjust_tail; adjust_tail:=null;
19322 cur_pre_tail:=pre_adjust_tail; pre_adjust_tail:=null;
19323 end
19324 else begin u:=vpackage(link(head),natural,0); w:=height(u);
19325 end;
19326 n:=min_quarterword; {this represents a span count of 1}
19327 if cur_span<>cur_align then @<Update width entry for spanned columns@>
19328 else if w>width(cur_align) then width(cur_align):=w;
19329 type(u):=unset_node; span_count(u):=n;@/
19330 @<Determine the stretch order@>;
19331 glue_order(u):=o; glue_stretch(u):=total_stretch[o];@/
19332 @<Determine the shrink order@>;
19333 glue_sign(u):=o; glue_shrink(u):=total_shrink[o];@/
19334 pop_nest; link(tail):=u; tail:=u;
19335 end
19336
19337 @ A span node is a 2-word record containing |width|, |info|, and |link|
19338 fields. The |link| field is not really a link, it indicates the number of
19339 spanned columns; the |info| field points to a span node for the same
19340 starting column, having a greater extent of spanning, or to |end_span|,
19341 which has the largest possible |link| field; the |width| field holds the
19342 largest natural width corresponding to a particular set of spanned columns.
19343
19344 A list of the maximum widths so far, for spanned columns starting at a
19345 given column, begins with the |info| field of the alignrecord for that
19346 column.
19347
19348 @d span_node_size=2 {number of |mem| words for a span node}
19349
19350 @<Initialize the special list heads...@>=
19351 link(end_span):=max_quarterword+1; info(end_span):=null;
19352
19353 @ @<Update width entry for spanned columns@>=
19354 begin q:=cur_span;
19355 repeat incr(n); q:=link(link(q));
19356 until q=cur_align;
19357 if n>max_quarterword then confusion("too many spans");
19358 {this can happen, but won't}
19359 @^system dependencies@>
19360 @:this can't happen too many spans}{\quad too many spans@>
19361 q:=cur_span; while link(info(q))<n do q:=info(q);
19362 if link(info(q))>n then
19363 begin s:=get_node(span_node_size); info(s):=info(q); link(s):=n;
19364 info(q):=s; width(s):=w;
19365 end
19366 else if width(info(q))<w then width(info(q)):=w;
19367 end
19368
19369 @ At the end of a row, we append an unset box to the current vlist (for
19370 \.{\\halign}) or the current hlist (for \.{\\valign}). This unset box
19371 contains the unset boxes for the columns, separated by the tabskip glue.
19372 Everything will be set later.
19373
19374 @p procedure fin_row;
19375 var p:pointer; {the new unset box}
19376 begin if mode=-hmode then
19377 begin p:=hpack(link(head),natural);
19378 pop_nest;
19379 if cur_pre_head <> cur_pre_tail then
19380 append_list(cur_pre_head)(cur_pre_tail);
19381 append_to_vlist(p);
19382 if cur_head <> cur_tail then
19383 append_list(cur_head)(cur_tail);
19384 end
19385 else begin p:=vpack(link(head),natural); pop_nest;
19386 link(tail):=p; tail:=p; space_factor:=1000;
19387 end;
19388 type(p):=unset_node; glue_stretch(p):=0;
19389 if every_cr<>null then begin_token_list(every_cr,every_cr_text);
19390 align_peek;
19391 end; {note that |glue_shrink(p)=0| since |glue_shrink==shift_amount|}
19392
19393 @ Finally, we will reach the end of the alignment, and we can breathe a
19394 sigh of relief that memory hasn't overflowed. All the unset boxes will now be
19395 set so that the columns line up, taking due account of spanned columns.
19396
19397 @p procedure@?do_assignments; forward;@t\2@>@/
19398 procedure@?resume_after_display; forward;@t\2@>@/
19399 procedure@?build_page; forward;@t\2@>@/
19400 procedure fin_align;
19401 var @!p,@!q,@!r,@!s,@!u,@!v: pointer; {registers for the list operations}
19402 @!t,@!w:scaled; {width of column}
19403 @!o:scaled; {shift offset for unset boxes}
19404 @!n:halfword; {matching span amount}
19405 @!rule_save:scaled; {temporary storage for |overfull_rule|}
19406 @!aux_save:memory_word; {temporary storage for |aux|}
19407 begin if cur_group<>align_group then confusion("align1");
19408 @:this can't happen align}{\quad align@>
19409 unsave; {that |align_group| was for individual entries}
19410 if cur_group<>align_group then confusion("align0");
19411 unsave; {that |align_group| was for the whole alignment}
19412 if nest[nest_ptr-1].mode_field=mmode then o:=display_indent
19413 else o:=0;
19414 @<Go through the preamble list, determining the column widths and
19415 changing the alignrecords to dummy unset boxes@>;
19416 @<Package the preamble list, to determine the actual tabskip glue amounts,
19417 and let |p| point to this prototype box@>;
19418 @<Set the glue in all the unset boxes of the current list@>;
19419 flush_node_list(p); pop_alignment;
19420 @<Insert the \(c)current list into its environment@>;
19421 end;@/
19422 @t\4@>@<Declare the procedure called |align_peek|@>
19423
19424 @ It's time now to dismantle the preamble list and to compute the column
19425 widths. Let $w_{ij}$ be the maximum of the natural widths of all entries
19426 that span columns $i$ through $j$, inclusive. The alignrecord for column~$i$
19427 contains $w_{ii}$ in its |width| field, and there is also a linked list of
19428 the nonzero $w_{ij}$ for increasing $j$, accessible via the |info| field;
19429 these span nodes contain the value $j-i+|min_quarterword|$ in their
19430 |link| fields. The values of $w_{ii}$ were initialized to |null_flag|, which
19431 we regard as $-\infty$.
19432
19433 The final column widths are defined by the formula
19434 $$w_j=\max_{1\L i\L j}\biggl( w_{ij}-\sum_{i\L k<j}(t_k+w_k)\biggr),$$
19435 where $t_k$ is the natural width of the tabskip glue between columns
19436 $k$ and~$k+1$. However, if $w_{ij}=-\infty$ for all |i| in the range
19437 |1<=i<=j| (i.e., if every entry that involved column~|j| also involved
19438 column~|j+1|), we let $w_j=0$, and we zero out the tabskip glue after
19439 column~|j|.
19440
19441 \TeX\ computes these values by using the following scheme: First $w_1=w_{11}$.
19442 Then replace $w_{2j}$ by $\max(w_{2j},w_{1j}-t_1-w_1)$, for all $j>1$.
19443 Then $w_2=w_{22}$. Then replace $w_{3j}$ by $\max(w_{3j},w_{2j}-t_2-w_2)$
19444 for all $j>2$; and so on. If any $w_j$ turns out to be $-\infty$, its
19445 value is changed to zero and so is the next tabskip.
19446
19447 @<Go through the preamble list,...@>=
19448 q:=link(preamble);
19449 repeat flush_list(u_part(q)); flush_list(v_part(q));
19450 p:=link(link(q));
19451 if width(q)=null_flag then
19452 @<Nullify |width(q)| and the tabskip glue following this column@>;
19453 if info(q)<>end_span then
19454 @<Merge the widths in the span nodes of |q| with those of |p|,
19455 destroying the span nodes of |q|@>;
19456 type(q):=unset_node; span_count(q):=min_quarterword; height(q):=0;
19457 depth(q):=0; glue_order(q):=normal; glue_sign(q):=normal;
19458 glue_stretch(q):=0; glue_shrink(q):=0; q:=p;
19459 until q=null
19460
19461 @ @<Nullify |width(q)| and the tabskip glue following this column@>=
19462 begin width(q):=0; r:=link(q); s:=glue_ptr(r);
19463 if s<>zero_glue then
19464 begin add_glue_ref(zero_glue); delete_glue_ref(s);
19465 glue_ptr(r):=zero_glue;
19466 end;
19467 end
19468
19469 @ Merging of two span-node lists is a typical exercise in the manipulation of
19470 linearly linked data structures. The essential invariant in the following
19471 |repeat| loop is that we want to dispense with node |r|, in |q|'s list,
19472 and |u| is its successor; all nodes of |p|'s list up to and including |s|
19473 have been processed, and the successor of |s| matches |r| or precedes |r|
19474 or follows |r|, according as |link(r)=n| or |link(r)>n| or |link(r)<n|.
19475
19476 @<Merge the widths...@>=
19477 begin t:=width(q)+width(glue_ptr(link(q)));
19478 r:=info(q); s:=end_span; info(s):=p; n:=min_quarterword+1;
19479 repeat width(r):=width(r)-t; u:=info(r);
19480 while link(r)>n do
19481 begin s:=info(s); n:=link(info(s))+1;
19482 end;
19483 if link(r)<n then
19484 begin info(r):=info(s); info(s):=r; decr(link(r)); s:=r;
19485 end
19486 else begin if width(r)>width(info(s)) then width(info(s)):=width(r);
19487 free_node(r,span_node_size);
19488 end;
19489 r:=u;
19490 until r=end_span;
19491 end
19492
19493 @ Now the preamble list has been converted to a list of alternating unset
19494 boxes and tabskip glue, where the box widths are equal to the final
19495 column sizes. In case of \.{\\valign}, we change the widths to heights,
19496 so that a correct error message will be produced if the alignment is
19497 overfull or underfull.
19498
19499 @<Package the preamble list...@>=
19500 save_ptr:=save_ptr-2; pack_begin_line:=-mode_line;
19501 if mode=-vmode then
19502 begin rule_save:=overfull_rule;
19503 overfull_rule:=0; {prevent rule from being packaged}
19504 p:=hpack(preamble,saved(1),saved(0)); overfull_rule:=rule_save;
19505 end
19506 else begin q:=link(preamble);
19507 repeat height(q):=width(q); width(q):=0; q:=link(link(q));
19508 until q=null;
19509 p:=vpack(preamble,saved(1),saved(0));
19510 q:=link(preamble);
19511 repeat width(q):=height(q); height(q):=0; q:=link(link(q));
19512 until q=null;
19513 end;
19514 pack_begin_line:=0
19515
19516 @ @<Set the glue in all the unset...@>=
19517 q:=link(head); s:=head;
19518 while q<>null do
19519 begin if not is_char_node(q) then
19520 if type(q)=unset_node then
19521 @<Set the unset box |q| and the unset boxes in it@>
19522 else if type(q)=rule_node then
19523 @<Make the running dimensions in rule |q| extend to the
19524 boundaries of the alignment@>;
19525 s:=q; q:=link(q);
19526 end
19527
19528 @ @<Make the running dimensions in rule |q| extend...@>=
19529 begin if is_running(width(q)) then width(q):=width(p);
19530 if is_running(height(q)) then height(q):=height(p);
19531 if is_running(depth(q)) then depth(q):=depth(p);
19532 if o<>0 then
19533 begin r:=link(q); link(q):=null; q:=hpack(q,natural);
19534 shift_amount(q):=o; link(q):=r; link(s):=q;
19535 end;
19536 end
19537
19538 @ The unset box |q| represents a row that contains one or more unset boxes,
19539 depending on how soon \.{\\cr} occurred in that row.
19540
19541 @<Set the unset box |q| and the unset boxes in it@>=
19542 begin if mode=-vmode then
19543 begin type(q):=hlist_node; width(q):=width(p);
19544 if nest[nest_ptr-1].mode_field=mmode then set_box_lr(q)(dlist); {for |ship_out|}
19545 end
19546 else begin type(q):=vlist_node; height(q):=height(p);
19547 end;
19548 glue_order(q):=glue_order(p); glue_sign(q):=glue_sign(p);
19549 glue_set(q):=glue_set(p); shift_amount(q):=o;
19550 r:=link(list_ptr(q)); s:=link(list_ptr(p));
19551 repeat @<Set the glue in node |r| and change it from an unset node@>;
19552 r:=link(link(r)); s:=link(link(s));
19553 until r=null;
19554 end
19555
19556 @ A box made from spanned columns will be followed by tabskip glue nodes and
19557 by empty boxes as if there were no spanning. This permits perfect alignment
19558 of subsequent entries, and it prevents values that depend on floating point
19559 arithmetic from entering into the dimensions of any boxes.
19560
19561 @<Set the glue in node |r|...@>=
19562 n:=span_count(r); t:=width(s); w:=t; u:=hold_head;
19563 set_box_lr(r)(0); {for |ship_out|}
19564 while n>min_quarterword do
19565 begin decr(n);
19566 @<Append tabskip glue and an empty box to list |u|,
19567 and update |s| and |t| as the prototype nodes are passed@>;
19568 end;
19569 if mode=-vmode then
19570 @<Make the unset node |r| into an |hlist_node| of width |w|,
19571 setting the glue as if the width were |t|@>
19572 else @<Make the unset node |r| into a |vlist_node| of height |w|,
19573 setting the glue as if the height were |t|@>;
19574 shift_amount(r):=0;
19575 if u<>hold_head then {append blank boxes to account for spanned nodes}
19576 begin link(u):=link(r); link(r):=link(hold_head); r:=u;
19577 end
19578
19579 @ @<Append tabskip glue and an empty box to list |u|...@>=
19580 s:=link(s); v:=glue_ptr(s); link(u):=new_glue(v); u:=link(u);
19581 subtype(u):=tab_skip_code+1; t:=t+width(v);
19582 if glue_sign(p)=stretching then
19583 begin if stretch_order(v)=glue_order(p) then
19584 t:=t+round(float(glue_set(p))*stretch(v));
19585 @^real multiplication@>
19586 end
19587 else if glue_sign(p)=shrinking then
19588 begin if shrink_order(v)=glue_order(p) then
19589 t:=t-round(float(glue_set(p))*shrink(v));
19590 end;
19591 s:=link(s); link(u):=new_null_box; u:=link(u); t:=t+width(s);
19592 if mode=-vmode then width(u):=width(s)@+else
19593 begin type(u):=vlist_node; height(u):=width(s);
19594 end
19595
19596 @ @<Make the unset node |r| into an |hlist_node| of width |w|...@>=
19597 begin height(r):=height(q); depth(r):=depth(q);
19598 if t=width(r) then
19599 begin glue_sign(r):=normal; glue_order(r):=normal;
19600 set_glue_ratio_zero(glue_set(r));
19601 end
19602 else if t>width(r) then
19603 begin glue_sign(r):=stretching;
19604 if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
19605 else glue_set(r):=unfloat((t-width(r))/glue_stretch(r));
19606 @^real division@>
19607 end
19608 else begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
19609 if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
19610 else if (glue_order(r)=normal)and(width(r)-t>glue_shrink(r)) then
19611 set_glue_ratio_one(glue_set(r))
19612 else glue_set(r):=unfloat((width(r)-t)/glue_shrink(r));
19613 end;
19614 width(r):=w; type(r):=hlist_node;
19615 end
19616
19617 @ @<Make the unset node |r| into a |vlist_node| of height |w|...@>=
19618 begin width(r):=width(q);
19619 if t=height(r) then
19620 begin glue_sign(r):=normal; glue_order(r):=normal;
19621 set_glue_ratio_zero(glue_set(r));
19622 end
19623 else if t>height(r) then
19624 begin glue_sign(r):=stretching;
19625 if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
19626 else glue_set(r):=unfloat((t-height(r))/glue_stretch(r));
19627 @^real division@>
19628 end
19629 else begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
19630 if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
19631 else if (glue_order(r)=normal)and(height(r)-t>glue_shrink(r)) then
19632 set_glue_ratio_one(glue_set(r))
19633 else glue_set(r):=unfloat((height(r)-t)/glue_shrink(r));
19634 end;
19635 height(r):=w; type(r):=vlist_node;
19636 end
19637
19638 @ We now have a completed alignment, in the list that starts at |head|
19639 and ends at |tail|. This list will be merged with the one that encloses
19640 it. (In case the enclosing mode is |mmode|, for displayed formulas,
19641 we will need to insert glue before and after the display; that part of the
19642 program will be deferred until we're more familiar with such operations.)
19643
19644 In restricted horizontal mode, the |clang| part of |aux| is undefined;
19645 an over-cautious \PASCAL\ runtime system may complain about this.
19646 @^dirty \PASCAL@>
19647
19648 @<Insert the \(c)current list into its environment@>=
19649 aux_save:=aux; p:=link(head); q:=tail; pop_nest;
19650 if mode=mmode then @<Finish an alignment in a display@>
19651 else begin aux:=aux_save; link(tail):=p;
19652 if p<>null then tail:=q;
19653 if mode=vmode then build_page;
19654 end
19655
19656 @* \[38] Breaking paragraphs into lines.
19657 We come now to what is probably the most interesting algorithm of \TeX:
19658 the mechanism for choosing the ``best possible'' breakpoints that yield
19659 the individual lines of a paragraph. \TeX's line-breaking algorithm takes
19660 a given horizontal list and converts it to a sequence of boxes that are
19661 appended to the current vertical list. In the course of doing this, it
19662 creates a special data structure containing three kinds of records that are
19663 not used elsewhere in \TeX. Such nodes are created while a paragraph is
19664 being processed, and they are destroyed afterwards; thus, the other parts
19665 of \TeX\ do not need to know anything about how line-breaking is done.
19666
19667 The method used here is based on an approach devised by Michael F. Plass and
19668 @^Plass, Michael Frederick@>
19669 @^Knuth, Donald Ervin@>
19670 the author in 1977, subsequently generalized and improved by the same two
19671 people in 1980. A detailed discussion appears in {\sl Software---Practice
19672 and Experience \bf11} (1981), 1119--1184, where it is shown that the
19673 line-breaking problem can be regarded as a special case of the problem of
19674 computing the shortest path in an acyclic network. The cited paper includes
19675 numerous examples and describes the history of line breaking as it has been
19676 practiced by printers through the ages. The present implementation adds two
19677 new ideas to the algorithm of 1980: Memory space requirements are considerably
19678 reduced by using smaller records for inactive nodes than for active ones,
19679 and arithmetic overflow is avoided by using ``delta distances'' instead of
19680 keeping track of the total distance from the beginning of the paragraph to the
19681 current point.
19682
19683 @ The |line_break| procedure should be invoked only in horizontal mode; it
19684 leaves that mode and places its output into the current vlist of the
19685 enclosing vertical mode (or internal vertical mode).
19686 There is one explicit parameter: |d| is true for partial paragraphs
19687 preceding display math mode; in this case the amount of additional
19688 penalty inserted before the final line is |display_widow_penalty|
19689 instead of |widow_penalty|.
19690
19691 There are also a number of implicit parameters: The hlist to be broken
19692 starts at |link(head)|, and it is nonempty. The value of |prev_graf| in the
19693 enclosing semantic level tells where the paragraph should begin in the
19694 sequence of line numbers, in case hanging indentation or \.{\\parshape}
19695 is in use; |prev_graf| is zero unless this paragraph is being continued
19696 after a displayed formula. Other implicit parameters, such as the
19697 |par_shape_ptr| and various penalties to use for hyphenation, etc., appear
19698 in |eqtb|.
19699
19700 After |line_break| has acted, it will have updated the current vlist and the
19701 value of |prev_graf|. Furthermore, the global variable |just_box| will
19702 point to the final box created by |line_break|, so that the width of this
19703 line can be ascertained when it is necessary to decide whether to use
19704 |above_display_skip| or |above_display_short_skip| before a displayed formula.
19705
19706 @<Glob...@>=
19707 @!just_box:pointer; {the |hlist_node| for the last line of the new paragraph}
19708
19709 @ Since |line_break| is a rather lengthy procedure---sort of a small world unto
19710 itself---we must build it up little by little, somewhat more cautiously
19711 than we have done with the simpler procedures of \TeX. Here is the
19712 general outline.
19713
19714 @p@t\4@>@<Declare subprocedures for |line_break|@>
19715 procedure line_break(@!d:boolean);
19716 label done,done1,done2,done3,done4,done5,done6,continue, restart;
19717 var @<Local variables for line breaking@>@;
19718 begin pack_begin_line:=mode_line; {this is for over/underfull box messages}
19719 @<Get ready to start line breaking@>;
19720 @<Find optimal breakpoints@>;
19721 @<Break the paragraph at the chosen breakpoints, justify the resulting lines
19722 to the correct widths, and append them to the current vertical list@>;
19723 @<Clean up the memory by removing the break nodes@>;
19724 pack_begin_line:=0;
19725 end;
19726 @#
19727 @t\4@>@<Declare \eTeX\ procedures for use by |main_control|@>
19728
19729 @ The first task is to move the list from |head| to |temp_head| and go
19730 into the enclosing semantic level. We also append the \.{\\parfillskip}
19731 glue to the end of the paragraph, removing a space (or other glue node) if
19732 it was there, since spaces usually precede blank lines and instances of
19733 `\.{\$\$}'. The |par_fill_skip| is preceded by an infinite penalty, so
19734 it will never be considered as a potential breakpoint.
19735
19736 This code assumes that a |glue_node| and a |penalty_node| occupy the
19737 same number of |mem|~words.
19738 @^data structure assumptions@>
19739
19740 @<Get ready to start...@>=
19741 link(temp_head):=link(head);
19742 if is_char_node(tail) then tail_append(new_penalty(inf_penalty))
19743 else if type(tail)<>glue_node then tail_append(new_penalty(inf_penalty))
19744 else begin type(tail):=penalty_node; delete_glue_ref(glue_ptr(tail));
19745 flush_node_list(leader_ptr(tail)); penalty(tail):=inf_penalty;
19746 end;
19747 link(tail):=new_param_glue(par_fill_skip_code);
19748 last_line_fill:=link(tail);
19749 init_cur_lang:=prev_graf mod @'200000;
19750 init_l_hyf:=prev_graf div @'20000000;
19751 init_r_hyf:=(prev_graf div @'200000) mod @'100;
19752 pop_nest;
19753
19754 @ When looking for optimal line breaks, \TeX\ creates a ``break node'' for
19755 each break that is {\sl feasible}, in the sense that there is a way to end
19756 a line at the given place without requiring any line to stretch more than
19757 a given tolerance. A break node is characterized by three things: the position
19758 of the break (which is a pointer to a |glue_node|, |math_node|, |penalty_node|,
19759 or |disc_node|); the ordinal number of the line that will follow this
19760 breakpoint; and the fitness classification of the line that has just
19761 ended, i.e., |tight_fit|, |decent_fit|, |loose_fit|, or |very_loose_fit|.
19762
19763 @d tight_fit=3 {fitness classification for lines shrinking 0.5 to 1.0 of their
19764 shrinkability}
19765 @d loose_fit=1 {fitness classification for lines stretching 0.5 to 1.0 of their
19766 stretchability}
19767 @d very_loose_fit=0 {fitness classification for lines stretching more than
19768 their stretchability}
19769 @d decent_fit=2 {fitness classification for all other lines}
19770
19771 @ The algorithm essentially determines the best possible way to achieve
19772 each feasible combination of position, line, and fitness. Thus, it answers
19773 questions like, ``What is the best way to break the opening part of the
19774 paragraph so that the fourth line is a tight line ending at such-and-such
19775 a place?'' However, the fact that all lines are to be the same length
19776 after a certain point makes it possible to regard all sufficiently large
19777 line numbers as equivalent, when the looseness parameter is zero, and this
19778 makes it possible for the algorithm to save space and time.
19779
19780 An ``active node'' and a ``passive node'' are created in |mem| for each
19781 feasible breakpoint that needs to be considered. Active nodes are three
19782 words long and passive nodes are two words long. We need active nodes only
19783 for breakpoints near the place in the paragraph that is currently being
19784 examined, so they are recycled within a comparatively short time after
19785 they are created.
19786
19787 @ An active node for a given breakpoint contains six fields:
19788
19789 \yskip\hang|link| points to the next node in the list of active nodes; the
19790 last active node has |link=last_active|.
19791
19792 \yskip\hang|break_node| points to the passive node associated with this
19793 breakpoint.
19794
19795 \yskip\hang|line_number| is the number of the line that follows this
19796 breakpoint.
19797
19798 \yskip\hang|fitness| is the fitness classification of the line ending at this
19799 breakpoint.
19800
19801 \yskip\hang|type| is either |hyphenated| or |unhyphenated|, depending on
19802 whether this breakpoint is a |disc_node|.
19803
19804 \yskip\hang|total_demerits| is the minimum possible sum of demerits over all
19805 lines leading from the beginning of the paragraph to this breakpoint.
19806
19807 \yskip\noindent
19808 The value of |link(active)| points to the first active node on a linked list
19809 of all currently active nodes. This list is in order by |line_number|,
19810 except that nodes with |line_number>easy_line| may be in any order relative
19811 to each other.
19812
19813 @d active_node_size_normal=3 {number of words in normal active nodes}
19814 @d fitness==subtype {|very_loose_fit..tight_fit| on final line for this break}
19815 @d break_node==rlink {pointer to the corresponding passive node}
19816 @d line_number==llink {line that begins at this breakpoint}
19817 @d total_demerits(#)==mem[#+2].int {the quantity that \TeX\ minimizes}
19818 @d unhyphenated=0 {the |type| of a normal active break node}
19819 @d hyphenated=1 {the |type| of an active node that breaks at a |disc_node|}
19820 @d last_active==active {the active list ends where it begins}
19821
19822 @ @<Initialize the special list heads...@>=
19823 type(last_active):=hyphenated; line_number(last_active):=max_halfword;
19824 subtype(last_active):=0; {the |subtype| is never examined by the algorithm}
19825
19826 @ The passive node for a given breakpoint contains only four fields:
19827
19828 \yskip\hang|link| points to the passive node created just before this one,
19829 if any, otherwise it is |null|.
19830
19831 \yskip\hang|cur_break| points to the position of this breakpoint in the
19832 horizontal list for the paragraph being broken.
19833
19834 \yskip\hang|prev_break| points to the passive node that should precede this
19835 one in an optimal path to this breakpoint.
19836
19837 \yskip\hang|serial| is equal to |n| if this passive node is the |n|th
19838 one created during the current pass. (This field is used only when
19839 printing out detailed statistics about the line-breaking calculations.)
19840
19841 \yskip\noindent
19842 There is a global variable called |passive| that points to the most
19843 recently created passive node. Another global variable, |printed_node|,
19844 is used to help print out the paragraph when detailed information about
19845 the line-breaking computation is being displayed.
19846
19847 @d passive_node_size=2 {number of words in passive nodes}
19848 @d cur_break==rlink {in passive node, points to position of this breakpoint}
19849 @d prev_break==llink {points to passive node that should precede this one}
19850 @d serial==info {serial number for symbolic identification}
19851
19852 @<Glob...@>=
19853 @!passive:pointer; {most recent node on passive list}
19854 @!printed_node:pointer; {most recent node that has been printed}
19855 @!pass_number:halfword; {the number of passive nodes allocated on this pass}
19856
19857 @ The active list also contains ``delta'' nodes that help the algorithm
19858 compute the badness of individual lines. Such nodes appear only between two
19859 active nodes, and they have |type=delta_node|. If |p| and |r| are active nodes
19860 and if |q| is a delta node between them, so that |link(p)=q| and |link(q)=r|,
19861 then |q| tells the space difference between lines in the horizontal list that
19862 start after breakpoint |p| and lines that start after breakpoint |r|. In
19863 other words, if we know the length of the line that starts after |p| and
19864 ends at our current position, then the corresponding length of the line that
19865 starts after |r| is obtained by adding the amounts in node~|q|. A delta node
19866 contains six scaled numbers, since it must record the net change in glue
19867 stretchability with respect to all orders of infinity. The natural width
19868 difference appears in |mem[q+1].sc|; the stretch differences in units of
19869 pt, fil, fill, and filll appear in |mem[q+2..q+5].sc|; and the shrink difference
19870 appears in |mem[q+6].sc|. The |subtype| field of a delta node is not used.
19871
19872 @d delta_node_size=7 {number of words in a delta node}
19873 @d delta_node=2 {|type| field in a delta node}
19874
19875 @ As the algorithm runs, it maintains a set of six delta-like registers
19876 for the length of the line following the first active breakpoint to the
19877 current position in the given hlist. When it makes a pass through the
19878 active list, it also maintains a similar set of six registers for the
19879 length following the active breakpoint of current interest. A third set
19880 holds the length of an empty line (namely, the sum of \.{\\leftskip} and
19881 \.{\\rightskip}); and a fourth set is used to create new delta nodes.
19882
19883 When we pass a delta node we want to do operations like
19884 $$\hbox{\ignorespaces|for
19885 k:=1 to 6 do cur_active_width[k]:=cur_active_width[k]+mem[q+k].sc|};$$ and we
19886 want to do this without the overhead of |for| loops. The |do_all_six|
19887 macro makes such six-tuples convenient.
19888
19889 @d do_all_six(#)==#(1);#(2);#(3);#(4);#(5);#(6)
19890
19891 @<Glob...@>=
19892 @!active_width:array[1..6] of scaled;
19893 {distance from first active node to~|cur_p|}
19894 @!cur_active_width:array[1..6] of scaled; {distance from current active node}
19895 @!background:array[1..6] of scaled; {length of an ``empty'' line}
19896 @!break_width:array[1..6] of scaled; {length being computed after current break}
19897
19898 @ Let's state the principles of the delta nodes more precisely and concisely,
19899 so that the following programs will be less obscure. For each legal
19900 breakpoint~|p| in the paragraph, we define two quantities $\alpha(p)$ and
19901 $\beta(p)$ such that the length of material in a line from breakpoint~|p|
19902 to breakpoint~|q| is $\gamma+\beta(q)-\alpha(p)$, for some fixed $\gamma$.
19903 Intuitively, $\alpha(p)$ and $\beta(q)$ are the total length of material from
19904 the beginning of the paragraph to a point ``after'' a break at |p| and to a
19905 point ``before'' a break at |q|; and $\gamma$ is the width of an empty line,
19906 namely the length contributed by \.{\\leftskip} and \.{\\rightskip}.
19907
19908 Suppose, for example, that the paragraph consists entirely of alternating
19909 boxes and glue skips; let the boxes have widths $x_1\ldots x_n$ and
19910 let the skips have widths $y_1\ldots y_n$, so that the paragraph can be
19911 represented by $x_1y_1\ldots x_ny_n$. Let $p_i$ be the legal breakpoint
19912 at $y_i$; then $\alpha(p_i)=x_1+y_1+\cdots+x_i+y_i$, and $\beta(p_i)=
19913 x_1+y_1+\cdots+x_i$. To check this, note that the length of material from
19914 $p_2$ to $p_5$, say, is $\gamma+x_3+y_3+x_4+y_4+x_5=\gamma+\beta(p_5)
19915 -\alpha(p_2)$.
19916
19917 The quantities $\alpha$, $\beta$, $\gamma$ involve glue stretchability and
19918 shrinkability as well as a natural width. If we were to compute $\alpha(p)$
19919 and $\beta(p)$ for each |p|, we would need multiple precision arithmetic, and
19920 the multiprecise numbers would have to be kept in the active nodes.
19921 \TeX\ avoids this problem by working entirely with relative differences
19922 or ``deltas.'' Suppose, for example, that the active list contains
19923 $a_1\,\delta_1\,a_2\,\delta_2\,a_3$, where the |a|'s are active breakpoints
19924 and the $\delta$'s are delta nodes. Then $\delta_1=\alpha(a_1)-\alpha(a_2)$
19925 and $\delta_2=\alpha(a_2)-\alpha(a_3)$. If the line breaking algorithm is
19926 currently positioned at some other breakpoint |p|, the |active_width| array
19927 contains the value $\gamma+\beta(p)-\alpha(a_1)$. If we are scanning through
19928 the list of active nodes and considering a tentative line that runs from
19929 $a_2$ to~|p|, say, the |cur_active_width| array will contain the value
19930 $\gamma+\beta(p)-\alpha(a_2)$. Thus, when we move from $a_2$ to $a_3$,
19931 we want to add $\alpha(a_2)-\alpha(a_3)$ to |cur_active_width|; and this
19932 is just $\delta_2$, which appears in the active list between $a_2$ and
19933 $a_3$. The |background| array contains $\gamma$. The |break_width| array
19934 will be used to calculate values of new delta nodes when the active
19935 list is being updated.
19936
19937 @ Glue nodes in a horizontal list that is being paragraphed are not supposed to
19938 include ``infinite'' shrinkability; that is why the algorithm maintains
19939 four registers for stretching but only one for shrinking. If the user tries to
19940 introduce infinite shrinkability, the shrinkability will be reset to finite
19941 and an error message will be issued. A boolean variable |no_shrink_error_yet|
19942 prevents this error message from appearing more than once per paragraph.
19943
19944 @d check_shrinkage(#)==if (shrink_order(#)<>normal)and(shrink(#)<>0) then
19945 begin #:=finite_shrink(#);
19946 end
19947
19948 @<Glob...@>=
19949 @!no_shrink_error_yet:boolean; {have we complained about infinite shrinkage?}
19950
19951 @ @<Declare subprocedures for |line_break|@>=
19952 function finite_shrink(@!p:pointer):pointer; {recovers from infinite shrinkage}
19953 var q:pointer; {new glue specification}
19954 begin if no_shrink_error_yet then
19955 begin no_shrink_error_yet:=false;
19956 @!stat if tracing_paragraphs>0 then end_diagnostic(true);@+tats@;
19957 print_err("Infinite glue shrinkage found in a paragraph");
19958 @.Infinite glue shrinkage...@>
19959 help5("The paragraph just ended includes some glue that has")@/
19960 ("infinite shrinkability, e.g., `\hskip 0pt minus 1fil'.")@/
19961 ("Such glue doesn't belong there---it allows a paragraph")@/
19962 ("of any length to fit on one line. But it's safe to proceed,")@/
19963 ("since the offensive shrinkability has been made finite.");
19964 error;
19965 @!stat if tracing_paragraphs>0 then begin_diagnostic;@+tats@;
19966 end;
19967 q:=new_spec(p); shrink_order(q):=normal;
19968 delete_glue_ref(p); finite_shrink:=q;
19969 end;
19970
19971 @ @<Get ready to start...@>=
19972 no_shrink_error_yet:=true;@/
19973 check_shrinkage(left_skip); check_shrinkage(right_skip);@/
19974 q:=left_skip; r:=right_skip; background[1]:=width(q)+width(r);@/
19975 background[2]:=0; background[3]:=0; background[4]:=0; background[5]:=0;@/
19976 background[2+stretch_order(q)]:=stretch(q);@/
19977 background[2+stretch_order(r)]:=@|background[2+stretch_order(r)]+stretch(r);@/
19978 background[6]:=shrink(q)+shrink(r);
19979 @<Check for special treatment of last line of paragraph@>;
19980
19981 @ A pointer variable |cur_p| runs through the given horizontal list as we look
19982 for breakpoints. This variable is global, since it is used both by |line_break|
19983 and by its subprocedure |try_break|.
19984
19985 Another global variable called |threshold| is used to determine the feasibility
19986 of individual lines: Breakpoints are feasible if there is a way to reach
19987 them without creating lines whose badness exceeds |threshold|. (The
19988 badness is compared to |threshold| before penalties are added, so that
19989 penalty values do not affect the feasibility of breakpoints, except that
19990 no break is allowed when the penalty is 10000 or more.) If |threshold|
19991 is 10000 or more, all legal breaks are considered feasible, since the
19992 |badness| function specified above never returns a value greater than~10000.
19993
19994 Up to three passes might be made through the paragraph in an attempt to find at
19995 least one set of feasible breakpoints. On the first pass, we have
19996 |threshold=pretolerance| and |second_pass=final_pass=false|.
19997 If this pass fails to find a
19998 feasible solution, |threshold| is set to |tolerance|, |second_pass| is set
19999 |true|, and an attempt is made to hyphenate as many words as possible.
20000 If that fails too, we add |emergency_stretch| to the background
20001 stretchability and set |final_pass=true|.
20002
20003 @<Glob...@>=
20004 @!cur_p:pointer; {the current breakpoint under consideration}
20005 @!second_pass:boolean; {is this our second attempt to break this paragraph?}
20006 @!final_pass:boolean; {is this our final attempt to break this paragraph?}
20007 @!threshold:integer; {maximum badness on feasible lines}
20008
20009 @ The heart of the line-breaking procedure is `|try_break|', a subroutine
20010 that tests if the current breakpoint |cur_p| is feasible, by running
20011 through the active list to see what lines of text can be made from active
20012 nodes to~|cur_p|. If feasible breaks are possible, new break nodes are
20013 created. If |cur_p| is too far from an active node, that node is
20014 deactivated.
20015
20016 The parameter |pi| to |try_break| is the penalty associated
20017 with a break at |cur_p|; we have |pi=eject_penalty| if the break is forced,
20018 and |pi=inf_penalty| if the break is illegal.
20019
20020 The other parameter, |break_type|, is set to |hyphenated| or |unhyphenated|,
20021 depending on whether or not the current break is at a |disc_node|. The
20022 end of a paragraph is also regarded as `|hyphenated|'; this case is
20023 distinguishable by the condition |cur_p=null|.
20024
20025 @d copy_to_cur_active(#)==cur_active_width[#]:=active_width[#]
20026 @d deactivate=60 {go here when node |r| should be deactivated}
20027
20028 @d cp_skipable(#) == {skipable nodes at the margins during character protrusion}
20029 (
20030 not is_char_node(#) and
20031 (
20032 (type(#) = ins_node)
20033 or (type(#) = mark_node)
20034 or (type(#) = adjust_node)
20035 or (type(#) = penalty_node)
20036 or ((type(#) = disc_node) and
20037 (pre_break(#) = null) and
20038 (post_break(#) = null) and
20039 (replace_count(#) = 0)) {an empty |disc_node|}
20040 or ((type(#) = math_node) and (width(#) = 0))
20041 or ((type(#) = kern_node) and
20042 ((width(#) = 0) or (subtype(#) = normal)))
20043 or ((type(#) = glue_node) and (glue_ptr(#) = zero_glue))
20044 or ((type(#) = hlist_node) and (width(#) = 0) and (height(#) = 0) and
20045 (depth(#) = 0) and (list_ptr(#) = null))
20046 )
20047 )
20048
20049 @<Declare subprocedures for |line_break|@>=
20050 procedure push_node(p: pointer);
20051 begin
20052 if hlist_stack_level > max_hlist_stack then
20053 pdf_error("push_node", "stack overflow");
20054 hlist_stack[hlist_stack_level]:=p;
20055 hlist_stack_level:=hlist_stack_level + 1;
20056 end;
20057
20058 function pop_node: pointer;
20059 begin
20060 hlist_stack_level:=hlist_stack_level - 1;
20061 if hlist_stack_level < 0 then {would point to some bug}
20062 pdf_error("pop_node", "stack underflow (internal error)");
20063 pop_node:=hlist_stack[hlist_stack_level];
20064 end;
20065
20066 function find_protchar_left(l: pointer; d: boolean): pointer;
20067 {searches left to right from list head |l|, returns 1st non-skipable item}
20068 var t: pointer;
20069 run: boolean;
20070 begin
20071 if (link(l) <> null) and (type(l) = hlist_node) and (width(l) = 0)
20072 and (height(l) = 0) and (depth(l) = 0) and (list_ptr(l) = null) then
20073 l:=link(l) {for paragraph start with \.{\\parindent = 0pt}}
20074 else if d then
20075 while (link(l) <> null) and (not (is_char_node(l) or non_discardable(l))) do
20076 l:=link(l); {std.\ discardables at line break, \TeX book, p 95}
20077 hlist_stack_level:=0;
20078 run:=true;
20079 repeat
20080 t:=l;
20081 while run and (type(l) = hlist_node) and (list_ptr(l) <> null) do begin
20082 push_node(l);
20083 l:=list_ptr(l);
20084 end;
20085 while run and cp_skipable(l) do begin
20086 while (link(l) = null) and (hlist_stack_level > 0) do begin
20087 l:=pop_node; {don't visit this node again}
20088 end;
20089 if link(l) <> null then
20090 l:=link(l)
20091 else if hlist_stack_level = 0 then run:=false
20092 end;
20093 until t = l;
20094 find_protchar_left:=l;
20095 end;
20096
20097 function find_protchar_right(l, r: pointer): pointer;
20098 {searches right to left from list tail |r| to head |l|, returns 1st non-skipable item}
20099 var t: pointer;
20100 run: boolean;
20101 begin
20102 find_protchar_right:=null;
20103 if r = null then return;
20104 hlist_stack_level:=0;
20105 run:=true;
20106 repeat
20107 t:=r;
20108 while run and (type(r) = hlist_node) and (list_ptr(r) <> null) do begin
20109 push_node(l);
20110 push_node(r);
20111 l:=list_ptr(r);
20112 r:=l;
20113 while link(r) <> null do
20114 r:=link(r);
20115 end;
20116 while run and cp_skipable(r) do begin
20117 while (r = l) and (hlist_stack_level > 0) do begin
20118 r:=pop_node; {don't visit this node again}
20119 l:=pop_node;
20120 end;
20121 if (r <> l) and (r <> null) then
20122 r:=prev_rightmost(l, r)
20123 else if (r = l) and (hlist_stack_level = 0) then run:=false
20124 end;
20125 until t = r;
20126 find_protchar_right:=r;
20127 end;
20128
20129 function total_pw(q, p: pointer): scaled;
20130 {returns the total width of character protrusion of a line;
20131 |cur_break(break_node(q))| and |p| is the leftmost resp. rightmost node in the
20132 horizontal list representing the actual line}
20133 var l, r: pointer;
20134 n: integer;
20135 begin
20136 if break_node(q) = null then
20137 l:=first_p
20138 else
20139 l:=cur_break(break_node(q));
20140 r:=prev_rightmost(global_prev_p, p); {get |link(r)=p|}
20141 {let's look at the right margin first}
20142 if (p <> null) and (type(p) = disc_node) and (pre_break(p) <> null) then
20143 {a |disc_node| with non-empty |pre_break|, protrude the last char of |pre_break|}
20144 begin
20145 r:=pre_break(p);
20146 while link(r) <> null do
20147 r:=link(r);
20148 end else r:=find_protchar_right(l, r);
20149 {now the left margin}
20150 if (l <> null) and (type(l) = disc_node) then begin
20151 if post_break(l) <> null then begin
20152 l:=post_break(l); {protrude the first char}
20153 goto done;
20154 end else {discard |replace_count(l)| nodes}
20155 begin
20156 n:=replace_count(l);
20157 l:=link(l);
20158 while n > 0 do begin
20159 if link(l) <> null then
20160 l:=link(l);
20161 decr(n);
20162 end;
20163 end;
20164 end;
20165 l:=find_protchar_left(l, true);
20166 done:
20167 total_pw:=left_pw(l) + right_pw(r);
20168 end;
20169 procedure try_break(@!pi:integer;@!break_type:small_number);
20170 label exit,done,done1,continue,deactivate,found,not_found;
20171 var r:pointer; {runs through the active list}
20172 @!prev_r:pointer; {stays a step behind |r|}
20173 @!old_l:halfword; {maximum line number in current equivalence class of lines}
20174 @!no_break_yet:boolean; {have we found a feasible break at |cur_p|?}
20175 @<Other local variables for |try_break|@>@;
20176 begin @<Make sure that |pi| is in the proper range@>;
20177 no_break_yet:=true; prev_r:=active; old_l:=0;
20178 do_all_six(copy_to_cur_active);
20179 loop@+ begin continue: r:=link(prev_r);
20180 @<If node |r| is of type |delta_node|, update |cur_active_width|,
20181 set |prev_r| and |prev_prev_r|, then |goto continue|@>;
20182 @<If a line number class has ended, create new active nodes for
20183 the best feasible breaks in that class; then |return|
20184 if |r=last_active|, otherwise compute the new |line_width|@>;
20185 @<Consider the demerits for a line from |r| to |cur_p|;
20186 deactivate node |r| if it should no longer be active;
20187 then |goto continue| if a line from |r| to |cur_p| is infeasible,
20188 otherwise record a new feasible break@>;
20189 end;
20190 exit: @!stat @<Update the value of |printed_node| for
20191 symbolic displays@>@+tats@;
20192 end;
20193
20194 @ @<Other local variables for |try_break|@>=
20195 @!prev_prev_r:pointer; {a step behind |prev_r|, if |type(prev_r)=delta_node|}
20196 @!s:pointer; {runs through nodes ahead of |cur_p|}
20197 @!q:pointer; {points to a new node being created}
20198 @!v:pointer; {points to a glue specification or a node ahead of |cur_p|}
20199 @!t:integer; {node count, if |cur_p| is a discretionary node}
20200 @!f:internal_font_number; {used in character width calculation}
20201 @!l:halfword; {line number of current active node}
20202 @!node_r_stays_active:boolean; {should node |r| remain in the active list?}
20203 @!line_width:scaled; {the current line will be justified to this width}
20204 @!fit_class:very_loose_fit..tight_fit; {possible fitness class of test line}
20205 @!b:halfword; {badness of test line}
20206 @!d:integer; {demerits of test line}
20207 @!artificial_demerits:boolean; {has |d| been forced to zero?}
20208 @!save_link:pointer; {temporarily holds value of |link(cur_p)|}
20209 @!shortfall:scaled; {used in badness calculations}
20210
20211 @ @<Make sure that |pi| is in the proper range@>=
20212 if abs(pi)>=inf_penalty then
20213 if pi>0 then return {this breakpoint is inhibited by infinite penalty}
20214 else pi:=eject_penalty {this breakpoint will be forced}
20215
20216 @ The following code uses the fact that |type(last_active)<>delta_node|.
20217
20218 @d update_width(#)==@|
20219 cur_active_width[#]:=cur_active_width[#]+mem[r+#].sc
20220
20221 @<If node |r|...@>=
20222 @^inner loop@>
20223 if type(r)=delta_node then
20224 begin do_all_six(update_width);
20225 prev_prev_r:=prev_r; prev_r:=r; goto continue;
20226 end
20227
20228 @ As we consider various ways to end a line at |cur_p|, in a given line number
20229 class, we keep track of the best total demerits known, in an array with
20230 one entry for each of the fitness classifications. For example,
20231 |minimal_demerits[tight_fit]| contains the fewest total demerits of feasible
20232 line breaks ending at |cur_p| with a |tight_fit| line; |best_place[tight_fit]|
20233 points to the passive node for the break before~|cur_p| that achieves such
20234 an optimum; and |best_pl_line[tight_fit]| is the |line_number| field in the
20235 active node corresponding to |best_place[tight_fit]|. When no feasible break
20236 sequence is known, the |minimal_demerits| entries will be equal to
20237 |awful_bad|, which is $2^{30}-1$. Another variable, |minimum_demerits|,
20238 keeps track of the smallest value in the |minimal_demerits| array.
20239
20240 @d awful_bad==@'7777777777 {more than a billion demerits}
20241
20242 @<Global...@>=
20243 @!minimal_demerits:array[very_loose_fit..tight_fit] of integer; {best total
20244 demerits known for current line class and position, given the fitness}
20245 @!minimum_demerits:integer; {best total demerits known for current line class
20246 and position}
20247 @!best_place:array[very_loose_fit..tight_fit] of pointer; {how to achieve
20248 |minimal_demerits|}
20249 @!best_pl_line:array[very_loose_fit..tight_fit] of halfword; {corresponding
20250 line number}
20251
20252 @ @<Get ready to start...@>=
20253 minimum_demerits:=awful_bad;
20254 minimal_demerits[tight_fit]:=awful_bad;
20255 minimal_demerits[decent_fit]:=awful_bad;
20256 minimal_demerits[loose_fit]:=awful_bad;
20257 minimal_demerits[very_loose_fit]:=awful_bad;
20258
20259 @ The first part of the following code is part of \TeX's inner loop, so
20260 we don't want to waste any time. The current active node, namely node |r|,
20261 contains the line number that will be considered next. At the end of the
20262 list we have arranged the data structure so that |r=last_active| and
20263 |line_number(last_active)>old_l|.
20264 @^inner loop@>
20265
20266 @<If a line number class...@>=
20267 begin l:=line_number(r);
20268 if l>old_l then
20269 begin {now we are no longer in the inner loop}
20270 if (minimum_demerits<awful_bad)and@|
20271 ((old_l<>easy_line)or(r=last_active)) then
20272 @<Create new active nodes for the best feasible breaks
20273 just found@>;
20274 if r=last_active then return;
20275 @<Compute the new line width@>;
20276 end;
20277 end
20278
20279 @ It is not necessary to create new active nodes having |minimal_demerits|
20280 greater than
20281 |minimum_demerits+abs(adj_demerits)|, since such active nodes will never
20282 be chosen in the final paragraph breaks. This observation allows us to
20283 omit a substantial number of feasible breakpoints from further consideration.
20284
20285 @<Create new active nodes...@>=
20286 begin if no_break_yet then @<Compute the values of |break_width|@>;
20287 @<Insert a delta node to prepare for breaks at |cur_p|@>;
20288 if abs(adj_demerits)>=awful_bad-minimum_demerits then
20289 minimum_demerits:=awful_bad-1
20290 else minimum_demerits:=minimum_demerits+abs(adj_demerits);
20291 for fit_class:=very_loose_fit to tight_fit do
20292 begin if minimal_demerits[fit_class]<=minimum_demerits then
20293 @<Insert a new active node
20294 from |best_place[fit_class]| to |cur_p|@>;
20295 minimal_demerits[fit_class]:=awful_bad;
20296 end;
20297 minimum_demerits:=awful_bad;
20298 @<Insert a delta node to prepare for the next active node@>;
20299 end
20300
20301 @ When we insert a new active node for a break at |cur_p|, suppose this
20302 new node is to be placed just before active node |a|; then we essentially
20303 want to insert `$\delta\,|cur_p|\,\delta^\prime$' before |a|, where
20304 $\delta=\alpha(a)-\alpha(|cur_p|)$ and $\delta^\prime=\alpha(|cur_p|)-\alpha(a)$
20305 in the notation explained above. The |cur_active_width| array now holds
20306 $\gamma+\beta(|cur_p|)-\alpha(a)$; so $\delta$ can be obtained by
20307 subtracting |cur_active_width| from the quantity $\gamma+\beta(|cur_p|)-
20308 \alpha(|cur_p|)$. The latter quantity can be regarded as the length of a
20309 line ``from |cur_p| to |cur_p|''; we call it the |break_width| at |cur_p|.
20310
20311 The |break_width| is usually negative, since it consists of the background
20312 (which is normally zero) minus the width of nodes following~|cur_p| that are
20313 eliminated after a break. If, for example, node |cur_p| is a glue node, the
20314 width of this glue is subtracted from the background; and we also look
20315 ahead to eliminate all subsequent glue and penalty and kern and math
20316 nodes, subtracting their widths as well.
20317
20318 Kern nodes do not disappear at a line break unless they are |explicit|
20319 or |space_adjustment|.
20320
20321 @d set_break_width_to_background(#)==break_width[#]:=background[#]
20322
20323 @<Compute the values of |break...@>=
20324 begin no_break_yet:=false; do_all_six(set_break_width_to_background);
20325 s:=cur_p;
20326 if break_type>unhyphenated then if cur_p<>null then
20327 @<Compute the discretionary |break_width| values@>;
20328 while s<>null do
20329 begin if is_char_node(s) then goto done;
20330 case type(s) of
20331 glue_node:@<Subtract glue from |break_width|@>;
20332 penalty_node: do_nothing;
20333 math_node: break_width[1]:=break_width[1]-width(s);
20334 kern_node: if subtype(s)<>explicit then goto done
20335 else break_width[1]:=break_width[1]-width(s);
20336 othercases goto done
20337 endcases;@/
20338 s:=link(s);
20339 end;
20340 done: end
20341
20342 @ @<Subtract glue from |break...@>=
20343 begin v:=glue_ptr(s); break_width[1]:=break_width[1]-width(v);
20344 break_width[2+stretch_order(v)]:=break_width[2+stretch_order(v)]-stretch(v);
20345 break_width[6]:=break_width[6]-shrink(v);
20346 end
20347
20348 @ When |cur_p| is a discretionary break, the length of a line ``from |cur_p| to
20349 |cur_p|'' has to be defined properly so that the other calculations work out.
20350 Suppose that the pre-break text at |cur_p| has length $l_0$, the post-break
20351 text has length $l_1$, and the replacement text has length |l|. Suppose
20352 also that |q| is the node following the replacement text. Then length of a
20353 line from |cur_p| to |q| will be computed as $\gamma+\beta(q)-\alpha(|cur_p|)$,
20354 where $\beta(q)=\beta(|cur_p|)-l_0+l$. The actual length will be the background
20355 plus $l_1$, so the length from |cur_p| to |cur_p| should be $\gamma+l_0+l_1-l$.
20356 If the post-break text of the discretionary is empty, a break may also
20357 discard~|q|; in that unusual case we subtract the length of~|q| and any
20358 other nodes that will be discarded after the discretionary break.
20359
20360 The value of $l_0$ need not be computed, since |line_break| will put
20361 it into the global variable |disc_width| before calling |try_break|.
20362
20363 @<Glob...@>=
20364 @!disc_width:scaled; {the length of discretionary material preceding a break}
20365
20366 @ @<Compute the discretionary |break...@>=
20367 begin t:=replace_count(cur_p); v:=cur_p; s:=post_break(cur_p);
20368 while t>0 do
20369 begin decr(t); v:=link(v);
20370 @<Subtract the width of node |v| from |break_width|@>;
20371 end;
20372 while s<>null do
20373 begin @<Add the width of node |s| to |break_width|@>;
20374 s:=link(s);
20375 end;
20376 break_width[1]:=break_width[1]+disc_width;
20377 if post_break(cur_p)=null then s:=link(v);
20378 {nodes may be discardable after the break}
20379 end
20380
20381 @ Replacement texts and discretionary texts are supposed to contain
20382 only character nodes, kern nodes, ligature nodes, and box or rule nodes.
20383
20384 @<Subtract the width of node |v|...@>=
20385 if is_char_node(v) then
20386 begin f:=font(v);
20387 break_width[1]:=break_width[1]-char_width(f)(char_info(f)(character(v)));
20388 end
20389 else case type(v) of
20390 ligature_node: begin f:=font(lig_char(v));@/
20391 xtx_ligature_present:=true;
20392 break_width[1]:=@|break_width[1]-
20393 char_width(f)(char_info(f)(character(lig_char(v))));
20394 end;
20395 hlist_node,vlist_node,rule_node,kern_node:
20396 break_width[1]:=break_width[1]-width(v);
20397 whatsit_node:
20398 if (is_native_word_subtype(v))
20399 or (subtype(v)=glyph_node)
20400 or (subtype(v)=pic_node)
20401 or (subtype(v)=pdf_node)
20402 then break_width[1]:=break_width[1]-width(v)
20403 else confusion("disc1a");
20404 othercases confusion("disc1")
20405 @:this can't happen disc1}{\quad disc1@>
20406 endcases
20407
20408 @ @<Add the width of node |s| to |b...@>=
20409 if is_char_node(s) then
20410 begin f:=font(s);
20411 break_width[1]:=@|break_width[1]+char_width(f)(char_info(f)(character(s)));
20412 end
20413 else case type(s) of
20414 ligature_node: begin f:=font(lig_char(s));
20415 xtx_ligature_present:=true;
20416 break_width[1]:=break_width[1]+
20417 char_width(f)(char_info(f)(character(lig_char(s))));
20418 end;
20419 hlist_node,vlist_node,rule_node,kern_node:
20420 break_width[1]:=break_width[1]+width(s);
20421 whatsit_node:
20422 if (is_native_word_subtype(s))
20423 or (subtype(s)=glyph_node)
20424 or (subtype(s)=pic_node)
20425 or (subtype(s)=pdf_node)
20426 then break_width[1]:=break_width[1]+width(s)
20427 else confusion("disc2a");
20428 othercases confusion("disc2")
20429 @:this can't happen disc2}{\quad disc2@>
20430 endcases
20431
20432 @ We use the fact that |type(active)<>delta_node|.
20433
20434 @d convert_to_break_width(#)==@|
20435 mem[prev_r+#].sc:=@|@t\hskip10pt@>mem[prev_r+#].sc
20436 -cur_active_width[#]+break_width[#]
20437 @d store_break_width(#)==active_width[#]:=break_width[#]
20438 @d new_delta_to_break_width(#)==@|
20439 mem[q+#].sc:=break_width[#]-cur_active_width[#]
20440
20441 @<Insert a delta node to prepare for breaks at |cur_p|@>=
20442 if type(prev_r)=delta_node then {modify an existing delta node}
20443 begin do_all_six(convert_to_break_width);
20444 end
20445 else if prev_r=active then {no delta node needed at the beginning}
20446 begin do_all_six(store_break_width);
20447 end
20448 else begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
20449 subtype(q):=0; {the |subtype| is not used}
20450 do_all_six(new_delta_to_break_width);
20451 link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
20452 end
20453
20454 @ When the following code is performed, we will have just inserted at
20455 least one active node before |r|, so |type(prev_r)<>delta_node|.
20456
20457 @d new_delta_from_break_width(#)==@|mem[q+#].sc:=
20458 cur_active_width[#]-break_width[#]
20459
20460 @<Insert a delta node to prepare for the next active node@>=
20461 if r<>last_active then
20462 begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
20463 subtype(q):=0; {the |subtype| is not used}
20464 do_all_six(new_delta_from_break_width);
20465 link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
20466 end
20467
20468 @ When we create an active node, we also create the corresponding
20469 passive node.
20470
20471 @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>=
20472 begin q:=get_node(passive_node_size);
20473 link(q):=passive; passive:=q; cur_break(q):=cur_p;
20474 @!stat incr(pass_number); serial(q):=pass_number;@+tats@;@/
20475 prev_break(q):=best_place[fit_class];@/
20476 q:=get_node(active_node_size); break_node(q):=passive;
20477 line_number(q):=best_pl_line[fit_class]+1;
20478 fitness(q):=fit_class; type(q):=break_type;
20479 total_demerits(q):=minimal_demerits[fit_class];
20480 if do_last_line_fit then
20481 @<Store \(a)additional data in the new active node@>;
20482 link(q):=r; link(prev_r):=q; prev_r:=q;
20483 @!stat if tracing_paragraphs>0 then
20484 @<Print a symbolic description of the new break node@>;
20485 tats@;@/
20486 end
20487
20488 @ @<Print a symbolic description of the new break node@>=
20489 begin print_nl("@@@@"); print_int(serial(passive));
20490 @.\AT!\AT!@>
20491 print(": line "); print_int(line_number(q)-1);
20492 print_char("."); print_int(fit_class);
20493 if break_type=hyphenated then print_char("-");
20494 print(" t="); print_int(total_demerits(q));
20495 if do_last_line_fit then @<Print additional data in the new active node@>;
20496 print(" -> @@@@");
20497 if prev_break(passive)=null then print_char("0")
20498 else print_int(serial(prev_break(passive)));
20499 end
20500
20501 @ The length of lines depends on whether the user has specified
20502 \.{\\parshape} or \.{\\hangindent}. If |par_shape_ptr| is not null, it
20503 points to a $(2n+1)$-word record in |mem|, where the |info| in the first
20504 word contains the value of |n|, and the other $2n$ words contain the left
20505 margins and line lengths for the first |n| lines of the paragraph; the
20506 specifications for line |n| apply to all subsequent lines. If
20507 |par_shape_ptr=null|, the shape of the paragraph depends on the value of
20508 |n=hang_after|; if |n>=0|, hanging indentation takes place on lines |n+1|,
20509 |n+2|, \dots, otherwise it takes place on lines 1, \dots, $\vert
20510 n\vert$. When hanging indentation is active, the left margin is
20511 |hang_indent|, if |hang_indent>=0|, else it is 0; the line length is
20512 $|hsize|-\vert|hang_indent|\vert$. The normal setting is
20513 |par_shape_ptr=null|, |hang_after=1|, and |hang_indent=0|.
20514 Note that if |hang_indent=0|, the value of |hang_after| is irrelevant.
20515 @^length of lines@> @^hanging indentation@>
20516
20517 @<Glob...@>=
20518 @!easy_line:halfword; {line numbers |>easy_line| are equivalent in break nodes}
20519 @!last_special_line:halfword; {line numbers |>last_special_line| all have
20520 the same width}
20521 @!first_width:scaled; {the width of all lines |<=last_special_line|, if
20522 no \.{\\parshape} has been specified}
20523 @!second_width:scaled; {the width of all lines |>last_special_line|}
20524 @!first_indent:scaled; {left margin to go with |first_width|}
20525 @!second_indent:scaled; {left margin to go with |second_width|}
20526
20527 @ We compute the values of |easy_line| and the other local variables relating
20528 to line length when the |line_break| procedure is initializing itself.
20529
20530 @<Get ready to start...@>=
20531 if par_shape_ptr=null then
20532 if hang_indent=0 then
20533 begin last_special_line:=0; second_width:=hsize;
20534 second_indent:=0;
20535 end
20536 else @<Set line length parameters in preparation for hanging indentation@>
20537 else begin last_special_line:=info(par_shape_ptr)-1;
20538 second_width:=mem[par_shape_ptr+2*(last_special_line+1)].sc;
20539 second_indent:=mem[par_shape_ptr+2*last_special_line+1].sc;
20540 end;
20541 if looseness=0 then easy_line:=last_special_line
20542 else easy_line:=max_halfword
20543
20544 @ @<Set line length parameters in preparation for hanging indentation@>=
20545 begin last_special_line:=abs(hang_after);
20546 if hang_after<0 then
20547 begin first_width:=hsize-abs(hang_indent);
20548 if hang_indent>=0 then first_indent:=hang_indent
20549 else first_indent:=0;
20550 second_width:=hsize; second_indent:=0;
20551 end
20552 else begin first_width:=hsize; first_indent:=0;
20553 second_width:=hsize-abs(hang_indent);
20554 if hang_indent>=0 then second_indent:=hang_indent
20555 else second_indent:=0;
20556 end;
20557 end
20558
20559 @ When we come to the following code, we have just encountered the first
20560 active node~|r| whose |line_number| field contains |l|. Thus we want to
20561 compute the length of the $l\mskip1mu$th line of the current paragraph. Furthermore,
20562 we want to set |old_l| to the last number in the class of line numbers
20563 equivalent to~|l|.
20564
20565 @<Compute the new line width@>=
20566 if l>easy_line then
20567 begin line_width:=second_width; old_l:=max_halfword-1;
20568 end
20569 else begin old_l:=l;
20570 if l>last_special_line then line_width:=second_width
20571 else if par_shape_ptr=null then line_width:=first_width
20572 else line_width:=mem[par_shape_ptr+2*l@,].sc;
20573 end
20574
20575 @ The remaining part of |try_break| deals with the calculation of
20576 demerits for a break from |r| to |cur_p|.
20577
20578 The first thing to do is calculate the badness, |b|. This value will always
20579 be between zero and |inf_bad+1|; the latter value occurs only in the
20580 case of lines from |r| to |cur_p| that cannot shrink enough to fit the necessary
20581 width. In such cases, node |r| will be deactivated.
20582 We also deactivate node~|r| when a break at~|cur_p| is forced, since future
20583 breaks must go through a forced break.
20584
20585 @<Consider the demerits for a line from |r| to |cur_p|...@>=
20586 begin artificial_demerits:=false;@/
20587 @^inner loop@>
20588 shortfall:=line_width-cur_active_width[1]; {we're this much too short}
20589 if XeTeX_protrude_chars > 1 then
20590 shortfall:=shortfall + total_pw(r, cur_p);
20591 if shortfall>0 then
20592 @<Set the value of |b| to the badness for stretching the line,
20593 and compute the corresponding |fit_class|@>
20594 else @<Set the value of |b| to the badness for shrinking the line,
20595 and compute the corresponding |fit_class|@>;
20596 if do_last_line_fit then @<Adjust \(t)the additional data for last line@>;
20597 found:
20598 if (b>inf_bad)or(pi=eject_penalty) then
20599 @<Prepare to deactivate node~|r|, and |goto deactivate| unless
20600 there is a reason to consider lines of text from |r| to |cur_p|@>
20601 else begin prev_r:=r;
20602 if b>threshold then goto continue;
20603 node_r_stays_active:=true;
20604 end;
20605 @<Record a new feasible break@>;
20606 if node_r_stays_active then goto continue; {|prev_r| has been set to |r|}
20607 deactivate: @<Deactivate node |r|@>;
20608 end
20609
20610 @ When a line must stretch, the available stretchability can be found in the
20611 subarray |cur_active_width[2..5]|, in units of points, fil, fill, and filll.
20612
20613 The present section is part of \TeX's inner loop, and it is most often performed
20614 when the badness is infinite; therefore it is worth while to make a quick
20615 test for large width excess and small stretchability, before calling the
20616 |badness| subroutine.
20617 @^inner loop@>
20618
20619 @<Set the value of |b| to the badness for stretching...@>=
20620 if (cur_active_width[3]<>0)or(cur_active_width[4]<>0)or@|
20621 (cur_active_width[5]<>0) then
20622 begin if do_last_line_fit then
20623 begin if cur_p=null then {the last line of a paragraph}
20624 @<Perform computations for last line and |goto found|@>;
20625 shortfall:=0;
20626 end;
20627 b:=0; fit_class:=decent_fit; {infinite stretch}
20628 end
20629 else begin if shortfall>7230584 then if cur_active_width[2]<1663497 then
20630 begin b:=inf_bad; fit_class:=very_loose_fit; goto done1;
20631 end;
20632 b:=badness(shortfall,cur_active_width[2]);
20633 if b>12 then
20634 if b>99 then fit_class:=very_loose_fit
20635 else fit_class:=loose_fit
20636 else fit_class:=decent_fit;
20637 done1:
20638 end
20639
20640 @ Shrinkability is never infinite in a paragraph;
20641 we can shrink the line from |r| to |cur_p| by at most |cur_active_width[6]|.
20642
20643 @<Set the value of |b| to the badness for shrinking...@>=
20644 begin if -shortfall>cur_active_width[6] then b:=inf_bad+1
20645 else b:=badness(-shortfall,cur_active_width[6]);
20646 if b>12 then fit_class:=tight_fit@+else fit_class:=decent_fit;
20647 end
20648
20649 @ During the final pass, we dare not lose all active nodes, lest we lose
20650 touch with the line breaks already found. The code shown here makes sure
20651 that such a catastrophe does not happen, by permitting overfull boxes as
20652 a last resort. This particular part of \TeX\ was a source of several subtle
20653 bugs before the correct program logic was finally discovered; readers
20654 who seek to ``improve'' \TeX\ should therefore think thrice before daring
20655 to make any changes here.
20656 @^overfull boxes@>
20657
20658 @<Prepare to deactivate node~|r|, and |goto deactivate| unless...@>=
20659 begin if final_pass and (minimum_demerits=awful_bad) and@|
20660 (link(r)=last_active) and
20661 (prev_r=active) then
20662 artificial_demerits:=true {set demerits zero, this break is forced}
20663 else if b>threshold then goto deactivate;
20664 node_r_stays_active:=false;
20665 end
20666
20667 @ When we get to this part of the code, the line from |r| to |cur_p| is
20668 feasible, its badness is~|b|, and its fitness classification is |fit_class|.
20669 We don't want to make an active node for this break yet, but we will
20670 compute the total demerits and record them in the |minimal_demerits| array,
20671 if such a break is the current champion among all ways to get to |cur_p|
20672 in a given line-number class and fitness class.
20673
20674 @<Record a new feasible break@>=
20675 if artificial_demerits then d:=0
20676 else @<Compute the demerits, |d|, from |r| to |cur_p|@>;
20677 @!stat if tracing_paragraphs>0 then
20678 @<Print a symbolic description of this feasible break@>;
20679 tats@;@/
20680 d:=d+total_demerits(r); {this is the minimum total demerits
20681 from the beginning to |cur_p| via |r|}
20682 if d<=minimal_demerits[fit_class] then
20683 begin minimal_demerits[fit_class]:=d;
20684 best_place[fit_class]:=break_node(r); best_pl_line[fit_class]:=l;
20685 if do_last_line_fit then
20686 @<Store \(a)additional data for this feasible break@>;
20687 if d<minimum_demerits then minimum_demerits:=d;
20688 end
20689
20690 @ @<Print a symbolic description of this feasible break@>=
20691 begin if printed_node<>cur_p then
20692 @<Print the list between |printed_node| and |cur_p|,
20693 then set |printed_node:=cur_p|@>;
20694 print_nl("@@");
20695 @.\AT!@>
20696 if cur_p=null then print_esc("par")
20697 else if type(cur_p)<>glue_node then
20698 begin if type(cur_p)=penalty_node then print_esc("penalty")
20699 else if type(cur_p)=disc_node then print_esc("discretionary")
20700 else if type(cur_p)=kern_node then print_esc("kern")
20701 else print_esc("math");
20702 end;
20703 print(" via @@@@");
20704 if break_node(r)=null then print_char("0")
20705 else print_int(serial(break_node(r)));
20706 print(" b=");
20707 if b>inf_bad then print_char("*")@+else print_int(b);
20708 @.*\relax@>
20709 print(" p="); print_int(pi); print(" d=");
20710 if artificial_demerits then print_char("*")@+else print_int(d);
20711 end
20712
20713 @ @<Print the list between |printed_node| and |cur_p|...@>=
20714 begin print_nl("");
20715 if cur_p=null then short_display(link(printed_node))
20716 else begin save_link:=link(cur_p);
20717 link(cur_p):=null; print_nl(""); short_display(link(printed_node));
20718 link(cur_p):=save_link;
20719 end;
20720 printed_node:=cur_p;
20721 end
20722
20723 @ When the data for a discretionary break is being displayed, we will have
20724 printed the |pre_break| and |post_break| lists; we want to skip over the
20725 third list, so that the discretionary data will not appear twice. The
20726 following code is performed at the very end of |try_break|.
20727
20728 @<Update the value of |printed_node|...@>=
20729 if cur_p=printed_node then if cur_p<>null then if type(cur_p)=disc_node then
20730 begin t:=replace_count(cur_p);
20731 while t>0 do
20732 begin decr(t); printed_node:=link(printed_node);
20733 end;
20734 end
20735
20736 @ @<Compute the demerits, |d|, from |r| to |cur_p|@>=
20737 begin d:=line_penalty+b;
20738 if abs(d)>=10000 then d:=100000000@+else d:=d*d;
20739 if pi<>0 then
20740 if pi>0 then d:=d+pi*pi
20741 else if pi>eject_penalty then d:=d-pi*pi;
20742 if (break_type=hyphenated)and(type(r)=hyphenated) then
20743 if cur_p<>null then d:=d+double_hyphen_demerits
20744 else d:=d+final_hyphen_demerits;
20745 if abs(fit_class-fitness(r))>1 then d:=d+adj_demerits;
20746 end
20747
20748 @ When an active node disappears, we must delete an adjacent delta node if the
20749 active node was at the beginning or the end of the active list, or if it
20750 was surrounded by delta nodes. We also must preserve the property that
20751 |cur_active_width| represents the length of material from |link(prev_r)|
20752 to~|cur_p|.
20753
20754 @d combine_two_deltas(#)==@|mem[prev_r+#].sc:=mem[prev_r+#].sc+mem[r+#].sc
20755 @d downdate_width(#)==@|cur_active_width[#]:=cur_active_width[#]-
20756 mem[prev_r+#].sc
20757
20758 @<Deactivate node |r|@>=
20759 link(prev_r):=link(r); free_node(r,active_node_size);
20760 if prev_r=active then @<Update the active widths, since the first active
20761 node has been deleted@>
20762 else if type(prev_r)=delta_node then
20763 begin r:=link(prev_r);
20764 if r=last_active then
20765 begin do_all_six(downdate_width);
20766 link(prev_prev_r):=last_active;
20767 free_node(prev_r,delta_node_size); prev_r:=prev_prev_r;
20768 end
20769 else if type(r)=delta_node then
20770 begin do_all_six(update_width);
20771 do_all_six(combine_two_deltas);
20772 link(prev_r):=link(r); free_node(r,delta_node_size);
20773 end;
20774 end
20775
20776 @ The following code uses the fact that |type(last_active)<>delta_node|. If the
20777 active list has just become empty, we do not need to update the
20778 |active_width| array, since it will be initialized when an active
20779 node is next inserted.
20780
20781 @d update_active(#)==active_width[#]:=active_width[#]+mem[r+#].sc
20782
20783 @<Update the active widths,...@>=
20784 begin r:=link(active);
20785 if type(r)=delta_node then
20786 begin do_all_six(update_active);
20787 do_all_six(copy_to_cur_active);
20788 link(active):=link(r); free_node(r,delta_node_size);
20789 end;
20790 end
20791
20792 @* \[39] Breaking paragraphs into lines, continued.
20793 So far we have gotten a little way into the |line_break| routine, having
20794 covered its important |try_break| subroutine. Now let's consider the
20795 rest of the process.
20796
20797 The main loop of |line_break| traverses the given hlist,
20798 starting at |link(temp_head)|, and calls |try_break| at each legal
20799 breakpoint. A variable called |auto_breaking| is set to true except
20800 within math formulas, since glue nodes are not legal breakpoints when
20801 they appear in formulas.
20802
20803 The current node of interest in the hlist is pointed to by |cur_p|. Another
20804 variable, |prev_p|, is usually one step behind |cur_p|, but the real
20805 meaning of |prev_p| is this: If |type(cur_p)=glue_node| then |cur_p| is a legal
20806 breakpoint if and only if |auto_breaking| is true and |prev_p| does not
20807 point to a glue node, penalty node, explicit kern node, or math node.
20808
20809 The following declarations provide for a few other local variables that are
20810 used in special calculations.
20811
20812 @<Local variables for line breaking@>=
20813 @!auto_breaking:boolean; {is node |cur_p| outside a formula?}
20814 @!prev_p:pointer; {helps to determine when glue nodes are breakpoints}
20815 @!q,@!r,@!s,@!prev_s:pointer; {miscellaneous nodes of temporary interest}
20816 @!f:internal_font_number; {used when calculating character widths}
20817
20818 @ The `\ignorespaces|loop|\unskip' in the following code is performed at most
20819 thrice per call of |line_break|, since it is actually a pass over the
20820 entire paragraph.
20821
20822 @d update_prev_p == begin
20823 prev_p:=cur_p;
20824 global_prev_p:=cur_p;
20825 end
20826
20827 @<Find optimal breakpoints@>=
20828 threshold:=pretolerance;
20829 if threshold>=0 then
20830 begin @!stat if tracing_paragraphs>0 then
20831 begin begin_diagnostic; print_nl("@@firstpass");@+end;@;@+tats@;@/
20832 second_pass:=false; final_pass:=false;
20833 end
20834 else begin threshold:=tolerance; second_pass:=true;
20835 final_pass:=(emergency_stretch<=0);
20836 @!stat if tracing_paragraphs>0 then begin_diagnostic;@+tats@;
20837 end;
20838 loop@+ begin if threshold>inf_bad then threshold:=inf_bad;
20839 if second_pass then @<Initialize for hyphenating a paragraph@>;
20840 @<Create an active breakpoint representing the beginning of the paragraph@>;
20841 cur_p:=link(temp_head); auto_breaking:=true;@/
20842 update_prev_p; {glue at beginning is not a legal breakpoint}
20843 first_p:=cur_p; {to access the first node of paragraph as the first active
20844 node has |break_node=null|}
20845 while (cur_p<>null)and(link(active)<>last_active) do
20846 @<Call |try_break| if |cur_p| is a legal breakpoint;
20847 on the second pass, also try to hyphenate the next
20848 word, if |cur_p| is a glue node;
20849 then advance |cur_p| to the next node of the paragraph
20850 that could possibly be a legal breakpoint@>;
20851 if cur_p=null then
20852 @<Try the final line break at the end of the paragraph,
20853 and |goto done| if the desired breakpoints have been found@>;
20854 @<Clean up the memory by removing the break nodes@>;
20855 if not second_pass then
20856 begin@!stat if tracing_paragraphs>0 then print_nl("@@secondpass");@;@+tats@/
20857 threshold:=tolerance; second_pass:=true; final_pass:=(emergency_stretch<=0);
20858 end {if at first you don't succeed, \dots}
20859 else begin @!stat if tracing_paragraphs>0 then
20860 print_nl("@@emergencypass");@;@+tats@/
20861 background[2]:=background[2]+emergency_stretch; final_pass:=true;
20862 end;
20863 end;
20864 done: @!stat if tracing_paragraphs>0 then
20865 begin end_diagnostic(true); normalize_selector;
20866 end;@+tats@/
20867 if do_last_line_fit then @<Adjust \(t)the final line of the paragraph@>;
20868
20869 @ The active node that represents the starting point does not need a
20870 corresponding passive node.
20871
20872 @d store_background(#)==active_width[#]:=background[#]
20873
20874 @<Create an active breakpoint representing the beginning of the paragraph@>=
20875 q:=get_node(active_node_size);
20876 type(q):=unhyphenated; fitness(q):=decent_fit;
20877 link(q):=last_active; break_node(q):=null;
20878 line_number(q):=prev_graf+1; total_demerits(q):=0; link(active):=q;
20879 if do_last_line_fit then
20880 @<Initialize additional fields of the first active node@>;
20881 do_all_six(store_background);@/
20882 passive:=null; printed_node:=temp_head; pass_number:=0;
20883 font_in_short_display:=null_font
20884
20885 @ @<Clean...@>=
20886 q:=link(active);
20887 while q<>last_active do
20888 begin cur_p:=link(q);
20889 if type(q)=delta_node then free_node(q,delta_node_size)
20890 else free_node(q,active_node_size);
20891 q:=cur_p;
20892 end;
20893 q:=passive;
20894 while q<>null do
20895 begin cur_p:=link(q);
20896 free_node(q,passive_node_size);
20897 q:=cur_p;
20898 end
20899
20900 @ Here is the main switch in the |line_break| routine, where legal breaks
20901 are determined. As we move through the hlist, we need to keep the |active_width|
20902 array up to date, so that the badness of individual lines is readily calculated
20903 by |try_break|. It is convenient to use the short name |act_width| for
20904 the component of active width that represents real width as opposed to glue.
20905
20906 @d act_width==active_width[1] {length from first active node to current node}
20907 @d kern_break==begin if not is_char_node(link(cur_p)) and auto_breaking then
20908 if type(link(cur_p))=glue_node then try_break(0,unhyphenated);
20909 act_width:=act_width+width(cur_p);
20910 end
20911
20912 @<Call |try_break| if |cur_p| is a legal breakpoint...@>=
20913 begin if is_char_node(cur_p) then
20914 @<Advance \(c)|cur_p| to the node following the present
20915 string of characters@>;
20916 case type(cur_p) of
20917 hlist_node,vlist_node,rule_node: act_width:=act_width+width(cur_p);
20918 whatsit_node: @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>;
20919 glue_node: begin @<If node |cur_p| is a legal breakpoint, call |try_break|;
20920 then update the active widths by including the glue in |glue_ptr(cur_p)|@>;
20921 if second_pass and auto_breaking then
20922 @<Try to hyphenate the following word@>;
20923 end;
20924 kern_node: if subtype(cur_p)=explicit then kern_break
20925 else act_width:=act_width+width(cur_p);
20926 ligature_node: begin f:=font(lig_char(cur_p));
20927 xtx_ligature_present:=true;
20928 act_width:=act_width+char_width(f)(char_info(f)(character(lig_char(cur_p))));
20929 end;
20930 disc_node: @<Try to break after a discretionary fragment, then |goto done5|@>;
20931 math_node: begin if subtype(cur_p)<L_code then auto_breaking:=odd(subtype(cur_p));
20932 kern_break;
20933 end;
20934 penalty_node: try_break(penalty(cur_p),unhyphenated);
20935 mark_node,ins_node,adjust_node: do_nothing;
20936 othercases confusion("paragraph")
20937 @:this can't happen paragraph}{\quad paragraph@>
20938 endcases;@/
20939 update_prev_p; cur_p:=link(cur_p);
20940 done5:end
20941
20942 @ The code that passes over the characters of words in a paragraph is
20943 part of \TeX's inner loop, so it has been streamlined for speed. We use
20944 the fact that `\.{\\parfillskip}' glue appears at the end of each paragraph;
20945 it is therefore unnecessary to check if |link(cur_p)=null| when |cur_p| is a
20946 character node.
20947 @^inner loop@>
20948
20949 @<Advance \(c)|cur_p| to the node following the present string...@>=
20950 begin update_prev_p;
20951 repeat f:=font(cur_p);
20952 act_width:=act_width+char_width(f)(char_info(f)(character(cur_p)));
20953 cur_p:=link(cur_p);
20954 until not is_char_node(cur_p);
20955 end
20956
20957 @ When node |cur_p| is a glue node, we look at |prev_p| to see whether or not
20958 a breakpoint is legal at |cur_p|, as explained above.
20959
20960 @<If node |cur_p| is a legal breakpoint, call...@>=
20961 if auto_breaking then
20962 begin if is_char_node(prev_p) then try_break(0,unhyphenated)
20963 else if precedes_break(prev_p) then try_break(0,unhyphenated)
20964 else if (type(prev_p)=kern_node)and(subtype(prev_p)<>explicit) then
20965 try_break(0,unhyphenated);
20966 end;
20967 check_shrinkage(glue_ptr(cur_p)); q:=glue_ptr(cur_p);
20968 act_width:=act_width+width(q);@|
20969 active_width[2+stretch_order(q)]:=@|
20970 active_width[2+stretch_order(q)]+stretch(q);@/
20971 active_width[6]:=active_width[6]+shrink(q)
20972
20973 @ The following code knows that discretionary texts contain
20974 only character nodes, kern nodes, box nodes, rule nodes, and ligature nodes.
20975
20976 @<Try to break after a discretionary fragment...@>=
20977 begin s:=pre_break(cur_p); disc_width:=0;
20978 if s=null then try_break(ex_hyphen_penalty,hyphenated)
20979 else begin repeat @<Add the width of node |s| to |disc_width|@>;
20980 s:=link(s);
20981 until s=null;
20982 act_width:=act_width+disc_width;
20983 try_break(hyphen_penalty,hyphenated);
20984 act_width:=act_width-disc_width;
20985 end;
20986 r:=replace_count(cur_p); s:=link(cur_p);
20987 while r>0 do
20988 begin @<Add the width of node |s| to |act_width|@>;
20989 decr(r); s:=link(s);
20990 end;
20991 update_prev_p; cur_p:=s; goto done5;
20992 end
20993
20994 @ @<Add the width of node |s| to |disc_width|@>=
20995 if is_char_node(s) then
20996 begin f:=font(s);
20997 disc_width:=disc_width+char_width(f)(char_info(f)(character(s)));
20998 end
20999 else case type(s) of
21000 ligature_node: begin f:=font(lig_char(s));
21001 xtx_ligature_present:=true;
21002 disc_width:=disc_width+
21003 char_width(f)(char_info(f)(character(lig_char(s))));
21004 end;
21005 hlist_node,vlist_node,rule_node,kern_node:
21006 disc_width:=disc_width+width(s);
21007 whatsit_node:
21008 if (is_native_word_subtype(s))
21009 or (subtype(s)=glyph_node)
21010 or (subtype(s)=pic_node)
21011 or (subtype(s)=pdf_node)
21012 then disc_width:=disc_width+width(s)
21013 else confusion("disc3a");
21014 othercases confusion("disc3")
21015 @:this can't happen disc3}{\quad disc3@>
21016 endcases
21017
21018 @ @<Add the width of node |s| to |act_width|@>=
21019 if is_char_node(s) then
21020 begin f:=font(s);
21021 act_width:=act_width+char_width(f)(char_info(f)(character(s)));
21022 end
21023 else case type(s) of
21024 ligature_node: begin f:=font(lig_char(s));
21025 xtx_ligature_present:=true;
21026 act_width:=act_width+
21027 char_width(f)(char_info(f)(character(lig_char(s))));
21028 end;
21029 hlist_node,vlist_node,rule_node,kern_node:
21030 act_width:=act_width+width(s);
21031 whatsit_node:
21032 if (is_native_word_subtype(s))
21033 or (subtype(s)=glyph_node)
21034 or (subtype(s)=pic_node)
21035 or (subtype(s)=pdf_node)
21036 then act_width:=act_width+width(s)
21037 else confusion("disc4a");
21038 othercases confusion("disc4")
21039 @:this can't happen disc4}{\quad disc4@>
21040 endcases
21041
21042 @ The forced line break at the paragraph's end will reduce the list of
21043 breakpoints so that all active nodes represent breaks at |cur_p=null|.
21044 On the first pass, we insist on finding an active node that has the
21045 correct ``looseness.'' On the final pass, there will be at least one active
21046 node, and we will match the desired looseness as well as we can.
21047
21048 The global variable |best_bet| will be set to the active node for the best
21049 way to break the paragraph, and a few other variables are used to
21050 help determine what is best.
21051
21052 @<Glob...@>=
21053 @!best_bet:pointer; {use this passive node and its predecessors}
21054 @!fewest_demerits:integer; {the demerits associated with |best_bet|}
21055 @!best_line:halfword; {line number following the last line of the new paragraph}
21056 @!actual_looseness:integer; {the difference between |line_number(best_bet)|
21057 and the optimum |best_line|}
21058 @!line_diff:integer; {the difference between the current line number and
21059 the optimum |best_line|}
21060
21061 @ @<Try the final line break at the end of the paragraph...@>=
21062 begin try_break(eject_penalty,hyphenated);
21063 if link(active)<>last_active then
21064 begin @<Find an active node with fewest demerits@>;
21065 if looseness=0 then goto done;
21066 @<Find the best active node for the desired looseness@>;
21067 if (actual_looseness=looseness)or final_pass then goto done;
21068 end;
21069 end
21070
21071 @ @<Find an active node...@>=
21072 r:=link(active); fewest_demerits:=awful_bad;
21073 repeat if type(r)<>delta_node then if total_demerits(r)<fewest_demerits then
21074 begin fewest_demerits:=total_demerits(r); best_bet:=r;
21075 end;
21076 r:=link(r);
21077 until r=last_active;
21078 best_line:=line_number(best_bet)
21079
21080 @ The adjustment for a desired looseness is a slightly more complicated
21081 version of the loop just considered. Note that if a paragraph is broken
21082 into segments by displayed equations, each segment will be subject to the
21083 looseness calculation, independently of the other segments.
21084
21085 @<Find the best active node...@>=
21086 begin r:=link(active); actual_looseness:=0;
21087 repeat if type(r)<>delta_node then
21088 begin line_diff:=line_number(r)-best_line;
21089 if ((line_diff<actual_looseness)and(looseness<=line_diff))or@|
21090 ((line_diff>actual_looseness)and(looseness>=line_diff)) then
21091 begin best_bet:=r; actual_looseness:=line_diff;
21092 fewest_demerits:=total_demerits(r);
21093 end
21094 else if (line_diff=actual_looseness)and@|
21095 (total_demerits(r)<fewest_demerits) then
21096 begin best_bet:=r; fewest_demerits:=total_demerits(r);
21097 end;
21098 end;
21099 r:=link(r);
21100 until r=last_active;
21101 best_line:=line_number(best_bet);
21102 end
21103
21104 @ Once the best sequence of breakpoints has been found (hurray), we call on the
21105 procedure |post_line_break| to finish the remainder of the work.
21106 (By introducing this subprocedure, we are able to keep |line_break|
21107 from getting extremely long.)
21108
21109 @<Break the paragraph at the chosen...@>=
21110 post_line_break(d)
21111
21112 @ The total number of lines that will be set by |post_line_break|
21113 is |best_line-prev_graf-1|. The last breakpoint is specified by
21114 |break_node(best_bet)|, and this passive node points to the other breakpoints
21115 via the |prev_break| links. The finishing-up phase starts by linking the
21116 relevant passive nodes in forward order, changing |prev_break| to
21117 |next_break|. (The |next_break| fields actually reside in the same memory
21118 space as the |prev_break| fields did, but we give them a new name because
21119 of their new significance.) Then the lines are justified, one by one.
21120
21121 @d next_break==prev_break {new name for |prev_break| after links are reversed}
21122
21123 @<Declare subprocedures for |line_break|@>=
21124 procedure post_line_break(@!d:boolean);
21125 label done,done1;
21126 var q,@!r,@!s:pointer; {temporary registers for list manipulation}
21127 p, k: pointer;
21128 w: scaled;
21129 glue_break: boolean; {was a break at glue?}
21130 ptmp: pointer;
21131 @!disc_break:boolean; {was the current break at a discretionary node?}
21132 @!post_disc_break:boolean; {and did it have a nonempty post-break part?}
21133 @!cur_width:scaled; {width of line number |cur_line|}
21134 @!cur_indent:scaled; {left margin of line number |cur_line|}
21135 @!t:quarterword; {used for replacement counts in discretionary nodes}
21136 @!pen:integer; {use when calculating penalties between lines}
21137 @!cur_line: halfword; {the current line number being justified}
21138 @!LR_ptr:pointer; {stack of LR codes}
21139 begin LR_ptr:=LR_save;
21140 @<Reverse the links of the relevant passive nodes, setting |cur_p| to the
21141 first breakpoint@>;
21142 cur_line:=prev_graf+1;
21143 repeat @<Justify the line ending at breakpoint |cur_p|, and append it to the
21144 current vertical list, together with associated penalties and other
21145 insertions@>;
21146 incr(cur_line); cur_p:=next_break(cur_p);
21147 if cur_p<>null then if not post_disc_break then
21148 @<Prune unwanted nodes at the beginning of the next line@>;
21149 until cur_p=null;
21150 if (cur_line<>best_line)or(link(temp_head)<>null) then
21151 confusion("line breaking");
21152 @:this can't happen line breaking}{\quad line breaking@>
21153 prev_graf:=best_line-1;
21154 LR_save:=LR_ptr;
21155 end;
21156
21157 @ The job of reversing links in a list is conveniently regarded as the job
21158 of taking items off one stack and putting them on another. In this case we
21159 take them off a stack pointed to by |q| and having |prev_break| fields;
21160 we put them on a stack pointed to by |cur_p| and having |next_break| fields.
21161 Node |r| is the passive node being moved from stack to stack.
21162
21163 @<Reverse the links of the relevant passive nodes...@>=
21164 q:=break_node(best_bet); cur_p:=null;
21165 repeat r:=q; q:=prev_break(q); next_break(r):=cur_p; cur_p:=r;
21166 until q=null
21167
21168 @ Glue and penalty and kern and math nodes are deleted at the beginning of
21169 a line, except in the anomalous case that the node to be deleted is actually
21170 one of the chosen breakpoints. Otherwise
21171 the pruning done here is designed to match
21172 the lookahead computation in |try_break|, where the |break_width| values
21173 are computed for non-discretionary breakpoints.
21174
21175 @<Prune unwanted nodes at the beginning of the next line@>=
21176 begin r:=temp_head;
21177 loop@+ begin q:=link(r);
21178 if q=cur_break(cur_p) then goto done1;
21179 {|cur_break(cur_p)| is the next breakpoint}
21180 {now |q| cannot be |null|}
21181 if is_char_node(q) then goto done1;
21182 if non_discardable(q) then goto done1;
21183 if type(q)=kern_node then if (subtype(q)<>explicit) and (subtype(q)<>space_adjustment) then goto done1;
21184 r:=q; {now |type(q)=glue_node|, |kern_node|, |math_node|, or |penalty_node|}
21185 if type(q)=math_node then if TeXXeT_en then
21186 @<Adjust \(t)the LR stack for the |post_line_break| routine@>;
21187 end;
21188 done1: if r<>temp_head then
21189 begin link(r):=null; flush_node_list(link(temp_head));
21190 link(temp_head):=q;
21191 end;
21192 end
21193
21194 @ The current line to be justified appears in a horizontal list starting
21195 at |link(temp_head)| and ending at |cur_break(cur_p)|. If |cur_break(cur_p)| is
21196 a glue node, we reset the glue to equal the |right_skip| glue; otherwise
21197 we append the |right_skip| glue at the right. If |cur_break(cur_p)| is a
21198 discretionary node, we modify the list so that the discretionary break
21199 is compulsory, and we set |disc_break| to |true|. We also append
21200 the |left_skip| glue at the left of the line, unless it is zero.
21201
21202 @<Justify the line ending at breakpoint |cur_p|, and append it...@>=
21203 if TeXXeT_en then
21204 @<Insert LR nodes at the beginning of the current line and adjust
21205 the LR stack based on LR nodes in this line@>;
21206 @<Modify the end of the line to reflect the nature of the break and to include
21207 \.{\\rightskip}; also set the proper value of |disc_break|@>;
21208 if TeXXeT_en then @<Insert LR nodes at the end of the current line@>;
21209 @<Put the \(l)\.{\\leftskip} glue at the left and detach this line@>;
21210 @<Call the packaging subroutine, setting |just_box| to the justified box@>;
21211 @<Append the new box to the current vertical list, followed by the list of
21212 special nodes taken out of the box by the packager@>;
21213 @<Append a penalty node, if a nonzero penalty is appropriate@>
21214
21215 @ At the end of the following code, |q| will point to the final node on the
21216 list about to be justified.
21217
21218 @<Modify the end of the line...@>=
21219 q:=cur_break(cur_p); disc_break:=false; post_disc_break:=false;
21220 glue_break:=false;
21221 if q<>null then {|q| cannot be a |char_node|}
21222 if type(q)=glue_node then
21223 begin delete_glue_ref(glue_ptr(q));
21224 glue_ptr(q):=right_skip;
21225 subtype(q):=right_skip_code+1; add_glue_ref(right_skip);
21226 glue_break:=true;
21227 goto done;
21228 end
21229 else begin if type(q)=disc_node then
21230 @<Change discretionary to compulsory and set
21231 |disc_break:=true|@>
21232 else if type(q)=kern_node then width(q):=0
21233 else if type(q)=math_node then
21234 begin width(q):=0;
21235 if TeXXeT_en then @<Adjust \(t)the LR stack for the |p...@>;
21236 end;
21237 end
21238 else begin q:=temp_head;
21239 while link(q)<>null do q:=link(q);
21240 end;
21241 done:
21242 {at this point |q| is the rightmost breakpoint; the only exception is the case
21243 of a discretionary break with non-empty |pre_break|, then |q| has been changed
21244 to the last node of the |pre_break| list}
21245 if XeTeX_protrude_chars > 0 then begin
21246 if disc_break and (is_char_node(q) or (type(q) <> disc_node))
21247 {|q| has been reset to the last node of |pre_break|}
21248 then begin
21249 p:=q;
21250 ptmp:=p;
21251 end else begin
21252 p:=prev_rightmost(link(temp_head), q); {get |link(p) = q|}
21253 ptmp:=p;
21254 p:=find_protchar_right(link(temp_head), p);
21255 end;
21256 w:=right_pw(p);
21257 if w <> 0 then {we have found a marginal kern, append it after |ptmp|}
21258 begin
21259 k:=new_margin_kern(-w, last_rightmost_char, right_side);
21260 link(k):=link(ptmp);
21261 link(ptmp):=k;
21262 if (ptmp = q) then
21263 q:=link(q);
21264 end;
21265 end;
21266 {if |q| was not a breakpoint at glue and has been reset to |rightskip| then
21267 we append |rightskip| after |q| now}
21268 if not glue_break then begin
21269 @<Put the \(r)\.{\\rightskip} glue after node |q|@>;
21270 end;
21271
21272 @ @<Change discretionary to compulsory...@>=
21273 begin t:=replace_count(q);
21274 @<Destroy the |t| nodes following |q|, and
21275 make |r| point to the following node@>;
21276 if post_break(q)<>null then @<Transplant the post-break list@>;
21277 if pre_break(q)<>null then @<Transplant the pre-break list@>;
21278 link(q):=r; disc_break:=true;
21279 end
21280
21281 @ @<Destroy the |t| nodes following |q|...@>=
21282 if t=0 then r:=link(q)
21283 else begin r:=q;
21284 while t>1 do
21285 begin r:=link(r); decr(t);
21286 end;
21287 s:=link(r);
21288 r:=link(s); link(s):=null;
21289 flush_node_list(link(q)); replace_count(q):=0;
21290 end
21291
21292 @ We move the post-break list from inside node |q| to the main list by
21293 re\-attaching it just before the present node |r|, then resetting |r|.
21294
21295 @<Transplant the post-break list@>=
21296 begin s:=post_break(q);
21297 while link(s)<>null do s:=link(s);
21298 link(s):=r; r:=post_break(q); post_break(q):=null; post_disc_break:=true;
21299 end
21300
21301 @ We move the pre-break list from inside node |q| to the main list by
21302 re\-attaching it just after the present node |q|, then resetting |q|.
21303
21304 @<Transplant the pre-break list@>=
21305 begin s:=pre_break(q); link(q):=s;
21306 while link(s)<>null do s:=link(s);
21307 pre_break(q):=null; q:=s;
21308 end
21309
21310 @ @<Put the \(r)\.{\\rightskip} glue after node |q|@>=
21311 r:=new_param_glue(right_skip_code); link(r):=link(q); link(q):=r; q:=r
21312
21313 @ The following code begins with |q| at the end of the list to be
21314 justified. It ends with |q| at the beginning of that list, and with
21315 |link(temp_head)| pointing to the remainder of the paragraph, if any.
21316
21317 @<Put the \(l)\.{\\leftskip} glue at the left...@>=
21318 r:=link(q); link(q):=null; q:=link(temp_head); link(temp_head):=r;
21319 {at this point |q| is the leftmost node; all discardable nodes have been discarded}
21320 if XeTeX_protrude_chars > 0 then begin
21321 p:=q;
21322 p:=find_protchar_left(p, false); {no more discardables}
21323 w:=left_pw(p);
21324 if w <> 0 then begin
21325 k:=new_margin_kern(-w, last_leftmost_char, left_side);
21326 link(k):=q;
21327 q:=k;
21328 end;
21329 end;
21330 if left_skip<>zero_glue then
21331 begin r:=new_param_glue(left_skip_code);
21332 link(r):=q; q:=r;
21333 end
21334
21335 @ @<Append the new box to the current vertical list...@>=
21336 if pre_adjust_head <> pre_adjust_tail then
21337 append_list(pre_adjust_head)(pre_adjust_tail);
21338 pre_adjust_tail:=null;
21339 append_to_vlist(just_box);
21340 if adjust_head <> adjust_tail then
21341 append_list(adjust_head)(adjust_tail);
21342 adjust_tail:=null
21343
21344 @ Now |q| points to the hlist that represents the current line of the
21345 paragraph. We need to compute the appropriate line width, pack the
21346 line into a box of this size, and shift the box by the appropriate
21347 amount of indentation.
21348
21349 @<Call the packaging subroutine...@>=
21350 if cur_line>last_special_line then
21351 begin cur_width:=second_width; cur_indent:=second_indent;
21352 end
21353 else if par_shape_ptr=null then
21354 begin cur_width:=first_width; cur_indent:=first_indent;
21355 end
21356 else begin cur_width:=mem[par_shape_ptr+2*cur_line].sc;
21357 cur_indent:=mem[par_shape_ptr+2*cur_line-1].sc;
21358 end;
21359 adjust_tail:=adjust_head;
21360 pre_adjust_tail:=pre_adjust_head;
21361 just_box:=hpack(q,cur_width,exactly);
21362 shift_amount(just_box):=cur_indent
21363
21364 @ Penalties between the lines of a paragraph come from club and widow lines,
21365 from the |inter_line_penalty| parameter, and from lines that end at
21366 discretionary breaks. Breaking between lines of a two-line paragraph gets
21367 both club-line and widow-line penalties. The local variable |pen| will
21368 be set to the sum of all relevant penalties for the current line, except
21369 that the final line is never penalized.
21370
21371 @<Append a penalty node, if a nonzero penalty is appropriate@>=
21372 if cur_line+1<>best_line then
21373 begin q:=inter_line_penalties_ptr;
21374 if q<>null then
21375 begin r:=cur_line;
21376 if r>penalty(q) then r:=penalty(q);
21377 pen:=penalty(q+r);
21378 end
21379 else pen:=inter_line_penalty;
21380 q:=club_penalties_ptr;
21381 if q<>null then
21382 begin r:=cur_line-prev_graf;
21383 if r>penalty(q) then r:=penalty(q);
21384 pen:=pen+penalty(q+r);
21385 end
21386 else if cur_line=prev_graf+1 then pen:=pen+club_penalty;
21387 if d then q:=display_widow_penalties_ptr
21388 else q:=widow_penalties_ptr;
21389 if q<>null then
21390 begin r:=best_line-cur_line-1;
21391 if r>penalty(q) then r:=penalty(q);
21392 pen:=pen+penalty(q+r);
21393 end
21394 else if cur_line+2=best_line then
21395 if d then pen:=pen+display_widow_penalty
21396 else pen:=pen+widow_penalty;
21397 if disc_break then pen:=pen+broken_penalty;
21398 if pen<>0 then
21399 begin r:=new_penalty(pen);
21400 link(tail):=r; tail:=r;
21401 end;
21402 end
21403
21404 @* \[40] Pre-hyphenation.
21405 When the line-breaking routine is unable to find a feasible sequence of
21406 breakpoints, it makes a second pass over the paragraph, attempting to
21407 hyphenate the hyphenatable words. The goal of hyphenation is to insert
21408 discretionary material into the paragraph so that there are more
21409 potential places to break.
21410
21411 The general rules for hyphenation are somewhat complex and technical,
21412 because we want to be able to hyphenate words that are preceded or
21413 followed by punctuation marks, and because we want the rules to work
21414 for languages other than English. We also must contend with the fact
21415 that hyphens might radically alter the ligature and kerning structure
21416 of a word.
21417
21418 A sequence of characters will be considered for hyphenation only if it
21419 belongs to a ``potentially hyphenatable part'' of the current paragraph.
21420 This is a sequence of nodes $p_0p_1\ldots p_m$ where $p_0$ is a glue node,
21421 $p_1\ldots p_{m-1}$ are either character or ligature or whatsit or
21422 implicit kern or text direction nodes, and $p_m$ is a glue or penalty or
21423 insertion or adjust
21424 or mark or whatsit or explicit kern node. (Therefore hyphenation is
21425 disabled by boxes, math formulas, and discretionary nodes already inserted
21426 by the user.) The ligature nodes among $p_1\ldots p_{m-1}$ are effectively
21427 expanded into the original non-ligature characters; the kern nodes and
21428 whatsits are ignored. Each character |c| is now classified as either a
21429 nonletter (if |lc_code(c)=0|), a lowercase letter (if
21430 |lc_code(c)=c|), or an uppercase letter (otherwise); an uppercase letter
21431 is treated as if it were |lc_code(c)| for purposes of hyphenation. The
21432 characters generated by $p_1\ldots p_{m-1}$ may begin with nonletters; let
21433 $c_1$ be the first letter that is not in the middle of a ligature. Whatsit
21434 nodes preceding $c_1$ are ignored; a whatsit found after $c_1$ will be the
21435 terminating node $p_m$. All characters that do not have the same font as
21436 $c_1$ will be treated as nonletters. The |hyphen_char| for that font
21437 must be between 0 and 255, otherwise hyphenation will not be attempted.
21438 \TeX\ looks ahead for as many consecutive letters $c_1\ldots c_n$ as
21439 possible; however, |n| must be less than |max_hyphenatable_length+1|, so a character that would
21440 otherwise be $c_{|max_hyphenatable_length|+1}$ is effectively not a letter. Furthermore $c_n$ must
21441 not be in the middle of a ligature. In this way we obtain a string of
21442 letters $c_1\ldots c_n$ that are generated by nodes $p_a\ldots p_b$, where
21443 |1<=a<=b+1<=m|. If |n>=l_hyf+r_hyf|, this string qualifies for hyphenation;
21444 however, |uc_hyph| must be positive, if $c_1$ is uppercase.
21445
21446 The hyphenation process takes place in three stages. First, the candidate
21447 sequence $c_1\ldots c_n$ is found; then potential positions for hyphens
21448 are determined by referring to hyphenation tables; and finally, the nodes
21449 $p_a\ldots p_b$ are replaced by a new sequence of nodes that includes the
21450 discretionary breaks found.
21451
21452 Fortunately, we do not have to do all this calculation very often, because
21453 of the way it has been taken out of \TeX's inner loop. For example, when
21454 the second edition of the author's 700-page book {\sl Seminumerical
21455 Algorithms} was typeset by \TeX, only about 1.2 hyphenations needed to be
21456 @^Knuth, Donald Ervin@>
21457 tried per paragraph, since the line breaking algorithm needed to use two
21458 passes on only about 5 per cent of the paragraphs.
21459
21460 @<Initialize for hyphenating...@>=
21461 begin @!init if trie_not_ready then init_trie;@+tini@;@/
21462 cur_lang:=init_cur_lang; l_hyf:=init_l_hyf; r_hyf:=init_r_hyf;
21463 set_hyph_index;
21464 end
21465
21466 @ The letters $c_1\ldots c_n$ that are candidates for hyphenation are placed
21467 into an array called |hc|; the number |n| is placed into |hn|; pointers to
21468 nodes $p_{a-1}$ and~$p_b$ in the description above are placed into variables
21469 |ha| and |hb|; and the font number is placed into |hf|.
21470
21471 @<Glob...@>=
21472 @!hc:array[0..hyphenatable_length_limit+3] of 0..number_usvs; {word to be hyphenated}
21473 { note that element 0 needs to be a full UnicodeScalar, even though we
21474 basically work in UTF16 }
21475 @!hn:small_number; {the number of positions occupied in |hc|, 0..64 in TeX}
21476 @!ha,@!hb:pointer; {nodes |ha..hb| should be replaced by the hyphenated result}
21477 @!hf:internal_font_number; {font number of the letters in |hc|}
21478 @!hu:array[0..hyphenatable_length_limit+1] of 0..too_big_char;
21479 {like |hc|, before conversion to lowercase}
21480 @!hyf_char:integer; {hyphen character of the relevant font}
21481 @!cur_lang,@!init_cur_lang:0..biggest_lang;
21482 {current hyphenation table of interest}
21483 @!l_hyf,@!r_hyf,@!init_l_hyf,@!init_r_hyf:integer; {limits on fragment sizes}
21484 @!hyf_bchar:halfword; {boundary character after $c_n$}
21485 @!max_hyph_char:integer;
21486
21487 @ @<Set initial values of key variables@>=
21488 max_hyph_char:=too_big_lang;
21489
21490 @ Hyphenation routines need a few more local variables.
21491
21492 @<Local variables for line...@>=
21493 @!j:small_number; {an index into |hc| or |hu|}
21494 @!c:UnicodeScalar; {character being considered for hyphenation}
21495
21496 @ When the following code is activated, the |line_break| procedure is in its
21497 second pass, and |cur_p| points to a glue node.
21498
21499 @<Try to hyphenate...@>=
21500 begin prev_s:=cur_p; s:=link(prev_s);
21501 if s<>null then
21502 begin @<Skip to node |ha|, or |goto done1| if no hyphenation
21503 should be attempted@>;
21504 if l_hyf+r_hyf>max_hyphenatable_length then goto done1;
21505 if is_native_word_node(ha) then begin
21506 @<Check that nodes after |native_word| permit hyphenation; if not, |goto done1|@>;
21507 @<Prepare a |native_word_node| for hyphenation@>;
21508 end else begin
21509 @<Skip to node |hb|, putting letters into |hu| and |hc|@>;
21510 end;
21511 @<Check that the nodes following |hb| permit hyphenation and that at least
21512 |l_hyf+r_hyf| letters have been found, otherwise |goto done1|@>;
21513 hyphenate;
21514 end;
21515 done1: end
21516
21517 @ @<Declare subprocedures for |line_break|@>=
21518 @t\4@>@<Declare the function called |reconstitute|@>
21519 procedure hyphenate;
21520 label common_ending,done,found,found1,found2,not_found,exit;
21521 var @<Local variables for hyphenation@>@;
21522 begin @<Find hyphen locations for the word in |hc|, or |return|@>;
21523 @<If no hyphens were found, |return|@>;
21524 @<Replace nodes |ha..hb| by a sequence of nodes that includes
21525 the discretionary hyphens@>;
21526 exit:end;
21527
21528 function max_hyphenatable_length: integer;
21529 begin
21530 if XeTeX_hyphenatable_length>hyphenatable_length_limit then
21531 max_hyphenatable_length:=hyphenatable_length_limit
21532 else
21533 max_hyphenatable_length:=XeTeX_hyphenatable_length;
21534 end;
21535
21536 @ @<Check that nodes after |native_word| permit hyphenation; if not, |goto done1|@>=
21537 s:=link(ha);
21538 loop@+ begin if not(is_char_node(s)) then
21539 case type(s) of
21540 ligature_node: do_nothing;
21541 kern_node: if subtype(s)<>normal then goto done6;
21542 whatsit_node,glue_node,penalty_node,ins_node,adjust_node,mark_node:
21543 goto done6;
21544 othercases goto done1
21545 endcases;
21546 s:=link(s);
21547 end;
21548 done6:
21549
21550 @ @<Prepare a |native_word_node| for hyphenation@>=
21551 { note that if there are chars with |lccode = 0|, we split them out into separate |native_word| nodes }
21552 hn:=0;
21553 restart:
21554 for l:=0 to native_length(ha)-1 do begin
21555 c:=get_native_usv(ha, l);
21556 set_lc_code(c);
21557 if (hc[0] = 0) then begin
21558 if (hn > 0) then begin
21559 { we've got some letters, and now found a non-letter, so break off the tail of the |native_word|
21560 and link it after this node, and goto done3 }
21561 @<Split the |native_word_node| at |l| and link the second part after |ha|@>;
21562 goto done3;
21563 end
21564 end else if (hn = 0) and (l > 0) then begin
21565 { we've found the first letter after some non-letters, so break off the head of the |native_word| and restart }
21566 @<Split the |native_word_node| at |l| and link the second part after |ha|@>;
21567 ha:=link(ha);
21568 goto restart;
21569 end else if (hn = max_hyphenatable_length) then
21570 { reached max hyphenatable length }
21571 goto done3
21572 else begin
21573 { found a letter that is part of a potentially hyphenatable sequence }
21574 incr(hn);
21575 if c<@"10000 then begin
21576 hu[hn]:=c; hc[hn]:=hc[0];
21577 end
21578 else begin
21579 hu[hn]:=(c - @"10000) div @"400 + @"D800;
21580 hc[hn]:=(hc[0] - @"10000) div @"400 + @"D800;
21581 incr(hn);
21582 hu[hn]:=c mod @"400 + @"DC00;
21583 hc[hn]:=hc[0] mod @"400 + @"DC00;
21584 incr(l);
21585 end;
21586 hyf_bchar:=non_char;
21587 end
21588 end;
21589
21590 @ @<Split the |native_word_node| at |l| and link the second part after |ha|@>=
21591 q:=new_native_word_node(hf, native_length(ha) - l);
21592 subtype(q):=subtype(ha);
21593 for i:=l to native_length(ha) - 1 do
21594 set_native_char(q, i - l, get_native_char(ha, i));
21595 set_native_metrics(q, XeTeX_use_glyph_metrics);
21596 link(q):=link(ha);
21597 link(ha):=q;
21598 { truncate text in node |ha| }
21599 native_length(ha):=l;
21600 set_native_metrics(ha, XeTeX_use_glyph_metrics);
21601
21602 @ @<Local variables for line breaking@>=
21603 l: integer;
21604 i: integer;
21605
21606 @ The first thing we need to do is find the node |ha| just before the
21607 first letter.
21608
21609 @<Skip to node |ha|, or |goto done1|...@>=
21610 loop@+ begin if is_char_node(s) then
21611 begin c:=qo(character(s)); hf:=font(s);
21612 end
21613 else if type(s)=ligature_node then
21614 if lig_ptr(s)=null then goto continue
21615 else begin q:=lig_ptr(s); c:=qo(character(q)); hf:=font(q);
21616 end
21617 else if (type(s)=kern_node)and(subtype(s)=normal) then goto continue
21618 else if (type(s)=math_node)and(subtype(s)>=L_code) then goto continue
21619 else if type(s)=whatsit_node then
21620 begin
21621 if (is_native_word_subtype(s)) then begin
21622 { we only consider the node if it contains at least one letter, otherwise we'll skip it }
21623 for l:=0 to native_length(s) - 1 do begin
21624 c:=get_native_usv(s, l);
21625 if lc_code(c) <> 0 then begin
21626 hf:=native_font(s);
21627 prev_s:=s;
21628 if (lc_code(c)=c)or(uc_hyph>0) then goto done2
21629 else goto done1;
21630 end;
21631 if c>=@"10000 then incr(l);
21632 end
21633 end;
21634 @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>;
21635 goto continue
21636 end
21637 else goto done1;
21638 set_lc_code(c);
21639 if hc[0]<>0 then
21640 if (hc[0]=c)or(uc_hyph>0) then goto done2
21641 else goto done1;
21642 continue: prev_s:=s; s:=link(prev_s);
21643 end;
21644 done2: hyf_char:=hyphen_char[hf];
21645 if hyf_char<0 then goto done1;
21646 if hyf_char>biggest_char then goto done1;
21647 ha:=prev_s
21648
21649 @ The word to be hyphenated is now moved to the |hu| and |hc| arrays.
21650
21651 @<Skip to node |hb|, putting letters...@>=
21652 hn:=0;
21653 loop@+ begin if is_char_node(s) then
21654 begin if font(s)<>hf then goto done3;
21655 hyf_bchar:=character(s); c:=qo(hyf_bchar);
21656 set_lc_code(c);
21657 if hc[0]=0 then goto done3;
21658 if hc[0]>max_hyph_char then goto done3;
21659 if hn=max_hyphenatable_length then goto done3;
21660 hb:=s; incr(hn); hu[hn]:=c; hc[hn]:=hc[0]; hyf_bchar:=non_char;
21661 end
21662 else if type(s)=ligature_node then
21663 @<Move the characters of a ligature node to |hu| and |hc|;
21664 but |goto done3| if they are not all letters@>
21665 else if (type(s)=kern_node)and(subtype(s)=normal) then
21666 begin hb:=s;
21667 hyf_bchar:=font_bchar[hf];
21668 end
21669 else goto done3;
21670 s:=link(s);
21671 end;
21672 done3:
21673
21674 @ We let |j| be the index of the character being stored when a ligature node
21675 is being expanded, since we do not want to advance |hn| until we are sure
21676 that the entire ligature consists of letters. Note that it is possible
21677 to get to |done3| with |hn=0| and |hb| not set to any value.
21678
21679 @<Move the characters of a ligature node to |hu| and |hc|...@>=
21680 begin if font(lig_char(s))<>hf then goto done3;
21681 j:=hn; q:=lig_ptr(s);@+if q>null then hyf_bchar:=character(q);
21682 while q>null do
21683 begin c:=qo(character(q));
21684 set_lc_code(c);
21685 if hc[0]=0 then goto done3;
21686 if hc[0]>max_hyph_char then goto done3;
21687 if j=max_hyphenatable_length then goto done3;
21688 incr(j); hu[j]:=c; hc[j]:=hc[0];@/
21689 q:=link(q);
21690 end;
21691 hb:=s; hn:=j;
21692 if odd(subtype(s)) then hyf_bchar:=font_bchar[hf]@+else hyf_bchar:=non_char;
21693 end
21694
21695 @ @<Check that the nodes following |hb| permit hyphenation...@>=
21696 if hn<l_hyf+r_hyf then goto done1; {|l_hyf| and |r_hyf| are |>=1|}
21697 loop@+ begin if not(is_char_node(s)) then
21698 case type(s) of
21699 ligature_node: do_nothing;
21700 kern_node: if subtype(s)<>normal then goto done4;
21701 whatsit_node,glue_node,penalty_node,ins_node,adjust_node,mark_node:
21702 goto done4;
21703 math_node: if subtype(s)>=L_code then goto done4@+else goto done1;
21704 othercases goto done1
21705 endcases;
21706 s:=link(s);
21707 end;
21708 done4:
21709
21710 @* \[41] Post-hyphenation.
21711 If a hyphen may be inserted between |hc[j]| and |hc[j+1]|, the hyphenation
21712 procedure will set |hyf[j]| to some small odd number. But before we look
21713 at \TeX's hyphenation procedure, which is independent of the rest of the
21714 line-breaking algorithm, let us consider what we will do with the hyphens
21715 it finds, since it is better to work on this part of the program before
21716 forgetting what |ha| and |hb|, etc., are all about.
21717
21718 @<Glob...@>=
21719 @!hyf:array [0..hyphenatable_length_limit+1] of 0..9; {odd values indicate discretionary hyphens}
21720 @!init_list:pointer; {list of punctuation characters preceding the word}
21721 @!init_lig:boolean; {does |init_list| represent a ligature?}
21722 @!init_lft:boolean; {if so, did the ligature involve a left boundary?}
21723
21724 @ @<Local variables for hyphenation@>=
21725 @!i,@!j,@!l:0..hyphenatable_length_limit+2; {indices into |hc| or |hu|}
21726 @!q,@!r,@!s:pointer; {temporary registers for list manipulation}
21727 @!bchar:halfword; {boundary character of hyphenated word, or |non_char|}
21728
21729 @ \TeX\ will never insert a hyphen that has fewer than
21730 \.{\\lefthyphenmin} letters before it or fewer than
21731 \.{\\righthyphenmin} after it; hence, a short word has
21732 comparatively little chance of being hyphenated. If no hyphens have
21733 been found, we can save time by not having to make any changes to the
21734 paragraph.
21735
21736 @<If no hyphens were found, |return|@>=
21737 for j:=l_hyf to hn-r_hyf do if odd(hyf[j]) then goto found1;
21738 return;
21739 found1:
21740
21741 @ If hyphens are in fact going to be inserted, \TeX\ first deletes the
21742 subsequence of nodes between |ha| and~|hb|. An attempt is made to
21743 preserve the effect that implicit boundary characters and punctuation marks
21744 had on ligatures inside the hyphenated word, by storing a left boundary or
21745 preceding character in |hu[0]| and by storing a possible right boundary
21746 in |bchar|. We set |j:=0| if |hu[0]| is to be part of the reconstruction;
21747 otherwise |j:=1|.
21748 The variable |s| will point to the tail of the current hlist, and
21749 |q| will point to the node following |hb|, so that
21750 things can be hooked up after we reconstitute the hyphenated word.
21751
21752 @<Replace nodes |ha..hb| by a sequence of nodes...@>=
21753 if is_native_word_node(ha) then begin
21754 @<Hyphenate the |native_word_node| at |ha|@>;
21755 end else begin
21756 q:=link(hb); link(hb):=null; r:=link(ha); link(ha):=null; bchar:=hyf_bchar;
21757 if is_char_node(ha) then
21758 if font(ha)<>hf then goto found2
21759 else begin init_list:=ha; init_lig:=false; hu[0]:=qo(character(ha));
21760 end
21761 else if type(ha)=ligature_node then
21762 if font(lig_char(ha))<>hf then goto found2
21763 else begin init_list:=lig_ptr(ha); init_lig:=true; init_lft:=(subtype(ha)>1);
21764 hu[0]:=qo(character(lig_char(ha)));
21765 if init_list=null then if init_lft then
21766 begin hu[0]:=max_hyph_char; init_lig:=false;
21767 end; {in this case a ligature will be reconstructed from scratch}
21768 free_node(ha,small_node_size);
21769 end
21770 else begin {no punctuation found; look for left boundary}
21771 if not is_char_node(r) then if type(r)=ligature_node then
21772 if subtype(r)>1 then goto found2;
21773 j:=1; s:=ha; init_list:=null; goto common_ending;
21774 end;
21775 s:=cur_p; {we have |cur_p<>ha| because |type(cur_p)=glue_node|}
21776 while link(s)<>ha do s:=link(s);
21777 j:=0; goto common_ending;
21778 found2: s:=ha; j:=0; hu[0]:=max_hyph_char; init_lig:=false; init_list:=null;
21779 common_ending: flush_node_list(r);
21780 @<Reconstitute nodes for the hyphenated word, inserting discretionary hyphens@>;
21781 flush_list(init_list);
21782 end
21783
21784 @ @<Hyphenate the |native_word_node| at |ha|@>=
21785 { find the node immediately before the word to be hyphenated }
21786 s:=cur_p; {we have |cur_p<>ha| because |type(cur_p)=glue_node|}
21787 while link(s) <> ha do s:=link(s);
21788
21789 { for each hyphen position,
21790 create a |native_word_node| fragment for the text before this point,
21791 and a |disc_node| for the break, with the |hyf_char| in the |pre_break| text
21792 }
21793
21794 hyphen_passed:=0; { location of last hyphen we saw }
21795
21796 for j:=l_hyf to hn - r_hyf do begin
21797 { if this is a valid break.... }
21798 if odd(hyf[j]) then begin
21799
21800 { make a |native_word_node| for the fragment before the hyphen }
21801 q:=new_native_word_node(hf, j - hyphen_passed);
21802 subtype(q):=subtype(ha);
21803 for i:=0 to j - hyphen_passed - 1 do
21804 set_native_char(q, i, get_native_char(ha, i + hyphen_passed));
21805 set_native_metrics(q, XeTeX_use_glyph_metrics);
21806 link(s):=q; { append the new node }
21807 s:=q;
21808
21809 { make the |disc_node| for the hyphenation point }
21810 q:=new_disc;
21811 pre_break(q):=new_native_character(hf, hyf_char);
21812 link(s):=q;
21813 s:=q;
21814
21815 hyphen_passed:=j;
21816 end
21817 end;
21818
21819 { make a |native_word_node| for the last fragment of the word }
21820 hn:=native_length(ha); { ensure trailing punctuation is not lost! }
21821 q:=new_native_word_node(hf, hn - hyphen_passed);
21822 subtype(q):=subtype(ha);
21823 for i:=0 to hn - hyphen_passed - 1 do
21824 set_native_char(q, i, get_native_char(ha, i + hyphen_passed));
21825 set_native_metrics(q, XeTeX_use_glyph_metrics);
21826 link(s):=q; { append the new node }
21827 s:=q;
21828
21829 q:=link(ha);
21830 link(s):=q;
21831 link(ha):=null;
21832 flush_node_list(ha);
21833
21834 @ We must now face the fact that the battle is not over, even though the
21835 {\def\!{\kern-1pt}%
21836 hyphens have been found: The process of reconstituting a word can be nontrivial
21837 because ligatures might change when a hyphen is present. {\sl The \TeX book\/}
21838 discusses the difficulties of the word ``difficult'', and
21839 the discretionary material surrounding a
21840 hyphen can be considerably more complex than that. Suppose
21841 \.{abcdef} is a word in a font for which the only ligatures are \.{b\!c},
21842 \.{c\!d}, \.{d\!e}, and \.{e\!f}. If this word permits hyphenation
21843 between \.b and \.c, the two patterns with and without hyphenation are
21844 $\.a\,\.b\,\.-\,\.{c\!d}\,\.{e\!f}$ and $\.a\,\.{b\!c}\,\.{d\!e}\,\.f$.
21845 Thus the insertion of a hyphen might cause effects to ripple arbitrarily
21846 far into the rest of the word. A further complication arises if additional
21847 hyphens appear together with such rippling, e.g., if the word in the
21848 example just given could also be hyphenated between \.c and \.d; \TeX\
21849 avoids this by simply ignoring the additional hyphens in such weird cases.}
21850
21851 Still further complications arise in the presence of ligatures that do not
21852 delete the original characters. When punctuation precedes the word being
21853 hyphenated, \TeX's method is not perfect under all possible scenarios,
21854 because punctuation marks and letters can propagate information back and forth.
21855 For example, suppose the original pre-hyphenation pair
21856 \.{*a} changes to \.{*y} via a \.{\?=:} ligature, which changes to \.{xy}
21857 via a \.{=:\?} ligature; if $p_{a-1}=\.x$ and $p_a=\.y$, the reconstitution
21858 procedure isn't smart enough to obtain \.{xy} again. In such cases the
21859 font designer should include a ligature that goes from \.{xa} to \.{xy}.
21860
21861 @ The processing is facilitated by a subroutine called |reconstitute|. Given
21862 a string of characters $x_j\ldots x_n$, there is a smallest index $m\ge j$
21863 such that the ``translation'' of $x_j\ldots x_n$ by ligatures and kerning
21864 has the form $y_1\ldots y_t$ followed by the translation of $x_{m+1}\ldots x_n$,
21865 where $y_1\ldots y_t$ is some nonempty sequence of character, ligature, and
21866 kern nodes. We call $x_j\ldots x_m$ a ``cut prefix'' of $x_j\ldots x_n$.
21867 For example, if $x_1x_2x_3=\.{fly}$, and if the font contains `fl' as a
21868 ligature and a kern between `fl' and `y', then $m=2$, $t=2$, and $y_1$ will
21869 be a ligature node for `fl' followed by an appropriate kern node~$y_2$.
21870 In the most common case, $x_j$~forms no ligature with $x_{j+1}$ and we
21871 simply have $m=j$, $y_1=x_j$. If $m<n$ we can repeat the procedure on
21872 $x_{m+1}\ldots x_n$ until the entire translation has been found.
21873
21874 The |reconstitute| function returns the integer $m$ and puts the nodes
21875 $y_1\ldots y_t$ into a linked list starting at |link(hold_head)|,
21876 getting the input $x_j\ldots x_n$ from the |hu| array. If $x_j=256$,
21877 we consider $x_j$ to be an implicit left boundary character; in this
21878 case |j| must be strictly less than~|n|. There is a
21879 parameter |bchar|, which is either 256 or an implicit right boundary character
21880 assumed to be present just following~$x_n$. (The value |hu[n+1]| is never
21881 explicitly examined, but the algorithm imagines that |bchar| is there.)
21882
21883 If there exists an index |k| in the range $j\le k\le m$ such that |hyf[k]|
21884 is odd and such that the result of |reconstitute| would have been different
21885 if $x_{k+1}$ had been |hchar|, then |reconstitute| sets |hyphen_passed|
21886 to the smallest such~|k|. Otherwise it sets |hyphen_passed| to zero.
21887
21888 A special convention is used in the case |j=0|: Then we assume that the
21889 translation of |hu[0]| appears in a special list of charnodes starting at
21890 |init_list|; moreover, if |init_lig| is |true|, then |hu[0]| will be
21891 a ligature character, involving a left boundary if |init_lft| is |true|.
21892 This facility is provided for cases when a hyphenated
21893 word is preceded by punctuation (like single or double quotes) that might
21894 affect the translation of the beginning of the word.
21895
21896 @<Glob...@>=
21897 @!hyphen_passed:small_number; {first hyphen in a ligature, if any}
21898
21899 @ @<Declare the function called |reconstitute|@>=
21900 function reconstitute(@!j,@!n:small_number;@!bchar,@!hchar:halfword):
21901 small_number;
21902 label continue,done;
21903 var @!p:pointer; {temporary register for list manipulation}
21904 @!t:pointer; {a node being appended to}
21905 @!q:four_quarters; {character information or a lig/kern instruction}
21906 @!cur_rh:halfword; {hyphen character for ligature testing}
21907 @!test_char:halfword; {hyphen or other character for ligature testing}
21908 @!w:scaled; {amount of kerning}
21909 @!k:font_index; {position of current lig/kern instruction}
21910 begin hyphen_passed:=0; t:=hold_head; w:=0; link(hold_head):=null;
21911 {at this point |ligature_present=lft_hit=rt_hit=false|}
21912 @<Set up data structures with the cursor following position |j|@>;
21913 continue:@<If there's a ligature or kern at the cursor position, update the data
21914 structures, possibly advancing~|j|; continue until the cursor moves@>;
21915 @<Append a ligature and/or kern to the translation;
21916 |goto continue| if the stack of inserted ligatures is nonempty@>;
21917 reconstitute:=j;
21918 end;
21919
21920 @ The reconstitution procedure shares many of the global data structures
21921 by which \TeX\ has processed the words before they were hyphenated.
21922 There is an implied ``cursor'' between characters |cur_l| and |cur_r|;
21923 these characters will be tested for possible ligature activity. If
21924 |ligature_present| then |cur_l| is a ligature character formed from the
21925 original characters following |cur_q| in the current translation list.
21926 There is a ``ligature stack'' between the cursor and character |j+1|,
21927 consisting of pseudo-ligature nodes linked together by their |link| fields.
21928 This stack is normally empty unless a ligature command has created a new
21929 character that will need to be processed later. A pseudo-ligature is
21930 a special node having a |character| field that represents a potential
21931 ligature and a |lig_ptr| field that points to a |char_node| or is |null|.
21932 We have
21933 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
21934 |qi(hu[j+1])|,&if |lig_stack=null| and |j<n|;\cr
21935 bchar,&if |lig_stack=null| and |j=n|.\cr}$$
21936
21937 @<Glob...@>=
21938 @!cur_l,@!cur_r:halfword; {characters before and after the cursor}
21939 @!cur_q:pointer; {where a ligature should be detached}
21940 @!lig_stack:pointer; {unfinished business to the right of the cursor}
21941 @!ligature_present:boolean; {should a ligature node be made for |cur_l|?}
21942 @!lft_hit,@!rt_hit:boolean; {did we hit a ligature with a boundary character?}
21943
21944 @ @d append_charnode_to_t(#)== begin link(t):=get_avail; t:=link(t);
21945 font(t):=hf; character(t):=#;
21946 end
21947 @d set_cur_r==begin if j<n then cur_r:=qi(hu[j+1])@+else cur_r:=bchar;
21948 if odd(hyf[j]) then cur_rh:=hchar@+else cur_rh:=non_char;
21949 end
21950
21951 @<Set up data structures with the cursor following position |j|@>=
21952 cur_l:=qi(hu[j]); cur_q:=t;
21953 if j=0 then
21954 begin ligature_present:=init_lig; p:=init_list;
21955 if ligature_present then lft_hit:=init_lft;
21956 while p>null do
21957 begin append_charnode_to_t(character(p)); p:=link(p);
21958 end;
21959 end
21960 else if cur_l<non_char then append_charnode_to_t(cur_l);
21961 lig_stack:=null; set_cur_r
21962
21963 @ We may want to look at the lig/kern program twice, once for a hyphen
21964 and once for a normal letter. (The hyphen might appear after the letter
21965 in the program, so we'd better not try to look for both at once.)
21966
21967 @<If there's a ligature or kern at the cursor position, update...@>=
21968 if cur_l=non_char then
21969 begin k:=bchar_label[hf];
21970 if k=non_address then goto done@+else q:=font_info[k].qqqq;
21971 end
21972 else begin q:=char_info(hf)(cur_l);
21973 if char_tag(q)<>lig_tag then goto done;
21974 k:=lig_kern_start(hf)(q); q:=font_info[k].qqqq;
21975 if skip_byte(q)>stop_flag then
21976 begin k:=lig_kern_restart(hf)(q); q:=font_info[k].qqqq;
21977 end;
21978 end; {now |k| is the starting address of the lig/kern program}
21979 if cur_rh<non_char then test_char:=cur_rh@+else test_char:=cur_r;
21980 loop@+begin if next_char(q)=test_char then if skip_byte(q)<=stop_flag then
21981 if cur_rh<non_char then
21982 begin hyphen_passed:=j; hchar:=non_char; cur_rh:=non_char;
21983 goto continue;
21984 end
21985 else begin if hchar<non_char then if odd(hyf[j]) then
21986 begin hyphen_passed:=j; hchar:=non_char;
21987 end;
21988 if op_byte(q)<kern_flag then
21989 @<Carry out a ligature replacement, updating the cursor structure
21990 and possibly advancing~|j|; |goto continue| if the cursor doesn't
21991 advance, otherwise |goto done|@>;
21992 w:=char_kern(hf)(q); goto done; {this kern will be inserted below}
21993 end;
21994 if skip_byte(q)>=stop_flag then
21995 if cur_rh=non_char then goto done
21996 else begin cur_rh:=non_char; goto continue;
21997 end;
21998 k:=k+qo(skip_byte(q))+1; q:=font_info[k].qqqq;
21999 end;
22000 done:
22001
22002 @ @d wrap_lig(#)==if ligature_present then
22003 begin p:=new_ligature(hf,cur_l,link(cur_q));
22004 if lft_hit then
22005 begin subtype(p):=2; lft_hit:=false;
22006 end;
22007 if # then if lig_stack=null then
22008 begin incr(subtype(p)); rt_hit:=false;
22009 end;
22010 link(cur_q):=p; t:=p; ligature_present:=false;
22011 end
22012 @d pop_lig_stack==begin if lig_ptr(lig_stack)>null then
22013 begin link(t):=lig_ptr(lig_stack); {this is a charnode for |hu[j+1]|}
22014 t:=link(t); incr(j);
22015 end;
22016 p:=lig_stack; lig_stack:=link(p); free_node(p,small_node_size);
22017 if lig_stack=null then set_cur_r@+else cur_r:=character(lig_stack);
22018 end {if |lig_stack| isn't |null| we have |cur_rh=non_char|}
22019
22020 @<Append a ligature and/or kern to the translation...@>=
22021 wrap_lig(rt_hit);
22022 if w<>0 then
22023 begin link(t):=new_kern(w); t:=link(t); w:=0;
22024 end;
22025 if lig_stack>null then
22026 begin cur_q:=t; cur_l:=character(lig_stack); ligature_present:=true;
22027 pop_lig_stack; goto continue;
22028 end
22029
22030 @ @<Carry out a ligature replacement, updating the cursor structure...@>=
22031 begin if cur_l=non_char then lft_hit:=true;
22032 if j=n then if lig_stack=null then rt_hit:=true;
22033 check_interrupt; {allow a way out in case there's an infinite ligature loop}
22034 case op_byte(q) of
22035 qi(1),qi(5):begin cur_l:=rem_byte(q); {\.{=:\?}, \.{=:\?>}}
22036 ligature_present:=true;
22037 end;
22038 qi(2),qi(6):begin cur_r:=rem_byte(q); {\.{\?=:}, \.{\?=:>}}
22039 if lig_stack>null then character(lig_stack):=cur_r
22040 else begin lig_stack:=new_lig_item(cur_r);
22041 if j=n then bchar:=non_char
22042 else begin p:=get_avail; lig_ptr(lig_stack):=p;
22043 character(p):=qi(hu[j+1]); font(p):=hf;
22044 end;
22045 end;
22046 end;
22047 qi(3):begin cur_r:=rem_byte(q); {\.{\?=:\?}}
22048 p:=lig_stack; lig_stack:=new_lig_item(cur_r); link(lig_stack):=p;
22049 end;
22050 qi(7),qi(11):begin wrap_lig(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
22051 cur_q:=t; cur_l:=rem_byte(q); ligature_present:=true;
22052 end;
22053 othercases begin cur_l:=rem_byte(q); ligature_present:=true; {\.{=:}}
22054 if lig_stack>null then pop_lig_stack
22055 else if j=n then goto done
22056 else begin append_charnode_to_t(cur_r); incr(j); set_cur_r;
22057 end;
22058 end
22059 endcases;
22060 if op_byte(q)>qi(4) then if op_byte(q)<>qi(7) then goto done;
22061 goto continue;
22062 end
22063
22064 @ Okay, we're ready to insert the potential hyphenations that were found.
22065 When the following program is executed, we want to append the word
22066 |hu[1..hn]| after node |ha|, and node |q| should be appended to the result.
22067 During this process, the variable |i| will be a temporary
22068 index into |hu|; the variable |j| will be an index to our current position
22069 in |hu|; the variable |l| will be the counterpart of |j|, in a discretionary
22070 branch; the variable |r| will point to new nodes being created; and
22071 we need a few new local variables:
22072
22073 @<Local variables for hyph...@>=
22074 @!major_tail,@!minor_tail:pointer; {the end of lists in the main and
22075 discretionary branches being reconstructed}
22076 @!c:UnicodeScalar; {character temporarily replaced by a hyphen}
22077 @!c_loc:0..hyphenatable_length_limit; {where that character came from}
22078 @!r_count:integer; {replacement count for discretionary}
22079 @!hyf_node:pointer; {the hyphen, if it exists}
22080
22081 @ When the following code is performed, |hyf[0]| and |hyf[hn]| will be zero.
22082
22083 @<Reconstitute nodes for the hyphenated word...@>=
22084 repeat l:=j; j:=reconstitute(j,hn,bchar,qi(hyf_char))+1;
22085 if hyphen_passed=0 then
22086 begin link(s):=link(hold_head);
22087 while link(s)>null do s:=link(s);
22088 if odd(hyf[j-1]) then
22089 begin l:=j; hyphen_passed:=j-1; link(hold_head):=null;
22090 end;
22091 end;
22092 if hyphen_passed>0 then
22093 @<Create and append a discretionary node as an alternative to the
22094 unhyphenated word, and continue to develop both branches until they
22095 become equivalent@>;
22096 until j>hn;
22097 link(s):=q
22098
22099 @ In this repeat loop we will insert another discretionary if |hyf[j-1]| is
22100 odd, when both branches of the previous discretionary end at position |j-1|.
22101 Strictly speaking, we aren't justified in doing this, because we don't know
22102 that a hyphen after |j-1| is truly independent of those branches. But in almost
22103 all applications we would rather not lose a potentially valuable hyphenation
22104 point. (Consider the word `difficult', where the letter `c' is in position |j|.)
22105
22106 @d advance_major_tail==begin major_tail:=link(major_tail); incr(r_count);
22107 end
22108
22109 @<Create and append a discretionary node as an alternative...@>=
22110 repeat r:=get_node(small_node_size);
22111 link(r):=link(hold_head); type(r):=disc_node;
22112 major_tail:=r; r_count:=0;
22113 while link(major_tail)>null do advance_major_tail;
22114 i:=hyphen_passed; hyf[i]:=0;
22115 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>;
22116 @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|, appending to this
22117 list and to |major_tail| until synchronization has been achieved@>;
22118 @<Move pointer |s| to the end of the current list, and set |replace_count(r)|
22119 appropriately@>;
22120 hyphen_passed:=j-1; link(hold_head):=null;
22121 until not odd(hyf[j-1])
22122
22123 @ The new hyphen might combine with the previous character via ligature
22124 or kern. At this point we have |l-1<=i<j| and |i<hn|.
22125
22126 @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>=
22127 minor_tail:=null; pre_break(r):=null; hyf_node:=new_character(hf,hyf_char);
22128 if hyf_node<>null then
22129 begin incr(i); c:=hu[i]; hu[i]:=hyf_char; free_avail(hyf_node);
22130 end;
22131 while l<=i do
22132 begin l:=reconstitute(l,i,font_bchar[hf],non_char)+1;
22133 if link(hold_head)>null then
22134 begin if minor_tail=null then pre_break(r):=link(hold_head)
22135 else link(minor_tail):=link(hold_head);
22136 minor_tail:=link(hold_head);
22137 while link(minor_tail)>null do minor_tail:=link(minor_tail);
22138 end;
22139 end;
22140 if hyf_node<>null then
22141 begin hu[i]:=c; {restore the character in the hyphen position}
22142 l:=i; decr(i);
22143 end
22144
22145 @ The synchronization algorithm begins with |l=i+1<=j|.
22146
22147 @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|...@>=
22148 minor_tail:=null; post_break(r):=null; c_loc:=0;
22149 if bchar_label[hf]<>non_address then {put left boundary at beginning of new line}
22150 begin decr(l); c:=hu[l]; c_loc:=l; hu[l]:=max_hyph_char;
22151 end;
22152 while l<j do
22153 begin repeat l:=reconstitute(l,hn,bchar,non_char)+1;
22154 if c_loc>0 then
22155 begin hu[c_loc]:=c; c_loc:=0;
22156 end;
22157 if link(hold_head)>null then
22158 begin if minor_tail=null then post_break(r):=link(hold_head)
22159 else link(minor_tail):=link(hold_head);
22160 minor_tail:=link(hold_head);
22161 while link(minor_tail)>null do minor_tail:=link(minor_tail);
22162 end;
22163 until l>=j;
22164 while l>j do
22165 @<Append characters of |hu[j..@,]| to |major_tail|, advancing~|j|@>;
22166 end
22167
22168 @ @<Append characters of |hu[j..@,]|...@>=
22169 begin j:=reconstitute(j,hn,bchar,non_char)+1;
22170 link(major_tail):=link(hold_head);
22171 while link(major_tail)>null do advance_major_tail;
22172 end
22173
22174 @ Ligature insertion can cause a word to grow exponentially in size. Therefore
22175 we must test the size of |r_count| here, even though the hyphenated text
22176 was at most |max_hyphenatable_length| characters long.
22177
22178 @<Move pointer |s| to the end of the current list...@>=
22179 if r_count>127 then {we have to forget the discretionary hyphen}
22180 begin link(s):=link(r); link(r):=null; flush_node_list(r);
22181 end
22182 else begin link(s):=r; replace_count(r):=r_count;
22183 end;
22184 s:=major_tail
22185
22186 @* \[42] Hyphenation.
22187 When a word |hc[1..hn]| has been set up to contain a candidate for hyphenation,
22188 \TeX\ first looks to see if it is in the user's exception dictionary. If not,
22189 hyphens are inserted based on patterns that appear within the given word,
22190 using an algorithm due to Frank~M. Liang.
22191 @^Liang, Franklin Mark@>
22192
22193 Let's consider Liang's method first, since it is much more interesting than the
22194 exception-lookup routine. The algorithm begins by setting |hyf[j]| to zero
22195 for all |j|, and invalid characters are inserted into |hc[0]|
22196 and |hc[hn+1]| to serve as delimiters. Then a reasonably fast method is
22197 used to see which of a given set of patterns occurs in the word
22198 |hc[0..(hn+1)]|. Each pattern $p_1\ldots p_k$ of length |k| has an associated
22199 sequence of |k+1| numbers $n_0\ldots n_k$; and if the pattern occurs in
22200 |hc[(j+1)..(j+k)]|, \TeX\ will set |hyf[j+i]:=@tmax@>(hyf[j+i],@t$n_i$@>)| for
22201 |0<=i<=k|. After this has been done for each pattern that occurs, a
22202 discretionary hyphen will be inserted between |hc[j]| and |hc[j+1]| when
22203 |hyf[j]| is odd, as we have already seen.
22204
22205 The set of patterns $p_1\ldots p_k$ and associated numbers $n_0\ldots n_k$
22206 depends, of course, on the language whose words are being hyphenated, and
22207 on the degree of hyphenation that is desired. A method for finding
22208 appropriate |p|'s and |n|'s, from a given dictionary of words and acceptable
22209 hyphenations, is discussed in Liang's Ph.D. thesis (Stanford University,
22210 1983); \TeX\ simply starts with the patterns and works from there.
22211
22212 @ The patterns are stored in a compact table that is also efficient for
22213 retrieval, using a variant of ``trie memory'' [cf.\ {\sl The Art of
22214 Computer Programming \bf3} (1973), 481--505]. We can find each pattern
22215 $p_1\ldots p_k$ by letting $z_0$ be one greater than the relevant language
22216 index and then, for |1<=i<=k|,
22217 setting |@t$z_i$@>:=trie_link@t$(z_{i-1})+p_i$@>|; the pattern will be
22218 identified by the number $z_k$. Since all the pattern information is
22219 packed together into a single |trie_link| array, it is necessary to
22220 prevent confusion between the data from inequivalent patterns, so another
22221 table is provided such that |trie_char@t$(z_i)=p_i$@>| for all |i|. There
22222 is also a table |trie_op|$(z_k)$ to identify the numbers $n_0\ldots n_k$
22223 associated with $p_1\ldots p_k$.
22224
22225 Comparatively few different number sequences $n_0\ldots n_k$ actually occur,
22226 since most of the |n|'s are generally zero. Therefore the number sequences
22227 are encoded in such a way that |trie_op|$(z_k)$ is only one byte long.
22228 If |trie_op(@t$z_k$@>)<>min_quarterword|, when $p_1\ldots p_k$ has matched
22229 the letters in |hc[(l-k+1)..l@,]| of language |t|,
22230 we perform all of the required operations
22231 for this pattern by carrying out the following little program: Set
22232 |v:=trie_op(@t$z_k$@>)|. Then set |v:=v+op_start[t]|,
22233 |hyf[l-hyf_distance[v]]:=@tmax@>(hyf[l-hyf_distance[v]], hyf_num[v])|,
22234 and |v:=hyf_next[v]|; repeat, if necessary, until |v=min_quarterword|.
22235
22236 @<Types...@>=
22237 @!trie_pointer=0..trie_size; {an index into |trie|}
22238
22239 @ @d trie_link(#)==trie[#].rh {``downward'' link in a trie}
22240 @d trie_char(#)==trie[#].b1 {character matched at this trie location}
22241 @d trie_op(#)==trie[#].b0 {program for hyphenation at this trie location}
22242
22243 @<Glob...@>=
22244 @!trie:array[trie_pointer] of two_halves; {|trie_link|, |trie_char|, |trie_op|}
22245 @!hyf_distance:array[1..trie_op_size] of small_number; {position |k-j| of $n_j$}
22246 @!hyf_num:array[1..trie_op_size] of small_number; {value of $n_j$}
22247 @!hyf_next:array[1..trie_op_size] of quarterword; {continuation code}
22248 @!op_start:array[0..biggest_lang] of 0..trie_op_size; {offset for current language}
22249
22250 @ @<Local variables for hyph...@>=
22251 @!z:trie_pointer; {an index into |trie|}
22252 @!v:integer; {an index into |hyf_distance|, etc.}
22253
22254 @ Assuming that these auxiliary tables have been set up properly, the
22255 hyphenation algorithm is quite short. In the following code we set |hc[hn+2]|
22256 to the impossible value 256, in order to guarantee that |hc[hn+3]| will
22257 never be fetched.
22258
22259 @<Find hyphen locations for the word in |hc|...@>=
22260 for j:=0 to hn do hyf[j]:=0;
22261 @<Look for the word |hc[1..hn]| in the exception table, and |goto found| (with
22262 |hyf| containing the hyphens) if an entry is found@>;
22263 if trie_char(cur_lang+1)<>qi(cur_lang) then return; {no patterns for |cur_lang|}
22264 hc[0]:=0; hc[hn+1]:=0; hc[hn+2]:=max_hyph_char; {insert delimiters}
22265 for j:=0 to hn-r_hyf+1 do
22266 begin z:=trie_link(cur_lang+1)+hc[j]; l:=j;
22267 while hc[l]=qo(trie_char(z)) do
22268 begin if trie_op(z)<>min_quarterword then
22269 @<Store \(m)maximum values in the |hyf| table@>;
22270 incr(l); z:=trie_link(z)+hc[l];
22271 end;
22272 end;
22273 found: for j:=0 to l_hyf-1 do hyf[j]:=0;
22274 for j:=0 to r_hyf-1 do hyf[hn-j]:=0
22275
22276 @ @<Store \(m)maximum values in the |hyf| table@>=
22277 begin v:=trie_op(z);
22278 repeat v:=v+op_start[cur_lang]; i:=l-hyf_distance[v];
22279 if hyf_num[v]>hyf[i] then hyf[i]:=hyf_num[v];
22280 v:=hyf_next[v];
22281 until v=min_quarterword;
22282 end
22283
22284 @ The exception table that is built by \TeX's \.{\\hyphenation} primitive is
22285 organized as an ordered hash table [cf.\ Amble and Knuth, {\sl The Computer
22286 @^Amble, Ole@> @^Knuth, Donald Ervin@>
22287 Journal\/ \bf17} (1974), 135--142] using linear probing. If $\alpha$ and
22288 $\beta$ are words, we will say that $\alpha<\beta$ if $\vert\alpha\vert<
22289 \vert\beta\vert$ or if $\vert\alpha\vert=\vert\beta\vert$ and
22290 $\alpha$ is lexicographically smaller than $\beta$. (The notation $\vert
22291 \alpha\vert$ stands for the length of $\alpha$.) The idea of ordered hashing
22292 is to arrange the table so that a given word $\alpha$ can be sought by computing
22293 a hash address $h=h(\alpha)$ and then looking in table positions |h|, |h-1|,
22294 \dots, until encountering the first word $\L\alpha$. If this word is
22295 different from $\alpha$, we can conclude that $\alpha$ is not in the table.
22296
22297 The words in the table point to lists in |mem| that specify hyphen positions
22298 in their |info| fields. The list for $c_1\ldots c_n$ contains the number |k| if
22299 the word $c_1\ldots c_n$ has a discretionary hyphen between $c_k$ and
22300 $c_{k+1}$.
22301
22302 @<Types...@>=
22303 @!hyph_pointer=0..hyph_size; {an index into the ordered hash table}
22304
22305 @ @<Glob...@>=
22306 @!hyph_word:array[hyph_pointer] of str_number; {exception words}
22307 @!hyph_list:array[hyph_pointer] of pointer; {lists of hyphen positions}
22308 @!hyph_count:hyph_pointer; {the number of words in the exception dictionary}
22309
22310 @ @<Local variables for init...@>=
22311 @!z:hyph_pointer; {runs through the exception dictionary}
22312
22313 @ @<Set init...@>=
22314 for z:=0 to hyph_size do
22315 begin hyph_word[z]:=0; hyph_list[z]:=null;
22316 end;
22317 hyph_count:=0;
22318
22319 @ The algorithm for exception lookup is quite simple, as soon as we have
22320 a few more local variables to work with.
22321
22322 @<Local variables for hyph...@>=
22323 @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
22324 @!k:str_number; {an index into |str_start|}
22325 @!u:pool_pointer; {an index into |str_pool|}
22326
22327 @ First we compute the hash code |h|, then we search until we either
22328 find the word or we don't. Words from different languages are kept
22329 separate by appending the language code to the string.
22330
22331 @<Look for the word |hc[1...@>=
22332 h:=hc[1]; incr(hn); hc[hn]:=cur_lang;
22333 for j:=2 to hn do h:=(h+h+hc[j]) mod hyph_size;
22334 loop@+ begin @<If the string |hyph_word[h]| is less than \(hc)|hc[1..hn]|,
22335 |goto not_found|; but if the two strings are equal,
22336 set |hyf| to the hyphen positions and |goto found|@>;
22337 if h>0 then decr(h)@+else h:=hyph_size;
22338 end;
22339 not_found: decr(hn)
22340
22341 @ @<If the string |hyph_word[h]| is less than \(hc)...@>=
22342 k:=hyph_word[h]; if k=0 then goto not_found;
22343 if length(k)<hn then goto not_found;
22344 if length(k)=hn then
22345 begin j:=1; u:=str_start_macro(k);
22346 repeat if so(str_pool[u])<hc[j] then goto not_found;
22347 if so(str_pool[u])>hc[j] then goto done;
22348 incr(j); incr(u);
22349 until j>hn;
22350 @<Insert hyphens as specified in |hyph_list[h]|@>;
22351 decr(hn); goto found;
22352 end;
22353 done:
22354
22355 @ @<Insert hyphens as specified...@>=
22356 s:=hyph_list[h];
22357 while s<>null do
22358 begin hyf[info(s)]:=1; s:=link(s);
22359 end
22360
22361 @ @<Search |hyph_list| for pointers to |p|@>=
22362 for q:=0 to hyph_size do
22363 begin if hyph_list[q]=p then
22364 begin print_nl("HYPH("); print_int(q); print_char(")");
22365 end;
22366 end
22367
22368 @ We have now completed the hyphenation routine, so the |line_break| procedure
22369 is finished at last. Since the hyphenation exception table is fresh in our
22370 minds, it's a good time to deal with the routine that adds new entries to it.
22371
22372 When \TeX\ has scanned `\.{\\hyphenation}', it calls on a procedure named
22373 |new_hyph_exceptions| to do the right thing.
22374
22375 @d set_cur_lang==if language<=0 then cur_lang:=0
22376 else if language>biggest_lang then cur_lang:=0
22377 else cur_lang:=language
22378
22379 @p procedure new_hyph_exceptions; {enters new exceptions}
22380 label reswitch, exit, found, not_found, not_found1;
22381 var n:0..hyphenatable_length_limit+1; {length of current word; not always a |small_number|}
22382 @!j:0..hyphenatable_length_limit+1; {an index into |hc|}
22383 @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
22384 @!k:str_number; {an index into |str_start|}
22385 @!p:pointer; {head of a list of hyphen positions}
22386 @!q:pointer; {used when creating a new node for list |p|}
22387 @!s,@!t:str_number; {strings being compared or stored}
22388 @!u,@!v:pool_pointer; {indices into |str_pool|}
22389 begin scan_left_brace; {a left brace must follow \.{\\hyphenation}}
22390 set_cur_lang;
22391 @!init if trie_not_ready then
22392 begin hyph_index:=0; goto not_found1;
22393 end;
22394 tini@/
22395 set_hyph_index;
22396 not_found1:
22397 @<Enter as many hyphenation exceptions as are listed,
22398 until coming to a right brace; then |return|@>;
22399 exit:end;
22400
22401 @ @<Enter as many...@>=
22402 n:=0; p:=null;
22403 loop@+ begin get_x_token;
22404 reswitch: case cur_cmd of
22405 letter,other_char,char_given:@<Append a new letter or hyphen@>;
22406 char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
22407 goto reswitch;
22408 end;
22409 spacer,right_brace: begin if n>1 then @<Enter a hyphenation exception@>;
22410 if cur_cmd=right_brace then return;
22411 n:=0; p:=null;
22412 end;
22413 othercases @<Give improper \.{\\hyphenation} error@>
22414 endcases;
22415 end
22416
22417 @ @<Give improper \.{\\hyph...@>=
22418 begin print_err("Improper "); print_esc("hyphenation");
22419 @.Improper \\hyphenation...@>
22420 print(" will be flushed");
22421 help2("Hyphenation exceptions must contain only letters")@/
22422 ("and hyphens. But continue; I'll forgive and forget.");
22423 error;
22424 end
22425
22426 @ @<Append a new letter or hyphen@>=
22427 if cur_chr="-" then @<Append the value |n| to list |p|@>
22428 else begin set_lc_code(cur_chr);
22429 if hc[0]=0 then
22430 begin print_err("Not a letter");
22431 @.Not a letter@>
22432 help2("Letters in \hyphenation words must have \lccode>0.")@/
22433 ("Proceed; I'll ignore the character I just read.");
22434 error;
22435 end
22436 else if n<max_hyphenatable_length then
22437 begin incr(n);
22438 if hc[0]<@"10000 then hc[n]:=hc[0]
22439 else begin
22440 hc[n]:=(hc[0] - @"10000) div @"400 + @"D800;
22441 incr(n);
22442 hc[n]:=hc[0] mod @"400 + @"DC00;
22443 end;
22444 end;
22445 end
22446
22447 @ @<Append the value |n| to list |p|@>=
22448 begin if n<max_hyphenatable_length then
22449 begin q:=get_avail; link(q):=p; info(q):=n; p:=q;
22450 end;
22451 end
22452
22453 @ @<Enter a hyphenation exception@>=
22454 begin incr(n); hc[n]:=cur_lang; str_room(n); h:=0;
22455 for j:=1 to n do
22456 begin h:=(h+h+hc[j]) mod hyph_size;
22457 append_char(hc[j]);
22458 end;
22459 s:=make_string;
22460 @<Insert the \(p)pair |(s,p)| into the exception table@>;
22461 end
22462
22463 @ @<Insert the \(p)pair |(s,p)|...@>=
22464 if hyph_count=hyph_size then overflow("exception dictionary",hyph_size);
22465 @:TeX capacity exceeded exception dictionary}{\quad exception dictionary@>
22466 incr(hyph_count);
22467 while hyph_word[h]<>0 do
22468 begin @<If the string |hyph_word[h]| is less than \(or)or equal to
22469 |s|, interchange |(hyph_word[h],hyph_list[h])| with |(s,p)|@>;
22470 if h>0 then decr(h)@+else h:=hyph_size;
22471 end;
22472 hyph_word[h]:=s; hyph_list[h]:=p
22473
22474 @ @<If the string |hyph_word[h]| is less than \(or)...@>=
22475 k:=hyph_word[h];
22476 if length(k)<length(s) then goto found;
22477 if length(k)>length(s) then goto not_found;
22478 u:=str_start_macro(k); v:=str_start_macro(s);
22479 repeat if str_pool[u]<str_pool[v] then goto found;
22480 if str_pool[u]>str_pool[v] then goto not_found;
22481 incr(u); incr(v);
22482 until u=str_start_macro(k+1);
22483 found:q:=hyph_list[h]; hyph_list[h]:=p; p:=q;@/
22484 t:=hyph_word[h]; hyph_word[h]:=s; s:=t;
22485 not_found:
22486
22487 @* \[43] Initializing the hyphenation tables.
22488 The trie for \TeX's hyphenation algorithm is built from a sequence of
22489 patterns following a \.{\\patterns} specification. Such a specification
22490 is allowed only in \.{INITEX}, since the extra memory for auxiliary tables
22491 and for the initialization program itself would only clutter up the
22492 production version of \TeX\ with a lot of deadwood.
22493
22494 The first step is to build a trie that is linked, instead of packed
22495 into sequential storage, so that insertions are readily made.
22496 After all patterns have been processed, \.{INITEX}
22497 compresses the linked trie by identifying common subtries. Finally the
22498 trie is packed into the efficient sequential form that the hyphenation
22499 algorithm actually uses.
22500
22501 @<Declare subprocedures for |line_break|@>=
22502 @!init @<Declare procedures for preprocessing hyphenation patterns@>@;
22503 tini
22504
22505 @ Before we discuss trie building in detail, let's consider the simpler
22506 problem of creating the |hyf_distance|, |hyf_num|, and |hyf_next| arrays.
22507
22508 Suppose, for example, that \TeX\ reads the pattern `\.{ab2cde1}'. This is
22509 a pattern of length 5, with $n_0\ldots n_5=0\,0\,2\,0\,0\,1$ in the
22510 notation above. We want the corresponding |trie_op| code |v| to have
22511 |hyf_distance[v]=3|, |hyf_num[v]=2|, and |hyf_next[v]=@t$v^\prime$@>|,
22512 where the auxiliary |trie_op| code $v^\prime$ has
22513 |hyf_distance[@t$v^\prime$@>]=0|, |hyf_num[@t$v^\prime$@>]=1|, and
22514 |hyf_next[@t$v^\prime$@>]=min_quarterword|.
22515
22516 \TeX\ computes an appropriate value |v| with the |new_trie_op| subroutine
22517 below, by setting
22518 $$\hbox{|@t$v^\prime$@>:=new_trie_op(0,1,min_quarterword)|,\qquad
22519 |v:=new_trie_op(3,2,@t$v^\prime$@>)|.}$$
22520 This subroutine looks up its three
22521 parameters in a special hash table, assigning a new value only if these
22522 three have not appeared before for the current language.
22523
22524 The hash table is called |trie_op_hash|, and the number of entries it contains
22525 is |trie_op_ptr|.
22526
22527 @<Glob...@>=
22528 @!init @!trie_op_hash:array[-trie_op_size..trie_op_size] of 0..trie_op_size;
22529 {trie op codes for quadruples}
22530 @!trie_used:array[ASCII_code] of quarterword;
22531 {largest opcode used so far for this language}
22532 @!trie_op_lang:array[1..trie_op_size] of 0..biggest_lang;
22533 {language part of a hashed quadruple}
22534 @!trie_op_val:array[1..trie_op_size] of quarterword;
22535 {opcode corresponding to a hashed quadruple}
22536 @!trie_op_ptr:0..trie_op_size; {number of stored ops so far}
22537 tini
22538
22539 @ It's tempting to remove the |overflow| stops in the following procedure;
22540 |new_trie_op| could return |min_quarterword| (thereby simply ignoring
22541 part of a hyphenation pattern) instead of aborting the job. However, that would
22542 lead to different hyphenation results on different installations of \TeX\
22543 using the same patterns. The |overflow| stops are necessary for portability
22544 of patterns.
22545
22546 @<Declare procedures for preprocessing hyph...@>=
22547 function new_trie_op(@!d,@!n:small_number;@!v:quarterword):quarterword;
22548 label exit;
22549 var h:-trie_op_size..trie_op_size; {trial hash location}
22550 @!u:quarterword; {trial op code}
22551 @!l:0..trie_op_size; {pointer to stored data}
22552 begin h:=abs(n+313*d+361*v+1009*cur_lang) mod (trie_op_size+trie_op_size)
22553 - trie_op_size;
22554 loop@+ begin l:=trie_op_hash[h];
22555 if l=0 then {empty position found for a new op}
22556 begin if trie_op_ptr=trie_op_size then
22557 overflow("pattern memory ops",trie_op_size);
22558 u:=trie_used[cur_lang];
22559 if u=max_quarterword then
22560 overflow("pattern memory ops per language",
22561 max_quarterword-min_quarterword);
22562 incr(trie_op_ptr); incr(u); trie_used[cur_lang]:=u;
22563 hyf_distance[trie_op_ptr]:=d;
22564 hyf_num[trie_op_ptr]:=n; hyf_next[trie_op_ptr]:=v;
22565 trie_op_lang[trie_op_ptr]:=cur_lang; trie_op_hash[h]:=trie_op_ptr;
22566 trie_op_val[trie_op_ptr]:=u; new_trie_op:=u; return;
22567 end;
22568 if (hyf_distance[l]=d)and(hyf_num[l]=n)and(hyf_next[l]=v)
22569 and(trie_op_lang[l]=cur_lang) then
22570 begin new_trie_op:=trie_op_val[l]; return;
22571 end;
22572 if h>-trie_op_size then decr(h)@+else h:=trie_op_size;
22573 end;
22574 exit:end;
22575
22576 @ After |new_trie_op| has compressed the necessary opcode information,
22577 plenty of information is available to unscramble the data into the
22578 final form needed by our hyphenation algorithm.
22579
22580 @<Sort \(t)the hyphenation op tables into proper order@>=
22581 op_start[0]:=-min_quarterword;
22582 for j:=1 to biggest_lang do op_start[j]:=op_start[j-1]+qo(trie_used[j-1]);
22583 for j:=1 to trie_op_ptr do
22584 trie_op_hash[j]:=op_start[trie_op_lang[j]]+trie_op_val[j]; {destination}
22585 for j:=1 to trie_op_ptr do while trie_op_hash[j]>j do
22586 begin k:=trie_op_hash[j];@/
22587 t:=hyf_distance[k]; hyf_distance[k]:=hyf_distance[j]; hyf_distance[j]:=t;@/
22588 t:=hyf_num[k]; hyf_num[k]:=hyf_num[j]; hyf_num[j]:=t;@/
22589 t:=hyf_next[k]; hyf_next[k]:=hyf_next[j]; hyf_next[j]:=t;@/
22590 trie_op_hash[j]:=trie_op_hash[k]; trie_op_hash[k]:=k;
22591 end
22592
22593 @ Before we forget how to initialize the data structures that have been
22594 mentioned so far, let's write down the code that gets them started.
22595
22596 @<Initialize table entries...@>=
22597 for k:=-trie_op_size to trie_op_size do trie_op_hash[k]:=0;
22598 for k:=0 to 255 do trie_used[k]:=min_quarterword;
22599 trie_op_ptr:=0;
22600
22601 @ The linked trie that is used to preprocess hyphenation patterns appears
22602 in several global arrays. Each node represents an instruction of the form
22603 ``if you see character |c|, then perform operation |o|, move to the
22604 next character, and go to node |l|; otherwise go to node |r|.''
22605 The four quantities |c|, |o|, |l|, and |r| are stored in four arrays
22606 |trie_c|, |trie_o|, |trie_l|, and |trie_r|. The root of the trie
22607 is |trie_l[0]|, and the number of nodes is |trie_ptr|. Null trie
22608 pointers are represented by zero. To initialize the trie, we simply
22609 set |trie_l[0]| and |trie_ptr| to zero. We also set |trie_c[0]| to some
22610 arbitrary value, since the algorithm may access it.
22611
22612 The algorithms maintain the condition
22613 $$\hbox{|trie_c[trie_r[z]]>trie_c[z]|\qquad
22614 whenever |z<>0| and |trie_r[z]<>0|};$$ in other words, sibling nodes are
22615 ordered by their |c| fields.
22616
22617 @d trie_root==trie_l[0] {root of the linked trie}
22618
22619 @<Glob...@>=
22620 @!init @!trie_c:packed array[trie_pointer] of packed_ASCII_code;
22621 {characters to match}
22622 @t\hskip10pt@>@!trie_o:packed array[trie_pointer] of quarterword;
22623 {operations to perform}
22624 @t\hskip10pt@>@!trie_l:packed array[trie_pointer] of trie_pointer;
22625 {left subtrie links}
22626 @t\hskip10pt@>@!trie_r:packed array[trie_pointer] of trie_pointer;
22627 {right subtrie links}
22628 @t\hskip10pt@>@!trie_ptr:trie_pointer; {the number of nodes in the trie}
22629 @t\hskip10pt@>@!trie_hash:packed array[trie_pointer] of trie_pointer;
22630 {used to identify equivalent subtries}
22631 tini
22632
22633 @ Let us suppose that a linked trie has already been constructed.
22634 Experience shows that we can often reduce its size by recognizing common
22635 subtries; therefore another hash table is introduced for this purpose,
22636 somewhat similar to |trie_op_hash|. The new hash table will be
22637 initialized to zero.
22638
22639 The function |trie_node(p)| returns |p| if |p| is distinct from other nodes
22640 that it has seen, otherwise it returns the number of the first equivalent
22641 node that it has seen.
22642
22643 Notice that we might make subtries equivalent even if they correspond to
22644 patterns for different languages, in which the trie ops might mean quite
22645 different things. That's perfectly all right.
22646
22647 @<Declare procedures for preprocessing hyph...@>=
22648 function trie_node(@!p:trie_pointer):trie_pointer; {converts
22649 to a canonical form}
22650 label exit;
22651 var h:trie_pointer; {trial hash location}
22652 @!q:trie_pointer; {trial trie node}
22653 begin h:=abs(trie_c[p]+1009*trie_o[p]+@|
22654 2718*trie_l[p]+3142*trie_r[p]) mod trie_size;
22655 loop@+ begin q:=trie_hash[h];
22656 if q=0 then
22657 begin trie_hash[h]:=p; trie_node:=p; return;
22658 end;
22659 if (trie_c[q]=trie_c[p])and(trie_o[q]=trie_o[p])and@|
22660 (trie_l[q]=trie_l[p])and(trie_r[q]=trie_r[p]) then
22661 begin trie_node:=q; return;
22662 end;
22663 if h>0 then decr(h)@+else h:=trie_size;
22664 end;
22665 exit:end;
22666
22667 @ A neat recursive procedure is now able to compress a trie by
22668 traversing it and applying |trie_node| to its nodes in ``bottom up''
22669 fashion. We will compress the entire trie by clearing |trie_hash| to
22670 zero and then saying `|trie_root:=compress_trie(trie_root)|'.
22671 @^recursion@>
22672
22673 @<Declare procedures for preprocessing hyph...@>=
22674 function compress_trie(@!p:trie_pointer):trie_pointer;
22675 begin if p=0 then compress_trie:=0
22676 else begin trie_l[p]:=compress_trie(trie_l[p]);
22677 trie_r[p]:=compress_trie(trie_r[p]);
22678 compress_trie:=trie_node(p);
22679 end;
22680 end;
22681
22682 @ The compressed trie will be packed into the |trie| array using a
22683 ``top-down first-fit'' procedure. This is a little tricky, so the reader
22684 should pay close attention: The |trie_hash| array is cleared to zero
22685 again and renamed |trie_ref| for this phase of the operation; later on,
22686 |trie_ref[p]| will be nonzero only if the linked trie node |p| is the
22687 smallest character
22688 in a family and if the characters |c| of that family have been allocated to
22689 locations |trie_ref[p]+c| in the |trie| array. Locations of |trie| that
22690 are in use will have |trie_link=0|, while the unused holes in |trie|
22691 will be doubly linked with |trie_link| pointing to the next larger vacant
22692 location and |trie_back| pointing to the next smaller one. This double
22693 linking will have been carried out only as far as |trie_max|, where
22694 |trie_max| is the largest index of |trie| that will be needed.
22695 To save time at the low end of the trie, we maintain array entries
22696 |trie_min[c]| pointing to the smallest hole that is greater than~|c|.
22697 Another array |trie_taken| tells whether or not a given location is
22698 equal to |trie_ref[p]| for some |p|; this array is used to ensure that
22699 distinct nodes in the compressed trie will have distinct |trie_ref|
22700 entries.
22701
22702 @d trie_ref==trie_hash {where linked trie families go into |trie|}
22703 @d trie_back(#)==trie[#].lh {backward links in |trie| holes}
22704
22705 @<Glob...@>=
22706 @!init @!trie_taken:packed array[1..trie_size] of boolean;
22707 {does a family start here?}
22708 @t\hskip10pt@>@!trie_min:array[ASCII_code] of trie_pointer;
22709 {the first possible slot for each character}
22710 @t\hskip10pt@>@!trie_max:trie_pointer; {largest location used in |trie|}
22711 @t\hskip10pt@>@!trie_not_ready:boolean; {is the trie still in linked form?}
22712 tini
22713
22714 @ Each time \.{\\patterns} appears, it contributes further patterns to
22715 the future trie, which will be built only when hyphenation is attempted or
22716 when a format file is dumped. The boolean variable |trie_not_ready|
22717 will change to |false| when the trie is compressed; this will disable
22718 further patterns.
22719
22720 @<Initialize table entries...@>=
22721 trie_not_ready:=true; trie_root:=0; trie_c[0]:=si(0); trie_ptr:=0;
22722
22723 @ Here is how the trie-compression data structures are initialized.
22724 If storage is tight, it would be possible to overlap |trie_op_hash|,
22725 |trie_op_lang|, and |trie_op_val| with |trie|, |trie_hash|, and |trie_taken|,
22726 because we finish with the former just before we need the latter.
22727
22728 @<Get ready to compress the trie@>=
22729 @<Sort \(t)the hyphenation...@>;
22730 for p:=0 to trie_size do trie_hash[p]:=0;
22731 hyph_root:=compress_trie(hyph_root);
22732 trie_root:=compress_trie(trie_root); {identify equivalent subtries}
22733 for p:=0 to trie_ptr do trie_ref[p]:=0;
22734 for p:=0 to biggest_char do trie_min[p]:=p+1;
22735 trie_link(0):=1; trie_max:=0
22736
22737 @ The |first_fit| procedure finds the smallest hole |z| in |trie| such that
22738 a trie family starting at a given node |p| will fit into vacant positions
22739 starting at |z|. If |c=trie_c[p]|, this means that location |z-c| must
22740 not already be taken by some other family, and that |z-c+@t$c^\prime$@>|
22741 must be vacant for all characters $c^\prime$ in the family. The procedure
22742 sets |trie_ref[p]| to |z-c| when the first fit has been found.
22743
22744 @<Declare procedures for preprocessing hyph...@>=
22745 procedure first_fit(@!p:trie_pointer); {packs a family into |trie|}
22746 label not_found,found;
22747 var h:trie_pointer; {candidate for |trie_ref[p]|}
22748 @!z:trie_pointer; {runs through holes}
22749 @!q:trie_pointer; {runs through the family starting at |p|}
22750 @!c:ASCII_code; {smallest character in the family}
22751 @!l,@!r:trie_pointer; {left and right neighbors}
22752 @!ll:1..too_big_char; {upper limit of |trie_min| updating}
22753 begin c:=so(trie_c[p]);
22754 z:=trie_min[c]; {get the first conceivably good hole}
22755 loop@+ begin h:=z-c;@/
22756 @<Ensure that |trie_max>=h+max_hyph_char|@>;
22757 if trie_taken[h] then goto not_found;
22758 @<If all characters of the family fit relative to |h|, then
22759 |goto found|,\30\ otherwise |goto not_found|@>;
22760 not_found: z:=trie_link(z); {move to the next hole}
22761 end;
22762 found: @<Pack the family into |trie| relative to |h|@>;
22763 end;
22764
22765 @ By making sure that |trie_max| is at least |h+max_hyph_char|,
22766 we can be sure that
22767 |trie_max>z|, since |h=z-c|. It follows that location |trie_max| will
22768 never be occupied in |trie|, and we will have |trie_max>=trie_link(z)|.
22769
22770 @<Ensure that |trie_max>=h+max_hyph_char|@>=
22771 if trie_max<h+max_hyph_char then
22772 begin if trie_size<=h+max_hyph_char then overflow("pattern memory",trie_size);
22773 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
22774 repeat incr(trie_max); trie_taken[trie_max]:=false;
22775 trie_link(trie_max):=trie_max+1; trie_back(trie_max):=trie_max-1;
22776 until trie_max=h+max_hyph_char;
22777 end
22778
22779 @ @<If all characters of the family fit relative to |h|...@>=
22780 q:=trie_r[p];
22781 while q>0 do
22782 begin if trie_link(h+so(trie_c[q]))=0 then goto not_found;
22783 q:=trie_r[q];
22784 end;
22785 goto found
22786
22787 @ @<Pack the family into |trie| relative to |h|@>=
22788 trie_taken[h]:=true; trie_ref[p]:=h; q:=p;
22789 repeat z:=h+so(trie_c[q]); l:=trie_back(z); r:=trie_link(z);
22790 trie_back(r):=l; trie_link(l):=r; trie_link(z):=0;
22791 if l<max_hyph_char then
22792 begin if z<max_hyph_char then ll:=z @+else ll:=max_hyph_char;
22793 repeat trie_min[l]:=r; incr(l);
22794 until l=ll;
22795 end;
22796 q:=trie_r[q];
22797 until q=0
22798
22799 @ To pack the entire linked trie, we use the following recursive procedure.
22800 @^recursion@>
22801
22802 @<Declare procedures for preprocessing hyph...@>=
22803 procedure trie_pack(@!p:trie_pointer); {pack subtries of a family}
22804 var q:trie_pointer; {a local variable that need not be saved on recursive calls}
22805 begin repeat q:=trie_l[p];
22806 if (q>0)and(trie_ref[q]=0) then
22807 begin first_fit(q); trie_pack(q);
22808 end;
22809 p:=trie_r[p];
22810 until p=0;
22811 end;
22812
22813 @ When the whole trie has been allocated into the sequential table, we
22814 must go through it once again so that |trie| contains the correct
22815 information. Null pointers in the linked trie will be represented by the
22816 value~0, which properly implements an ``empty'' family.
22817
22818 @<Move the data into |trie|@>=
22819 h.rh:=0; h.b0:=min_quarterword; h.b1:=min_quarterword; {|trie_link:=0|,
22820 |trie_op:=min_quarterword|, |trie_char:=qi(0)|}
22821 if trie_max=0 then {no patterns were given}
22822 begin for r:=0 to 256 do trie[r]:=h;
22823 trie_max:=256;
22824 end
22825 else begin if hyph_root>0 then trie_fix(hyph_root);
22826 if trie_root>0 then trie_fix(trie_root); {this fixes the non-holes in |trie|}
22827 r:=0; {now we will zero out all the holes}
22828 repeat s:=trie_link(r); trie[r]:=h; r:=s;
22829 until r>trie_max;
22830 end;
22831 trie_char(0):=qi("?"); {make |trie_char(c)<>c| for all |c|}
22832
22833 @ The fixing-up procedure is, of course, recursive. Since the linked trie
22834 usually has overlapping subtries, the same data may be moved several
22835 times; but that causes no harm, and at most as much work is done as it
22836 took to build the uncompressed trie.
22837 @^recursion@>
22838
22839 @<Declare procedures for preprocessing hyph...@>=
22840 procedure trie_fix(@!p:trie_pointer); {moves |p| and its siblings into |trie|}
22841 var q:trie_pointer; {a local variable that need not be saved on recursive calls}
22842 @!c:ASCII_code; {another one that need not be saved}
22843 @!z:trie_pointer; {|trie| reference; this local variable must be saved}
22844 begin z:=trie_ref[p];
22845 repeat q:=trie_l[p]; c:=so(trie_c[p]);
22846 trie_link(z+c):=trie_ref[q]; trie_char(z+c):=qi(c); trie_op(z+c):=trie_o[p];
22847 if q>0 then trie_fix(q);
22848 p:=trie_r[p];
22849 until p=0;
22850 end;
22851
22852 @ Now let's go back to the easier problem, of building the linked
22853 trie. When \.{INITEX} has scanned the `\.{\\patterns}' control
22854 sequence, it calls on |new_patterns| to do the right thing.
22855
22856 @<Declare procedures for preprocessing hyph...@>=
22857 procedure new_patterns; {initializes the hyphenation pattern data}
22858 label done, done1;
22859 var k,@!l:0..hyphenatable_length_limit+1; {indices into |hc| and |hyf|;
22860 not always in |small_number| range}
22861 @!digit_sensed:boolean; {should the next digit be treated as a letter?}
22862 @!v:quarterword; {trie op code}
22863 @!p,@!q:trie_pointer; {nodes of trie traversed during insertion}
22864 @!first_child:boolean; {is |p=trie_l[q]|?}
22865 @!c:ASCII_code; {character being inserted}
22866 begin if trie_not_ready then
22867 begin set_cur_lang; scan_left_brace; {a left brace must follow \.{\\patterns}}
22868 @<Enter all of the patterns into a linked trie, until coming to a right
22869 brace@>;
22870 if saving_hyph_codes>0 then
22871 @<Store hyphenation codes for current language@>;
22872 end
22873 else begin print_err("Too late for "); print_esc("patterns");
22874 help1("All patterns must be given before typesetting begins.");
22875 error; link(garbage):=scan_toks(false,false); flush_list(def_ref);
22876 end;
22877 end;
22878
22879 @ Novices are not supposed to be using \.{\\patterns}, so the error
22880 messages are terse. (Note that all error messages appear in \TeX's string
22881 pool, even if they are used only by \.{INITEX}.)
22882
22883 @<Enter all of the patterns into a linked trie...@>=
22884 k:=0; hyf[0]:=0; digit_sensed:=false;
22885 loop@+ begin get_x_token;
22886 case cur_cmd of
22887 letter,other_char:@<Append a new letter or a hyphen level@>;
22888 spacer,right_brace: begin if k>0 then
22889 @<Insert a new pattern into the linked trie@>;
22890 if cur_cmd=right_brace then goto done;
22891 k:=0; hyf[0]:=0; digit_sensed:=false;
22892 end;
22893 othercases begin print_err("Bad "); print_esc("patterns");
22894 @.Bad \\patterns@>
22895 help1("(See Appendix H.)"); error;
22896 end
22897 endcases;
22898 end;
22899 done:
22900
22901 @ @<Append a new letter or a hyphen level@>=
22902 if digit_sensed or(cur_chr<"0")or(cur_chr>"9") then
22903 begin if cur_chr="." then cur_chr:=0 {edge-of-word delimiter}
22904 else begin cur_chr:=lc_code(cur_chr);
22905 if cur_chr=0 then
22906 begin print_err("Nonletter");
22907 @.Nonletter@>
22908 help1("(See Appendix H.)"); error;
22909 end;
22910 end;
22911 if cur_chr>max_hyph_char then max_hyph_char:=cur_chr;
22912 if k<max_hyphenatable_length then
22913 begin incr(k); hc[k]:=cur_chr; hyf[k]:=0; digit_sensed:=false;
22914 end;
22915 end
22916 else if k<max_hyphenatable_length then
22917 begin hyf[k]:=cur_chr-"0"; digit_sensed:=true;
22918 end
22919
22920 @ When the following code comes into play, the pattern $p_1\ldots p_k$
22921 appears in |hc[1..k]|, and the corresponding sequence of numbers $n_0\ldots
22922 n_k$ appears in |hyf[0..k]|.
22923
22924 @<Insert a new pattern into the linked trie@>=
22925 begin @<Compute the trie op code, |v|, and set |l:=0|@>;
22926 q:=0; hc[0]:=cur_lang;
22927 while l<=k do
22928 begin c:=hc[l]; incr(l); p:=trie_l[q]; first_child:=true;
22929 while (p>0)and(c>so(trie_c[p])) do
22930 begin q:=p; p:=trie_r[q]; first_child:=false;
22931 end;
22932 if (p=0)or(c<so(trie_c[p])) then
22933 @<Insert a new trie node between |q| and |p|, and
22934 make |p| point to it@>;
22935 q:=p; {now node |q| represents $p_1\ldots p_{l-1}$}
22936 end;
22937 if trie_o[q]<>min_quarterword then
22938 begin print_err("Duplicate pattern");
22939 @.Duplicate pattern@>
22940 help1("(See Appendix H.)"); error;
22941 end;
22942 trie_o[q]:=v;
22943 end
22944
22945 @ @<Insert a new trie node between |q| and |p|...@>=
22946 begin if trie_ptr=trie_size then overflow("pattern memory",trie_size);
22947 @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
22948 incr(trie_ptr); trie_r[trie_ptr]:=p; p:=trie_ptr; trie_l[p]:=0;
22949 if first_child then trie_l[q]:=p@+else trie_r[q]:=p;
22950 trie_c[p]:=si(c); trie_o[p]:=min_quarterword;
22951 end
22952
22953 @ @<Compute the trie op code, |v|...@>=
22954 if hc[1]=0 then hyf[0]:=0;
22955 if hc[k]=0 then hyf[k]:=0;
22956 l:=k; v:=min_quarterword;
22957 loop@+ begin if hyf[l]<>0 then v:=new_trie_op(k-l,hyf[l],v);
22958 if l>0 then decr(l)@+else goto done1;
22959 end;
22960 done1:
22961
22962 @ Finally we put everything together: Here is how the trie gets to its
22963 final, efficient form.
22964 The following packing routine is rigged so that the root of the linked
22965 tree gets mapped into location 1 of |trie|, as required by the hyphenation
22966 algorithm. This happens because the first call of |first_fit| will
22967 ``take'' location~1.
22968
22969 @<Declare procedures for preprocessing hyphenation patterns@>=
22970 procedure init_trie;
22971 var @!p:trie_pointer; {pointer for initialization}
22972 @!j,@!k,@!t:integer; {all-purpose registers for initialization}
22973 @!r,@!s:trie_pointer; {used to clean up the packed |trie|}
22974 @!h:two_halves; {template used to zero out |trie|'s holes}
22975 begin
22976 incr(max_hyph_char);
22977 @<Get ready to compress the trie@>;
22978 if trie_root<>0 then
22979 begin first_fit(trie_root); trie_pack(trie_root);
22980 end;
22981 if hyph_root<>0 then @<Pack all stored |hyph_codes|@>;
22982 @<Move the data into |trie|@>;
22983 trie_not_ready:=false;
22984 end;
22985
22986 @* \[44] Breaking vertical lists into pages.
22987 The |vsplit| procedure, which implements \TeX's \.{\\vsplit} operation,
22988 is considerably simpler than |line_break| because it doesn't have to
22989 worry about hyphenation, and because its mission is to discover a single
22990 break instead of an optimum sequence of breakpoints. But before we get
22991 into the details of |vsplit|, we need to consider a few more basic things.
22992
22993 @ A subroutine called |prune_page_top| takes a pointer to a vlist and
22994 returns a pointer to a modified vlist in which all glue, kern, and penalty nodes
22995 have been deleted before the first box or rule node. However, the first
22996 box or rule is actually preceded by a newly created glue node designed so that
22997 the topmost baseline will be at distance |split_top_skip| from the top,
22998 whenever this is possible without backspacing.
22999
23000 When the second argument |s| is |false| the deleted nodes are destroyed,
23001 otherwise they are collected in a list starting at |split_disc|.
23002
23003 In this routine and those that follow, we make use of the fact that a
23004 vertical list contains no character nodes, hence the |type| field exists
23005 for each node in the list.
23006 @^data structure assumptions@>
23007
23008 @p function prune_page_top(@!p:pointer;@!s:boolean):pointer;
23009 {adjust top after page break}
23010 var prev_p:pointer; {lags one step behind |p|}
23011 @!q,@!r:pointer; {temporary variables for list manipulation}
23012 begin prev_p:=temp_head; link(temp_head):=p;
23013 while p<>null do
23014 case type(p) of
23015 hlist_node,vlist_node,rule_node:@<Insert glue for |split_top_skip|
23016 and set~|p:=null|@>;
23017 whatsit_node,mark_node,ins_node: begin prev_p:=p; p:=link(prev_p);
23018 end;
23019 glue_node,kern_node,penalty_node: begin q:=p; p:=link(q); link(q):=null;
23020 link(prev_p):=p;
23021 if s then
23022 begin if split_disc=null then split_disc:=q@+else link(r):=q;
23023 r:=q;
23024 end
23025 else flush_node_list(q);
23026 end;
23027 othercases confusion("pruning")
23028 @:this can't happen pruning}{\quad pruning@>
23029 endcases;
23030 prune_page_top:=link(temp_head);
23031 end;
23032
23033 @ @<Insert glue for |split_top_skip|...@>=
23034 begin q:=new_skip_param(split_top_skip_code); link(prev_p):=q; link(q):=p;
23035 {now |temp_ptr=glue_ptr(q)|}
23036 if XeTeX_upwards then
23037 begin
23038 if width(temp_ptr)>depth(p) then width(temp_ptr):=width(temp_ptr)-depth(p)
23039 else width(temp_ptr):=0;
23040 end
23041 else
23042 begin
23043 if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
23044 else width(temp_ptr):=0;
23045 end;
23046 p:=null;
23047 end
23048
23049 @ The next subroutine finds the best place to break a given vertical list
23050 so as to obtain a box of height~|h|, with maximum depth~|d|.
23051 A pointer to the beginning of the vertical list is given,
23052 and a pointer to the optimum breakpoint is returned. The list is effectively
23053 followed by a forced break, i.e., a penalty node with the |eject_penalty|;
23054 if the best break occurs at this artificial node, the value |null| is returned.
23055
23056 An array of six |scaled| distances is used to keep track of the height
23057 from the beginning of the list to the current place, just as in |line_break|.
23058 In fact, we use one of the same arrays, only changing its name to reflect
23059 its new significance.
23060
23061 @d active_height==active_width {new name for the six distance variables}
23062 @d cur_height==active_height[1] {the natural height}
23063 @d set_height_zero(#)==active_height[#]:=0 {initialize the height to zero}
23064 @#
23065 @d update_heights=90 {go here to record glue in the |active_height| table}
23066
23067 @p function vert_break(@!p:pointer; @!h,@!d:scaled):pointer;
23068 {finds optimum page break}
23069 label done,not_found,update_heights;
23070 var prev_p:pointer; {if |p| is a glue node, |type(prev_p)| determines
23071 whether |p| is a legal breakpoint}
23072 @!q,@!r:pointer; {glue specifications}
23073 @!pi:integer; {penalty value}
23074 @!b:integer; {badness at a trial breakpoint}
23075 @!least_cost:integer; {the smallest badness plus penalties found so far}
23076 @!best_place:pointer; {the most recent break that leads to |least_cost|}
23077 @!prev_dp:scaled; {depth of previous box in the list}
23078 @!t:small_number; {|type| of the node following a kern}
23079 begin prev_p:=p; {an initial glue node is not a legal breakpoint}
23080 least_cost:=awful_bad; do_all_six(set_height_zero); prev_dp:=0;
23081 loop@+ begin @<If node |p| is a legal breakpoint, check if this break is
23082 the best known, and |goto done| if |p| is null or
23083 if the page-so-far is already too full to accept more stuff@>;
23084 prev_p:=p; p:=link(prev_p);
23085 end;
23086 done: vert_break:=best_place;
23087 end;
23088
23089 @ A global variable |best_height_plus_depth| will be set to the natural size
23090 of the box that corresponds to the optimum breakpoint found by |vert_break|.
23091 (This value is used by the insertion-splitting algorithm of the page builder.)
23092
23093 @<Glob...@>=
23094 @!best_height_plus_depth:scaled; {height of the best box, without stretching or
23095 shrinking}
23096
23097 @ A subtle point to be noted here is that the maximum depth~|d| might be
23098 negative, so |cur_height| and |prev_dp| might need to be corrected even
23099 after a glue or kern node.
23100
23101 @<If node |p| is a legal breakpoint, check...@>=
23102 if p=null then pi:=eject_penalty
23103 else @<Use node |p| to update the current height and depth measurements;
23104 if this node is not a legal breakpoint, |goto not_found|
23105 or |update_heights|,
23106 otherwise set |pi| to the associated penalty at the break@>;
23107 @<Check if node |p| is a new champion breakpoint; then \(go)|goto done|
23108 if |p| is a forced break or if the page-so-far is already too full@>;
23109 if (type(p)<glue_node)or(type(p)>kern_node) then goto not_found;
23110 update_heights: @<Update the current height and depth measurements with
23111 respect to a glue or kern node~|p|@>;
23112 not_found: if prev_dp>d then
23113 begin cur_height:=cur_height+prev_dp-d;
23114 prev_dp:=d;
23115 end;
23116
23117 @ @<Use node |p| to update the current height and depth measurements...@>=
23118 case type(p) of
23119 hlist_node,vlist_node,rule_node: begin@t@>@;@/
23120 cur_height:=cur_height+prev_dp+height(p); prev_dp:=depth(p);
23121 goto not_found;
23122 end;
23123 whatsit_node:@<Process whatsit |p| in |vert_break| loop, |goto not_found|@>;
23124 glue_node: if precedes_break(prev_p) then pi:=0
23125 else goto update_heights;
23126 kern_node: begin if link(p)=null then t:=penalty_node
23127 else t:=type(link(p));
23128 if t=glue_node then pi:=0@+else goto update_heights;
23129 end;
23130 penalty_node: pi:=penalty(p);
23131 mark_node,ins_node: goto not_found;
23132 othercases confusion("vertbreak")
23133 @:this can't happen vertbreak}{\quad vertbreak@>
23134 endcases
23135
23136 @ @d deplorable==100000 {more than |inf_bad|, but less than |awful_bad|}
23137
23138 @<Check if node |p| is a new champion breakpoint; then \(go)...@>=
23139 if pi<inf_penalty then
23140 begin @<Compute the badness, |b|, using |awful_bad|
23141 if the box is too full@>;
23142 if b<awful_bad then
23143 if pi<=eject_penalty then b:=pi
23144 else if b<inf_bad then b:=b+pi
23145 else b:=deplorable;
23146 if b<=least_cost then
23147 begin best_place:=p; least_cost:=b;
23148 best_height_plus_depth:=cur_height+prev_dp;
23149 end;
23150 if (b=awful_bad)or(pi<=eject_penalty) then goto done;
23151 end
23152
23153 @ @<Compute the badness, |b|, using |awful_bad| if the box is too full@>=
23154 if cur_height<h then
23155 if (active_height[3]<>0) or (active_height[4]<>0) or
23156 (active_height[5]<>0) then b:=0
23157 else b:=badness(h-cur_height,active_height[2])
23158 else if cur_height-h>active_height[6] then b:=awful_bad
23159 else b:=badness(cur_height-h,active_height[6])
23160
23161 @ Vertical lists that are subject to the |vert_break| procedure should not
23162 contain infinite shrinkability, since that would permit any amount of
23163 information to ``fit'' on one page.
23164
23165 @<Update the current height and depth measurements with...@>=
23166 if type(p)=kern_node then q:=p
23167 else begin q:=glue_ptr(p);
23168 active_height[2+stretch_order(q)]:=@|
23169 active_height[2+stretch_order(q)]+stretch(q);@/
23170 active_height[6]:=active_height[6]+shrink(q);
23171 if (shrink_order(q)<>normal)and(shrink(q)<>0) then
23172 begin@t@>@;@/
23173 if is_bit_set(ignore_primitive_error, 1) then
23174 print_ignored_err("Infinite glue shrinkage found in box being split")
23175 else begin
23176 print_err("Infinite glue shrinkage found in box being split");@/
23177 @.Infinite glue shrinkage...@>
23178 help4("The box you are \vsplitting contains some infinitely")@/
23179 ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
23180 ("Such glue doesn't belong there; but you can safely proceed,")@/
23181 ("since the offensive shrinkability has been made finite.");
23182 error;
23183 end;
23184 r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
23185 glue_ptr(p):=r; q:=r;
23186 end;
23187 end;
23188 cur_height:=cur_height+prev_dp+width(q); prev_dp:=0
23189
23190 @ Now we are ready to consider |vsplit| itself. Most of
23191 its work is accomplished by the two subroutines that we have just considered.
23192
23193 Given the number of a vlist box |n|, and given a desired page height |h|,
23194 the |vsplit| function finds the best initial segment of the vlist and
23195 returns a box for a page of height~|h|. The remainder of the vlist, if
23196 any, replaces the original box, after removing glue and penalties and
23197 adjusting for |split_top_skip|. Mark nodes in the split-off box are used to
23198 set the values of |split_first_mark| and |split_bot_mark|; we use the
23199 fact that |split_first_mark=null| if and only if |split_bot_mark=null|.
23200
23201 The original box becomes ``void'' if and only if it has been entirely
23202 extracted. The extracted box is ``void'' if and only if the original
23203 box was void (or if it was, erroneously, an hlist box).
23204
23205 @p @t\4@>@<Declare the function called |do_marks|@>@;
23206 function vsplit(@!n:halfword; @!h:scaled):pointer;
23207 {extracts a page of height |h| from box |n|}
23208 label exit,done;
23209 var v:pointer; {the box to be split}
23210 p:pointer; {runs through the vlist}
23211 q:pointer; {points to where the break occurs}
23212 begin cur_val:=n; fetch_box(v);
23213 flush_node_list(split_disc); split_disc:=null;
23214 if sa_mark<>null then
23215 if do_marks(vsplit_init,0,sa_mark) then sa_mark:=null;
23216 if split_first_mark<>null then
23217 begin delete_token_ref(split_first_mark); split_first_mark:=null;
23218 delete_token_ref(split_bot_mark); split_bot_mark:=null;
23219 end;
23220 @<Dispense with trivial cases of void or bad boxes@>;
23221 q:=vert_break(list_ptr(v),h,split_max_depth);
23222 @<Look at all the marks in nodes before the break, and set the final
23223 link to |null| at the break@>;
23224 q:=prune_page_top(q,saving_vdiscards>0);
23225 p:=list_ptr(v); free_node(v,box_node_size);
23226 if q<>null then q:=vpack(q,natural);
23227 change_box(q); {the |eq_level| of the box stays the same}
23228 vsplit:=vpackage(p,h,exactly,split_max_depth);
23229 exit: end;
23230
23231 @ @<Dispense with trivial cases of void or bad boxes@>=
23232 if v=null then
23233 begin vsplit:=null; return;
23234 end;
23235 if type(v)<>vlist_node then
23236 begin print_err(""); print_esc("vsplit"); print(" needs a ");
23237 print_esc("vbox");
23238 @:vsplit_}{\.{\\vsplit needs a \\vbox}@>
23239 help2("The box you are trying to split is an \hbox.")@/
23240 ("I can't split such a box, so I'll leave it alone.");
23241 error; vsplit:=null; return;
23242 end
23243
23244 @ It's possible that the box begins with a penalty node that is the
23245 ``best'' break, so we must be careful to handle this special case correctly.
23246
23247 @<Look at all the marks...@>=
23248 p:=list_ptr(v);
23249 if p=q then list_ptr(v):=null
23250 else loop@+begin if type(p)=mark_node then
23251 if mark_class(p)<>0 then @<Update the current marks for |vsplit|@>
23252 else if split_first_mark=null then
23253 begin split_first_mark:=mark_ptr(p);
23254 split_bot_mark:=split_first_mark;
23255 token_ref_count(split_first_mark):=@|
23256 token_ref_count(split_first_mark)+2;
23257 end
23258 else begin delete_token_ref(split_bot_mark);
23259 split_bot_mark:=mark_ptr(p);
23260 add_token_ref(split_bot_mark);
23261 end;
23262 if link(p)=q then
23263 begin link(p):=null; goto done;
23264 end;
23265 p:=link(p);
23266 end;
23267 done:
23268
23269 @* \[45] The page builder.
23270 When \TeX\ appends new material to its main vlist in vertical mode, it uses
23271 a method something like |vsplit| to decide where a page ends, except that
23272 the calculations are done ``on line'' as new items come in.
23273 The main complication in this process is that insertions must be put
23274 into their boxes and removed from the vlist, in a more-or-less optimum manner.
23275
23276 We shall use the term ``current page'' for that part of the main vlist that
23277 is being considered as a candidate for being broken off and sent to the
23278 user's output routine. The current page starts at |link(page_head)|, and
23279 it ends at |page_tail|. We have |page_head=page_tail| if this list is empty.
23280 @^current page@>
23281
23282 Utter chaos would reign if the user kept changing page specifications
23283 while a page is being constructed, so the page builder keeps the pertinent
23284 specifications frozen as soon as the page receives its first box or
23285 insertion. The global variable |page_contents| is |empty| when the
23286 current page contains only mark nodes and content-less whatsit nodes; it
23287 is |inserts_only| if the page contains only insertion nodes in addition to
23288 marks and whatsits. Glue nodes, kern nodes, and penalty nodes are
23289 discarded until a box or rule node appears, at which time |page_contents|
23290 changes to |box_there|. As soon as |page_contents| becomes non-|empty|,
23291 the current |vsize| and |max_depth| are squirreled away into |page_goal|
23292 and |page_max_depth|; the latter values will be used until the page has
23293 been forwarded to the user's output routine. The \.{\\topskip} adjustment
23294 is made when |page_contents| changes to |box_there|.
23295
23296 Although |page_goal| starts out equal to |vsize|, it is decreased by the
23297 scaled natural height-plus-depth of the insertions considered so far, and by
23298 the \.{\\skip} corrections for those insertions. Therefore it represents
23299 the size into which the non-inserted material should fit, assuming that
23300 all insertions in the current page have been made.
23301
23302 The global variables |best_page_break| and |least_page_cost| correspond
23303 respectively to the local variables |best_place| and |least_cost| in the
23304 |vert_break| routine that we have already studied; i.e., they record the
23305 location and value of the best place currently known for breaking the
23306 current page. The value of |page_goal| at the time of the best break is
23307 stored in |best_size|.
23308
23309 @d inserts_only=1
23310 {|page_contents| when an insert node has been contributed, but no boxes}
23311 @d box_there=2 {|page_contents| when a box or rule has been contributed}
23312
23313 @<Glob...@>=
23314 @!page_tail:pointer; {the final node on the current page}
23315 @!page_contents:empty..box_there; {what is on the current page so far?}
23316 @!page_max_depth:scaled; {maximum box depth on page being built}
23317 @!best_page_break:pointer; {break here to get the best page known so far}
23318 @!least_page_cost:integer; {the score for this currently best page}
23319 @!best_size:scaled; {its |page_goal|}
23320
23321 @ The page builder has another data structure to keep track of insertions.
23322 This is a list of four-word nodes, starting and ending at |page_ins_head|.
23323 That is, the first element of the list is node |r@t$_1$@>=link(page_ins_head)|;
23324 node $r_j$ is followed by |r@t$_{j+1}$@>=link(r@t$_j$@>)|; and if there are
23325 |n| items we have |r@t$_{n+1}$@>=page_ins_head|. The |subtype| field of
23326 each node in this list refers to an insertion number; for example, `\.{\\insert
23327 250}' would correspond to a node whose |subtype| is |qi(250)|
23328 (the same as the |subtype| field of the relevant |ins_node|). These |subtype|
23329 fields are in increasing order, and |subtype(page_ins_head)=
23330 qi(255)|, so |page_ins_head| serves as a convenient sentinel
23331 at the end of the list. A record is present for each insertion number that
23332 appears in the current page.
23333
23334 The |type| field in these nodes distinguishes two possibilities that
23335 might occur as we look ahead before deciding on the optimum page break.
23336 If |type(r)=inserting|, then |height(r)| contains the total of the
23337 height-plus-depth dimensions of the box and all its inserts seen so far.
23338 If |type(r)=split_up|, then no more insertions will be made into this box,
23339 because at least one previous insertion was too big to fit on the current
23340 page; |broken_ptr(r)| points to the node where that insertion will be
23341 split, if \TeX\ decides to split it, |broken_ins(r)| points to the
23342 insertion node that was tentatively split, and |height(r)| includes also the
23343 natural height plus depth of the part that would be split off.
23344
23345 In both cases, |last_ins_ptr(r)| points to the last |ins_node|
23346 encountered for box |qo(subtype(r))| that would be at least partially
23347 inserted on the next page; and |best_ins_ptr(r)| points to the last
23348 such |ins_node| that should actually be inserted, to get the page with
23349 minimum badness among all page breaks considered so far. We have
23350 |best_ins_ptr(r)=null| if and only if no insertion for this box should
23351 be made to produce this optimum page.
23352
23353 The data structure definitions here use the fact that the |@!height| field
23354 appears in the fourth word of a box node.
23355 @^data structure assumptions@>
23356
23357 @d page_ins_node_size=4 {number of words for a page insertion node}
23358 @d inserting=0 {an insertion class that has not yet overflowed}
23359 @d split_up=1 {an overflowed insertion class}
23360 @d broken_ptr(#)==link(#+1)
23361 {an insertion for this class will break here if anywhere}
23362 @d broken_ins(#)==info(#+1) {this insertion might break at |broken_ptr|}
23363 @d last_ins_ptr(#)==link(#+2) {the most recent insertion for this |subtype|}
23364 @d best_ins_ptr(#)==info(#+2) {the optimum most recent insertion}
23365
23366 @<Initialize the special list heads...@>=
23367 subtype(page_ins_head):=qi(255);
23368 type(page_ins_head):=split_up; link(page_ins_head):=page_ins_head;
23369
23370 @ An array |page_so_far| records the heights and depths of everything
23371 on the current page. This array contains six |scaled| numbers, like the
23372 similar arrays already considered in |line_break| and |vert_break|; and it
23373 also contains |page_goal| and |page_depth|, since these values are
23374 all accessible to the user via |set_page_dimen| commands. The
23375 value of |page_so_far[1]| is also called |page_total|. The stretch
23376 and shrink components of the \.{\\skip} corrections for each insertion are
23377 included in |page_so_far|, but the natural space components of these
23378 corrections are not, since they have been subtracted from |page_goal|.
23379
23380 The variable |page_depth| records the depth of the current page; it has been
23381 adjusted so that it is at most |page_max_depth|. The variable
23382 |last_glue| points to the glue specification of the most recent node
23383 contributed from the contribution list, if this was a glue node; otherwise
23384 |last_glue=max_halfword|. (If the contribution list is nonempty,
23385 however, the value of |last_glue| is not necessarily accurate.)
23386 The variables |last_penalty|, |last_kern|, and |last_node_type|
23387 are similar. And
23388 finally, |insert_penalties| holds the sum of the penalties associated with
23389 all split and floating insertions.
23390
23391 @d page_goal==page_so_far[0] {desired height of information on page being built}
23392 @d page_total==page_so_far[1] {height of the current page}
23393 @d page_shrink==page_so_far[6] {shrinkability of the current page}
23394 @d page_depth==page_so_far[7] {depth of the current page}
23395
23396 @<Glob...@>=
23397 @!page_so_far:array [0..7] of scaled; {height and glue of the current page}
23398 @!last_glue:pointer; {used to implement \.{\\lastskip}}
23399 @!last_penalty:integer; {used to implement \.{\\lastpenalty}}
23400 @!last_kern:scaled; {used to implement \.{\\lastkern}}
23401 @!last_node_type:integer; {used to implement \.{\\lastnodetype}}
23402 @!insert_penalties:integer; {sum of the penalties for insertions
23403 that were held over}
23404
23405 @ @<Put each...@>=
23406 primitive("pagegoal",set_page_dimen,0);
23407 @!@:page_goal_}{\.{\\pagegoal} primitive@>
23408 primitive("pagetotal",set_page_dimen,1);
23409 @!@:page_total_}{\.{\\pagetotal} primitive@>
23410 primitive("pagestretch",set_page_dimen,2);
23411 @!@:page_stretch_}{\.{\\pagestretch} primitive@>
23412 primitive("pagefilstretch",set_page_dimen,3);
23413 @!@:page_fil_stretch_}{\.{\\pagefilstretch} primitive@>
23414 primitive("pagefillstretch",set_page_dimen,4);
23415 @!@:page_fill_stretch_}{\.{\\pagefillstretch} primitive@>
23416 primitive("pagefilllstretch",set_page_dimen,5);
23417 @!@:page_filll_stretch_}{\.{\\pagefilllstretch} primitive@>
23418 primitive("pageshrink",set_page_dimen,6);
23419 @!@:page_shrink_}{\.{\\pageshrink} primitive@>
23420 primitive("pagedepth",set_page_dimen,7);
23421 @!@:page_depth_}{\.{\\pagedepth} primitive@>
23422
23423 @ @<Cases of |print_cmd_chr|...@>=
23424 set_page_dimen: case chr_code of
23425 0: print_esc("pagegoal");
23426 1: print_esc("pagetotal");
23427 2: print_esc("pagestretch");
23428 3: print_esc("pagefilstretch");
23429 4: print_esc("pagefillstretch");
23430 5: print_esc("pagefilllstretch");
23431 6: print_esc("pageshrink");
23432 othercases print_esc("pagedepth")
23433 endcases;
23434
23435 @ @d print_plus_end(#)==print(#);@+end
23436 @d print_plus(#)==if page_so_far[#]<>0 then
23437 begin print(" plus "); print_scaled(page_so_far[#]); print_plus_end
23438
23439 @p procedure print_totals;
23440 begin print_scaled(page_total);
23441 print_plus(2)("");
23442 print_plus(3)("fil");
23443 print_plus(4)("fill");
23444 print_plus(5)("filll");
23445 if page_shrink<>0 then
23446 begin print(" minus "); print_scaled(page_shrink);
23447 end;
23448 end;
23449
23450 @ @<Show the status of the current page@>=
23451 if page_head<>page_tail then
23452 begin print_nl("### current page:");
23453 if output_active then print(" (held over for next output)");
23454 @.held over for next output@>
23455 show_box(link(page_head));
23456 if page_contents>empty then
23457 begin print_nl("total height "); print_totals;
23458 @:total_height}{\.{total height}@>
23459 print_nl(" goal height "); print_scaled(page_goal);
23460 @.goal height@>
23461 r:=link(page_ins_head);
23462 while r<>page_ins_head do
23463 begin print_ln; print_esc("insert"); t:=qo(subtype(r));
23464 print_int(t); print(" adds ");
23465 if count(t)=1000 then t:=height(r)
23466 else t:=x_over_n(height(r),1000)*count(t);
23467 print_scaled(t);
23468 if type(r)=split_up then
23469 begin q:=page_head; t:=0;
23470 repeat q:=link(q);
23471 if (type(q)=ins_node)and(subtype(q)=subtype(r)) then incr(t);
23472 until q=broken_ins(r);
23473 print(", #"); print_int(t); print(" might split");
23474 end;
23475 r:=link(r);
23476 end;
23477 end;
23478 end
23479
23480 @ Here is a procedure that is called when the |page_contents| is changing
23481 from |empty| to |inserts_only| or |box_there|.
23482
23483 @d set_page_so_far_zero(#)==page_so_far[#]:=0
23484
23485 @p procedure freeze_page_specs(@!s:small_number);
23486 begin page_contents:=s;
23487 page_goal:=vsize; page_max_depth:=max_depth;
23488 page_depth:=0; do_all_six(set_page_so_far_zero);
23489 least_page_cost:=awful_bad;
23490 @!stat if tracing_pages>0 then
23491 begin begin_diagnostic;
23492 print_nl("%% goal height="); print_scaled(page_goal);
23493 @.goal height@>
23494 print(", max depth="); print_scaled(page_max_depth);
23495 end_diagnostic(false);
23496 end;@;@+tats@;@/
23497 end;
23498
23499 @ Pages are built by appending nodes to the current list in \TeX's
23500 vertical mode, which is at the outermost level of the semantic nest. This
23501 vlist is split into two parts; the ``current page'' that we have been
23502 talking so much about already, and the ``contribution list'' that receives
23503 new nodes as they are created. The current page contains everything that
23504 the page builder has accounted for in its data structures, as described
23505 above, while the contribution list contains other things that have been
23506 generated by other parts of \TeX\ but have not yet been
23507 seen by the page builder.
23508 The contribution list starts at |link(contrib_head)|, and it ends at the
23509 current node in \TeX's vertical mode.
23510
23511 When \TeX\ has appended new material in vertical mode, it calls the procedure
23512 |build_page|, which tries to catch up by moving nodes from the contribution
23513 list to the current page. This procedure will succeed in its goal of
23514 emptying the contribution list, unless a page break is discovered, i.e.,
23515 unless the current page has grown to the point where the optimum next
23516 page break has been determined. In the latter case, the nodes after the
23517 optimum break will go back onto the contribution list, and control will
23518 effectively pass to the user's output routine.
23519
23520 We make |type(page_head)=glue_node|, so that an initial glue node on
23521 the current page will not be considered a valid breakpoint.
23522
23523 @<Initialize the special list...@>=
23524 type(page_head):=glue_node; subtype(page_head):=normal;
23525
23526 @ The global variable |output_active| is true during the time the
23527 user's output routine is driving \TeX.
23528
23529 @<Glob...@>=
23530 @!output_active:boolean; {are we in the midst of an output routine?}
23531
23532 @ @<Set init...@>=
23533 output_active:=false; insert_penalties:=0;
23534
23535 @ The page builder is ready to start a fresh page if we initialize
23536 the following state variables. (However, the page insertion list is initialized
23537 elsewhere.)
23538
23539 @<Start a new current page@>=
23540 page_contents:=empty; page_tail:=page_head; link(page_head):=null;@/
23541 last_glue:=max_halfword; last_penalty:=0; last_kern:=0;
23542 last_node_type:=-1;
23543 page_depth:=0; page_max_depth:=0
23544
23545 @ At certain times box 255 is supposed to be void (i.e., |null|),
23546 or an insertion box is supposed to be ready to accept a vertical list.
23547 If not, an error message is printed, and the following subroutine
23548 flushes the unwanted contents, reporting them to the user.
23549
23550 @p procedure box_error(@!n:eight_bits);
23551 begin error; begin_diagnostic;
23552 print_nl("The following box has been deleted:");
23553 @.The following...deleted@>
23554 show_box(box(n)); end_diagnostic(true);
23555 flush_node_list(box(n)); box(n):=null;
23556 end;
23557
23558 @ The following procedure guarantees that a given box register
23559 does not contain an \.{\\hbox}.
23560
23561 @p procedure ensure_vbox(@!n:eight_bits);
23562 var p:pointer; {the box register contents}
23563 begin p:=box(n);
23564 if p<>null then if type(p)=hlist_node then
23565 begin print_err("Insertions can only be added to a vbox");
23566 @.Insertions can only...@>
23567 help3("Tut tut: You're trying to \insert into a")@/
23568 ("\box register that now contains an \hbox.")@/
23569 ("Proceed, and I'll discard its present contents.");
23570 box_error(n);
23571 end;
23572 end;
23573
23574 @ \TeX\ is not always in vertical mode at the time |build_page|
23575 is called; the current mode reflects what \TeX\ should return to, after
23576 the contribution list has been emptied. A call on |build_page| should
23577 be immediately followed by `|goto big_switch|', which is \TeX's central
23578 control point.
23579
23580 @d contribute=80 {go here to link a node into the current page}
23581
23582 @p @t\4@>@<Declare the procedure called |fire_up|@>@;@/
23583 procedure build_page; {append contributions to the current page}
23584 label exit,done,done1,continue,contribute,update_heights;
23585 var p:pointer; {the node being appended}
23586 @!q,@!r:pointer; {nodes being examined}
23587 @!b,@!c:integer; {badness and cost of current page}
23588 @!pi:integer; {penalty to be added to the badness}
23589 @!n:min_quarterword..biggest_reg; {insertion box number}
23590 @!delta,@!h,@!w:scaled; {sizes used for insertion calculations}
23591 begin if (link(contrib_head)=null)or output_active then return;
23592 repeat continue: p:=link(contrib_head);@/
23593 @<Update the values of |last_glue|, |last_penalty|, and |last_kern|@>;
23594 @<Move node |p| to the current page; if it is time for a page break,
23595 put the nodes following the break back onto the contribution list,
23596 and |return| to the user's output routine if there is one@>;
23597 until link(contrib_head)=null;
23598 @<Make the contribution list empty by setting its tail to |contrib_head|@>;
23599 exit:end;
23600
23601 @ @d contrib_tail==nest[0].tail_field {tail of the contribution list}
23602
23603 @<Make the contribution list empty...@>=
23604 if nest_ptr=0 then tail:=contrib_head {vertical mode}
23605 else contrib_tail:=contrib_head {other modes}
23606
23607 @ @<Update the values of |last_glue|...@>=
23608 if last_glue<>max_halfword then delete_glue_ref(last_glue);
23609 last_penalty:=0; last_kern:=0;
23610 last_node_type:=type(p)+1;
23611 if type(p)=glue_node then
23612 begin last_glue:=glue_ptr(p); add_glue_ref(last_glue);
23613 end
23614 else begin last_glue:=max_halfword;
23615 if type(p)=penalty_node then last_penalty:=penalty(p)
23616 else if type(p)=kern_node then last_kern:=width(p);
23617 end
23618
23619 @ The code here is an example of a many-way switch into routines that
23620 merge together in different places. Some people call this unstructured
23621 programming, but the author doesn't see much wrong with it, as long as
23622 @^Knuth, Donald Ervin@>
23623 the various labels have a well-understood meaning.
23624
23625 @<Move node |p| to the current page; ...@>=
23626 @<If the current page is empty and node |p| is to be deleted, |goto done1|;
23627 otherwise use node |p| to update the state of the current page;
23628 if this node is an insertion, |goto contribute|; otherwise if this node
23629 is not a legal breakpoint, |goto contribute| or |update_heights|;
23630 otherwise set |pi| to the penalty associated with this breakpoint@>;
23631 @<Check if node |p| is a new champion breakpoint; then \(if)if it is time for
23632 a page break, prepare for output, and either fire up the user's
23633 output routine and |return| or ship out the page and |goto done|@>;
23634 if (type(p)<glue_node)or(type(p)>kern_node) then goto contribute;
23635 update_heights:@<Update the current page measurements with respect to the
23636 glue or kern specified by node~|p|@>;
23637 contribute: @<Make sure that |page_max_depth| is not exceeded@>;
23638 @<Link node |p| into the current page and |goto done|@>;
23639 done1:@<Recycle node |p|@>;
23640 done:
23641
23642 @ @<Link node |p| into the current page and |goto done|@>=
23643 link(page_tail):=p; page_tail:=p;
23644 link(contrib_head):=link(p); link(p):=null; goto done
23645
23646 @ @<Recycle node |p|@>=
23647 link(contrib_head):=link(p); link(p):=null;
23648 if saving_vdiscards>0 then
23649 begin if page_disc=null then page_disc:=p@+else link(tail_page_disc):=p;
23650 tail_page_disc:=p;
23651 end
23652 else flush_node_list(p)
23653
23654 @ The title of this section is already so long, it seems best to avoid
23655 making it more accurate but still longer, by mentioning the fact that a
23656 kern node at the end of the contribution list will not be contributed until
23657 we know its successor.
23658
23659 @<If the current page is empty...@>=
23660 case type(p) of
23661 hlist_node,vlist_node,rule_node: if page_contents<box_there then
23662 @<Initialize the current page, insert the \.{\\topskip} glue
23663 ahead of |p|, and |goto continue|@>
23664 else @<Prepare to move a box or rule node to the current page,
23665 then |goto contribute|@>;
23666 whatsit_node: @<Prepare to move whatsit |p| to the current page,
23667 then |goto contribute|@>;
23668 glue_node: if page_contents<box_there then goto done1
23669 else if precedes_break(page_tail) then pi:=0
23670 else goto update_heights;
23671 kern_node: if page_contents<box_there then goto done1
23672 else if link(p)=null then return
23673 else if type(link(p))=glue_node then pi:=0
23674 else goto update_heights;
23675 penalty_node: if page_contents<box_there then goto done1@+else pi:=penalty(p);
23676 mark_node: goto contribute;
23677 ins_node: @<Append an insertion to the current page and |goto contribute|@>;
23678 othercases confusion("page")
23679 @:this can't happen page}{\quad page@>
23680 endcases
23681
23682 @ @<Initialize the current page, insert the \.{\\topskip} glue...@>=
23683 begin if page_contents=empty then freeze_page_specs(box_there)
23684 else page_contents:=box_there;
23685 q:=new_skip_param(top_skip_code); {now |temp_ptr=glue_ptr(q)|}
23686 if XeTeX_upwards then
23687 begin
23688 if width(temp_ptr)>depth(p) then width(temp_ptr):=width(temp_ptr)-depth(p)
23689 else width(temp_ptr):=0;
23690 end
23691 else
23692 begin
23693 if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
23694 else width(temp_ptr):=0;
23695 end;
23696 link(q):=p; link(contrib_head):=q; goto continue;
23697 end
23698
23699 @ @<Prepare to move a box or rule node to the current page...@>=
23700 begin page_total:=page_total+page_depth+height(p);
23701 page_depth:=depth(p);
23702 goto contribute;
23703 end
23704
23705 @ @<Make sure that |page_max_depth| is not exceeded@>=
23706 if page_depth>page_max_depth then
23707 begin page_total:=@|
23708 page_total+page_depth-page_max_depth;@/
23709 page_depth:=page_max_depth;
23710 end;
23711
23712 @ @<Update the current page measurements with respect to the glue...@>=
23713 if type(p)=kern_node then q:=p
23714 else begin q:=glue_ptr(p);
23715 page_so_far[2+stretch_order(q)]:=@|
23716 page_so_far[2+stretch_order(q)]+stretch(q);@/
23717 page_shrink:=page_shrink+shrink(q);
23718 if (shrink_order(q)<>normal)and(shrink(q)<>0) then
23719 begin@t@>@;@/
23720 print_err("Infinite glue shrinkage found on current page");@/
23721 @.Infinite glue shrinkage...@>
23722 help4("The page about to be output contains some infinitely")@/
23723 ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
23724 ("Such glue doesn't belong there; but you can safely proceed,")@/
23725 ("since the offensive shrinkability has been made finite.");
23726 error;
23727 r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
23728 glue_ptr(p):=r; q:=r;
23729 end;
23730 end;
23731 page_total:=page_total+page_depth+width(q); page_depth:=0
23732
23733 @ @<Check if node |p| is a new champion breakpoint; then \(if)...@>=
23734 if pi<inf_penalty then
23735 begin @<Compute the badness, |b|, of the current page,
23736 using |awful_bad| if the box is too full@>;
23737 if b<awful_bad then
23738 if pi<=eject_penalty then c:=pi
23739 else if b<inf_bad then c:=b+pi+insert_penalties
23740 else c:=deplorable
23741 else c:=b;
23742 if insert_penalties>=10000 then c:=awful_bad;
23743 @!stat if tracing_pages>0 then @<Display the page break cost@>;@+tats@;@/
23744 if c<=least_page_cost then
23745 begin best_page_break:=p; best_size:=page_goal;
23746 least_page_cost:=c;
23747 r:=link(page_ins_head);
23748 while r<>page_ins_head do
23749 begin best_ins_ptr(r):=last_ins_ptr(r);
23750 r:=link(r);
23751 end;
23752 end;
23753 if (c=awful_bad)or(pi<=eject_penalty) then
23754 begin fire_up(p); {output the current page at the best place}
23755 if output_active then return; {user's output routine will act}
23756 goto done; {the page has been shipped out by default output routine}
23757 end;
23758 end
23759
23760 @ @<Display the page break cost@>=
23761 begin begin_diagnostic; print_nl("%");
23762 print(" t="); print_totals;@/
23763 print(" g="); print_scaled(page_goal);@/
23764 print(" b=");
23765 if b=awful_bad then print_char("*")@+else print_int(b);
23766 @.*\relax@>
23767 print(" p="); print_int(pi);
23768 print(" c=");
23769 if c=awful_bad then print_char("*")@+else print_int(c);
23770 if c<=least_page_cost then print_char("#");
23771 end_diagnostic(false);
23772 end
23773
23774 @ @<Compute the badness, |b|, of the current page...@>=
23775 if page_total<page_goal then
23776 if (page_so_far[3]<>0) or (page_so_far[4]<>0) or@|
23777 (page_so_far[5]<>0) then b:=0
23778 else b:=badness(page_goal-page_total,page_so_far[2])
23779 else if page_total-page_goal>page_shrink then b:=awful_bad
23780 else b:=badness(page_total-page_goal,page_shrink)
23781
23782 @ @<Append an insertion to the current page and |goto contribute|@>=
23783 begin if page_contents=empty then freeze_page_specs(inserts_only);
23784 n:=subtype(p); r:=page_ins_head;
23785 while n>=subtype(link(r)) do r:=link(r);
23786 n:=qo(n);
23787 if subtype(r)<>qi(n) then
23788 @<Create a page insertion node with |subtype(r)=qi(n)|, and
23789 include the glue correction for box |n| in the
23790 current page state@>;
23791 if type(r)=split_up then insert_penalties:=insert_penalties+float_cost(p)
23792 else begin last_ins_ptr(r):=p;
23793 delta:=page_goal-page_total-page_depth+page_shrink;
23794 {this much room is left if we shrink the maximum}
23795 if count(n)=1000 then h:=height(p)
23796 else h:=x_over_n(height(p),1000)*count(n); {this much room is needed}
23797 if ((h<=0)or(h<=delta))and(height(p)+height(r)<=dimen(n)) then
23798 begin page_goal:=page_goal-h; height(r):=height(r)+height(p);
23799 end
23800 else @<Find the best way to split the insertion, and change
23801 |type(r)| to |split_up|@>;
23802 end;
23803 goto contribute;
23804 end
23805
23806 @ We take note of the value of \.{\\skip} |n| and the height plus depth
23807 of \.{\\box}~|n| only when the first \.{\\insert}~|n| node is
23808 encountered for a new page. A user who changes the contents of \.{\\box}~|n|
23809 after that first \.{\\insert}~|n| had better be either extremely careful
23810 or extremely lucky, or both.
23811
23812 @<Create a page insertion node...@>=
23813 begin q:=get_node(page_ins_node_size); link(q):=link(r); link(r):=q; r:=q;
23814 subtype(r):=qi(n); type(r):=inserting; ensure_vbox(n);
23815 if box(n)=null then height(r):=0
23816 else height(r):=height(box(n))+depth(box(n));
23817 best_ins_ptr(r):=null;@/
23818 q:=skip(n);
23819 if count(n)=1000 then h:=height(r)
23820 else h:=x_over_n(height(r),1000)*count(n);
23821 page_goal:=page_goal-h-width(q);@/
23822 page_so_far[2+stretch_order(q)]:=@|page_so_far[2+stretch_order(q)]+stretch(q);@/
23823 page_shrink:=page_shrink+shrink(q);
23824 if (shrink_order(q)<>normal)and(shrink(q)<>0) then
23825 begin print_err("Infinite glue shrinkage inserted from "); print_esc("skip");
23826 @.Infinite glue shrinkage...@>
23827 print_int(n);
23828 help3("The correction glue for page breaking with insertions")@/
23829 ("must have finite shrinkability. But you may proceed,")@/
23830 ("since the offensive shrinkability has been made finite.");
23831 error;
23832 end;
23833 end
23834
23835 @ Here is the code that will split a long footnote between pages, in an
23836 emergency. The current situation deserves to be recapitulated: Node |p|
23837 is an insertion into box |n|; the insertion will not fit, in its entirety,
23838 either because it would make the total contents of box |n| greater than
23839 \.{\\dimen} |n|, or because it would make the incremental amount of growth
23840 |h| greater than the available space |delta|, or both. (This amount |h| has
23841 been weighted by the insertion scaling factor, i.e., by \.{\\count} |n|
23842 over 1000.) Now we will choose the best way to break the vlist of the
23843 insertion, using the same criteria as in the \.{\\vsplit} operation.
23844
23845 @<Find the best way to split the insertion...@>=
23846 begin if count(n)<=0 then w:=max_dimen
23847 else begin w:=page_goal-page_total-page_depth;
23848 if count(n)<>1000 then w:=x_over_n(w,count(n))*1000;
23849 end;
23850 if w>dimen(n)-height(r) then w:=dimen(n)-height(r);
23851 q:=vert_break(ins_ptr(p),w,depth(p));
23852 height(r):=height(r)+best_height_plus_depth;
23853 @!stat if tracing_pages>0 then @<Display the insertion split cost@>;@+tats@;@/
23854 if count(n)<>1000 then
23855 best_height_plus_depth:=x_over_n(best_height_plus_depth,1000)*count(n);
23856 page_goal:=page_goal-best_height_plus_depth;
23857 type(r):=split_up; broken_ptr(r):=q; broken_ins(r):=p;
23858 if q=null then insert_penalties:=insert_penalties+eject_penalty
23859 else if type(q)=penalty_node then insert_penalties:=insert_penalties+penalty(q);
23860 end
23861
23862 @ @<Display the insertion split cost@>=
23863 begin begin_diagnostic; print_nl("% split"); print_int(n);
23864 @.split@>
23865 print(" to "); print_scaled(w);
23866 print_char(","); print_scaled(best_height_plus_depth);@/
23867 print(" p=");
23868 if q=null then print_int(eject_penalty)
23869 else if type(q)=penalty_node then print_int(penalty(q))
23870 else print_char("0");
23871 end_diagnostic(false);
23872 end
23873
23874 @ When the page builder has looked at as much material as could appear before
23875 the next page break, it makes its decision. The break that gave minimum
23876 badness will be used to put a completed ``page'' into box 255, with insertions
23877 appended to their other boxes.
23878
23879 We also set the values of |top_mark|, |first_mark|, and |bot_mark|. The
23880 program uses the fact that |bot_mark<>null| implies |first_mark<>null|;
23881 it also knows that |bot_mark=null| implies |top_mark=first_mark=null|.
23882
23883 The |fire_up| subroutine prepares to output the current page at the best
23884 place; then it fires up the user's output routine, if there is one,
23885 or it simply ships out the page. There is one parameter, |c|, which represents
23886 the node that was being contributed to the page when the decision to
23887 force an output was made.
23888
23889 @<Declare the procedure called |fire_up|@>=
23890 procedure fire_up(@!c:pointer);
23891 label exit;
23892 var p,@!q,@!r,@!s:pointer; {nodes being examined and/or changed}
23893 @!prev_p:pointer; {predecessor of |p|}
23894 @!n:min_quarterword..biggest_reg; {insertion box number}
23895 @!wait:boolean; {should the present insertion be held over?}
23896 @!save_vbadness:integer; {saved value of |vbadness|}
23897 @!save_vfuzz: scaled; {saved value of |vfuzz|}
23898 @!save_split_top_skip: pointer; {saved value of |split_top_skip|}
23899 begin @<Set the value of |output_penalty|@>;
23900 if sa_mark<>null then
23901 if do_marks(fire_up_init,0,sa_mark) then sa_mark:=null;
23902 if bot_mark<>null then
23903 begin if top_mark<>null then delete_token_ref(top_mark);
23904 top_mark:=bot_mark; add_token_ref(top_mark);
23905 delete_token_ref(first_mark); first_mark:=null;
23906 end;
23907 @<Put the \(o)optimal current page into box 255, update |first_mark| and
23908 |bot_mark|, append insertions to their boxes, and put the
23909 remaining nodes back on the contribution list@>;
23910 if sa_mark<>null then
23911 if do_marks(fire_up_done,0,sa_mark) then sa_mark:=null;
23912 if (top_mark<>null)and(first_mark=null) then
23913 begin first_mark:=top_mark; add_token_ref(top_mark);
23914 end;
23915 if output_routine<>null then
23916 if dead_cycles>=max_dead_cycles then
23917 @<Explain that too many dead cycles have occurred in a row@>
23918 else @<Fire up the user's output routine and |return|@>;
23919 @<Perform the default output routine@>;
23920 exit:end;
23921
23922 @ @<Set the value of |output_penalty|@>=
23923 if type(best_page_break)=penalty_node then
23924 begin geq_word_define(int_base+output_penalty_code,penalty(best_page_break));
23925 penalty(best_page_break):=inf_penalty;
23926 end
23927 else geq_word_define(int_base+output_penalty_code,inf_penalty)
23928
23929 @ As the page is finally being prepared for output,
23930 pointer |p| runs through the vlist, with |prev_p| trailing behind;
23931 pointer |q| is the tail of a list of insertions that
23932 are being held over for a subsequent page.
23933
23934 @<Put the \(o)optimal current page into box 255...@>=
23935 if c=best_page_break then best_page_break:=null; {|c| not yet linked in}
23936 @<Ensure that box 255 is empty before output@>;
23937 insert_penalties:=0; {this will count the number of insertions held over}
23938 save_split_top_skip:=split_top_skip;
23939 if holding_inserts<=0 then
23940 @<Prepare all the boxes involved in insertions to act as queues@>;
23941 q:=hold_head; link(q):=null; prev_p:=page_head; p:=link(prev_p);
23942 while p<>best_page_break do
23943 begin if type(p)=ins_node then
23944 begin if holding_inserts<=0 then
23945 @<Either insert the material specified by node |p| into the
23946 appropriate box, or hold it for the next page;
23947 also delete node |p| from the current page@>;
23948 end
23949 else if type(p)=mark_node then
23950 if mark_class(p)<>0 then @<Update the current marks for |fire_up|@>
23951 else @<Update the values of
23952 |first_mark| and |bot_mark|@>;
23953 prev_p:=p; p:=link(prev_p);
23954 end;
23955 split_top_skip:=save_split_top_skip;
23956 @<Break the current page at node |p|, put it in box~255,
23957 and put the remaining nodes on the contribution list@>;
23958 @<Delete \(t)the page-insertion nodes@>
23959
23960 @ @<Ensure that box 255 is empty before output@>=
23961 if box(255)<>null then
23962 begin print_err(""); print_esc("box"); print("255 is not void");
23963 @:box255}{\.{\\box255 is not void}@>
23964 help2("You shouldn't use \box255 except in \output routines.")@/
23965 ("Proceed, and I'll discard its present contents.");
23966 box_error(255);
23967 end
23968
23969 @ @<Update the values of |first_mark| and |bot_mark|@>=
23970 begin if first_mark=null then
23971 begin first_mark:=mark_ptr(p);
23972 add_token_ref(first_mark);
23973 end;
23974 if bot_mark<>null then delete_token_ref(bot_mark);
23975 bot_mark:=mark_ptr(p); add_token_ref(bot_mark);
23976 end
23977
23978 @ When the following code is executed, the current page runs from node
23979 |link(page_head)| to node |prev_p|, and the nodes from |p| to |page_tail|
23980 are to be placed back at the front of the contribution list. Furthermore
23981 the heldover insertions appear in a list from |link(hold_head)| to |q|; we
23982 will put them into the current page list for safekeeping while the user's
23983 output routine is active. We might have |q=hold_head|; and |p=null| if
23984 and only if |prev_p=page_tail|. Error messages are suppressed within
23985 |vpackage|, since the box might appear to be overfull or underfull simply
23986 because the stretch and shrink from the \.{\\skip} registers for inserts
23987 are not actually present in the box.
23988
23989 @<Break the current page at node |p|, put it...@>=
23990 if p<>null then
23991 begin if link(contrib_head)=null then
23992 if nest_ptr=0 then tail:=page_tail
23993 else contrib_tail:=page_tail;
23994 link(page_tail):=link(contrib_head);
23995 link(contrib_head):=p;
23996 link(prev_p):=null;
23997 end;
23998 save_vbadness:=vbadness; vbadness:=inf_bad;
23999 save_vfuzz:=vfuzz; vfuzz:=max_dimen; {inhibit error messages}
24000 box(255):=vpackage(link(page_head),best_size,exactly,page_max_depth);
24001 vbadness:=save_vbadness; vfuzz:=save_vfuzz;
24002 if last_glue<>max_halfword then delete_glue_ref(last_glue);
24003 @<Start a new current page@>; {this sets |last_glue:=max_halfword|}
24004 if q<>hold_head then
24005 begin link(page_head):=link(hold_head); page_tail:=q;
24006 end
24007
24008 @ If many insertions are supposed to go into the same box, we want to know
24009 the position of the last node in that box, so that we don't need to waste time
24010 when linking further information into it. The |last_ins_ptr| fields of the
24011 page insertion nodes are therefore used for this purpose during the
24012 packaging phase.
24013
24014 @<Prepare all the boxes involved in insertions to act as queues@>=
24015 begin r:=link(page_ins_head);
24016 while r<>page_ins_head do
24017 begin if best_ins_ptr(r)<>null then
24018 begin n:=qo(subtype(r)); ensure_vbox(n);
24019 if box(n)=null then box(n):=new_null_box;
24020 p:=box(n)+list_offset;
24021 while link(p)<>null do p:=link(p);
24022 last_ins_ptr(r):=p;
24023 end;
24024 r:=link(r);
24025 end;
24026 end
24027
24028 @ @<Delete \(t)the page-insertion nodes@>=
24029 r:=link(page_ins_head);
24030 while r<>page_ins_head do
24031 begin q:=link(r); free_node(r,page_ins_node_size); r:=q;
24032 end;
24033 link(page_ins_head):=page_ins_head
24034
24035 @ We will set |best_ins_ptr:=null| and package the box corresponding to
24036 insertion node~|r|, just after making the final insertion into that box.
24037 If this final insertion is `|split_up|', the remainder after splitting
24038 and pruning (if any) will be carried over to the next page.
24039
24040 @<Either insert the material specified by node |p| into...@>=
24041 begin r:=link(page_ins_head);
24042 while subtype(r)<>subtype(p) do r:=link(r);
24043 if best_ins_ptr(r)=null then wait:=true
24044 else begin wait:=false; s:=last_ins_ptr(r); link(s):=ins_ptr(p);
24045 if best_ins_ptr(r)=p then
24046 @<Wrap up the box specified by node |r|, splitting node |p| if
24047 called for; set |wait:=true| if node |p| holds a remainder after
24048 splitting@>
24049 else begin while link(s)<>null do s:=link(s);
24050 last_ins_ptr(r):=s;
24051 end;
24052 end;
24053 @<Either append the insertion node |p| after node |q|, and remove it
24054 from the current page, or delete |node(p)|@>;
24055 end
24056
24057 @ @<Wrap up the box specified by node |r|, splitting node |p| if...@>=
24058 begin if type(r)=split_up then
24059 if (broken_ins(r)=p)and(broken_ptr(r)<>null) then
24060 begin while link(s)<>broken_ptr(r) do s:=link(s);
24061 link(s):=null;
24062 split_top_skip:=split_top_ptr(p);
24063 ins_ptr(p):=prune_page_top(broken_ptr(r),false);
24064 if ins_ptr(p)<>null then
24065 begin temp_ptr:=vpack(ins_ptr(p),natural);
24066 height(p):=height(temp_ptr)+depth(temp_ptr);
24067 free_node(temp_ptr,box_node_size); wait:=true;
24068 end;
24069 end;
24070 best_ins_ptr(r):=null;
24071 n:=qo(subtype(r));
24072 temp_ptr:=list_ptr(box(n));
24073 free_node(box(n),box_node_size);
24074 box(n):=vpack(temp_ptr,natural);
24075 end
24076
24077 @ @<Either append the insertion node |p|...@>=
24078 link(prev_p):=link(p); link(p):=null;
24079 if wait then
24080 begin link(q):=p; q:=p; incr(insert_penalties);
24081 end
24082 else begin delete_glue_ref(split_top_ptr(p));
24083 free_node(p,ins_node_size);
24084 end;
24085 p:=prev_p
24086
24087 @ The list of heldover insertions, running from |link(page_head)| to
24088 |page_tail|, must be moved to the contribution list when the user has
24089 specified no output routine.
24090
24091 @<Perform the default output routine@>=
24092 begin if link(page_head)<>null then
24093 begin if link(contrib_head)=null then
24094 if nest_ptr=0 then tail:=page_tail@+else contrib_tail:=page_tail
24095 else link(page_tail):=link(contrib_head);
24096 link(contrib_head):=link(page_head);
24097 link(page_head):=null; page_tail:=page_head;
24098 end;
24099 flush_node_list(page_disc); page_disc:=null;
24100 ship_out(box(255)); box(255):=null;
24101 end
24102
24103 @ @<Explain that too many dead cycles have occurred in a row@>=
24104 begin print_err("Output loop---"); print_int(dead_cycles);
24105 @.Output loop...@>
24106 print(" consecutive dead cycles");
24107 help3("I've concluded that your \output is awry; it never does a")@/
24108 ("\shipout, so I'm shipping \box255 out myself. Next time")@/
24109 ("increase \maxdeadcycles if you want me to be more patient!"); error;
24110 end
24111
24112 @ @<Fire up the user's output routine and |return|@>=
24113 begin output_active:=true;
24114 incr(dead_cycles);
24115 push_nest; mode:=-vmode; prev_depth:=ignore_depth; mode_line:=-line;
24116 begin_token_list(output_routine,output_text);
24117 new_save_level(output_group); normal_paragraph;
24118 scan_left_brace;
24119 return;
24120 end
24121
24122 @ When the user's output routine finishes, it has constructed a vlist
24123 in internal vertical mode, and \TeX\ will do the following:
24124
24125 @<Resume the page builder after an output routine has come to an end@>=
24126 begin if (loc<>null) or
24127 ((token_type<>output_text)and(token_type<>backed_up)) then
24128 @<Recover from an unbalanced output routine@>;
24129 end_token_list; {conserve stack space in case more outputs are triggered}
24130 end_graf; unsave; output_active:=false; insert_penalties:=0;@/
24131 @<Ensure that box 255 is empty after output@>;
24132 if tail<>head then {current list goes after heldover insertions}
24133 begin link(page_tail):=link(head);
24134 page_tail:=tail;
24135 end;
24136 if link(page_head)<>null then {and both go before heldover contributions}
24137 begin if link(contrib_head)=null then contrib_tail:=page_tail;
24138 link(page_tail):=link(contrib_head);
24139 link(contrib_head):=link(page_head);
24140 link(page_head):=null; page_tail:=page_head;
24141 end;
24142 flush_node_list(page_disc); page_disc:=null;
24143 pop_nest; build_page;
24144 end
24145
24146 @ @<Recover from an unbalanced output routine@>=
24147 begin print_err("Unbalanced output routine");
24148 @.Unbalanced output routine@>
24149 help2("Your sneaky output routine has problematic {'s and/or }'s.")@/
24150 ("I can't handle that very well; good luck."); error;
24151 repeat get_token;
24152 until loc=null;
24153 end {loops forever if reading from a file, since |null=min_halfword<=0|}
24154
24155 @ @<Ensure that box 255 is empty after output@>=
24156 if box(255)<>null then
24157 begin print_err("Output routine didn't use all of ");
24158 print_esc("box"); print_int(255);
24159 @.Output routine didn't use...@>
24160 help3("Your \output commands should empty \box255,")@/
24161 ("e.g., by saying `\shipout\box255'.")@/
24162 ("Proceed; I'll discard its present contents.");
24163 box_error(255);
24164 end
24165
24166 @* \[46] The chief executive.
24167 We come now to the |main_control| routine, which contains the master
24168 switch that causes all the various pieces of \TeX\ to do their things,
24169 in the right order.
24170
24171 In a sense, this is the grand climax of the program: It applies all the
24172 tools that we have worked so hard to construct. In another sense, this is
24173 the messiest part of the program: It necessarily refers to other pieces
24174 of code all over the place, so that a person can't fully understand what is
24175 going on without paging back and forth to be reminded of conventions that
24176 are defined elsewhere. We are now at the hub of the web, the central nervous
24177 system that touches most of the other parts and ties them together.
24178 @^brain@>
24179
24180 The structure of |main_control| itself is quite simple. There's a label
24181 called |big_switch|, at which point the next token of input is fetched
24182 using |get_x_token|. Then the program branches at high speed into one of
24183 about 100 possible directions, based on the value of the current
24184 mode and the newly fetched command code; the sum |abs(mode)+cur_cmd|
24185 indicates what to do next. For example, the case `|vmode+letter|' arises
24186 when a letter occurs in vertical mode (or internal vertical mode); this
24187 case leads to instructions that initialize a new paragraph and enter
24188 horizontal mode.
24189
24190 The big |case| statement that contains this multiway switch has been labeled
24191 |reswitch|, so that the program can |goto reswitch| when the next token
24192 has already been fetched. Most of the cases are quite short; they call
24193 an ``action procedure'' that does the work for that case, and then they
24194 either |goto reswitch| or they ``fall through'' to the end of the |case|
24195 statement, which returns control back to |big_switch|. Thus, |main_control|
24196 is not an extremely large procedure, in spite of the multiplicity of things
24197 it must do; it is small enough to be handled by \PASCAL\ compilers that put
24198 severe restrictions on procedure size.
24199 @!@^action procedure@>
24200
24201 One case is singled out for special treatment, because it accounts for most
24202 of \TeX's activities in typical applications. The process of reading simple
24203 text and converting it into |char_node| records, while looking for ligatures
24204 and kerns, is part of \TeX's ``inner loop''; the whole program runs
24205 efficiently when its inner loop is fast, so this part has been written
24206 with particular care.
24207
24208 @ We shall concentrate first on the inner loop of |main_control|, deferring
24209 consideration of the other cases until later.
24210 @^inner loop@>
24211
24212 @d big_switch=60 {go here to branch on the next token of input}
24213 @d main_loop=70 {go here to typeset a string of consecutive characters}
24214 @d collect_native=71 {go here to collect characters in a "native" font string}
24215 @d collected=72
24216 @d main_loop_wrapup=80 {go here to finish a character or ligature}
24217 @d main_loop_move=90 {go here to advance the ligature cursor}
24218 @d main_loop_move_lig=95 {same, when advancing past a generated ligature}
24219 @d main_loop_lookahead=100 {go here to bring in another character, if any}
24220 @d main_lig_loop=110 {go here to check for ligatures or kerning}
24221 @d append_normal_space=120 {go here to append a normal space between words}
24222 @#
24223 @d pdfbox_crop=1 {|pdf_box_type| passed to |find_pic_file|}
24224 @d pdfbox_media=2
24225 @d pdfbox_bleed=3
24226 @d pdfbox_trim=4
24227 @d pdfbox_art=5
24228 @d pdfbox_none=6
24229
24230 @p @t\4@>@<Declare action procedures for use by |main_control|@>@;
24231 @t\4@>@<Declare the procedure called |handle_right_brace|@>@;
24232 procedure main_control; {governs \TeX's activities}
24233 label big_switch,reswitch,main_loop,main_loop_wrapup,
24234 main_loop_move,main_loop_move+1,main_loop_move+2,main_loop_move_lig,
24235 main_loop_lookahead,main_loop_lookahead+1,
24236 main_lig_loop,main_lig_loop+1,main_lig_loop+2,
24237 collect_native,collected,
24238 append_normal_space,exit;
24239 var@!t:integer; {general-purpose temporary variable}
24240 begin if every_job<>null then begin_token_list(every_job,every_job_text);
24241 big_switch: get_x_token;@/
24242 reswitch: @<Give diagnostic information, if requested@>;
24243 case abs(mode)+cur_cmd of
24244 hmode+letter,hmode+other_char,hmode+char_given: goto main_loop;
24245 hmode+char_num: begin scan_usv_num; cur_chr:=cur_val; goto main_loop;@+end;
24246 hmode+no_boundary: begin get_x_token;
24247 if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given)or
24248 (cur_cmd=char_num) then cancel_boundary:=true;
24249 goto reswitch;
24250 end;
24251 othercases begin
24252 if abs(mode)=hmode then check_for_post_char_toks(big_switch);
24253 case abs(mode)+cur_cmd of
24254 hmode+spacer: if space_factor=1000 then goto append_normal_space
24255 else app_space;
24256 hmode+ex_space,mmode+ex_space: goto append_normal_space;
24257 @t\4@>@<Cases of |main_control| that are not part of the inner loop@>
24258 end
24259 end
24260 endcases; {of the big |case| statement}
24261 goto big_switch;
24262 main_loop:@<Append character |cur_chr| and the following characters (if~any)
24263 to the current hlist in the current font; |goto reswitch| when
24264 a non-character has been fetched@>;
24265 append_normal_space:check_for_post_char_toks(big_switch);
24266 @<Append a normal inter-word space to the current list,
24267 then |goto big_switch|@>;
24268 exit:end;
24269
24270 @ When a new token has just been fetched at |big_switch|, we have an
24271 ideal place to monitor \TeX's activity.
24272 @^debugging@>
24273
24274 @<Give diagnostic information, if requested@>=
24275 if interrupt<>0 then if OK_to_interrupt then
24276 begin back_input; check_interrupt; goto big_switch;
24277 end;
24278 @!debug if panicking then check_mem(false);@+@;@+gubed
24279 if tracing_commands>0 then show_cur_cmd_chr
24280
24281 @ The following part of the program was first written in a structured
24282 manner, according to the philosophy that ``premature optimization is
24283 the root of all evil.'' Then it was rearranged into pieces of
24284 spaghetti so that the most common actions could proceed with little or
24285 no redundancy.
24286
24287 The original unoptimized form of this algorithm resembles the
24288 |reconstitute| procedure, which was described earlier in connection with
24289 hyphenation. Again we have an implied ``cursor'' between characters
24290 |cur_l| and |cur_r|. The main difference is that the |lig_stack| can now
24291 contain a charnode as well as pseudo-ligatures; that stack is now
24292 usually nonempty, because the next character of input (if any) has been
24293 appended to it. In |main_control| we have
24294 $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
24295 |font_bchar[cur_font]|,&otherwise;\cr}$$
24296 except when |character(lig_stack)=font_false_bchar[cur_font]|.
24297 Several additional global variables are needed.
24298
24299 @<Glob...@>=
24300 @!main_f:internal_font_number; {the current font}
24301 @!main_i:four_quarters; {character information bytes for |cur_l|}
24302 @!main_j:four_quarters; {ligature/kern command}
24303 @!main_k:font_index; {index into |font_info|}
24304 @!main_p:pointer; {temporary register for list manipulation}
24305 @!main_pp,@!main_ppp:pointer; {more temporary registers for list manipulation}
24306 @!main_h:pointer; {temp for hyphen offset in native-font text}
24307 @!is_hyph:boolean; {whether the last char seen is the font's hyphenchar}
24308 @!space_class:integer;
24309 @!prev_class:integer;
24310 @!main_s:integer; {space factor value}
24311 @!bchar:halfword; {boundary character of current font, or |non_char|}
24312 @!false_bchar:halfword; {nonexistent character matching |bchar|, or |non_char|}
24313 @!cancel_boundary:boolean; {should the left boundary be ignored?}
24314 @!ins_disc:boolean; {should we insert a discretionary node?}
24315
24316 @ The boolean variables of the main loop are normally false, and always reset
24317 to false before the loop is left. That saves us the extra work of initializing
24318 each time.
24319
24320 @<Set init...@>=
24321 ligature_present:=false; cancel_boundary:=false; lft_hit:=false; rt_hit:=false;
24322 ins_disc:=false;
24323
24324 @ We leave the |space_factor| unchanged if |sf_code(cur_chr)=0|; otherwise we
24325 set it equal to |sf_code(cur_chr)|, except that it should never change
24326 from a value less than 1000 to a value exceeding 1000. The most common
24327 case is |sf_code(cur_chr)=1000|, so we want that case to be fast.
24328
24329 The overall structure of the main loop is presented here. Some program labels
24330 are inside the individual sections.
24331 @^inner loop@>
24332
24333 @d adjust_space_factor==@t@>@;@/
24334 main_s:=sf_code(cur_chr) mod @"10000;
24335 if main_s=1000 then space_factor:=1000
24336 else if main_s<1000 then
24337 begin if main_s>0 then space_factor:=main_s;
24338 end
24339 else if space_factor<1000 then space_factor:=1000
24340 else space_factor:=main_s
24341
24342 @d check_for_inter_char_toks(#)=={check for a spacing token list, goto |#| if found,
24343 or |big_switch| in case of the initial letter of a run}
24344 cur_ptr:=null;
24345 space_class:=sf_code(cur_chr) div @"10000;
24346
24347 if XeTeX_inter_char_tokens_en and space_class <> char_class_ignored then begin {class 4096 = ignored (for combining marks etc)}
24348 if prev_class = char_class_boundary then begin {boundary}
24349 if (state<>token_list) or (token_type<>backed_up_char) then begin
24350 find_sa_element(inter_char_val, char_class_boundary*char_class_limit + space_class, false);
24351 if (cur_ptr<>null) and (sa_ptr(cur_ptr)<>null) then begin
24352 if cur_cmd<>letter then cur_cmd:=other_char;
24353 cur_tok:=(cur_cmd*max_char_val)+cur_chr;
24354 back_input; token_type:=backed_up_char;
24355 begin_token_list(sa_ptr(cur_ptr), inter_char_text);
24356 goto big_switch;
24357 end
24358 end
24359 end else begin
24360 find_sa_element(inter_char_val, prev_class*char_class_limit + space_class, false);
24361 if (cur_ptr<>null) and (sa_ptr(cur_ptr)<>null) then begin
24362 if cur_cmd<>letter then cur_cmd:=other_char;
24363 cur_tok:=(cur_cmd*max_char_val)+cur_chr;
24364 back_input; token_type:=backed_up_char;
24365 begin_token_list(sa_ptr(cur_ptr), inter_char_text);
24366 prev_class:=char_class_boundary;
24367 goto #;
24368 end;
24369 end;
24370 prev_class:=space_class;
24371 end
24372
24373 @d check_for_post_char_toks(#)==
24374 if XeTeX_inter_char_tokens_en and (space_class<>char_class_ignored) and (prev_class<>char_class_boundary) then begin
24375 prev_class:=char_class_boundary;
24376 find_sa_element(inter_char_val, space_class*char_class_limit + char_class_boundary, false); {boundary}
24377 if (cur_ptr<>null) and (sa_ptr(cur_ptr)<>null) then begin
24378 if cur_cs=0 then begin
24379 if cur_cmd=char_num then cur_cmd:=other_char;
24380 cur_tok:=(cur_cmd*max_char_val)+cur_chr;
24381 end else cur_tok:=cs_token_flag+cur_cs;
24382 back_input;
24383 begin_token_list(sa_ptr(cur_ptr), inter_char_text);
24384 goto #;
24385 end;
24386 end
24387
24388 @<Append character |cur_chr|...@>=
24389
24390 prev_class:=char_class_boundary; {boundary}
24391
24392 { added code for native font support }
24393 if is_native_font(cur_font) then begin
24394 if mode>0 then if language<>clang then fix_language;
24395
24396 main_h:=0;
24397 main_f:=cur_font;
24398 native_len:=0;
24399
24400 collect_native:
24401 adjust_space_factor;
24402
24403 check_for_inter_char_toks(collected);
24404
24405 if (cur_chr > @"FFFF) then begin
24406 native_room(2);
24407 append_native((cur_chr - @"10000) div 1024 + @"D800);
24408 append_native((cur_chr - @"10000) mod 1024 + @"DC00);
24409 end else begin
24410 native_room(1);
24411 append_native(cur_chr);
24412 end;
24413 is_hyph:=(cur_chr = hyphen_char[main_f])
24414 or (XeTeX_dash_break_en and ((cur_chr = @"2014) or (cur_chr = @"2013)));
24415 if (main_h = 0) and is_hyph then main_h:=native_len;
24416
24417 {try to collect as many chars as possible in the same font}
24418 get_next;
24419 if (cur_cmd=letter) or (cur_cmd=other_char) or (cur_cmd=char_given) then goto collect_native;
24420 x_token;
24421 if (cur_cmd=letter) or (cur_cmd=other_char) or (cur_cmd=char_given) then goto collect_native;
24422 if cur_cmd=char_num then begin
24423 scan_usv_num;
24424 cur_chr:=cur_val;
24425 goto collect_native;
24426 end;
24427
24428 check_for_post_char_toks(collected);
24429
24430 collected:
24431 if (font_mapping[main_f] <> 0) then begin
24432 main_k:=apply_mapping(font_mapping[main_f], native_text, native_len);
24433 native_len:=0;
24434 native_room(main_k);
24435 main_h:=0;
24436 for main_p:=0 to main_k - 1 do begin
24437 append_native(mapped_text[main_p]);
24438 if (main_h = 0) and ((mapped_text[main_p] = hyphen_char[main_f])
24439 or (XeTeX_dash_break_en and ((mapped_text[main_p] = @"2014) or (mapped_text[main_p] = @"2013)) ) )
24440 then main_h:=native_len;
24441 end
24442 end;
24443
24444 if tracing_lost_chars > 0 then begin
24445 temp_ptr:=0;
24446 while (temp_ptr < native_len) do begin
24447 main_k:=native_text[temp_ptr];
24448 incr(temp_ptr);
24449 if (main_k >= @"D800) and (main_k < @"DC00) then begin
24450 main_k:=@"10000 + (main_k - @"D800) * 1024;
24451 main_k:=main_k + native_text[temp_ptr] - @"DC00;
24452 incr(temp_ptr);
24453 end;
24454 if map_char_to_glyph(main_f, main_k) = 0 then
24455 char_warning(main_f, main_k);
24456 end
24457 end;
24458
24459 main_k:=native_len;
24460 main_pp:=tail;
24461
24462 if mode=hmode then begin
24463 main_ppp:=head;
24464
24465 { find node preceding tail, skipping discretionaries }
24466 while (main_ppp<>main_pp) and (link(main_ppp)<>main_pp) do begin
24467 if (not is_char_node(main_ppp)) and (type(main_ppp)=disc_node) then begin
24468 temp_ptr:=main_ppp;
24469 for main_p:=1 to replace_count(temp_ptr) do main_ppp:=link(main_ppp);
24470 end;
24471 if main_ppp<>main_pp then main_ppp:=link(main_ppp);
24472 end;
24473
24474 temp_ptr:=0;
24475 repeat
24476 if main_h = 0 then main_h:=main_k;
24477
24478 if is_native_word_node(main_pp)
24479 and (native_font(main_pp)=main_f)
24480 and (main_ppp<>main_pp)
24481 and (not is_char_node(main_ppp))
24482 and (type(main_ppp)<>disc_node)
24483 then begin
24484 { make a new temp string that contains the concatenated text of |tail| + the current word/fragment }
24485 main_k:=main_h + native_length(main_pp);
24486 native_room(main_k);
24487
24488 save_native_len:=native_len;
24489 for main_p:=0 to native_length(main_pp) - 1 do
24490 append_native(get_native_char(main_pp, main_p));
24491 for main_p:=0 to main_h - 1 do
24492 append_native(native_text[temp_ptr + main_p]);
24493
24494 do_locale_linebreaks(save_native_len, main_k);
24495
24496 native_len:=save_native_len; { discard the temp string }
24497 main_k:=native_len - main_h - temp_ptr; { and set |main_k| to remaining length of new word }
24498 temp_ptr:=main_h; { pointer to remaining fragment }
24499
24500 main_h:=0;
24501 while (main_h < main_k) and (native_text[temp_ptr + main_h] <> hyphen_char[main_f])
24502 and ( (not XeTeX_dash_break_en)
24503 or ((native_text[temp_ptr + main_h] <> @"2014) and (native_text[temp_ptr + main_h] <> @"2013)) )
24504 do incr(main_h); { look for next hyphen or end of text }
24505 if (main_h < main_k) then incr(main_h);
24506
24507 { remove the preceding node from the list }
24508 link(main_ppp):=link(main_pp);
24509 link(main_pp):=null;
24510 flush_node_list(main_pp);
24511 main_pp:=tail;
24512 while (link(main_ppp)<>main_pp) do
24513 main_ppp:=link(main_ppp);
24514 end else begin
24515 do_locale_linebreaks(temp_ptr, main_h); { append fragment of current word }
24516
24517 temp_ptr:=temp_ptr + main_h; { advance ptr to remaining fragment }
24518 main_k:=main_k - main_h; { decrement remaining length }
24519
24520 main_h:=0;
24521 while (main_h < main_k) and (native_text[temp_ptr + main_h] <> hyphen_char[main_f])
24522 and ( (not XeTeX_dash_break_en)
24523 or ((native_text[temp_ptr + main_h] <> @"2014) and (native_text[temp_ptr + main_h] <> @"2013)) )
24524 do incr(main_h); { look for next hyphen or end of text }
24525 if (main_h < main_k) then incr(main_h);
24526 end;
24527
24528 if (main_k > 0) or is_hyph then begin
24529 tail_append(new_disc); { add a break if we aren't at end of text (must be a hyphen),
24530 or if last char in original text was a hyphen }
24531 main_pp:=tail;
24532 end;
24533 until main_k = 0;
24534 end else begin
24535 { must be restricted hmode, so no need for line-breaking or discretionaries }
24536 { but there might already be explicit |disc_node|s in the list }
24537 main_ppp:=head;
24538
24539 { find node preceding tail, skipping discretionaries }
24540 while (main_ppp<>main_pp) and (link(main_ppp)<>main_pp) do begin
24541 if (not is_char_node(main_ppp)) and (type(main_ppp)=disc_node) then begin
24542 temp_ptr:=main_ppp;
24543 for main_p:=1 to replace_count(temp_ptr) do main_ppp:=link(main_ppp);
24544 end;
24545 if main_ppp<>main_pp then main_ppp:=link(main_ppp);
24546 end;
24547
24548 if is_native_word_node(main_pp)
24549 and (native_font(main_pp)=main_f)
24550 and (main_ppp<>main_pp)
24551 and (not is_char_node(main_ppp))
24552 and (type(main_ppp)<>disc_node)
24553 then begin
24554 { total string length for the new merged whatsit }
24555 link(main_pp):=new_native_word_node(main_f, main_k + native_length(main_pp));
24556 tail:=link(main_pp);
24557
24558 { copy text from the old one into the new }
24559 for main_p:=0 to native_length(main_pp) - 1 do
24560 set_native_char(tail, main_p, get_native_char(main_pp, main_p));
24561 { append the new text }
24562 for main_p:=0 to main_k - 1 do
24563 set_native_char(tail, main_p + native_length(main_pp), native_text[main_p]);
24564 set_native_metrics(tail, XeTeX_use_glyph_metrics);
24565
24566 { remove the preceding node from the list }
24567 main_p:=head;
24568 if main_p<>main_pp then
24569 while link(main_p)<>main_pp do
24570 main_p:=link(main_p);
24571 link(main_p):=link(main_pp);
24572 link(main_pp):=null;
24573 flush_node_list(main_pp);
24574 end else begin
24575 { package the current string into a |native_word| whatsit }
24576 link(main_pp):=new_native_word_node(main_f, main_k);
24577 tail:=link(main_pp);
24578 for main_p:=0 to main_k - 1 do
24579 set_native_char(tail, main_p, native_text[main_p]);
24580 set_native_metrics(tail, XeTeX_use_glyph_metrics);
24581 end
24582 end;
24583
24584 if XeTeX_interword_space_shaping_state > 0 then begin
24585 { |tail| is a word we have just appended. If it is preceded by another word
24586 with a normal inter-word space between (all in the same font), then we will
24587 measure that space in context and replace it with an adjusted glue value
24588 if it differs from the font's normal space. }
24589
24590 { First we look for the most recent |native_word| in the list and set |main_pp| to it.
24591 This is potentially expensive, in the case of very long paragraphs,
24592 but in practice it's negligible compared to the cost of shaping and measurement. }
24593 main_p := head;
24594 main_pp := null;
24595 while main_p <> tail do begin
24596 if is_native_word_node(main_p) then main_pp := main_p;
24597 main_p := link(main_p);
24598 end;
24599
24600 if (main_pp <> null) then begin
24601 { check if the font matches; if so, check the intervening nodes }
24602 if (native_font(main_pp) = main_f) then begin
24603 main_p := link(main_pp);
24604
24605 { Skip nodes that should be invisible to inter-word spacing, so that
24606 e.g., `\.{\\nobreak\\ }' doesn't prevent contextual measurement.
24607 This loop is guaranteed to end safely because it'll eventually hit
24608 |tail|, which is a |native_word| node, if nothing else intervenes. }
24609 while node_is_invisible_to_interword_space(main_p) do
24610 main_p := link(main_p);
24611
24612 if not is_char_node(main_p) and (type(main_p) = glue_node) then begin
24613 { We found a glue node: we might have an inter-word space to deal with.
24614 Again, skip nodes that should be invisible to inter-word spacing.
24615 We leave |main_p| pointing to the glue node; |main_pp| is the preceding word. }
24616 main_ppp := link(main_p);
24617 while node_is_invisible_to_interword_space(main_ppp) do
24618 main_ppp := link(main_ppp);
24619
24620 if main_ppp = tail then begin
24621 { We found a candidate inter-word space! Collect the characters of both words,
24622 separated by a single space, into a |native_word| node and measure its overall width. }
24623 temp_ptr := new_native_word_node(main_f, native_length(main_pp) + 1 + native_length(tail));
24624 main_k := 0;
24625 for t := 0 to native_length(main_pp)-1 do begin
24626 set_native_char(temp_ptr, main_k, get_native_char(main_pp, t));
24627 incr(main_k);
24628 end;
24629 set_native_char(temp_ptr, main_k, " ");
24630 incr(main_k);
24631 for t := 0 to native_length(tail)-1 do begin
24632 set_native_char(temp_ptr, main_k, get_native_char(tail, t));
24633 incr(main_k);
24634 end;
24635 set_native_metrics(temp_ptr, XeTeX_use_glyph_metrics);
24636
24637 { The contextual space width is the difference between this width and
24638 the sum of the two words measured separately. }
24639 t := width(temp_ptr) - width(main_pp) - width(tail);
24640 free_node(temp_ptr, native_size(temp_ptr));
24641
24642 { If the desired width differs from the font's default word space,
24643 we will insert a suitable kern after the existing glue.
24644 Because kerns are discardable, this will behave OK during line breaking,
24645 and it's easier than actually modifying/replacing the glue node. }
24646 if t <> width(font_glue[main_f]) then begin
24647 temp_ptr := new_kern(t - width(font_glue[main_f]));
24648 subtype(temp_ptr) := space_adjustment;
24649 link(temp_ptr) := link(main_p);
24650 link(main_p) := temp_ptr;
24651 end
24652 end
24653 end
24654 end
24655 end
24656 end;
24657
24658 if cur_ptr<>null then goto big_switch
24659 else goto reswitch;
24660 end;
24661 { End of added code for native fonts }
24662
24663 adjust_space_factor;@/
24664 check_for_inter_char_toks(big_switch);
24665 main_f:=cur_font;
24666 bchar:=font_bchar[main_f]; false_bchar:=font_false_bchar[main_f];
24667 if mode>0 then if language<>clang then fix_language;
24668 fast_get_avail(lig_stack); font(lig_stack):=main_f; cur_l:=qi(cur_chr);
24669 character(lig_stack):=cur_l;@/
24670 cur_q:=tail;
24671 if cancel_boundary then
24672 begin cancel_boundary:=false; main_k:=non_address;
24673 end
24674 else main_k:=bchar_label[main_f];
24675 if main_k=non_address then goto main_loop_move+2; {no left boundary processing}
24676 cur_r:=cur_l; cur_l:=non_char;
24677 goto main_lig_loop+1; {begin with cursor after left boundary}
24678 @#
24679 main_loop_wrapup:@<Make a ligature node, if |ligature_present|;
24680 insert a null discretionary, if appropriate@>;
24681 main_loop_move:@<If the cursor is immediately followed by the right boundary,
24682 |goto reswitch|; if it's followed by an invalid character, |goto big_switch|;
24683 otherwise move the cursor one step to the right and |goto main_lig_loop|@>;
24684 main_loop_lookahead:@<Look ahead for another character, or leave |lig_stack|
24685 empty if there's none there@>;
24686 main_lig_loop:@<If there's a ligature/kern command relevant to |cur_l| and
24687 |cur_r|, adjust the text appropriately; exit to |main_loop_wrapup|@>;
24688 main_loop_move_lig:@<Move the cursor past a pseudo-ligature, then
24689 |goto main_loop_lookahead| or |main_lig_loop|@>
24690
24691 @ If |link(cur_q)| is nonnull when |wrapup| is invoked, |cur_q| points to
24692 the list of characters that were consumed while building the ligature
24693 character~|cur_l|.
24694
24695 A discretionary break is not inserted for an explicit hyphen when we are in
24696 restricted horizontal mode. In particular, this avoids putting discretionary
24697 nodes inside of other discretionaries.
24698 @^inner loop@>
24699
24700 @d pack_lig(#)== {the parameter is either |rt_hit| or |false|}
24701 begin main_p:=new_ligature(main_f,cur_l,link(cur_q));
24702 if lft_hit then
24703 begin subtype(main_p):=2; lft_hit:=false;
24704 end;
24705 if # then if lig_stack=null then
24706 begin incr(subtype(main_p)); rt_hit:=false;
24707 end;
24708 link(cur_q):=main_p; tail:=main_p; ligature_present:=false;
24709 end
24710
24711 @d wrapup(#)==if cur_l<non_char then
24712 begin if link(cur_q)>null then
24713 if character(tail)=qi(hyphen_char[main_f]) then ins_disc:=true;
24714 if ligature_present then pack_lig(#);
24715 if ins_disc then
24716 begin ins_disc:=false;
24717 if mode>0 then tail_append(new_disc);
24718 end;
24719 end
24720
24721 @<Make a ligature node, if |ligature_present|;...@>=
24722 wrapup(rt_hit)
24723
24724 @ @<If the cursor is immediately followed by the right boundary...@>=
24725 @^inner loop@>
24726 if lig_stack=null then goto reswitch;
24727 cur_q:=tail; cur_l:=character(lig_stack);
24728 main_loop_move+1:if not is_char_node(lig_stack) then goto main_loop_move_lig;
24729 main_loop_move+2:if(cur_chr<font_bc[main_f])or(cur_chr>font_ec[main_f]) then
24730 begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
24731 end;
24732 main_i:=char_info(main_f)(cur_l);
24733 if not char_exists(main_i) then
24734 begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
24735 end;
24736 link(tail):=lig_stack; tail:=lig_stack {|main_loop_lookahead| is next}
24737
24738 @ Here we are at |main_loop_move_lig|.
24739 When we begin this code we have |cur_q=tail| and |cur_l=character(lig_stack)|.
24740
24741 @<Move the cursor past a pseudo-ligature...@>=
24742 main_p:=lig_ptr(lig_stack);
24743 if main_p>null then tail_append(main_p); {append a single character}
24744 temp_ptr:=lig_stack; lig_stack:=link(temp_ptr);
24745 free_node(temp_ptr,small_node_size);
24746 main_i:=char_info(main_f)(cur_l); ligature_present:=true;
24747 if lig_stack=null then
24748 if main_p>null then goto main_loop_lookahead
24749 else cur_r:=bchar
24750 else cur_r:=character(lig_stack);
24751 goto main_lig_loop
24752
24753 @ The result of \.{\\char} can participate in a ligature or kern, so we must
24754 look ahead for it.
24755
24756 @<Look ahead for another character...@>=
24757 get_next; {set only |cur_cmd| and |cur_chr|, for speed}
24758 if cur_cmd=letter then goto main_loop_lookahead+1;
24759 if cur_cmd=other_char then goto main_loop_lookahead+1;
24760 if cur_cmd=char_given then goto main_loop_lookahead+1;
24761 x_token; {now expand and set |cur_cmd|, |cur_chr|, |cur_tok|}
24762 if cur_cmd=letter then goto main_loop_lookahead+1;
24763 if cur_cmd=other_char then goto main_loop_lookahead+1;
24764 if cur_cmd=char_given then goto main_loop_lookahead+1;
24765 if cur_cmd=char_num then
24766 begin scan_char_num; cur_chr:=cur_val; goto main_loop_lookahead+1;
24767 end;
24768 if cur_cmd=no_boundary then bchar:=non_char;
24769 cur_r:=bchar; lig_stack:=null; goto main_lig_loop;
24770 main_loop_lookahead+1: adjust_space_factor;
24771 check_for_inter_char_toks(big_switch);
24772 fast_get_avail(lig_stack); font(lig_stack):=main_f;
24773 cur_r:=qi(cur_chr); character(lig_stack):=cur_r;
24774 if cur_r=false_bchar then cur_r:=non_char {this prevents spurious ligatures}
24775
24776 @ Even though comparatively few characters have a lig/kern program, several
24777 of the instructions here count as part of \TeX's inner loop, since a
24778 @^inner loop@>
24779 potentially long sequential search must be performed. For example, tests with
24780 Computer Modern Roman showed that about 40 per cent of all characters
24781 actually encountered in practice had a lig/kern program, and that about four
24782 lig/kern commands were investigated for every such character.
24783
24784 At the beginning of this code we have |main_i=char_info(main_f)(cur_l)|.
24785
24786 @<If there's a ligature/kern command...@>=
24787 if char_tag(main_i)<>lig_tag then goto main_loop_wrapup;
24788 if cur_r=non_char then goto main_loop_wrapup;
24789 main_k:=lig_kern_start(main_f)(main_i); main_j:=font_info[main_k].qqqq;
24790 if skip_byte(main_j)<=stop_flag then goto main_lig_loop+2;
24791 main_k:=lig_kern_restart(main_f)(main_j);
24792 main_lig_loop+1:main_j:=font_info[main_k].qqqq;
24793 main_lig_loop+2:if next_char(main_j)=cur_r then
24794 if skip_byte(main_j)<=stop_flag then
24795 @<Do ligature or kern command, returning to |main_lig_loop|
24796 or |main_loop_wrapup| or |main_loop_move|@>;
24797 if skip_byte(main_j)=qi(0) then incr(main_k)
24798 else begin if skip_byte(main_j)>=stop_flag then goto main_loop_wrapup;
24799 main_k:=main_k+qo(skip_byte(main_j))+1;
24800 end;
24801 goto main_lig_loop+1
24802
24803 @ When a ligature or kern instruction matches a character, we know from
24804 |read_font_info| that the character exists in the font, even though we
24805 haven't verified its existence in the normal way.
24806
24807 This section could be made into a subroutine, if the code inside
24808 |main_control| needs to be shortened.
24809
24810 \chardef\?='174 % vertical line to indicate character retention
24811
24812 @<Do ligature or kern command...@>=
24813 begin if op_byte(main_j)>=kern_flag then
24814 begin wrapup(rt_hit);
24815 tail_append(new_kern(char_kern(main_f)(main_j))); goto main_loop_move;
24816 end;
24817 if cur_l=non_char then lft_hit:=true
24818 else if lig_stack=null then rt_hit:=true;
24819 check_interrupt; {allow a way out in case there's an infinite ligature loop}
24820 case op_byte(main_j) of
24821 qi(1),qi(5):begin cur_l:=rem_byte(main_j); {\.{=:\?}, \.{=:\?>}}
24822 main_i:=char_info(main_f)(cur_l); ligature_present:=true;
24823 end;
24824 qi(2),qi(6):begin cur_r:=rem_byte(main_j); {\.{\?=:}, \.{\?=:>}}
24825 if lig_stack=null then {right boundary character is being consumed}
24826 begin lig_stack:=new_lig_item(cur_r); bchar:=non_char;
24827 end
24828 else if is_char_node(lig_stack) then {|link(lig_stack)=null|}
24829 begin main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
24830 lig_ptr(lig_stack):=main_p;
24831 end
24832 else character(lig_stack):=cur_r;
24833 end;
24834 qi(3):begin cur_r:=rem_byte(main_j); {\.{\?=:\?}}
24835 main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
24836 link(lig_stack):=main_p;
24837 end;
24838 qi(7),qi(11):begin wrapup(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
24839 cur_q:=tail; cur_l:=rem_byte(main_j);
24840 main_i:=char_info(main_f)(cur_l); ligature_present:=true;
24841 end;
24842 othercases begin cur_l:=rem_byte(main_j); ligature_present:=true; {\.{=:}}
24843 if lig_stack=null then goto main_loop_wrapup
24844 else goto main_loop_move+1;
24845 end
24846 endcases;
24847 if op_byte(main_j)>qi(4) then
24848 if op_byte(main_j)<>qi(7) then goto main_loop_wrapup;
24849 if cur_l<non_char then goto main_lig_loop;
24850 main_k:=bchar_label[main_f]; goto main_lig_loop+1;
24851 end
24852
24853 @ The occurrence of blank spaces is almost part of \TeX's inner loop,
24854 @^inner loop@>
24855 since we usually encounter about one space for every five non-blank characters.
24856 Therefore |main_control| gives second-highest priority to ordinary spaces.
24857
24858 When a glue parameter like \.{\\spaceskip} is set to `\.{0pt}', we will
24859 see to it later that the corresponding glue specification is precisely
24860 |zero_glue|, not merely a pointer to some specification that happens
24861 to be full of zeroes. Therefore it is simple to test whether a glue parameter
24862 is zero or~not.
24863
24864 @<Append a normal inter-word space...@>=
24865 if space_skip=zero_glue then
24866 begin @<Find the glue specification, |main_p|, for
24867 text spaces in the current font@>;
24868 temp_ptr:=new_glue(main_p);
24869 end
24870 else temp_ptr:=new_param_glue(space_skip_code);
24871 link(tail):=temp_ptr; tail:=temp_ptr;
24872 goto big_switch
24873
24874 @ Having |font_glue| allocated for each text font saves both time and memory.
24875 If any of the three spacing parameters are subsequently changed by the
24876 use of \.{\\fontdimen}, the |find_font_dimen| procedure deallocates the
24877 |font_glue| specification allocated here.
24878
24879 @<Find the glue specification...@>=
24880 begin main_p:=font_glue[cur_font];
24881 if main_p=null then
24882 begin main_p:=new_spec(zero_glue); main_k:=param_base[cur_font]+space_code;
24883 width(main_p):=font_info[main_k].sc; {that's |space(cur_font)|}
24884 stretch(main_p):=font_info[main_k+1].sc; {and |space_stretch(cur_font)|}
24885 shrink(main_p):=font_info[main_k+2].sc; {and |space_shrink(cur_font)|}
24886 font_glue[cur_font]:=main_p;
24887 end;
24888 end
24889
24890 @ @<Declare act...@>=
24891 procedure app_space; {handle spaces when |space_factor<>1000|}
24892 var@!q:pointer; {glue node}
24893 begin if (space_factor>=2000)and(xspace_skip<>zero_glue) then
24894 q:=new_param_glue(xspace_skip_code)
24895 else begin if space_skip<>zero_glue then main_p:=space_skip
24896 else @<Find the glue specification...@>;
24897 main_p:=new_spec(main_p);
24898 @<Modify the glue specification in |main_p| according to the space factor@>;
24899 q:=new_glue(main_p); glue_ref_count(main_p):=null;
24900 end;
24901 link(tail):=q; tail:=q;
24902 end;
24903
24904 @ @<Modify the glue specification in |main_p| according to the space factor@>=
24905 if space_factor>=2000 then width(main_p):=width(main_p)+extra_space(cur_font);
24906 stretch(main_p):=xn_over_d(stretch(main_p),space_factor,1000);
24907 shrink(main_p):=xn_over_d(shrink(main_p),1000,space_factor)
24908
24909 @ Whew---that covers the main loop. We can now proceed at a leisurely
24910 pace through the other combinations of possibilities.
24911
24912 @d any_mode(#)==vmode+#,hmode+#,mmode+# {for mode-independent commands}
24913
24914 @<Cases of |main_control| that are not part of the inner loop@>=
24915 any_mode(relax),vmode+spacer,mmode+spacer,mmode+no_boundary:do_nothing;
24916 any_mode(ignore_spaces): begin
24917 if cur_chr = 0 then begin
24918 @<Get the next non-blank non-call...@>;
24919 goto reswitch;
24920 end
24921 else begin
24922 t:=scanner_status;
24923 scanner_status:=normal;
24924 get_next;
24925 scanner_status:=t;
24926 if cur_cs < hash_base then
24927 cur_cs:=prim_lookup(cur_cs-single_base)
24928 else
24929 cur_cs :=prim_lookup(text(cur_cs));
24930 if cur_cs<>undefined_primitive then begin
24931 cur_cmd:=prim_eq_type(cur_cs);
24932 cur_chr:=prim_equiv(cur_cs);
24933 cur_tok := cs_token_flag+prim_eqtb_base+cur_cs;
24934 goto reswitch;
24935 end;
24936 end;
24937 end;
24938 vmode+stop: if its_all_over then return; {this is the only way out}
24939 @t\4@>@<Forbidden cases detected in |main_control|@>@+@,any_mode(mac_param):
24940 report_illegal_case;
24941 @<Math-only cases in non-math modes, or vice versa@>: insert_dollar_sign;
24942 @t\4@>@<Cases of |main_control| that build boxes and lists@>@;
24943 @t\4@>@<Cases of |main_control| that don't depend on |mode|@>@;
24944 @t\4@>@<Cases of |main_control| that are for extensions to \TeX@>@;
24945
24946 @ Here is a list of cases where the user has probably gotten into or out of math
24947 mode by mistake. \TeX\ will insert a dollar sign and rescan the current token.
24948
24949 @d non_math(#)==vmode+#,hmode+#
24950
24951 @<Math-only cases in non-math modes...@>=
24952 non_math(sup_mark), non_math(sub_mark), non_math(math_char_num),
24953 non_math(math_given), non_math(XeTeX_math_given), non_math(math_comp), non_math(delim_num),
24954 non_math(left_right), non_math(above), non_math(radical),
24955 non_math(math_style), non_math(math_choice), non_math(vcenter),
24956 non_math(non_script), non_math(mkern), non_math(limit_switch),
24957 non_math(mskip), non_math(math_accent),
24958 mmode+endv, mmode+par_end, mmode+stop, mmode+vskip, mmode+un_vbox,
24959 mmode+valign, mmode+hrule
24960
24961 @ @<Declare action...@>=
24962 procedure insert_dollar_sign;
24963 begin back_input; cur_tok:=math_shift_token+"$";
24964 print_err("Missing $ inserted");
24965 @.Missing \$ inserted@>
24966 help2("I've inserted a begin-math/end-math symbol since I think")@/
24967 ("you left one out. Proceed, with fingers crossed."); ins_error;
24968 end;
24969
24970 @ When erroneous situations arise, \TeX\ usually issues an error message
24971 specific to the particular error. For example, `\.{\\noalign}' should
24972 not appear in any mode, since it is recognized by the |align_peek| routine
24973 in all of its legitimate appearances; a special error message is given
24974 when `\.{\\noalign}' occurs elsewhere. But sometimes the most appropriate
24975 error message is simply that the user is not allowed to do what he or she
24976 has attempted. For example, `\.{\\moveleft}' is allowed only in vertical mode,
24977 and `\.{\\lower}' only in non-vertical modes. Such cases are enumerated
24978 here and in the other sections referred to under `See also \dots.'
24979
24980 @<Forbidden cases...@>=
24981 vmode+vmove,hmode+hmove,mmode+hmove,any_mode(last_item),
24982
24983 @ The `|you_cant|' procedure prints a line saying that the current command
24984 is illegal in the current mode; it identifies these things symbolically.
24985
24986 @<Declare action...@>=
24987 procedure you_cant;
24988 begin print_err("You can't use `");
24989 @.You can't use x in y mode@>
24990 print_cmd_chr(cur_cmd,cur_chr);
24991 print("' in "); print_mode(mode);
24992 end;
24993
24994 @ @<Declare act...@>=
24995 procedure report_illegal_case;
24996 begin you_cant;
24997 help4("Sorry, but I'm not programmed to handle this case;")@/
24998 ("I'll just pretend that you didn't ask for it.")@/
24999 ("If you're in the wrong mode, you might be able to")@/
25000 ("return to the right one by typing `I}' or `I$' or `I\par'.");@/
25001 error;
25002 end;
25003
25004 @ Some operations are allowed only in privileged modes, i.e., in cases
25005 that |mode>0|. The |privileged| function is used to detect violations
25006 of this rule; it issues an error message and returns |false| if the
25007 current |mode| is negative.
25008
25009 @<Declare act...@>=
25010 function privileged:boolean;
25011 begin if mode>0 then privileged:=true
25012 else begin report_illegal_case; privileged:=false;
25013 end;
25014 end;
25015
25016 @ Either \.{\\dump} or \.{\\end} will cause |main_control| to enter the
25017 endgame, since both of them have `|stop|' as their command code.
25018
25019 @<Put each...@>=
25020 primitive("end",stop,0);@/
25021 @!@:end_}{\.{\\end} primitive@>
25022 primitive("dump",stop,1);@/
25023 @!@:dump_}{\.{\\dump} primitive@>
25024
25025 @ @<Cases of |print_cmd_chr|...@>=
25026 stop:if chr_code=1 then print_esc("dump")@+else print_esc("end");
25027
25028 @ We don't want to leave |main_control| immediately when a |stop| command
25029 is sensed, because it may be necessary to invoke an \.{\\output} routine
25030 several times before things really grind to a halt. (The output routine
25031 might even say `\.{\\gdef\\end\{...\}}', to prolong the life of the job.)
25032 Therefore |its_all_over| is |true| only when the current page
25033 and contribution list are empty, and when the last output was not a
25034 ``dead cycle.''
25035
25036 @<Declare act...@>=
25037 function its_all_over:boolean; {do this when \.{\\end} or \.{\\dump} occurs}
25038 label exit;
25039 begin if privileged then
25040 begin if (page_head=page_tail)and(head=tail)and(dead_cycles=0) then
25041 begin its_all_over:=true; return;
25042 end;
25043 back_input; {we will try to end again after ejecting residual material}
25044 tail_append(new_null_box);
25045 width(tail):=hsize;
25046 tail_append(new_glue(fill_glue));
25047 tail_append(new_penalty(-@'10000000000));@/
25048 build_page; {append \.{\\hbox to \\hsize\{\}\\vfill\\penalty-'10000000000}}
25049 end;
25050 its_all_over:=false;
25051 exit:end;
25052
25053 @* \[47] Building boxes and lists.
25054 The most important parts of |main_control| are concerned with \TeX's
25055 chief mission of box-making. We need to control the activities that put
25056 entries on vlists and hlists, as well as the activities that convert
25057 those lists into boxes. All of the necessary machinery has already been
25058 developed; it remains for us to ``push the buttons'' at the right times.
25059
25060 @ As an introduction to these routines, let's consider one of the simplest
25061 cases: What happens when `\.{\\hrule}' occurs in vertical mode, or
25062 `\.{\\vrule}' in horizontal mode or math mode? The code in |main_control|
25063 is short, since the |scan_rule_spec| routine already does most of what is
25064 required; thus, there is no need for a special action procedure.
25065
25066 Note that baselineskip calculations are disabled after a rule in vertical
25067 mode, by setting |prev_depth:=ignore_depth|.
25068
25069 @<Cases of |main_control| that build...@>=
25070 vmode+hrule,hmode+vrule,mmode+vrule: begin tail_append(scan_rule_spec);
25071 if abs(mode)=vmode then prev_depth:=ignore_depth
25072 else if abs(mode)=hmode then space_factor:=1000;
25073 end;
25074
25075 @ The processing of things like \.{\\hskip} and \.{\\vskip} is slightly
25076 more complicated. But the code in |main_control| is very short, since
25077 it simply calls on the action routine |append_glue|. Similarly, \.{\\kern}
25078 activates |append_kern|.
25079
25080 @<Cases of |main_control| that build...@>=
25081 vmode+vskip,hmode+hskip,mmode+hskip,mmode+mskip: append_glue;
25082 any_mode(kern),mmode+mkern: append_kern;
25083
25084 @ The |hskip| and |vskip| command codes are used for control sequences
25085 like \.{\\hss} and \.{\\vfil} as well as for \.{\\hskip} and \.{\\vskip}.
25086 The difference is in the value of |cur_chr|.
25087
25088 @d fil_code=0 {identifies \.{\\hfil} and \.{\\vfil}}
25089 @d fill_code=1 {identifies \.{\\hfill} and \.{\\vfill}}
25090 @d ss_code=2 {identifies \.{\\hss} and \.{\\vss}}
25091 @d fil_neg_code=3 {identifies \.{\\hfilneg} and \.{\\vfilneg}}
25092 @d skip_code=4 {identifies \.{\\hskip} and \.{\\vskip}}
25093 @d mskip_code=5 {identifies \.{\\mskip}}
25094
25095 @<Put each...@>=
25096 primitive("hskip",hskip,skip_code);@/
25097 @!@:hskip_}{\.{\\hskip} primitive@>
25098 primitive("hfil",hskip,fil_code);
25099 @!@:hfil_}{\.{\\hfil} primitive@>
25100 primitive("hfill",hskip,fill_code);@/
25101 @!@:hfill_}{\.{\\hfill} primitive@>
25102 primitive("hss",hskip,ss_code);
25103 @!@:hss_}{\.{\\hss} primitive@>
25104 primitive("hfilneg",hskip,fil_neg_code);@/
25105 @!@:hfil_neg_}{\.{\\hfilneg} primitive@>
25106 primitive("vskip",vskip,skip_code);@/
25107 @!@:vskip_}{\.{\\vskip} primitive@>
25108 primitive("vfil",vskip,fil_code);
25109 @!@:vfil_}{\.{\\vfil} primitive@>
25110 primitive("vfill",vskip,fill_code);@/
25111 @!@:vfill_}{\.{\\vfill} primitive@>
25112 primitive("vss",vskip,ss_code);
25113 @!@:vss_}{\.{\\vss} primitive@>
25114 primitive("vfilneg",vskip,fil_neg_code);@/
25115 @!@:vfil_neg_}{\.{\\vfilneg} primitive@>
25116 primitive("mskip",mskip,mskip_code);@/
25117 @!@:mskip_}{\.{\\mskip} primitive@>
25118 primitive("kern",kern,explicit);
25119 @!@:kern_}{\.{\\kern} primitive@>
25120 primitive("mkern",mkern,mu_glue);@/
25121 @!@:mkern_}{\.{\\mkern} primitive@>
25122
25123 @ @<Cases of |print_cmd_chr|...@>=
25124 hskip: case chr_code of
25125 skip_code:print_esc("hskip");
25126 fil_code:print_esc("hfil");
25127 fill_code:print_esc("hfill");
25128 ss_code:print_esc("hss");
25129 othercases print_esc("hfilneg")
25130 endcases;
25131 vskip: case chr_code of
25132 skip_code:print_esc("vskip");
25133 fil_code:print_esc("vfil");
25134 fill_code:print_esc("vfill");
25135 ss_code:print_esc("vss");
25136 othercases print_esc("vfilneg")
25137 endcases;
25138 mskip: print_esc("mskip");
25139 kern: print_esc("kern");
25140 mkern: print_esc("mkern");
25141
25142 @ All the work relating to glue creation has been relegated to the
25143 following subroutine. It does not call |build_page|, because it is
25144 used in at least one place where that would be a mistake.
25145
25146 @<Declare action...@>=
25147 procedure append_glue;
25148 var s:small_number; {modifier of skip command}
25149 begin s:=cur_chr;
25150 case s of
25151 fil_code: cur_val:=fil_glue;
25152 fill_code: cur_val:=fill_glue;
25153 ss_code: cur_val:=ss_glue;
25154 fil_neg_code: cur_val:=fil_neg_glue;
25155 skip_code: scan_glue(glue_val);
25156 mskip_code: scan_glue(mu_val);
25157 end; {now |cur_val| points to the glue specification}
25158 tail_append(new_glue(cur_val));
25159 if s>=skip_code then
25160 begin decr(glue_ref_count(cur_val));
25161 if s>skip_code then subtype(tail):=mu_glue;
25162 end;
25163 end;
25164
25165 @ @<Declare act...@>=
25166 procedure append_kern;
25167 var s:quarterword; {|subtype| of the kern node}
25168 begin s:=cur_chr; scan_dimen(s=mu_glue,false,false);
25169 tail_append(new_kern(cur_val)); subtype(tail):=s;
25170 end;
25171
25172 @ Many of the actions related to box-making are triggered by the appearance
25173 of braces in the input. For example, when the user says `\.{\\hbox}
25174 \.{to} \.{100pt\{$\langle\,\hbox{\rm hlist}\,\rangle$\}}' in vertical mode,
25175 the information about the box size (100pt, |exactly|) is put onto |save_stack|
25176 with a level boundary word just above it, and |cur_group:=adjusted_hbox_group|;
25177 \TeX\ enters restricted horizontal mode to process the hlist. The right
25178 brace eventually causes |save_stack| to be restored to its former state,
25179 at which time the information about the box size (100pt, |exactly|) is
25180 available once again; a box is packaged and we leave restricted horizontal
25181 mode, appending the new box to the current list of the enclosing mode
25182 (in this case to the current list of vertical mode), followed by any
25183 vertical adjustments that were removed from the box by |hpack|.
25184
25185 The next few sections of the program are therefore concerned with the
25186 treatment of left and right curly braces.
25187
25188 @ If a left brace occurs in the middle of a page or paragraph, it simply
25189 introduces a new level of grouping, and the matching right brace will not have
25190 such a drastic effect. Such grouping affects neither the mode nor the
25191 current list.
25192
25193 @<Cases of |main_control| that build...@>=
25194 non_math(left_brace): new_save_level(simple_group);
25195 any_mode(begin_group): new_save_level(semi_simple_group);
25196 any_mode(end_group): if cur_group=semi_simple_group then unsave
25197 else off_save;
25198
25199 @ We have to deal with errors in which braces and such things are not
25200 properly nested. Sometimes the user makes an error of commission by
25201 inserting an extra symbol, but sometimes the user makes an error of omission.
25202 \TeX\ can't always tell one from the other, so it makes a guess and tries
25203 to avoid getting into a loop.
25204
25205 The |off_save| routine is called when the current group code is wrong. It tries
25206 to insert something into the user's input that will help clean off
25207 the top level.
25208
25209 @<Declare act...@>=
25210 procedure off_save;
25211 var p:pointer; {inserted token}
25212 begin if cur_group=bottom_level then
25213 @<Drop current token and complain that it was unmatched@>
25214 else begin back_input; p:=get_avail; link(temp_head):=p;
25215 print_err("Missing ");
25216 @<Prepare to insert a token that matches |cur_group|,
25217 and print what it is@>;
25218 print(" inserted"); ins_list(link(temp_head));
25219 help5("I've inserted something that you may have forgotten.")@/
25220 ("(See the <inserted text> above.)")@/
25221 ("With luck, this will get me unwedged. But if you")@/
25222 ("really didn't forget anything, try typing `2' now; then")@/
25223 ("my insertion and my current dilemma will both disappear.");
25224 error;
25225 end;
25226 end;
25227
25228 @ At this point, |link(temp_head)=p|, a pointer to an empty one-word node.
25229
25230 @<Prepare to insert a token that matches |cur_group|...@>=
25231 case cur_group of
25232 semi_simple_group: begin info(p):=cs_token_flag+frozen_end_group;
25233 print_esc("endgroup");
25234 @.Missing \\endgroup inserted@>
25235 end;
25236 math_shift_group: begin info(p):=math_shift_token+"$"; print_char("$");
25237 @.Missing \$ inserted@>
25238 end;
25239 math_left_group: begin info(p):=cs_token_flag+frozen_right; link(p):=get_avail;
25240 p:=link(p); info(p):=other_token+"."; print_esc("right.");
25241 @.Missing \\right\hbox{.} inserted@>
25242 @^null delimiter@>
25243 end;
25244 othercases begin info(p):=right_brace_token+"}"; print_char("}");
25245 @.Missing \} inserted@>
25246 end
25247 endcases
25248
25249 @ @<Drop current token and complain that it was unmatched@>=
25250 begin print_err("Extra "); print_cmd_chr(cur_cmd,cur_chr);
25251 @.Extra x@>
25252 help1("Things are pretty mixed up, but I think the worst is over.");@/
25253 error;
25254 end
25255
25256 @ The routine for a |right_brace| character branches into many subcases,
25257 since a variety of things may happen, depending on |cur_group|. Some
25258 types of groups are not supposed to be ended by a right brace; error
25259 messages are given in hopes of pinpointing the problem. Most branches
25260 of this routine will be filled in later, when we are ready to understand
25261 them; meanwhile, we must prepare ourselves to deal with such errors.
25262
25263 @<Cases of |main_control| that build...@>=
25264 any_mode(right_brace): handle_right_brace;
25265
25266 @ @<Declare the procedure called |handle_right_brace|@>=
25267 procedure handle_right_brace;
25268 var p,@!q:pointer; {for short-term use}
25269 @!d:scaled; {holds |split_max_depth| in |insert_group|}
25270 @!f:integer; {holds |floating_penalty| in |insert_group|}
25271 begin case cur_group of
25272 simple_group: unsave;
25273 bottom_level: begin print_err("Too many }'s");
25274 @.Too many \}'s@>
25275 help2("You've closed more groups than you opened.")@/
25276 ("Such booboos are generally harmless, so keep going."); error;
25277 end;
25278 semi_simple_group,math_shift_group,math_left_group: extra_right_brace;
25279 @t\4@>@<Cases of |handle_right_brace| where a |right_brace| triggers
25280 a delayed action@>@;
25281 othercases confusion("rightbrace")
25282 @:this can't happen rightbrace}{\quad rightbrace@>
25283 endcases;
25284 end;
25285
25286 @ @<Declare act...@>=
25287 procedure extra_right_brace;
25288 begin print_err("Extra }, or forgotten ");
25289 @.Extra \}, or forgotten x@>
25290 case cur_group of
25291 semi_simple_group: print_esc("endgroup");
25292 math_shift_group: print_char("$");
25293 math_left_group: print_esc("right");
25294 end;@/
25295 help5("I've deleted a group-closing symbol because it seems to be")@/
25296 ("spurious, as in `$x}$'. But perhaps the } is legitimate and")@/
25297 ("you forgot something else, as in `\hbox{$x}'. In such cases")@/
25298 ("the way to recover is to insert both the forgotten and the")@/
25299 ("deleted material, e.g., by typing `I$}'."); error;
25300 incr(align_state);
25301 end;
25302
25303 @ Here is where we clear the parameters that are supposed to revert to their
25304 default values after every paragraph and when internal vertical mode is entered.
25305
25306 @<Declare act...@>=
25307 procedure normal_paragraph;
25308 begin if looseness<>0 then eq_word_define(int_base+looseness_code,0);
25309 if hang_indent<>0 then eq_word_define(dimen_base+hang_indent_code,0);
25310 if hang_after<>1 then eq_word_define(int_base+hang_after_code,1);
25311 if par_shape_ptr<>null then eq_define(par_shape_loc,shape_ref,null);
25312 if inter_line_penalties_ptr<>null then
25313 eq_define(inter_line_penalties_loc,shape_ref,null);
25314 end;
25315
25316 @ Now let's turn to the question of how \.{\\hbox} is treated. We actually
25317 need to consider also a slightly larger context, since constructions like
25318 `\.{\\setbox3=}\penalty0\.{\\hbox...}' and
25319 `\.{\\leaders}\penalty0\.{\\hbox...}' and
25320 `\.{\\lower3.8pt\\hbox...}'
25321 are supposed to invoke quite
25322 different actions after the box has been packaged. Conversely,
25323 constructions like `\.{\\setbox3=}' can be followed by a variety of
25324 different kinds of boxes, and we would like to encode such things in an
25325 efficient way.
25326
25327 In other words, there are two problems: to represent the context of a box,
25328 and to represent its type.
25329
25330 The first problem is solved by putting a ``context code'' on the |save_stack|,
25331 just below the two entries that give the dimensions produced by |scan_spec|.
25332 The context code is either a (signed) shift amount, or it is a large
25333 integer |>=box_flag|, where |box_flag=@t$2^{30}$@>|. Codes |box_flag| through
25334 |global_box_flag-1| represent `\.{\\setbox0}' through `\.{\\setbox32767}';
25335 codes |global_box_flag| through |ship_out_flag-1| represent
25336 `\.{\\global\\setbox0}' through `\.{\\global\\setbox32767}';
25337 code |ship_out_flag| represents `\.{\\shipout}'; and codes |leader_flag|
25338 through |leader_flag+2| represent `\.{\\leaders}', `\.{\\cleaders}',
25339 and `\.{\\xleaders}'.
25340
25341 The second problem is solved by giving the command code |make_box| to all
25342 control sequences that produce a box, and by using the following |chr_code|
25343 values to distinguish between them: |box_code|, |copy_code|, |last_box_code|,
25344 |vsplit_code|, |vtop_code|, |vtop_code+vmode|, and |vtop_code+hmode|, where
25345 the latter two are used to denote \.{\\vbox} and \.{\\hbox}, respectively.
25346
25347 @d box_flag==@'10000000000 {context code for `\.{\\setbox0}'}
25348 @d global_box_flag==@'10000100000 {context code for `\.{\\global\\setbox0}'}
25349 @d ship_out_flag==@'10000200000 {context code for `\.{\\shipout}'}
25350 @d leader_flag==@'10000200001 {context code for `\.{\\leaders}'}
25351 @d box_code=0 {|chr_code| for `\.{\\box}'}
25352 @d copy_code=1 {|chr_code| for `\.{\\copy}'}
25353 @d last_box_code=2 {|chr_code| for `\.{\\lastbox}'}
25354 @d vsplit_code=3 {|chr_code| for `\.{\\vsplit}'}
25355 @d vtop_code=4 {|chr_code| for `\.{\\vtop}'}
25356
25357 @<Put each...@>=
25358 primitive("moveleft",hmove,1);
25359 @!@:move_left_}{\.{\\moveleft} primitive@>
25360 primitive("moveright",hmove,0);@/
25361 @!@:move_right_}{\.{\\moveright} primitive@>
25362 primitive("raise",vmove,1);
25363 @!@:raise_}{\.{\\raise} primitive@>
25364 primitive("lower",vmove,0);
25365 @!@:lower_}{\.{\\lower} primitive@>
25366 @#
25367 primitive("box",make_box,box_code);
25368 @!@:box_}{\.{\\box} primitive@>
25369 primitive("copy",make_box,copy_code);
25370 @!@:copy_}{\.{\\copy} primitive@>
25371 primitive("lastbox",make_box,last_box_code);
25372 @!@:last_box_}{\.{\\lastbox} primitive@>
25373 primitive("vsplit",make_box,vsplit_code);
25374 @!@:vsplit_}{\.{\\vsplit} primitive@>
25375 primitive("vtop",make_box,vtop_code);@/
25376 @!@:vtop_}{\.{\\vtop} primitive@>
25377 primitive("vbox",make_box,vtop_code+vmode);
25378 @!@:vbox_}{\.{\\vbox} primitive@>
25379 primitive("hbox",make_box,vtop_code+hmode);@/
25380 @!@:hbox_}{\.{\\hbox} primitive@>
25381 primitive("shipout",leader_ship,a_leaders-1); {|ship_out_flag=leader_flag-1|}
25382 @!@:ship_out_}{\.{\\shipout} primitive@>
25383 primitive("leaders",leader_ship,a_leaders);
25384 @!@:leaders_}{\.{\\leaders} primitive@>
25385 primitive("cleaders",leader_ship,c_leaders);
25386 @!@:c_leaders_}{\.{\\cleaders} primitive@>
25387 primitive("xleaders",leader_ship,x_leaders);
25388 @!@:x_leaders_}{\.{\\xleaders} primitive@>
25389
25390 @ @<Cases of |print_cmd_chr|...@>=
25391 hmove: if chr_code=1 then print_esc("moveleft")@+else print_esc("moveright");
25392 vmove: if chr_code=1 then print_esc("raise")@+else print_esc("lower");
25393 make_box: case chr_code of
25394 box_code: print_esc("box");
25395 copy_code: print_esc("copy");
25396 last_box_code: print_esc("lastbox");
25397 vsplit_code: print_esc("vsplit");
25398 vtop_code: print_esc("vtop");
25399 vtop_code+vmode: print_esc("vbox");
25400 othercases print_esc("hbox")
25401 endcases;
25402 leader_ship: if chr_code=a_leaders then print_esc("leaders")
25403 else if chr_code=c_leaders then print_esc("cleaders")
25404 else if chr_code=x_leaders then print_esc("xleaders")
25405 else print_esc("shipout");
25406
25407 @ Constructions that require a box are started by calling |scan_box| with
25408 a specified context code. The |scan_box| routine verifies
25409 that a |make_box| command comes next and then it calls |begin_box|.
25410
25411 @<Cases of |main_control| that build...@>=
25412 vmode+hmove,hmode+vmove,mmode+vmove: begin t:=cur_chr;
25413 scan_normal_dimen;
25414 if t=0 then scan_box(cur_val)@+else scan_box(-cur_val);
25415 end;
25416 any_mode(leader_ship): scan_box(leader_flag-a_leaders+cur_chr);
25417 any_mode(make_box): begin_box(0);
25418
25419 @ The global variable |cur_box| will point to a newly made box. If the box
25420 is void, we will have |cur_box=null|. Otherwise we will have
25421 |type(cur_box)=hlist_node| or |vlist_node| or |rule_node|; the |rule_node|
25422 case can occur only with leaders.
25423
25424 @<Glob...@>=
25425 @!cur_box:pointer; {box to be placed into its context}
25426
25427 @ The |box_end| procedure does the right thing with |cur_box|, if
25428 |box_context| represents the context as explained above.
25429
25430 @<Declare act...@>=
25431 procedure box_end(@!box_context:integer);
25432 var p:pointer; {|ord_noad| for new box in math mode}
25433 @!a:small_number; {global prefix}
25434 begin if box_context<box_flag then @<Append box |cur_box| to the current list,
25435 shifted by |box_context|@>
25436 else if box_context<ship_out_flag then @<Store \(c)|cur_box| in a box register@>
25437 else if cur_box<>null then
25438 if box_context>ship_out_flag then @<Append a new leader node that
25439 uses |cur_box|@>
25440 else ship_out(cur_box);
25441 end;
25442
25443 @ The global variable |adjust_tail| will be non-null if and only if the
25444 current box might include adjustments that should be appended to the
25445 current vertical list.
25446
25447 @<Append box |cur_box| to the current...@>=
25448 begin if cur_box<>null then
25449 begin shift_amount(cur_box):=box_context;
25450 if abs(mode)=vmode then
25451 begin
25452 if pre_adjust_tail <> null then begin
25453 if pre_adjust_head <> pre_adjust_tail then
25454 append_list(pre_adjust_head)(pre_adjust_tail);
25455 pre_adjust_tail:=null;
25456 end;
25457 append_to_vlist(cur_box);
25458 if adjust_tail <> null then begin
25459 if adjust_head <> adjust_tail then
25460 append_list(adjust_head)(adjust_tail);
25461 adjust_tail:=null;
25462 end;
25463 if mode>0 then build_page;
25464 end
25465 else begin if abs(mode)=hmode then space_factor:=1000
25466 else begin p:=new_noad;
25467 math_type(nucleus(p)):=sub_box;
25468 info(nucleus(p)):=cur_box; cur_box:=p;
25469 end;
25470 link(tail):=cur_box; tail:=cur_box;
25471 end;
25472 end;
25473 end
25474
25475 @ @<Store \(c)|cur_box| in a box register@>=
25476 begin if box_context<global_box_flag then
25477 begin cur_val:=box_context-box_flag; a:=0;
25478 end
25479 else begin cur_val:=box_context-global_box_flag; a:=4;
25480 end;
25481 if cur_val<256 then define(box_base+cur_val,box_ref,cur_box)
25482 else sa_def_box;
25483 end
25484
25485 @ @<Append a new leader node ...@>=
25486 begin @<Get the next non-blank non-relax...@>;
25487 if ((cur_cmd=hskip)and(abs(mode)<>vmode))or@|
25488 ((cur_cmd=vskip)and(abs(mode)=vmode)) then
25489 begin append_glue; subtype(tail):=box_context-(leader_flag-a_leaders);
25490 leader_ptr(tail):=cur_box;
25491 end
25492 else begin print_err("Leaders not followed by proper glue");
25493 @.Leaders not followed by...@>
25494 help3("You should say `\leaders <box or rule><hskip or vskip>'.")@/
25495 ("I found the <box or rule>, but there's no suitable")@/
25496 ("<hskip or vskip>, so I'm ignoring these leaders."); back_error;
25497 flush_node_list(cur_box);
25498 end;
25499 end
25500
25501 @ Now that we can see what eventually happens to boxes, we can consider
25502 the first steps in their creation. The |begin_box| routine is called when
25503 |box_context| is a context specification, |cur_chr| specifies the type of
25504 box desired, and |cur_cmd=make_box|.
25505
25506 @<Declare act...@>=
25507 procedure begin_box(@!box_context:integer);
25508 label exit, done;
25509 var @!p,@!q:pointer; {run through the current list}
25510 @!r:pointer; {running behind |p|}
25511 @!fm:boolean; {a final \.{\\beginM} \.{\\endM} node pair?}
25512 @!tx:pointer; {effective tail node}
25513 @!m:quarterword; {the length of a replacement list}
25514 @!k:halfword; {0 or |vmode| or |hmode|}
25515 @!n:halfword; {a box number}
25516 begin case cur_chr of
25517 box_code: begin scan_register_num; fetch_box(cur_box);
25518 change_box(null); {the box becomes void, at the same level}
25519 end;
25520 copy_code: begin scan_register_num; fetch_box(q); cur_box:=copy_node_list(q);
25521 end;
25522 last_box_code: @<If the current list ends with a box node, delete it from
25523 the list and make |cur_box| point to it; otherwise set |cur_box:=null|@>;
25524 vsplit_code: @<Split off part of a vertical box, make |cur_box| point to it@>;
25525 othercases @<Initiate the construction of an hbox or vbox, then |return|@>
25526 endcases;@/
25527 box_end(box_context); {in simple cases, we use the box immediately}
25528 exit:end;
25529
25530 @ Note that the condition |not is_char_node(tail)| implies that |head<>tail|,
25531 since |head| is a one-word node.
25532
25533 @d fetch_effective_tail_eTeX(#)== {extract |tx|,
25534 drop \.{\\beginM} \.{\\endM} pair}
25535 q:=head; p:=null;
25536 repeat r:=p; p:=q; fm:=false;
25537 if not is_char_node(q) then
25538 if type(q)=disc_node then
25539 begin for m:=1 to replace_count(q) do p:=link(p);
25540 if p=tx then #;
25541 end
25542 else if (type(q)=math_node)and(subtype(q)=begin_M_code) then fm:=true;
25543 q:=link(p);
25544 until q=tx; {found |r|$\to$|p|$\to$|q=tx|}
25545 q:=link(tx); link(p):=q; link(tx):=null;
25546 if q=null then if fm then confusion("tail1")
25547 @:this can't happen tail1}{\quad tail1@>
25548 else tail:=p
25549 else if fm then {|r|$\to$|p=begin_M|$\to$|q=end_M|}
25550 begin tail:=r; link(r):=null; flush_node_list(p);@+end
25551 @#
25552 @d check_effective_tail(#)==find_effective_tail_eTeX
25553 @d fetch_effective_tail==fetch_effective_tail_eTeX
25554
25555 @<If the current list ends with a box node, delete it...@>=
25556 begin cur_box:=null;
25557 if abs(mode)=mmode then
25558 begin you_cant; help1("Sorry; this \lastbox will be void."); error;
25559 end
25560 else if (mode=vmode)and(head=tail) then
25561 begin you_cant;
25562 help2("Sorry...I usually can't take things from the current page.")@/
25563 ("This \lastbox will therefore be void."); error;
25564 end
25565 else begin check_effective_tail(goto done);
25566 if not is_char_node(tx) then
25567 if (type(tx)=hlist_node)or(type(tx)=vlist_node) then
25568 @<Remove the last box, unless it's part of a discretionary@>;
25569 done:end;
25570 end
25571
25572 @ @<Remove the last box...@>=
25573 begin fetch_effective_tail(goto done);
25574 cur_box:=tx; shift_amount(cur_box):=0;
25575 end
25576
25577 @ Here we deal with things like `\.{\\vsplit 13 to 100pt}'.
25578
25579 @<Split off part of a vertical box, make |cur_box| point to it@>=
25580 begin scan_register_num; n:=cur_val;
25581 if not scan_keyword("to") then
25582 @.to@>
25583 begin print_err("Missing `to' inserted");
25584 @.Missing `to' inserted@>
25585 help2("I'm working on `\vsplit<box number> to <dimen>';")@/
25586 ("will look for the <dimen> next."); error;
25587 end;
25588 scan_normal_dimen;
25589 cur_box:=vsplit(n,cur_val);
25590 end
25591
25592 @ Here is where we enter restricted horizontal mode or internal vertical
25593 mode, in order to make a box.
25594
25595 @<Initiate the construction of an hbox or vbox, then |return|@>=
25596 begin k:=cur_chr-vtop_code; saved(0):=box_context;
25597 if k=hmode then
25598 if (box_context<box_flag)and(abs(mode)=vmode) then
25599 scan_spec(adjusted_hbox_group,true)
25600 else scan_spec(hbox_group,true)
25601 else begin if k=vmode then scan_spec(vbox_group,true)
25602 else begin scan_spec(vtop_group,true); k:=vmode;
25603 end;
25604 normal_paragraph;
25605 end;
25606 push_nest; mode:=-k;
25607 if k=vmode then
25608 begin prev_depth:=ignore_depth;
25609 if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
25610 end
25611 else begin space_factor:=1000;
25612 if every_hbox<>null then begin_token_list(every_hbox,every_hbox_text);
25613 end;
25614 return;
25615 end
25616
25617 @ @<Declare act...@>=
25618 procedure scan_box(@!box_context:integer);
25619 {the next input should specify a box or perhaps a rule}
25620 begin @<Get the next non-blank non-relax...@>;
25621 if cur_cmd=make_box then begin_box(box_context)
25622 else if (box_context>=leader_flag)and((cur_cmd=hrule)or(cur_cmd=vrule)) then
25623 begin cur_box:=scan_rule_spec; box_end(box_context);
25624 end
25625 else begin@t@>@;@/
25626 print_err("A <box> was supposed to be here");@/
25627 @.A <box> was supposed to...@>
25628 help3("I was expecting to see \hbox or \vbox or \copy or \box or")@/
25629 ("something like that. So you might find something missing in")@/
25630 ("your output. But keep trying; you can fix this later."); back_error;
25631 end;
25632 end;
25633
25634 @ When the right brace occurs at the end of an \.{\\hbox} or \.{\\vbox} or
25635 \.{\\vtop} construction, the |package| routine comes into action. We might
25636 also have to finish a paragraph that hasn't ended.
25637
25638 @<Cases of |handle...@>=
25639 hbox_group: package(0);
25640 adjusted_hbox_group: begin adjust_tail:=adjust_head;
25641 pre_adjust_tail:=pre_adjust_head; package(0);
25642 end;
25643 vbox_group: begin end_graf; package(0);
25644 end;
25645 vtop_group: begin end_graf; package(vtop_code);
25646 end;
25647
25648 @ @<Declare action...@>=
25649 procedure package(@!c:small_number);
25650 var h:scaled; {height of box}
25651 @!p:pointer; {first node in a box}
25652 @!d:scaled; {max depth}
25653 @!u,v:integer; {saved values for upwards mode flag}
25654 begin d:=box_max_depth; u:=XeTeX_upwards_state; unsave; save_ptr:=save_ptr-3;
25655 v:=XeTeX_upwards_state; XeTeX_upwards_state:=u;
25656 if mode=-hmode then cur_box:=hpack(link(head),saved(2),saved(1))
25657 else begin cur_box:=vpackage(link(head),saved(2),saved(1),d);
25658 if c=vtop_code then @<Readjust the height and depth of |cur_box|,
25659 for \.{\\vtop}@>;
25660 end;
25661 XeTeX_upwards_state:=v;
25662 pop_nest; box_end(saved(0));
25663 end;
25664
25665 @ The height of a `\.{\\vtop}' box is inherited from the first item on its list,
25666 if that item is an |hlist_node|, |vlist_node|, or |rule_node|; otherwise
25667 the \.{\\vtop} height is zero.
25668
25669
25670 @<Readjust the height...@>=
25671 begin h:=0; p:=list_ptr(cur_box);
25672 if p<>null then if type(p)<=rule_node then h:=height(p);
25673 depth(cur_box):=depth(cur_box)-h+height(cur_box); height(cur_box):=h;
25674 end
25675
25676 @ A paragraph begins when horizontal-mode material occurs in vertical mode,
25677 or when the paragraph is explicitly started by `\.{\\indent}' or
25678 `\.{\\noindent}'.
25679
25680 @<Put each...@>=
25681 primitive("indent",start_par,1);
25682 @!@:indent_}{\.{\\indent} primitive@>
25683 primitive("noindent",start_par,0);
25684 @!@:no_indent_}{\.{\\noindent} primitive@>
25685
25686 @ @<Cases of |print_cmd_chr|...@>=
25687 start_par: if chr_code=0 then print_esc("noindent")@+ else print_esc("indent");
25688
25689 @ @<Cases of |main_control| that build...@>=
25690 vmode+start_par: new_graf(cur_chr>0);
25691 vmode+letter,vmode+other_char,vmode+char_num,vmode+char_given,
25692 vmode+math_shift,vmode+un_hbox,vmode+vrule,
25693 vmode+accent,vmode+discretionary,vmode+hskip,vmode+valign,
25694 vmode+ex_space,vmode+no_boundary:@t@>@;@/
25695 begin back_input; new_graf(true);
25696 end;
25697
25698 @ @<Declare act...@>=
25699 function norm_min(@!h:integer):small_number;
25700 begin if h<=0 then norm_min:=1@+else if h>=63 then norm_min:=63@+
25701 else norm_min:=h;
25702 end;
25703 @#
25704 procedure new_graf(@!indented:boolean);
25705 begin prev_graf:=0;
25706 if (mode=vmode)or(head<>tail) then
25707 tail_append(new_param_glue(par_skip_code));
25708 push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
25709 prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
25710 *@'200000+cur_lang;
25711 if indented then
25712 begin tail:=new_null_box; link(head):=tail; width(tail):=par_indent;@+
25713 end;
25714 if every_par<>null then begin_token_list(every_par,every_par_text);
25715 if nest_ptr=1 then build_page; {put |par_skip| glue on current page}
25716 end;
25717
25718 @ @<Cases of |main_control| that build...@>=
25719 hmode+start_par,mmode+start_par: indent_in_hmode;
25720
25721 @ @<Declare act...@>=
25722 procedure indent_in_hmode;
25723 var p,@!q:pointer;
25724 begin if cur_chr>0 then {\.{\\indent}}
25725 begin p:=new_null_box; width(p):=par_indent;
25726 if abs(mode)=hmode then space_factor:=1000
25727 else begin q:=new_noad; math_type(nucleus(q)):=sub_box;
25728 info(nucleus(q)):=p; p:=q;
25729 end;
25730 tail_append(p);
25731 end;
25732 end;
25733
25734 @ A paragraph ends when a |par_end| command is sensed, or when we are in
25735 horizontal mode when reaching the right brace of vertical-mode routines
25736 like \.{\\vbox}, \.{\\insert}, or \.{\\output}.
25737
25738 @<Cases of |main_control| that build...@>=
25739 vmode+par_end: begin normal_paragraph;
25740 if mode>0 then build_page;
25741 end;
25742 hmode+par_end: begin if align_state<0 then off_save; {this tries to
25743 recover from an alignment that didn't end properly}
25744 end_graf; {this takes us to the enclosing mode, if |mode>0|}
25745 if mode=vmode then build_page;
25746 end;
25747 hmode+stop,hmode+vskip,hmode+hrule,hmode+un_vbox,hmode+halign: head_for_vmode;
25748
25749 @ @<Declare act...@>=
25750 procedure head_for_vmode;
25751 begin if mode<0 then
25752 if cur_cmd<>hrule then off_save
25753 else begin print_err("You can't use `");
25754 print_esc("hrule"); print("' here except with leaders");
25755 @.You can't use \\hrule...@>
25756 help2("To put a horizontal rule in an hbox or an alignment,")@/
25757 ("you should use \leaders or \hrulefill (see The TeXbook).");
25758 error;
25759 end
25760 else begin back_input; cur_tok:=par_token; back_input; token_type:=inserted;
25761 end;
25762 end;
25763
25764 @ @<Declare act...@>=
25765 procedure end_graf;
25766 begin if mode=hmode then
25767 begin if head=tail then pop_nest {null paragraphs are ignored}
25768 else line_break(false);
25769 if LR_save<>null then
25770 begin flush_list(LR_save); LR_save:=null;
25771 end;
25772 normal_paragraph;
25773 error_count:=0;
25774 end;
25775 end;
25776
25777 @ Insertion and adjustment and mark nodes are constructed by the following
25778 pieces of the program.
25779
25780 @<Cases of |main_control| that build...@>=
25781 any_mode(insert),hmode+vadjust,mmode+vadjust: begin_insert_or_adjust;
25782 any_mode(mark): make_mark;
25783
25784 @ @<Forbidden...@>=
25785 vmode+vadjust,
25786
25787 @ @<Declare act...@>=
25788 procedure begin_insert_or_adjust;
25789 begin if cur_cmd=vadjust then cur_val:=255
25790 else begin scan_eight_bit_int;
25791 if cur_val=255 then
25792 begin print_err("You can't "); print_esc("insert"); print_int(255);
25793 @.You can't \\insert255@>
25794 help1("I'm changing to \insert0; box 255 is special.");
25795 error; cur_val:=0;
25796 end;
25797 end;
25798 saved(0):=cur_val;
25799 if (cur_cmd = vadjust) and scan_keyword("pre") then
25800 saved(1):=1
25801 else
25802 saved(1):=0;
25803 save_ptr:=save_ptr + 2;
25804 new_save_level(insert_group); scan_left_brace; normal_paragraph;
25805 push_nest; mode:=-vmode; prev_depth:=ignore_depth;
25806 end;
25807
25808 @ @<Cases of |handle...@>=
25809 insert_group: begin end_graf; q:=split_top_skip; add_glue_ref(q);
25810 d:=split_max_depth; f:=floating_penalty; unsave; save_ptr:=save_ptr-2;
25811 {now |saved(0)| is the insertion number, or 255 for |vadjust|}
25812 p:=vpack(link(head),natural); pop_nest;
25813 if saved(0)<255 then
25814 begin tail_append(get_node(ins_node_size));
25815 type(tail):=ins_node; subtype(tail):=qi(saved(0));
25816 height(tail):=height(p)+depth(p); ins_ptr(tail):=list_ptr(p);
25817 split_top_ptr(tail):=q; depth(tail):=d; float_cost(tail):=f;
25818 end
25819 else begin tail_append(get_node(small_node_size));
25820 type(tail):=adjust_node;@/
25821 adjust_pre(tail):=saved(1); {the |subtype| is used for |adjust_pre|}
25822 adjust_ptr(tail):=list_ptr(p); delete_glue_ref(q);
25823 end;
25824 free_node(p,box_node_size);
25825 if nest_ptr=0 then build_page;
25826 end;
25827 output_group: @<Resume the page builder...@>;
25828
25829 @ @<Declare act...@>=
25830 procedure make_mark;
25831 var p:pointer; {new node}
25832 @!c:halfword; {the mark class}
25833 begin if cur_chr=0 then c:=0
25834 else begin scan_register_num; c:=cur_val;
25835 end;
25836 p:=scan_toks(false,true); p:=get_node(small_node_size);
25837 mark_class(p):=c;
25838 type(p):=mark_node; subtype(p):=0; {the |subtype| is not used}
25839 mark_ptr(p):=def_ref; link(tail):=p; tail:=p;
25840 end;
25841
25842 @ Penalty nodes get into a list via the |break_penalty| command.
25843 @^penalties@>
25844
25845 @<Cases of |main_control| that build...@>=
25846 any_mode(break_penalty): append_penalty;
25847
25848 @ @<Declare action...@>=
25849 procedure append_penalty;
25850 begin scan_int; tail_append(new_penalty(cur_val));
25851 if mode=vmode then build_page;
25852 end;
25853
25854 @ The |remove_item| command removes a penalty, kern, or glue node if it
25855 appears at the tail of the current list, using a brute-force linear scan.
25856 Like \.{\\lastbox}, this command is not allowed in vertical mode (except
25857 internal vertical mode), since the current list in vertical mode is sent
25858 to the page builder. But if we happen to be able to implement it in
25859 vertical mode, we do.
25860
25861 @<Cases of |main_control| that build...@>=
25862 any_mode(remove_item): delete_last;
25863
25864 @ When |delete_last| is called, |cur_chr| is the |type| of node that
25865 will be deleted, if present.
25866
25867 @<Declare action...@>=
25868 procedure delete_last;
25869 label exit;
25870 var @!p,@!q:pointer; {run through the current list}
25871 @!r:pointer; {running behind |p|}
25872 @!fm:boolean; {a final \.{\\beginM} \.{\\endM} node pair?}
25873 @!tx:pointer; {effective tail node}
25874 @!m:quarterword; {the length of a replacement list}
25875 begin if (mode=vmode)and(tail=head) then
25876 @<Apologize for inability to do the operation now,
25877 unless \.{\\unskip} follows non-glue@>
25878 else begin check_effective_tail(return);
25879 if not is_char_node(tx) then if type(tx)=cur_chr then
25880 begin fetch_effective_tail(return);
25881 flush_node_list(tx);
25882 end;
25883 end;
25884 exit:end;
25885
25886 @ @<Apologize for inability to do the operation...@>=
25887 begin if (cur_chr<>glue_node)or(last_glue<>max_halfword) then
25888 begin you_cant;
25889 help2("Sorry...I usually can't take things from the current page.")@/
25890 ("Try `I\vskip-\lastskip' instead.");
25891 if cur_chr=kern_node then help_line[0]:=
25892 ("Try `I\kern-\lastkern' instead.")
25893 else if cur_chr<>glue_node then help_line[0]:=@|
25894 ("Perhaps you can make the output routine do it.");
25895 error;
25896 end;
25897 end
25898
25899 @ @<Put each...@>=
25900 primitive("unpenalty",remove_item,penalty_node);@/
25901 @!@:un_penalty_}{\.{\\unpenalty} primitive@>
25902 primitive("unkern",remove_item,kern_node);@/
25903 @!@:un_kern_}{\.{\\unkern} primitive@>
25904 primitive("unskip",remove_item,glue_node);@/
25905 @!@:un_skip_}{\.{\\unskip} primitive@>
25906 primitive("unhbox",un_hbox,box_code);@/
25907 @!@:un_hbox_}{\.{\\unhbox} primitive@>
25908 primitive("unhcopy",un_hbox,copy_code);@/
25909 @!@:un_hcopy_}{\.{\\unhcopy} primitive@>
25910 primitive("unvbox",un_vbox,box_code);@/
25911 @!@:un_vbox_}{\.{\\unvbox} primitive@>
25912 primitive("unvcopy",un_vbox,copy_code);@/
25913 @!@:un_vcopy_}{\.{\\unvcopy} primitive@>
25914
25915 @ @<Cases of |print_cmd_chr|...@>=
25916 remove_item: if chr_code=glue_node then print_esc("unskip")
25917 else if chr_code=kern_node then print_esc("unkern")
25918 else print_esc("unpenalty");
25919 un_hbox: if chr_code=copy_code then print_esc("unhcopy")
25920 else print_esc("unhbox");
25921 un_vbox: if chr_code=copy_code then print_esc("unvcopy")
25922 @<Cases of |un_vbox| for |print_cmd_chr|@>@/
25923 else print_esc("unvbox");
25924
25925 @ The |un_hbox| and |un_vbox| commands unwrap one of the 256 current boxes.
25926
25927 @<Cases of |main_control| that build...@>=
25928 vmode+un_vbox,hmode+un_hbox,mmode+un_hbox: unpackage;
25929
25930 @ @<Declare act...@>=
25931 procedure unpackage;
25932 label done, exit;
25933 var p:pointer; {the box}
25934 r: pointer; {to remove marginal kern nodes}
25935 @!c:box_code..copy_code; {should we copy?}
25936 begin if cur_chr>copy_code then @<Handle saved items and |goto done|@>;
25937 c:=cur_chr; scan_register_num; fetch_box(p);
25938 if p=null then return;
25939 if (abs(mode)=mmode)or((abs(mode)=vmode)and(type(p)<>vlist_node))or@|
25940 ((abs(mode)=hmode)and(type(p)<>hlist_node)) then
25941 begin print_err("Incompatible list can't be unboxed");
25942 @.Incompatible list...@>
25943 help3("Sorry, Pandora. (You sneaky devil.)")@/
25944 ("I refuse to unbox an \hbox in vertical mode or vice versa.")@/
25945 ("And I can't open any boxes in math mode.");@/
25946 error; return;
25947 end;
25948 if c=copy_code then link(tail):=copy_node_list(list_ptr(p))
25949 else begin link(tail):=list_ptr(p); change_box(null);
25950 free_node(p,box_node_size);
25951 end;
25952 done:
25953 while link(tail) <> null do begin
25954 r:=link(tail);
25955 if not is_char_node(r) and (type(r) = margin_kern_node) then begin
25956 link(tail):=link(r);
25957 free_node(r, margin_kern_node_size);
25958 end;
25959 tail:=link(tail);
25960 end;
25961 exit:end;
25962
25963 @ @<Forbidden...@>=vmode+ital_corr,
25964
25965 @ Italic corrections are converted to kern nodes when the |ital_corr| command
25966 follows a character. In math mode the same effect is achieved by appending
25967 a kern of zero here, since italic corrections are supplied later.
25968
25969 @<Cases of |main_control| that build...@>=
25970 hmode+ital_corr: append_italic_correction;
25971 mmode+ital_corr: tail_append(new_kern(0));
25972
25973 @ @<Declare act...@>=
25974 procedure append_italic_correction;
25975 label exit;
25976 var p:pointer; {|char_node| at the tail of the current list}
25977 @!f:internal_font_number; {the font in the |char_node|}
25978 begin if tail<>head then
25979 begin if is_char_node(tail) then p:=tail
25980 else if type(tail)=ligature_node then p:=lig_char(tail)
25981 else if (type(tail)=whatsit_node) then begin
25982 if is_native_word_subtype(tail) then begin
25983 tail_append(new_kern(get_native_italic_correction(tail))); subtype(tail):=explicit;
25984 end
25985 else if (subtype(tail)=glyph_node) then begin
25986 tail_append(new_kern(get_native_glyph_italic_correction(tail))); subtype(tail):=explicit;
25987 end;
25988 return;
25989 end
25990 else return;
25991 f:=font(p);
25992 tail_append(new_kern(char_italic(f)(char_info(f)(character(p)))));
25993 subtype(tail):=explicit;
25994 end;
25995 exit:end;
25996
25997 @ Discretionary nodes are easy in the common case `\.{\\-}', but in the
25998 general case we must process three braces full of items.
25999
26000 @<Put each...@>=
26001 primitive("-",discretionary,1);
26002 @!@:Single-character primitives -}{\quad\.{\\-}@>
26003 primitive("discretionary",discretionary,0);
26004 @!@:discretionary_}{\.{\\discretionary} primitive@>
26005
26006 @ @<Cases of |print_cmd_chr|...@>=
26007 discretionary: if chr_code=1 then
26008 print_esc("-")@+else print_esc("discretionary");
26009
26010 @ @<Cases of |main_control| that build...@>=
26011 hmode+discretionary,mmode+discretionary: append_discretionary;
26012
26013 @ The space factor does not change when we append a discretionary node,
26014 but it starts out as 1000 in the subsidiary lists.
26015
26016 @<Declare act...@>=
26017 procedure append_discretionary;
26018 var c:integer; {hyphen character}
26019 begin tail_append(new_disc);
26020 if cur_chr=1 then
26021 begin c:=hyphen_char[cur_font];
26022 if c>=0 then if c<=biggest_char then pre_break(tail):=new_character(cur_font,c);
26023 end
26024 else begin incr(save_ptr); saved(-1):=0; new_save_level(disc_group);
26025 scan_left_brace; push_nest; mode:=-hmode; space_factor:=1000;
26026 end;
26027 end;
26028
26029 @ The three discretionary lists are constructed somewhat as if they were
26030 hboxes. A~subroutine called |build_discretionary| handles the transitions.
26031 (This is sort of fun.)
26032
26033 @<Cases of |handle...@>=
26034 disc_group: build_discretionary;
26035
26036 @ @<Declare act...@>=
26037 procedure build_discretionary;
26038 label done,exit;
26039 var p,@!q:pointer; {for link manipulation}
26040 @!n:integer; {length of discretionary list}
26041 begin unsave;
26042 @<Prune the current list, if necessary, until it contains only
26043 |char_node|, |kern_node|, |hlist_node|, |vlist_node|, |rule_node|,
26044 and |ligature_node| items; set |n| to the length of the list,
26045 and set |q| to the list's tail@>;
26046 p:=link(head); pop_nest;
26047 case saved(-1) of
26048 0:pre_break(tail):=p;
26049 1:post_break(tail):=p;
26050 2:@<Attach list |p| to the current list, and record its length;
26051 then finish up and |return|@>;
26052 end; {there are no other cases}
26053 incr(saved(-1)); new_save_level(disc_group); scan_left_brace;
26054 push_nest; mode:=-hmode; space_factor:=1000;
26055 exit:end;
26056
26057 @ @<Attach list |p| to the current...@>=
26058 begin if (n>0)and(abs(mode)=mmode) then
26059 begin print_err("Illegal math "); print_esc("discretionary");
26060 @.Illegal math \\disc...@>
26061 help2("Sorry: The third part of a discretionary break must be")@/
26062 ("empty, in math formulas. I had to delete your third part.");
26063 flush_node_list(p); n:=0; error;
26064 end
26065 else link(tail):=p;
26066 if n<=max_quarterword then replace_count(tail):=n
26067 else begin print_err("Discretionary list is too long");
26068 @.Discretionary list is too long@>
26069 help2("Wow---I never thought anybody would tweak me here.")@/
26070 ("You can't seriously need such a huge discretionary list?");
26071 error;
26072 end;
26073 if n>0 then tail:=q;
26074 decr(save_ptr); return;
26075 end
26076
26077 @ During this loop, |p=link(q)| and there are |n| items preceding |p|.
26078
26079 @<Prune the current list, if necessary...@>=
26080 q:=head; p:=link(q); n:=0;
26081 while p<>null do
26082 begin if not is_char_node(p) then if type(p)>rule_node then
26083 if type(p)<>kern_node then if type(p)<>ligature_node then
26084 if (type(p)<>whatsit_node)
26085 or (not is_native_word_subtype(p) and (subtype(p)<>glyph_node)) then
26086 begin print_err("Improper discretionary list");
26087 @.Improper discretionary list@>
26088 help1("Discretionary lists must contain only boxes and kerns.");@/
26089 error;
26090 begin_diagnostic;
26091 print_nl("The following discretionary sublist has been deleted:");
26092 @.The following...deleted@>
26093 show_box(p);
26094 end_diagnostic(true);
26095 flush_node_list(p); link(q):=null; goto done;
26096 end;
26097 q:=p; p:=link(q); incr(n);
26098 end;
26099 done:
26100
26101 @ We need only one more thing to complete the horizontal mode routines, namely
26102 the \.{\\accent} primitive.
26103
26104 @<Cases of |main_control| that build...@>=
26105 hmode+accent: make_accent;
26106
26107 @ The positioning of accents is straightforward but tedious. Given an accent
26108 of width |a|, designed for characters of height |x| and slant |s|;
26109 and given a character of width |w|, height |h|, and slant |t|: We will shift
26110 the accent down by |x-h|, and we will insert kern nodes that have the effect of
26111 centering the accent over the character and shifting the accent to the
26112 right by $\delta={1\over2}(w-a)+h\cdot t-x\cdot s$. If either character is
26113 absent from the font, we will simply use the other, without shifting.
26114
26115 @<Declare act...@>=
26116 procedure make_accent;
26117 var s,@!t: real; {amount of slant}
26118 @!p,@!q,@!r:pointer; {character, box, and kern nodes}
26119 @!f:internal_font_number; {relevant font}
26120 @!a,@!h,@!x,@!w,@!delta,@!lsb,@!rsb:scaled; {heights and widths, as explained above}
26121 @!i:four_quarters; {character information}
26122 begin scan_char_num; f:=cur_font; p:=new_character(f,cur_val);
26123 if p<>null then
26124 begin x:=x_height(f); s:=slant(f)/float_constant(65536);
26125 @^real division@>
26126 if is_native_font(f) then
26127 begin a:=width(p);
26128 if a=0 then get_native_char_sidebearings(f, cur_val, addressof(lsb), addressof(rsb))
26129 end
26130 else a:=char_width(f)(char_info(f)(character(p)));@/
26131 do_assignments;@/
26132 @<Create a character node |q| for the next character,
26133 but set |q:=null| if problems arise@>;
26134 if q<>null then @<Append the accent with appropriate kerns,
26135 then set |p:=q|@>;
26136 link(tail):=p; tail:=p; space_factor:=1000;
26137 end;
26138 end;
26139
26140 @ @<Create a character node |q| for the next...@>=
26141 q:=null; f:=cur_font;
26142 if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given) then
26143 begin q:=new_character(f,cur_chr); cur_val:=cur_chr
26144 end
26145 else if cur_cmd=char_num then
26146 begin scan_char_num; q:=new_character(f,cur_val);
26147 end
26148 else back_input
26149
26150 @ The kern nodes appended here must be distinguished from other kerns, lest
26151 they be wiped away by the hyphenation algorithm or by a previous line break.
26152
26153 The two kerns are computed with (machine-dependent) |real| arithmetic, but
26154 their sum is machine-independent; the net effect is machine-independent,
26155 because the user cannot remove these nodes nor access them via \.{\\lastkern}.
26156
26157 @<Append the accent with appropriate kerns...@>=
26158 begin t:=slant(f)/float_constant(65536);
26159 @^real division@>
26160 if is_native_font(f) then begin
26161 w:=width(q);
26162 get_native_char_height_depth(f, cur_val, addressof(h), addressof(delta))
26163 {using delta as scratch space for the unneeded depth value}
26164 end else begin
26165 i:=char_info(f)(character(q));
26166 w:=char_width(f)(i); h:=char_height(f)(height_depth(i))
26167 end;
26168 if h<>x then {the accent must be shifted up or down}
26169 begin p:=hpack(p,natural); shift_amount(p):=x-h;
26170 end;
26171 if is_native_font(f) and (a=0) then { special case for non-spacing marks }
26172 delta:=round((w-lsb+rsb)/float_constant(2)+h*t-x*s)
26173 else delta:=round((w-a)/float_constant(2)+h*t-x*s);
26174 @^real multiplication@>
26175 @^real addition@>
26176 r:=new_kern(delta); subtype(r):=acc_kern; link(tail):=r; link(r):=p;
26177 tail:=new_kern(-a-delta); subtype(tail):=acc_kern; link(p):=tail; p:=q;
26178 end
26179
26180 @ When `\.{\\cr}' or `\.{\\span}' or a tab mark comes through the scanner
26181 into |main_control|, it might be that the user has foolishly inserted
26182 one of them into something that has nothing to do with alignment. But it is
26183 far more likely that a left brace or right brace has been omitted, since
26184 |get_next| takes actions appropriate to alignment only when `\.{\\cr}'
26185 or `\.{\\span}' or tab marks occur with |align_state=0|. The following
26186 program attempts to make an appropriate recovery.
26187
26188 @<Cases of |main_control| that build...@>=
26189 any_mode(car_ret), any_mode(tab_mark): align_error;
26190 any_mode(no_align): no_align_error;
26191 any_mode(omit): omit_error;
26192
26193 @ @<Declare act...@>=
26194 procedure align_error;
26195 begin if abs(align_state)>2 then
26196 @<Express consternation over the fact that no alignment is in progress@>
26197 else begin back_input;
26198 if align_state<0 then
26199 begin print_err("Missing { inserted");
26200 @.Missing \{ inserted@>
26201 incr(align_state); cur_tok:=left_brace_token+"{";
26202 end
26203 else begin print_err("Missing } inserted");
26204 @.Missing \} inserted@>
26205 decr(align_state); cur_tok:=right_brace_token+"}";
26206 end;
26207 help3("I've put in what seems to be necessary to fix")@/
26208 ("the current column of the current alignment.")@/
26209 ("Try to go on, since this might almost work."); ins_error;
26210 end;
26211 end;
26212
26213 @ @<Express consternation...@>=
26214 begin print_err("Misplaced "); print_cmd_chr(cur_cmd,cur_chr);
26215 @.Misplaced \&@>
26216 @.Misplaced \\span@>
26217 @.Misplaced \\cr@>
26218 if cur_tok=tab_token+"&" then
26219 begin help6("I can't figure out why you would want to use a tab mark")@/
26220 ("here. If you just want an ampersand, the remedy is")@/
26221 ("simple: Just type `I\&' now. But if some right brace")@/
26222 ("up above has ended a previous alignment prematurely,")@/
26223 ("you're probably due for more error messages, and you")@/
26224 ("might try typing `S' now just to see what is salvageable.");
26225 end
26226 else begin help5("I can't figure out why you would want to use a tab mark")@/
26227 ("or \cr or \span just now. If something like a right brace")@/
26228 ("up above has ended a previous alignment prematurely,")@/
26229 ("you're probably due for more error messages, and you")@/
26230 ("might try typing `S' now just to see what is salvageable.");
26231 end;
26232 error;
26233 end
26234
26235 @ The help messages here contain a little white lie, since \.{\\noalign}
26236 and \.{\\omit} are allowed also after `\.{\\noalign\{...\}}'.
26237
26238 @<Declare act...@>=
26239 procedure no_align_error;
26240 begin print_err("Misplaced "); print_esc("noalign");
26241 @.Misplaced \\noalign@>
26242 help2("I expect to see \noalign only after the \cr of")@/
26243 ("an alignment. Proceed, and I'll ignore this case."); error;
26244 end;
26245 procedure omit_error;
26246 begin print_err("Misplaced "); print_esc("omit");
26247 @.Misplaced \\omit@>
26248 help2("I expect to see \omit only after tab marks or the \cr of")@/
26249 ("an alignment. Proceed, and I'll ignore this case."); error;
26250 end;
26251
26252 @ We've now covered most of the abuses of \.{\\halign} and \.{\\valign}.
26253 Let's take a look at what happens when they are used correctly.
26254
26255 @<Cases of |main_control| that build...@>=
26256 vmode+halign:init_align;
26257 hmode+valign:@<Cases of |main_control| for |hmode+valign|@>@; init_align;
26258 mmode+halign: if privileged then
26259 if cur_group=math_shift_group then init_align
26260 else off_save;
26261 vmode+endv,hmode+endv: do_endv;
26262
26263 @ An |align_group| code is supposed to remain on the |save_stack|
26264 during an entire alignment, until |fin_align| removes it.
26265
26266 A devious user might force an |endv| command to occur just about anywhere;
26267 we must defeat such hacks.
26268
26269 @<Declare act...@>=
26270 procedure do_endv;
26271 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
26272 while (input_stack[base_ptr].index_field<>v_template) and
26273 (input_stack[base_ptr].loc_field=null) and
26274 (input_stack[base_ptr].state_field=token_list) do decr(base_ptr);
26275 if (input_stack[base_ptr].index_field<>v_template) or
26276 (input_stack[base_ptr].loc_field<>null) or
26277 (input_stack[base_ptr].state_field<>token_list) then
26278 fatal_error("(interwoven alignment preambles are not allowed)");
26279 @.interwoven alignment preambles...@>
26280 if cur_group=align_group then
26281 begin end_graf;
26282 if fin_col then fin_row;
26283 end
26284 else off_save;
26285 end;
26286
26287 @ @<Cases of |handle_right_brace|...@>=
26288 align_group: begin back_input; cur_tok:=cs_token_flag+frozen_cr;
26289 print_err("Missing "); print_esc("cr"); print(" inserted");
26290 @.Missing \\cr inserted@>
26291 help1("I'm guessing that you meant to end an alignment here.");
26292 ins_error;
26293 end;
26294
26295 @ @<Cases of |handle_right_brace|...@>=
26296 no_align_group: begin end_graf; unsave; align_peek;
26297 end;
26298
26299 @ Finally, \.{\\endcsname} is not supposed to get through to |main_control|.
26300
26301 @<Cases of |main_control| that build...@>=
26302 any_mode(end_cs_name): cs_error;
26303
26304 @ @<Declare act...@>=
26305 procedure cs_error;
26306 begin print_err("Extra "); print_esc("endcsname");
26307 @.Extra \\endcsname@>
26308 help1("I'm ignoring this, since I wasn't doing a \csname.");
26309 error;
26310 end;
26311
26312 @* \[48] Building math lists.
26313 The routines that \TeX\ uses to create mlists are similar to those we have
26314 just seen for the generation of hlists and vlists. But it is necessary to
26315 make ``noads'' as well as nodes, so the reader should review the
26316 discussion of math mode data structures before trying to make sense out of
26317 the following program.
26318
26319 Here is a little routine that needs to be done whenever a subformula
26320 is about to be processed. The parameter is a code like |math_group|.
26321
26322 @<Declare act...@>=
26323 procedure push_math(@!c:group_code);
26324 begin push_nest; mode:=-mmode; incompleat_noad:=null; new_save_level(c);
26325 end;
26326
26327 @ We get into math mode from horizontal mode when a `\.\$' (i.e., a
26328 |math_shift| character) is scanned. We must check to see whether this
26329 `\.\$' is immediately followed by another, in case display math mode is
26330 called for.
26331
26332 @<Cases of |main_control| that build...@>=
26333 hmode+math_shift:init_math;
26334
26335 @ @<Declare act...@>=
26336 @t\4@>@<Declare subprocedures for |init_math|@>@;
26337 procedure init_math;
26338 label reswitch,found,not_found,done;
26339 var w:scaled; {new or partial |pre_display_size|}
26340 @!j:pointer; {prototype box for display}
26341 @!x:integer; {new |pre_display_direction|}
26342 @!l:scaled; {new |display_width|}
26343 @!s:scaled; {new |display_indent|}
26344 @!p:pointer; {current node when calculating |pre_display_size|}
26345 @!q:pointer; {glue specification when calculating |pre_display_size|}
26346 @!f:internal_font_number; {font in current |char_node|}
26347 @!n:integer; {scope of paragraph shape specification}
26348 @!v:scaled; {|w| plus possible glue amount}
26349 @!d:scaled; {increment to |v|}
26350 begin get_token; {|get_x_token| would fail on \.{\\ifmmode}\thinspace!}
26351 if (cur_cmd=math_shift)and(mode>0) then @<Go into display math mode@>
26352 else begin back_input; @<Go into ordinary math mode@>;
26353 end;
26354 end;
26355
26356 @ @<Go into ordinary math mode@>=
26357 begin push_math(math_shift_group); eq_word_define(int_base+cur_fam_code,-1);
26358 if every_math<>null then begin_token_list(every_math,every_math_text);
26359 end
26360
26361 @ We get into ordinary math mode from display math mode when `\.{\\eqno}' or
26362 `\.{\\leqno}' appears. In such cases |cur_chr| will be 0 or~1, respectively;
26363 the value of |cur_chr| is placed onto |save_stack| for safe keeping.
26364
26365 @<Cases of |main_control| that build...@>=
26366 mmode+eq_no: if privileged then
26367 if cur_group=math_shift_group then start_eq_no
26368 else off_save;
26369
26370 @ @<Put each...@>=
26371 primitive("eqno",eq_no,0);
26372 @!@:eq_no_}{\.{\\eqno} primitive@>
26373 primitive("leqno",eq_no,1);
26374 @!@:leq_no_}{\.{\\leqno} primitive@>
26375
26376 @ When \TeX\ is in display math mode, |cur_group=math_shift_group|,
26377 so it is not necessary for the |start_eq_no| procedure to test for
26378 this condition.
26379
26380 @<Declare act...@>=
26381 procedure start_eq_no;
26382 begin saved(0):=cur_chr; incr(save_ptr);
26383 @<Go into ordinary math mode@>;
26384 end;
26385
26386 @ @<Cases of |print_cmd_chr|...@>=
26387 eq_no:if chr_code=1 then print_esc("leqno")@+else print_esc("eqno");
26388
26389 @ @<Forbidden...@>=non_math(eq_no),
26390
26391 @ When we enter display math mode, we need to call |line_break| to
26392 process the partial paragraph that has just been interrupted by the
26393 display. Then we can set the proper values of |display_width| and
26394 |display_indent| and |pre_display_size|.
26395
26396 @<Go into display math mode@>=
26397 begin j:=null; w:=-max_dimen;
26398 if head=tail then {`\.{\\noindent\$\$}' or `\.{\$\${ }\$\$}'}
26399 @<Prepare for display after an empty paragraph@>
26400 else begin line_break(true);@/
26401 @<Calculate the natural width, |w|, by which the characters of the
26402 final line extend to the right of the reference point,
26403 plus two ems; or set |w:=max_dimen| if the non-blank information
26404 on that line is affected by stretching or shrinking@>;
26405 end;
26406 {now we are in vertical mode, working on the list that will contain the display}
26407 @<Calculate the length, |l|, and the shift amount, |s|, of the display lines@>;
26408 push_math(math_shift_group); mode:=mmode;
26409 eq_word_define(int_base+cur_fam_code,-1);@/
26410 eq_word_define(dimen_base+pre_display_size_code,w);
26411 LR_box:=j;
26412 if eTeX_ex then eq_word_define(int_base+pre_display_direction_code,x);
26413 eq_word_define(dimen_base+display_width_code,l);
26414 eq_word_define(dimen_base+display_indent_code,s);
26415 if every_display<>null then begin_token_list(every_display,every_display_text);
26416 if nest_ptr=1 then build_page;
26417 end
26418
26419 @ @<Calculate the natural width, |w|, by which...@>=
26420 @<Prepare for display after a non-empty paragraph@>;
26421 while p<>null do
26422 begin @<Let |d| be the natural width of node |p|;
26423 if the node is ``visible,'' |goto found|;
26424 if the node is glue that stretches or shrinks, set |v:=max_dimen|@>;
26425 if v<max_dimen then v:=v+d;
26426 goto not_found;
26427 found: if v<max_dimen then
26428 begin v:=v+d; w:=v;
26429 end
26430 else begin w:=max_dimen; goto done;
26431 end;
26432 not_found: p:=link(p);
26433 end;
26434 done:
26435 @<Finish the natural width computation@>
26436
26437 @ @<Let |d| be the natural width of node |p|...@>=
26438 reswitch: if is_char_node(p) then
26439 begin f:=font(p); d:=char_width(f)(char_info(f)(character(p)));
26440 goto found;
26441 end;
26442 case type(p) of
26443 hlist_node,vlist_node,rule_node: begin d:=width(p); goto found;
26444 end;
26445 ligature_node:@<Make node |p| look like a |char_node|...@>;
26446 kern_node: d:=width(p);
26447 margin_kern_node: d:=width(p);
26448 @t\4@>@<Cases of `Let |d| be the natural width' that need special treatment@>@;
26449 glue_node:@<Let |d| be the natural width of this glue; if stretching
26450 or shrinking, set |v:=max_dimen|; |goto found| in the case of leaders@>;
26451 whatsit_node: @<Let |d| be the width of the whatsit |p|, and |goto found| if ``visible''@>;
26452 othercases d:=0
26453 endcases
26454
26455 @ We need to be careful that |w|, |v|, and |d| do not depend on any |glue_set|
26456 values, since such values are subject to system-dependent rounding.
26457 System-dependent numbers are not allowed to infiltrate parameters like
26458 |pre_display_size|, since \TeX82 is supposed to make the same decisions on all
26459 machines.
26460
26461 @<Let |d| be the natural width of this glue...@>=
26462 begin q:=glue_ptr(p); d:=width(q);
26463 if glue_sign(just_box)=stretching then
26464 begin if (glue_order(just_box)=stretch_order(q))and@|
26465 (stretch(q)<>0) then
26466 v:=max_dimen;
26467 end
26468 else if glue_sign(just_box)=shrinking then
26469 begin if (glue_order(just_box)=shrink_order(q))and@|
26470 (shrink(q)<>0) then
26471 v:=max_dimen;
26472 end;
26473 if subtype(p)>=a_leaders then goto found;
26474 end
26475
26476 @ A displayed equation is considered to be three lines long, so we
26477 calculate the length and offset of line number |prev_graf+2|.
26478
26479 @<Calculate the length, |l|, ...@>=
26480 if par_shape_ptr=null then
26481 if (hang_indent<>0)and@|
26482 (((hang_after>=0)and(prev_graf+2>hang_after))or@|
26483 (prev_graf+1<-hang_after)) then
26484 begin l:=hsize-abs(hang_indent);
26485 if hang_indent>0 then s:=hang_indent@+else s:=0;
26486 end
26487 else begin l:=hsize; s:=0;
26488 end
26489 else begin n:=info(par_shape_ptr);
26490 if prev_graf+2>=n then p:=par_shape_ptr+2*n
26491 else p:=par_shape_ptr+2*(prev_graf+2);
26492 s:=mem[p-1].sc; l:=mem[p].sc;
26493 end
26494
26495 @ Subformulas of math formulas cause a new level of math mode to be entered,
26496 on the semantic nest as well as the save stack. These subformulas arise in
26497 several ways: (1)~A left brace by itself indicates the beginning of a
26498 subformula that will be put into a box, thereby freezing its glue and
26499 preventing line breaks. (2)~A subscript or superscript is treated as a
26500 subformula if it is not a single character; the same applies to
26501 the nucleus of things like \.{\\underline}. (3)~The \.{\\left} primitive
26502 initiates a subformula that will be terminated by a matching \.{\\right}.
26503 The group codes placed on |save_stack| in these three cases are
26504 |math_group|, |math_group|, and |math_left_group|, respectively.
26505
26506 Here is the code that handles case (1); the other cases are not quite as
26507 trivial, so we shall consider them later.
26508
26509 @<Cases of |main_control| that build...@>=
26510 mmode+left_brace: begin tail_append(new_noad);
26511 back_input; scan_math(nucleus(tail));
26512 end;
26513
26514 @ Recall that the |nucleus|, |subscr|, and |supscr| fields in a noad are
26515 broken down into subfields called |math_type| and either |info| or
26516 |(fam,character)|. The job of |scan_math| is to figure out what to place
26517 in one of these principal fields; it looks at the subformula that
26518 comes next in the input, and places an encoding of that subformula
26519 into a given word of |mem|.
26520
26521 @d fam_in_range==((cur_fam>=0)and(cur_fam<number_math_families))
26522
26523 @<Declare act...@>=
26524 procedure scan_math(@!p:pointer);
26525 label restart,reswitch,exit;
26526 var c:integer; {math character code}
26527 begin restart:@<Get the next non-blank non-relax...@>;
26528 reswitch:case cur_cmd of
26529 letter,other_char,char_given: begin c:=ho(math_code(cur_chr));
26530 if is_active_math_char(c) then
26531 begin @<Treat |cur_chr| as an active character@>;
26532 goto restart;
26533 end;
26534 end;
26535 char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
26536 goto reswitch;
26537 end;
26538 math_char_num:
26539 if cur_chr = 2 then begin {\.{\\Umathchar}}
26540 scan_math_class_int; c:=set_class_field(cur_val);
26541 scan_math_fam_int; c:=c + set_family_field(cur_val);
26542 scan_usv_num; c:=c + cur_val;
26543 end else if cur_chr = 1 then begin {\.{\\Umathcharnum}}
26544 scan_xetex_math_char_int; c:=cur_val;
26545 end else begin scan_fifteen_bit_int;
26546 c:=set_class_field(cur_val div @"1000) +
26547 set_family_field((cur_val mod @"1000) div @"100) +
26548 (cur_val mod @"100);
26549 end;
26550 math_given: begin
26551 c:=set_class_field(cur_chr div @"1000) +
26552 set_family_field((cur_chr mod @"1000) div @"100) +
26553 (cur_chr mod @"100);
26554 end;
26555 XeTeX_math_given: c:=cur_chr;
26556 delim_num: begin
26557 if cur_chr=1 then begin {\.{\\Udelimiter <class> <fam> <usv>}}
26558 scan_math_class_int; c:=set_class_field(cur_val);
26559 scan_math_fam_int; c:=c + set_family_field(cur_val);
26560 scan_usv_num; c:=c + cur_val;
26561 end else begin {\.{\\delimiter <27-bit delcode>}}
26562 scan_delimiter_int;
26563 c:=cur_val div @'10000; {get the `small' delimiter field}
26564 c:=set_class_field(c div @"1000) +
26565 set_family_field((c mod @"1000) div @"100) +
26566 (c mod @"100); {and convert it to a \XeTeX\ mathchar code}
26567 end;
26568 end;
26569 othercases @<Scan a subformula enclosed in braces and |return|@>
26570 endcases;@/
26571 math_type(p):=math_char; character(p):=qi(c mod @"10000);
26572 if (is_var_family(c)) and fam_in_range then plane_and_fam_field(p):=cur_fam
26573 else plane_and_fam_field(p):=(math_fam_field(c));
26574 plane_and_fam_field(p):=plane_and_fam_field(p) + (math_char_field(c) div @"10000) * @"100;
26575 exit:end;
26576
26577 @ An active character that is an |outer_call| is allowed here.
26578
26579 @<Treat |cur_chr|...@>=
26580 begin cur_cs:=cur_chr+active_base;
26581 cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
26582 x_token; back_input;
26583 end
26584
26585 @ The pointer |p| is placed on |save_stack| while a complex subformula
26586 is being scanned.
26587
26588 @<Scan a subformula...@>=
26589 begin back_input; scan_left_brace;@/
26590 saved(0):=p; incr(save_ptr); push_math(math_group); return;
26591 end
26592
26593 @ The simplest math formula is, of course, `\.{\${ }\$}', when no noads are
26594 generated. The next simplest cases involve a single character, e.g.,
26595 `\.{\$x\$}'. Even though such cases may not seem to be very interesting,
26596 the reader can perhaps understand how happy the author was when `\.{\$x\$}'
26597 was first properly typeset by \TeX. The code in this section was used.
26598 @^Knuth, Donald Ervin@>
26599
26600 @<Cases of |main_control| that build...@>=
26601 mmode+letter,mmode+other_char,mmode+char_given:
26602 set_math_char(ho(math_code(cur_chr)));
26603 mmode+char_num: begin scan_char_num; cur_chr:=cur_val;
26604 set_math_char(ho(math_code(cur_chr)));
26605 end;
26606 mmode+math_char_num: if cur_chr = 2 then begin {\.{\\Umathchar}}
26607 scan_math_class_int; t:=set_class_field(cur_val);
26608 scan_math_fam_int; t:=t + set_family_field(cur_val);
26609 scan_usv_num; t:=t + cur_val;
26610 set_math_char(t);
26611 end else if cur_chr = 1 then begin {\.{\\Umathcharnum}}
26612 scan_xetex_math_char_int; set_math_char(cur_val);
26613 end else begin scan_fifteen_bit_int;
26614 set_math_char(set_class_field(cur_val div @"1000) +
26615 set_family_field((cur_val mod @"1000) div @"100) +
26616 (cur_val mod @"100));
26617 end;
26618 mmode+math_given: begin
26619 set_math_char(set_class_field(cur_chr div @"1000) +
26620 set_family_field((cur_chr mod @"1000) div @"100) +
26621 (cur_chr mod @"100));
26622 end;
26623 mmode+XeTeX_math_given: set_math_char(cur_chr);
26624 mmode+delim_num: begin
26625 if cur_chr=1 then begin {\.{\\Udelimiter}}
26626 scan_math_class_int; t:=set_class_field(cur_val);
26627 scan_math_fam_int; t:=t + set_family_field(cur_val);
26628 scan_usv_num; t:=t + cur_val;
26629 set_math_char(t);
26630 end else begin
26631 scan_delimiter_int;
26632 cur_val:=cur_val div @'10000; {discard the large delimiter code}
26633 set_math_char(set_class_field(cur_val div @"1000) +
26634 set_family_field((cur_val mod @"1000) div @"100) +
26635 (cur_val mod @"100));
26636 end;
26637 end;
26638
26639 @ The |set_math_char| procedure creates a new noad appropriate to a given
26640 math code, and appends it to the current mlist. However, if the math code
26641 is sufficiently large, the |cur_chr| is treated as an active character and
26642 nothing is appended.
26643
26644 @<Declare act...@>=
26645 procedure set_math_char(@!c:integer);
26646 var p:pointer; {the new noad}
26647 ch: UnicodeScalar;
26648 begin if is_active_math_char(c) then
26649 @<Treat |cur_chr|...@>
26650 else begin p:=new_noad; math_type(nucleus(p)):=math_char;
26651 ch:=math_char_field(c);
26652 character(nucleus(p)):=qi(ch mod @"10000);
26653 plane_and_fam_field(nucleus(p)):=math_fam_field(c);
26654 if is_var_family(c) then
26655 begin if fam_in_range then plane_and_fam_field(nucleus(p)):=cur_fam;
26656 type(p):=ord_noad;
26657 end
26658 else type(p):=ord_noad+math_class_field(c);
26659 plane_and_fam_field(nucleus(p)):=plane_and_fam_field(nucleus(p)) + (ch div @"10000) * @"100;
26660 link(tail):=p; tail:=p;
26661 end;
26662 end;
26663
26664 @ Primitive math operators like \.{\\mathop} and \.{\\underline} are given
26665 the command code |math_comp|, supplemented by the noad type that they
26666 generate.
26667
26668 @<Put each...@>=
26669 primitive("mathord",math_comp,ord_noad);
26670 @!@:math_ord_}{\.{\\mathord} primitive@>
26671 primitive("mathop",math_comp,op_noad);
26672 @!@:math_op_}{\.{\\mathop} primitive@>
26673 primitive("mathbin",math_comp,bin_noad);
26674 @!@:math_bin_}{\.{\\mathbin} primitive@>
26675 primitive("mathrel",math_comp,rel_noad);
26676 @!@:math_rel_}{\.{\\mathrel} primitive@>
26677 primitive("mathopen",math_comp,open_noad);
26678 @!@:math_open_}{\.{\\mathopen} primitive@>
26679 primitive("mathclose",math_comp,close_noad);
26680 @!@:math_close_}{\.{\\mathclose} primitive@>
26681 primitive("mathpunct",math_comp,punct_noad);
26682 @!@:math_punct_}{\.{\\mathpunct} primitive@>
26683 primitive("mathinner",math_comp,inner_noad);
26684 @!@:math_inner_}{\.{\\mathinner} primitive@>
26685 primitive("underline",math_comp,under_noad);
26686 @!@:underline_}{\.{\\underline} primitive@>
26687 primitive("overline",math_comp,over_noad);@/
26688 @!@:overline_}{\.{\\overline} primitive@>
26689 primitive("displaylimits",limit_switch,normal);
26690 @!@:display_limits_}{\.{\\displaylimits} primitive@>
26691 primitive("limits",limit_switch,limits);
26692 @!@:limits_}{\.{\\limits} primitive@>
26693 primitive("nolimits",limit_switch,no_limits);
26694 @!@:no_limits_}{\.{\\nolimits} primitive@>
26695
26696 @ @<Cases of |print_cmd_chr|...@>=
26697 math_comp: case chr_code of
26698 ord_noad: print_esc("mathord");
26699 op_noad: print_esc("mathop");
26700 bin_noad: print_esc("mathbin");
26701 rel_noad: print_esc("mathrel");
26702 open_noad: print_esc("mathopen");
26703 close_noad: print_esc("mathclose");
26704 punct_noad: print_esc("mathpunct");
26705 inner_noad: print_esc("mathinner");
26706 under_noad: print_esc("underline");
26707 othercases print_esc("overline")
26708 endcases;
26709 limit_switch: if chr_code=limits then print_esc("limits")
26710 else if chr_code=no_limits then print_esc("nolimits")
26711 else print_esc("displaylimits");
26712
26713 @ @<Cases of |main_control| that build...@>=
26714 mmode+math_comp: begin tail_append(new_noad);
26715 type(tail):=cur_chr; scan_math(nucleus(tail));
26716 end;
26717 mmode+limit_switch: math_limit_switch;
26718
26719 @ @<Declare act...@>=
26720 procedure math_limit_switch;
26721 label exit;
26722 begin if head<>tail then if type(tail)=op_noad then
26723 begin subtype(tail):=cur_chr; return;
26724 end;
26725 print_err("Limit controls must follow a math operator");
26726 @.Limit controls must follow...@>
26727 help1("I'm ignoring this misplaced \limits or \nolimits command."); error;
26728 exit:end;
26729
26730 @ Delimiter fields of noads are filled in by the |scan_delimiter| routine.
26731 The first parameter of this procedure is the |mem| address where the
26732 delimiter is to be placed; the second tells if this delimiter follows
26733 \.{\\radical} or not.
26734
26735 @<Declare act...@>=
26736 procedure scan_delimiter(@!p:pointer;@!r:boolean);
26737 begin
26738 if r then begin
26739 if cur_chr=1 then begin {\.{\\Uradical}}
26740 cur_val1:=@"40000000; {extended delimiter code flag}
26741 scan_math_fam_int; cur_val1:=cur_val1 + cur_val * @"200000;
26742 scan_usv_num; cur_val:=cur_val1 + cur_val;
26743 end else {radical}
26744 scan_delimiter_int;
26745 end
26746 else begin @<Get the next non-blank non-relax...@>;
26747 case cur_cmd of
26748 letter,other_char: begin
26749 cur_val:=del_code(cur_chr);
26750 end;
26751 delim_num: if cur_chr=1 then begin {\.{\\Udelimiter}}
26752 cur_val1:=@"40000000; {extended delimiter code flag}
26753 scan_math_class_int; {discarded}
26754 scan_math_fam_int; cur_val1:=cur_val1 + cur_val * @"200000;
26755 scan_usv_num; cur_val:=cur_val1 + cur_val;
26756 end else scan_delimiter_int; {normal delimiter}
26757 othercases begin cur_val:=-1; end;
26758 endcases;
26759 end;
26760 if cur_val<0 then begin @<Report that an invalid delimiter code is being changed
26761 to null; set~|cur_val:=0|@>;
26762 end;
26763 if cur_val>=@"40000000 then begin {extended delimiter code, only one size}
26764 small_plane_and_fam_field(p):=((cur_val mod @"200000) div @"10000) * @"100 {plane}
26765 + (cur_val div @"200000) mod @"100; {family}
26766 small_char_field(p):=qi(cur_val mod @"10000);
26767 large_plane_and_fam_field(p):=0;
26768 large_char_field(p):=0;
26769 end else begin {standard delimiter code, 4-bit families and 8-bit char codes}
26770 small_plane_and_fam_field(p):=(cur_val div @'4000000) mod 16;
26771 small_char_field(p):=qi((cur_val div @'10000) mod 256);
26772 large_plane_and_fam_field(p):=(cur_val div 256) mod 16;
26773 large_char_field(p):=qi(cur_val mod 256);
26774 end;
26775 end;
26776
26777 @ @<Report that an invalid delimiter...@>=
26778 begin print_err("Missing delimiter (. inserted)");
26779 @.Missing delimiter...@>
26780 help6("I was expecting to see something like `(' or `\{' or")@/
26781 ("`\}' here. If you typed, e.g., `{' instead of `\{', you")@/
26782 ("should probably delete the `{' by typing `1' now, so that")@/
26783 ("braces don't get unbalanced. Otherwise just proceed.")@/
26784 ("Acceptable delimiters are characters whose \delcode is")@/
26785 ("nonnegative, or you can use `\delimiter <delimiter code>'.");
26786 back_error; cur_val:=0;
26787 end
26788
26789 @ @<Cases of |main_control| that build...@>=
26790 mmode+radical:math_radical;
26791
26792 @ @<Declare act...@>=
26793 procedure math_radical;
26794 begin tail_append(get_node(radical_noad_size));
26795 type(tail):=radical_noad; subtype(tail):=normal;
26796 mem[nucleus(tail)].hh:=empty_field;
26797 mem[subscr(tail)].hh:=empty_field;
26798 mem[supscr(tail)].hh:=empty_field;
26799 scan_delimiter(left_delimiter(tail),true); scan_math(nucleus(tail));
26800 end;
26801
26802 @ @<Cases of |main_control| that build...@>=
26803 mmode+accent,mmode+math_accent:math_ac;
26804
26805 @ @<Declare act...@>=
26806 procedure math_ac;
26807 var c: integer;
26808 begin if cur_cmd=accent then
26809 @<Complain that the user should have said \.{\\mathaccent}@>;
26810 tail_append(get_node(accent_noad_size));
26811 type(tail):=accent_noad; subtype(tail):=normal;
26812 mem[nucleus(tail)].hh:=empty_field;
26813 mem[subscr(tail)].hh:=empty_field;
26814 mem[supscr(tail)].hh:=empty_field;
26815 math_type(accent_chr(tail)):=math_char;
26816 if cur_chr=1 then begin
26817 if scan_keyword("fixed") then
26818 subtype(tail):=fixed_acc
26819 else if scan_keyword("bottom") then begin
26820 if scan_keyword("fixed") then
26821 subtype(tail):=bottom_acc+fixed_acc
26822 else
26823 subtype(tail):=bottom_acc;
26824 end;
26825 scan_math_class_int; c:=set_class_field(cur_val);
26826 scan_math_fam_int; c:=c + set_family_field(cur_val);
26827 scan_usv_num; cur_val:=cur_val + c;
26828 end
26829 else begin
26830 scan_fifteen_bit_int;
26831 cur_val:=set_class_field(cur_val div @"1000) +
26832 set_family_field((cur_val mod @"1000) div @"100) +
26833 (cur_val mod @"100);
26834 end;
26835 character(accent_chr(tail)):=qi(cur_val mod @"10000);
26836 if (is_var_family(cur_val))and fam_in_range then plane_and_fam_field(accent_chr(tail)):=cur_fam
26837 else plane_and_fam_field(accent_chr(tail)):=math_fam_field(cur_val);
26838 plane_and_fam_field(accent_chr(tail))
26839 :=plane_and_fam_field(accent_chr(tail)) + (math_char_field(cur_val) div @"10000) * @"100;
26840 scan_math(nucleus(tail));
26841 end;
26842
26843 @ @<Complain that the user should have said \.{\\mathaccent}@>=
26844 begin print_err("Please use "); print_esc("mathaccent");
26845 print(" for accents in math mode");
26846 @.Please use \\mathaccent...@>
26847 help2("I'm changing \accent to \mathaccent here; wish me luck.")@/
26848 ("(Accents are not the same in formulas as they are in text.)");
26849 error;
26850 end
26851
26852 @ @<Cases of |main_control| that build...@>=
26853 mmode+vcenter: begin scan_spec(vcenter_group,false); normal_paragraph;
26854 push_nest; mode:=-vmode; prev_depth:=ignore_depth;
26855 if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
26856 end;
26857
26858 @ @<Cases of |handle...@>=
26859 vcenter_group: begin end_graf; unsave; save_ptr:=save_ptr-2;
26860 p:=vpack(link(head),saved(1),saved(0)); pop_nest;
26861 tail_append(new_noad); type(tail):=vcenter_noad;
26862 math_type(nucleus(tail)):=sub_box; info(nucleus(tail)):=p;
26863 end;
26864
26865 @ The routine that inserts a |style_node| holds no surprises.
26866
26867 @<Put each...@>=
26868 primitive("displaystyle",math_style,display_style);
26869 @!@:display_style_}{\.{\\displaystyle} primitive@>
26870 primitive("textstyle",math_style,text_style);
26871 @!@:text_style_}{\.{\\textstyle} primitive@>
26872 primitive("scriptstyle",math_style,script_style);
26873 @!@:script_style_}{\.{\\scriptstyle} primitive@>
26874 primitive("scriptscriptstyle",math_style,script_script_style);
26875 @!@:script_script_style_}{\.{\\scriptscriptstyle} primitive@>
26876
26877 @ @<Cases of |print_cmd_chr|...@>=
26878 math_style: print_style(chr_code);
26879
26880 @ @<Cases of |main_control| that build...@>=
26881 mmode+math_style: tail_append(new_style(cur_chr));
26882 mmode+non_script: begin tail_append(new_glue(zero_glue));
26883 subtype(tail):=cond_math_glue;
26884 end;
26885 mmode+math_choice: append_choices;
26886
26887 @ The routine that scans the four mlists of a \.{\\mathchoice} is very
26888 much like the routine that builds discretionary nodes.
26889
26890 @<Declare act...@>=
26891 procedure append_choices;
26892 begin tail_append(new_choice); incr(save_ptr); saved(-1):=0;
26893 push_math(math_choice_group); scan_left_brace;
26894 end;
26895
26896 @ @<Cases of |handle_right_brace|...@>=
26897 math_choice_group: build_choices;
26898
26899 @ @<Declare act...@>=
26900 @t\4@>@<Declare the function called |fin_mlist|@>@t@>@;@/
26901 procedure build_choices;
26902 label exit;
26903 var p:pointer; {the current mlist}
26904 begin unsave; p:=fin_mlist(null);
26905 case saved(-1) of
26906 0:display_mlist(tail):=p;
26907 1:text_mlist(tail):=p;
26908 2:script_mlist(tail):=p;
26909 3:begin script_script_mlist(tail):=p; decr(save_ptr); return;
26910 end;
26911 end; {there are no other cases}
26912 incr(saved(-1)); push_math(math_choice_group); scan_left_brace;
26913 exit:end;
26914
26915 @ Subscripts and superscripts are attached to the previous nucleus by the
26916 @^superscripts@>@^subscripts@>
26917 action procedure called |sub_sup|. We use the facts that |sub_mark=sup_mark+1|
26918 and |subscr(p)=supscr(p)+1|.
26919
26920 @<Cases of |main_control| that build...@>=
26921 mmode+sub_mark,mmode+sup_mark: sub_sup;
26922
26923 @ @<Declare act...@>=
26924 procedure sub_sup;
26925 var t:small_number; {type of previous sub/superscript}
26926 @!p:pointer; {field to be filled by |scan_math|}
26927 begin t:=empty; p:=null;
26928 if tail<>head then if scripts_allowed(tail) then
26929 begin p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
26930 t:=math_type(p);
26931 end;
26932 if (p=null)or(t<>empty) then @<Insert a dummy noad to be sub/superscripted@>;
26933 scan_math(p);
26934 end;
26935
26936 @ @<Insert a dummy...@>=
26937 begin tail_append(new_noad);
26938 p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
26939 if t<>empty then
26940 begin if cur_cmd=sup_mark then
26941 begin print_err("Double superscript");
26942 @.Double superscript@>
26943 help1("I treat `x^1^2' essentially like `x^1{}^2'.");
26944 end
26945 else begin print_err("Double subscript");
26946 @.Double subscript@>
26947 help1("I treat `x_1_2' essentially like `x_1{}_2'.");
26948 end;
26949 error;
26950 end;
26951 end
26952
26953 @ An operation like `\.{\\over}' causes the current mlist to go into a
26954 state of suspended animation: |incompleat_noad| points to a |fraction_noad|
26955 that contains the mlist-so-far as its numerator, while the denominator
26956 is yet to come. Finally when the mlist is finished, the denominator will
26957 go into the incompleat fraction noad, and that noad will become the
26958 whole formula, unless it is surrounded by `\.{\\left}' and `\.{\\right}'
26959 delimiters.
26960
26961 @d above_code=0 { `\.{\\above}' }
26962 @d over_code=1 { `\.{\\over}' }
26963 @d atop_code=2 { `\.{\\atop}' }
26964 @d delimited_code=3 { `\.{\\abovewithdelims}', etc.}
26965
26966 @<Put each...@>=
26967 primitive("above",above,above_code);@/
26968 @!@:above_}{\.{\\above} primitive@>
26969 primitive("over",above,over_code);@/
26970 @!@:over_}{\.{\\over} primitive@>
26971 primitive("atop",above,atop_code);@/
26972 @!@:atop_}{\.{\\atop} primitive@>
26973 primitive("abovewithdelims",above,delimited_code+above_code);@/
26974 @!@:above_with_delims_}{\.{\\abovewithdelims} primitive@>
26975 primitive("overwithdelims",above,delimited_code+over_code);@/
26976 @!@:over_with_delims_}{\.{\\overwithdelims} primitive@>
26977 primitive("atopwithdelims",above,delimited_code+atop_code);
26978 @!@:atop_with_delims_}{\.{\\atopwithdelims} primitive@>
26979
26980 @ @<Cases of |print_cmd_chr|...@>=
26981 above: case chr_code of
26982 over_code:print_esc("over");
26983 atop_code:print_esc("atop");
26984 delimited_code+above_code:print_esc("abovewithdelims");
26985 delimited_code+over_code:print_esc("overwithdelims");
26986 delimited_code+atop_code:print_esc("atopwithdelims");
26987 othercases print_esc("above")
26988 endcases;
26989
26990 @ @<Cases of |main_control| that build...@>=
26991 mmode+above: math_fraction;
26992
26993 @ @<Declare act...@>=
26994 procedure math_fraction;
26995 var c:small_number; {the type of generalized fraction we are scanning}
26996 begin c:=cur_chr;
26997 if incompleat_noad<>null then
26998 @<Ignore the fraction operation and complain about this ambiguous case@>
26999 else begin incompleat_noad:=get_node(fraction_noad_size);
27000 type(incompleat_noad):=fraction_noad;
27001 subtype(incompleat_noad):=normal;
27002 math_type(numerator(incompleat_noad)):=sub_mlist;
27003 info(numerator(incompleat_noad)):=link(head);
27004 mem[denominator(incompleat_noad)].hh:=empty_field;
27005 mem[left_delimiter(incompleat_noad)].qqqq:=null_delimiter;
27006 mem[right_delimiter(incompleat_noad)].qqqq:=null_delimiter;@/
27007 link(head):=null; tail:=head;
27008 @<Use code |c| to distinguish between generalized fractions@>;
27009 end;
27010 end;
27011
27012 @ @<Use code |c|...@>=
27013 if c>=delimited_code then
27014 begin scan_delimiter(left_delimiter(incompleat_noad),false);
27015 scan_delimiter(right_delimiter(incompleat_noad),false);
27016 end;
27017 case c mod delimited_code of
27018 above_code: begin scan_normal_dimen;
27019 thickness(incompleat_noad):=cur_val;
27020 end;
27021 over_code: thickness(incompleat_noad):=default_code;
27022 atop_code: thickness(incompleat_noad):=0;
27023 end {there are no other cases}
27024
27025 @ @<Ignore the fraction...@>=
27026 begin if c>=delimited_code then
27027 begin scan_delimiter(garbage,false); scan_delimiter(garbage,false);
27028 end;
27029 if c mod delimited_code=above_code then scan_normal_dimen;
27030 print_err("Ambiguous; you need another { and }");
27031 @.Ambiguous...@>
27032 help3("I'm ignoring this fraction specification, since I don't")@/
27033 ("know whether a construction like `x \over y \over z'")@/
27034 ("means `{x \over y} \over z' or `x \over {y \over z}'.");
27035 error;
27036 end
27037
27038 @ At the end of a math formula or subformula, the |fin_mlist| routine is
27039 called upon to return a pointer to the newly completed mlist, and to
27040 pop the nest back to the enclosing semantic level. The parameter to
27041 |fin_mlist|, if not null, points to a |right_noad| that ends the
27042 current mlist; this |right_noad| has not yet been appended.
27043
27044 @<Declare the function called |fin_mlist|@>=
27045 function fin_mlist(@!p:pointer):pointer;
27046 var q:pointer; {the mlist to return}
27047 begin if incompleat_noad<>null then @<Compleat the incompleat noad@>
27048 else begin link(tail):=p; q:=link(head);
27049 end;
27050 pop_nest; fin_mlist:=q;
27051 end;
27052
27053 @ @<Compleat...@>=
27054 begin math_type(denominator(incompleat_noad)):=sub_mlist;
27055 info(denominator(incompleat_noad)):=link(head);
27056 if p=null then q:=incompleat_noad
27057 else begin q:=info(numerator(incompleat_noad));
27058 if (type(q)<>left_noad)or(delim_ptr=null) then confusion("right");
27059 @:this can't happen right}{\quad right@>
27060 info(numerator(incompleat_noad)):=link(delim_ptr);
27061 link(delim_ptr):=incompleat_noad; link(incompleat_noad):=p;
27062 end;
27063 end
27064
27065 @ Now at last we're ready to see what happens when a right brace occurs
27066 in a math formula. Two special cases are simplified here: Braces are effectively
27067 removed when they surround a single Ord without sub/superscripts, or when they
27068 surround an accent that is the nucleus of an Ord atom.
27069
27070 @<Cases of |handle...@>=
27071 math_group: begin unsave; decr(save_ptr);@/
27072 math_type(saved(0)):=sub_mlist; p:=fin_mlist(null); info(saved(0)):=p;
27073 if p<>null then if link(p)=null then
27074 if type(p)=ord_noad then
27075 begin if math_type(subscr(p))=empty then
27076 if math_type(supscr(p))=empty then
27077 begin mem[saved(0)].hh:=mem[nucleus(p)].hh;
27078 free_node(p,noad_size);
27079 end;
27080 end
27081 else if type(p)=accent_noad then if saved(0)=nucleus(tail) then
27082 if type(tail)=ord_noad then @<Replace the tail of the list by |p|@>;
27083 end;
27084
27085 @ @<Replace the tail...@>=
27086 begin q:=head; while link(q)<>tail do q:=link(q);
27087 link(q):=p; free_node(tail,noad_size); tail:=p;
27088 end
27089
27090 @ We have dealt with all constructions of math mode except `\.{\\left}' and
27091 `\.{\\right}', so the picture is completed by the following sections of
27092 the program.
27093
27094 @<Put each...@>=
27095 primitive("left",left_right,left_noad);
27096 @!@:left_}{\.{\\left} primitive@>
27097 primitive("right",left_right,right_noad);
27098 @!@:right_}{\.{\\right} primitive@>
27099 text(frozen_right):="right"; eqtb[frozen_right]:=eqtb[cur_val];
27100
27101 @ @<Cases of |print_cmd_chr|...@>=
27102 left_right: if chr_code=left_noad then print_esc("left")
27103 @/@<Cases of |left_right| for |print_cmd_chr|@>@/
27104 else print_esc("right");
27105
27106 @ @<Cases of |main_control| that build...@>=
27107 mmode+left_right: math_left_right;
27108
27109 @ @<Declare act...@>=
27110 procedure math_left_right;
27111 var t:small_number; {|left_noad| or |right_noad|}
27112 @!p:pointer; {new noad}
27113 @!q:pointer; {resulting mlist}
27114 begin t:=cur_chr;
27115 if (t<>left_noad)and(cur_group<>math_left_group) then
27116 @<Try to recover from mismatched \.{\\right}@>
27117 else begin p:=new_noad; type(p):=t;
27118 scan_delimiter(delimiter(p),false);
27119 if t=middle_noad then
27120 begin type(p):=right_noad; subtype(p):=middle_noad;
27121 end;
27122 if t=left_noad then q:=p
27123 else begin q:=fin_mlist(p); unsave; {end of |math_left_group|}
27124 end;
27125 if t<>right_noad then
27126 begin push_math(math_left_group); link(head):=q; tail:=p;
27127 delim_ptr:=p;
27128 end
27129 else begin
27130 tail_append(new_noad); type(tail):=inner_noad;
27131 math_type(nucleus(tail)):=sub_mlist;
27132 info(nucleus(tail)):=q;
27133 end;
27134 end;
27135 end;
27136
27137 @ @<Try to recover from mismatch...@>=
27138 begin if cur_group=math_shift_group then
27139 begin scan_delimiter(garbage,false);
27140 print_err("Extra ");
27141 if t=middle_noad then
27142 begin print_esc("middle");
27143 @.Extra \\middle.@>
27144 help1("I'm ignoring a \middle that had no matching \left.");
27145 end
27146 else begin print_esc("right");
27147 @.Extra \\right.@>
27148 help1("I'm ignoring a \right that had no matching \left.");
27149 end;
27150 error;
27151 end
27152 else off_save;
27153 end
27154
27155 @ Here is the only way out of math mode.
27156
27157 @<Cases of |main_control| that build...@>=
27158 mmode+math_shift: if cur_group=math_shift_group then after_math
27159 else off_save;
27160
27161 @ @<Declare act...@>=
27162 @t\4@>@<Declare subprocedures for |after_math|@>@;
27163 procedure after_math;
27164 var l:boolean; {`\.{\\leqno}' instead of `\.{\\eqno}'}
27165 @!danger:boolean; {not enough symbol fonts are present}
27166 @!m:integer; {|mmode| or |-mmode|}
27167 @!p:pointer; {the formula}
27168 @!a:pointer; {box containing equation number}
27169 @<Local variables for finishing a displayed formula@>@;
27170 begin danger:=false;
27171 @<Retrieve the prototype box@>;
27172 @<Check that the necessary fonts for math symbols are present;
27173 if not, flush the current math lists and set |danger:=true|@>;
27174 m:=mode; l:=false; p:=fin_mlist(null); {this pops the nest}
27175 if mode=-m then {end of equation number}
27176 begin @<Check that another \.\$ follows@>;
27177 cur_mlist:=p; cur_style:=text_style; mlist_penalties:=false;
27178 mlist_to_hlist; a:=hpack(link(temp_head),natural);
27179 set_box_lr(a)(dlist);
27180 unsave; decr(save_ptr); {now |cur_group=math_shift_group|}
27181 if saved(0)=1 then l:=true;
27182 danger:=false;
27183 @<Retrieve the prototype box@>;
27184 @<Check that the necessary fonts for math symbols are present;
27185 if not, flush the current math lists and set |danger:=true|@>;
27186 m:=mode; p:=fin_mlist(null);
27187 end
27188 else a:=null;
27189 if m<0 then @<Finish math in text@>
27190 else begin if a=null then @<Check that another \.\$ follows@>;
27191 @<Finish displayed math@>;
27192 end;
27193 end;
27194
27195 @ @<Check that the necessary fonts...@>=
27196 if ((font_params[fam_fnt(2+text_size)]<total_mathsy_params)
27197 and (not is_new_mathfont(fam_fnt(2+text_size)))) or@|
27198 ((font_params[fam_fnt(2+script_size)]<total_mathsy_params)
27199 and (not is_new_mathfont(fam_fnt(2+script_size)))) or@|
27200 ((font_params[fam_fnt(2+script_script_size)]<total_mathsy_params)
27201 and (not is_new_mathfont(fam_fnt(2+script_script_size)))) then
27202 begin print_err("Math formula deleted: Insufficient symbol fonts");@/
27203 @.Math formula deleted...@>
27204 help3("Sorry, but I can't typeset math unless \textfont 2")@/
27205 ("and \scriptfont 2 and \scriptscriptfont 2 have all")@/
27206 ("the \fontdimen values needed in math symbol fonts.");
27207 error; flush_math; danger:=true;
27208 end
27209 else if ((font_params[fam_fnt(3+text_size)]<total_mathex_params)
27210 and (not is_new_mathfont(fam_fnt(3+text_size)))) or@|
27211 ((font_params[fam_fnt(3+script_size)]<total_mathex_params)
27212 and (not is_new_mathfont(fam_fnt(3+script_size)))) or@|
27213 ((font_params[fam_fnt(3+script_script_size)]<total_mathex_params)
27214 and (not is_new_mathfont(fam_fnt(3+script_script_size)))) then
27215 begin print_err("Math formula deleted: Insufficient extension fonts");@/
27216 help3("Sorry, but I can't typeset math unless \textfont 3")@/
27217 ("and \scriptfont 3 and \scriptscriptfont 3 have all")@/
27218 ("the \fontdimen values needed in math extension fonts.");
27219 error; flush_math; danger:=true;
27220 end
27221
27222 @ The |unsave| is done after everything else here; hence an appearance of
27223 `\.{\\mathsurround}' inside of `\.{\$...\$}' affects the spacing at these
27224 particular \.\$'s. This is consistent with the conventions of
27225 `\.{\$\$...\$\$}', since `\.{\\abovedisplayskip}' inside a display affects the
27226 space above that display.
27227
27228 @<Finish math in text@>=
27229 begin tail_append(new_math(math_surround,before));
27230 cur_mlist:=p; cur_style:=text_style; mlist_penalties:=(mode>0); mlist_to_hlist;
27231 link(tail):=link(temp_head);
27232 while link(tail)<>null do tail:=link(tail);
27233 tail_append(new_math(math_surround,after));
27234 space_factor:=1000; unsave;
27235 end
27236
27237 @ \TeX\ gets to the following part of the program when the first `\.\$' ending
27238 a display has been scanned.
27239
27240 @<Check that another \.\$ follows@>=
27241 begin get_x_token;
27242 if cur_cmd<>math_shift then
27243 begin print_err("Display math should end with $$");
27244 @.Display math...with \$\$@>
27245 help2("The `$' that I just saw supposedly matches a previous `$$'.")@/
27246 ("So I shall assume that you typed `$$' both times.");
27247 back_error;
27248 end;
27249 end
27250
27251 @ We have saved the worst for last: The fussiest part of math mode processing
27252 occurs when a displayed formula is being centered and placed with an optional
27253 equation number.
27254
27255 @<Local variables for finishing...@>=
27256 @!b:pointer; {box containing the equation}
27257 @!w:scaled; {width of the equation}
27258 @!z:scaled; {width of the line}
27259 @!e:scaled; {width of equation number}
27260 @!q:scaled; {width of equation number plus space to separate from equation}
27261 @!d:scaled; {displacement of equation in the line}
27262 @!s:scaled; {move the line right this much}
27263 @!g1,@!g2:small_number; {glue parameter codes for before and after}
27264 @!r:pointer; {kern node used to position the display}
27265 @!t:pointer; {tail of adjustment list}
27266 @!pre_t:pointer; {tail of pre-adjustment list}
27267
27268 @ At this time |p| points to the mlist for the formula; |a| is either
27269 |null| or it points to a box containing the equation number; and we are in
27270 vertical mode (or internal vertical mode).
27271
27272 @<Finish displayed math@>=
27273 cur_mlist:=p; cur_style:=display_style; mlist_penalties:=false;
27274 mlist_to_hlist; p:=link(temp_head);@/
27275 adjust_tail:=adjust_head; pre_adjust_tail:=pre_adjust_head;
27276 b:=hpack(p,natural); p:=list_ptr(b);
27277 t:=adjust_tail; adjust_tail:=null;@/
27278 pre_t:=pre_adjust_tail; pre_adjust_tail:=null;@/
27279 w:=width(b); z:=display_width; s:=display_indent;
27280 if pre_display_direction<0 then s:=-s-z;
27281 if (a=null)or danger then
27282 begin e:=0; q:=0;
27283 end
27284 else begin e:=width(a); q:=e+math_quad(text_size);
27285 end;
27286 if w+q>z then
27287 @<Squeeze the equation as much as possible; if there is an equation
27288 number that should go on a separate line by itself,
27289 set~|e:=0|@>;
27290 @<Determine the displacement, |d|, of the left edge of the equation, with
27291 respect to the line size |z|, assuming that |l=false|@>;
27292 @<Append the glue or equation number preceding the display@>;
27293 @<Append the display and perhaps also the equation number@>;
27294 @<Append the glue or equation number following the display@>;
27295 @<Flush the prototype box@>;
27296 resume_after_display
27297
27298 @ @<Declare act...@>=
27299 procedure resume_after_display;
27300 begin if cur_group<>math_shift_group then confusion("display");
27301 @:this can't happen display}{\quad display@>
27302 unsave; prev_graf:=prev_graf+3;
27303 push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
27304 prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
27305 *@'200000+cur_lang;
27306 @<Scan an optional space@>;
27307 if nest_ptr=1 then build_page;
27308 end;
27309
27310 @ The user can force the equation number to go on a separate line
27311 by causing its width to be zero.
27312
27313 @<Squeeze the equation as much as possible...@>=
27314 begin if (e<>0)and((w-total_shrink[normal]+q<=z)or@|
27315 (total_shrink[fil]<>0)or(total_shrink[fill]<>0)or
27316 (total_shrink[filll]<>0)) then
27317 begin free_node(b,box_node_size);
27318 b:=hpack(p,z-q,exactly);
27319 end
27320 else begin e:=0;
27321 if w>z then
27322 begin free_node(b,box_node_size);
27323 b:=hpack(p,z,exactly);
27324 end;
27325 end;
27326 w:=width(b);
27327 end
27328
27329 @ We try first to center the display without regard to the existence of
27330 the equation number. If that would make it too close (where ``too close''
27331 means that the space between display and equation number is less than the
27332 width of the equation number), we either center it in the remaining space
27333 or move it as far from the equation number as possible. The latter alternative
27334 is taken only if the display begins with glue, since we assume that the
27335 user put glue there to control the spacing precisely.
27336
27337 @<Determine the displacement, |d|, of the left edge of the equation...@>=
27338 set_box_lr(b)(dlist);
27339 d:=half(z-w);
27340 if (e>0)and(d<2*e) then {too close}
27341 begin d:=half(z-w-e);
27342 if p<>null then if not is_char_node(p) then if type(p)=glue_node then d:=0;
27343 end
27344
27345 @ If the equation number is set on a line by itself, either before or
27346 after the formula, we append an infinite penalty so that no page break will
27347 separate the display from its number; and we use the same size and
27348 displacement for all three potential lines of the display, even though
27349 `\.{\\parshape}' may specify them differently.
27350
27351 @<Append the glue or equation number preceding the display@>=
27352 tail_append(new_penalty(pre_display_penalty));@/
27353 if (d+s<=pre_display_size)or l then {not enough clearance}
27354 begin g1:=above_display_skip_code; g2:=below_display_skip_code;
27355 end
27356 else begin g1:=above_display_short_skip_code;
27357 g2:=below_display_short_skip_code;
27358 end;
27359 if l and(e=0) then {it follows that |type(a)=hlist_node|}
27360 begin app_display(j,a,0);
27361 tail_append(new_penalty(inf_penalty));
27362 end
27363 else tail_append(new_param_glue(g1))
27364
27365 @ @<Append the display and perhaps also the equation number@>=
27366 if e<>0 then
27367 begin r:=new_kern(z-w-e-d);
27368 if l then
27369 begin link(a):=r; link(r):=b; b:=a; d:=0;
27370 end
27371 else begin link(b):=r; link(r):=a;
27372 end;
27373 b:=hpack(b,natural);
27374 end;
27375 app_display(j,b,d)
27376
27377 @ @<Append the glue or equation number following the display@>=
27378 if (a<>null)and(e=0)and not l then
27379 begin tail_append(new_penalty(inf_penalty));
27380 app_display(j,a,z-width(a));
27381 g2:=0;
27382 end;
27383 if t<>adjust_head then {migrating material comes after equation number}
27384 begin link(tail):=link(adjust_head); tail:=t;
27385 end;
27386 if pre_t<>pre_adjust_head then
27387 begin link(tail):=link(pre_adjust_head); tail:=pre_t;
27388 end;
27389 tail_append(new_penalty(post_display_penalty));
27390 if g2>0 then tail_append(new_param_glue(g2))
27391
27392 @ When \.{\\halign} appears in a display, the alignment routines operate
27393 essentially as they do in vertical mode. Then the following program is
27394 activated, with |p| and |q| pointing to the beginning and end of the
27395 resulting list, and with |aux_save| holding the |prev_depth| value.
27396
27397 @<Finish an alignment in a display@>=
27398 begin do_assignments;
27399 if cur_cmd<>math_shift then @<Pontificate about improper alignment in display@>
27400 else @<Check that another \.\$ follows@>;
27401 flush_node_list(LR_box);
27402 pop_nest;
27403 tail_append(new_penalty(pre_display_penalty));
27404 tail_append(new_param_glue(above_display_skip_code));
27405 link(tail):=p;
27406 if p<>null then tail:=q;
27407 tail_append(new_penalty(post_display_penalty));
27408 tail_append(new_param_glue(below_display_skip_code));
27409 prev_depth:=aux_save.sc; resume_after_display;
27410 end
27411
27412 @ @<Pontificate...@>=
27413 begin print_err("Missing $$ inserted");
27414 @.Missing {\$\$} inserted@>
27415 help2("Displays can use special alignments (like \eqalignno)")@/
27416 ("only if nothing but the alignment itself is between $$'s.");
27417 back_error;
27418 end
27419
27420 @* \[49] Mode-independent processing.
27421 The long |main_control| procedure has now been fully specified, except for
27422 certain activities that are independent of the current mode. These activities
27423 do not change the current vlist or hlist or mlist; if they change anything,
27424 it is the value of a parameter or the meaning of a control sequence.
27425
27426 Assignments to values in |eqtb| can be global or local. Furthermore, a
27427 control sequence can be defined to be `\.{\\long}', `\.{\\protected}',
27428 or `\.{\\outer}', and it might or might not be expanded. The prefixes
27429 `\.{\\global}', `\.{\\long}', `\.{\\protected}',
27430 and `\.{\\outer}' can occur in any order. Therefore we assign binary numeric
27431 codes, making it possible to accumulate the union of all specified prefixes
27432 by adding the corresponding codes. (\PASCAL's |set| operations could also
27433 have been used.)
27434
27435 @<Put each...@>=
27436 primitive("long",prefix,1);
27437 @!@:long_}{\.{\\long} primitive@>
27438 primitive("outer",prefix,2);
27439 @!@:outer_}{\.{\\outer} primitive@>
27440 primitive("global",prefix,4);
27441 @!@:global_}{\.{\\global} primitive@>
27442 primitive("def",def,0);
27443 @!@:def_}{\.{\\def} primitive@>
27444 primitive("gdef",def,1);
27445 @!@:gdef_}{\.{\\gdef} primitive@>
27446 primitive("edef",def,2);
27447 @!@:edef_}{\.{\\edef} primitive@>
27448 primitive("xdef",def,3);
27449 @!@:xdef_}{\.{\\xdef} primitive@>
27450
27451 @ @<Cases of |print_cmd_chr|...@>=
27452 prefix: if chr_code=1 then print_esc("long")
27453 else if chr_code=2 then print_esc("outer")
27454 @/@<Cases of |prefix| for |print_cmd_chr|@>@/
27455 else print_esc("global");
27456 def: if chr_code=0 then print_esc("def")
27457 else if chr_code=1 then print_esc("gdef")
27458 else if chr_code=2 then print_esc("edef")
27459 else print_esc("xdef");
27460
27461 @ Every prefix, and every command code that might or might not be prefixed,
27462 calls the action procedure |prefixed_command|. This routine accumulates
27463 a sequence of prefixes until coming to a non-prefix, then it carries out
27464 the command.
27465
27466 @<Cases of |main_control| that don't...@>=
27467 any_mode(toks_register),
27468 any_mode(assign_toks),
27469 any_mode(assign_int),
27470 any_mode(assign_dimen),
27471 any_mode(assign_glue),
27472 any_mode(assign_mu_glue),
27473 any_mode(assign_font_dimen),
27474 any_mode(assign_font_int),
27475 any_mode(set_aux),
27476 any_mode(set_prev_graf),
27477 any_mode(set_page_dimen),
27478 any_mode(set_page_int),
27479 any_mode(set_box_dimen),
27480 any_mode(set_shape),
27481 any_mode(def_code),
27482 any_mode(XeTeX_def_code),
27483 any_mode(def_family),
27484 any_mode(set_font),
27485 any_mode(def_font),
27486 any_mode(register),
27487 any_mode(advance),
27488 any_mode(multiply),
27489 any_mode(divide),
27490 any_mode(prefix),
27491 any_mode(let),
27492 any_mode(shorthand_def),
27493 any_mode(read_to_cs),
27494 any_mode(def),
27495 any_mode(set_box),
27496 any_mode(hyph_data),
27497 any_mode(set_interaction):prefixed_command;
27498
27499 @ If the user says, e.g., `\.{\\global\\global}', the redundancy is
27500 silently accepted.
27501
27502 @<Declare act...@>=
27503 @t\4@>@<Declare subprocedures for |prefixed_command|@>@t@>@;@/
27504 procedure prefixed_command;
27505 label done,exit;
27506 var a:small_number; {accumulated prefix codes so far}
27507 @!f:internal_font_number; {identifies a font}
27508 @!j:halfword; {index into a \.{\\parshape} specification}
27509 @!k:font_index; {index into |font_info|}
27510 @!p,@!q:pointer; {for temporary short-term use}
27511 @!n:integer; {ditto}
27512 @!e:boolean; {should a definition be expanded? or was \.{\\let} not done?}
27513 begin a:=0;
27514 while cur_cmd=prefix do
27515 begin if not odd(a div cur_chr) then a:=a+cur_chr;
27516 @<Get the next non-blank non-relax...@>;
27517 if cur_cmd<=max_non_prefixed_command then
27518 @<Discard erroneous prefixes and |return|@>;
27519 if tracing_commands>2 then if eTeX_ex then show_cur_cmd_chr;
27520 end;
27521 @<Discard the prefixes \.{\\long} and \.{\\outer} if they are irrelevant@>;
27522 @<Adjust \(f)for the setting of \.{\\globaldefs}@>;
27523 case cur_cmd of
27524 @t\4@>@<Assignments@>@;
27525 othercases confusion("prefix")
27526 @:this can't happen prefix}{\quad prefix@>
27527 endcases;
27528 done: @<Insert a token saved by \.{\\afterassignment}, if any@>;
27529 exit:end;
27530
27531 @ @<Discard erroneous...@>=
27532 begin print_err("You can't use a prefix with `");
27533 @.You can't use a prefix with x@>
27534 print_cmd_chr(cur_cmd,cur_chr); print_char("'");
27535 help1("I'll pretend you didn't say \long or \outer or \global.");
27536 if eTeX_ex then help_line[0]:=@|
27537 "I'll pretend you didn't say \long or \outer or \global or \protected.";
27538 back_error; return;
27539 end
27540
27541 @ @<Discard the prefixes...@>=
27542 if a>=8 then
27543 begin j:=protected_token; a:=a-8;
27544 end
27545 else j:=0;
27546 if (cur_cmd<>def)and((a mod 4<>0)or(j<>0)) then
27547 begin print_err("You can't use `"); print_esc("long"); print("' or `");
27548 print_esc("outer");
27549 help1("I'll pretend you didn't say \long or \outer here.");
27550 if eTeX_ex then
27551 begin help_line[0]:=@|
27552 "I'll pretend you didn't say \long or \outer or \protected here.";
27553 print("' or `"); print_esc("protected");
27554 end;
27555 print("' with `");
27556 @.You can't use \\long...@>
27557 print_cmd_chr(cur_cmd,cur_chr); print_char("'");
27558 error;
27559 end
27560
27561 @ The previous routine does not have to adjust |a| so that |a mod 4=0|,
27562 since the following routines test for the \.{\\global} prefix as follows.
27563
27564 @d global==(a>=4)
27565 @d define(#)==if global then geq_define(#)@+else eq_define(#)
27566 @d word_define(#)==if global then geq_word_define(#)@+else eq_word_define(#)
27567 @d word_define1(#)==if global then geq_word_define1(#)@+else eq_word_define1(#)
27568
27569 @<Adjust \(f)for the setting of \.{\\globaldefs}@>=
27570 if global_defs<>0 then
27571 if global_defs<0 then
27572 begin if global then a:=a-4;
27573 end
27574 else begin if not global then a:=a+4;
27575 end
27576
27577 @ When a control sequence is to be defined, by \.{\\def} or \.{\\let} or
27578 something similar, the |get_r_token| routine will substitute a special
27579 control sequence for a token that is not redefinable.
27580
27581 @<Declare subprocedures for |prefixed_command|@>=
27582 procedure get_r_token;
27583 label restart;
27584 begin restart: repeat get_token;
27585 until cur_tok<>space_token;
27586 if (cur_cs=0)or(cur_cs>frozen_control_sequence) then
27587 begin print_err("Missing control sequence inserted");
27588 @.Missing control...@>
27589 help5("Please don't say `\def cs{...}', say `\def\cs{...}'.")@/
27590 ("I've inserted an inaccessible control sequence so that your")@/
27591 ("definition will be completed without mixing me up too badly.")@/
27592 ("You can recover graciously from this error, if you're")@/
27593 ("careful; see exercise 27.2 in The TeXbook.");
27594 @:TeXbook}{\sl The \TeX book@>
27595 if cur_cs=0 then back_input;
27596 cur_tok:=cs_token_flag+frozen_protection; ins_error; goto restart;
27597 end;
27598 end;
27599
27600 @ @<Initialize table entries...@>=
27601 text(frozen_protection):="inaccessible";
27602 @.inaccessible@>
27603
27604 @ Here's an example of the way many of the following routines operate.
27605 (Unfortunately, they aren't all as simple as this.)
27606
27607 @<Assignments@>=
27608 set_font: define(cur_font_loc,data,cur_chr);
27609
27610 @ When a |def| command has been scanned,
27611 |cur_chr| is odd if the definition is supposed to be global, and
27612 |cur_chr>=2| if the definition is supposed to be expanded.
27613
27614 @<Assignments@>=
27615 def: begin if odd(cur_chr)and not global and(global_defs>=0) then a:=a+4;
27616 e:=(cur_chr>=2); get_r_token; p:=cur_cs;
27617 q:=scan_toks(true,e);
27618 if j<>0 then
27619 begin q:=get_avail; info(q):=j; link(q):=link(def_ref);
27620 link(def_ref):=q;
27621 end;
27622 define(p,call+(a mod 4),def_ref);
27623 end;
27624
27625 @ Both \.{\\let} and \.{\\futurelet} share the command code |let|.
27626
27627 @<Put each...@>=
27628 primitive("let",let,normal);@/
27629 @!@:let_}{\.{\\let} primitive@>
27630 primitive("futurelet",let,normal+1);@/
27631 @!@:future_let_}{\.{\\futurelet} primitive@>
27632
27633 @ @<Cases of |print_cmd_chr|...@>=
27634 let: if chr_code<>normal then print_esc("futurelet")@+else print_esc("let");
27635
27636 @ @<Assignments@>=
27637 let: begin n:=cur_chr;
27638 get_r_token; p:=cur_cs;
27639 if n=normal then
27640 begin repeat get_token;
27641 until cur_cmd<>spacer;
27642 if cur_tok=other_token+"=" then
27643 begin get_token;
27644 if cur_cmd=spacer then get_token;
27645 end;
27646 end
27647 else begin get_token; q:=cur_tok; get_token; back_input;
27648 cur_tok:=q; back_input; {look ahead, then back up}
27649 end; {note that |back_input| doesn't affect |cur_cmd|, |cur_chr|}
27650 if cur_cmd>=call then add_token_ref(cur_chr)
27651 else if (cur_cmd=register)or(cur_cmd=toks_register) then
27652 if (cur_chr<mem_bot)or(cur_chr>lo_mem_stat_max) then
27653 add_sa_ref(cur_chr);
27654 define(p,cur_cmd,cur_chr);
27655 end;
27656
27657 @ A \.{\\chardef} creates a control sequence whose |cmd| is |char_given|;
27658 a \.{\\mathchardef} creates a control sequence whose |cmd| is |math_given|;
27659 and the corresponding |chr| is the character code or math code. A \.{\\countdef}
27660 or \.{\\dimendef} or \.{\\skipdef} or \.{\\muskipdef} creates a control
27661 sequence whose |cmd| is |assign_int| or \dots\ or |assign_mu_glue|, and the
27662 corresponding |chr| is the |eqtb| location of the internal register in question.
27663
27664 @d char_def_code=0 {|shorthand_def| for \.{\\chardef}}
27665 @d math_char_def_code=1 {|shorthand_def| for \.{\\mathchardef}}
27666 @d count_def_code=2 {|shorthand_def| for \.{\\countdef}}
27667 @d dimen_def_code=3 {|shorthand_def| for \.{\\dimendef}}
27668 @d skip_def_code=4 {|shorthand_def| for \.{\\skipdef}}
27669 @d mu_skip_def_code=5 {|shorthand_def| for \.{\\muskipdef}}
27670 @d toks_def_code=6 {|shorthand_def| for \.{\\toksdef}}
27671 @d XeTeX_math_char_num_def_code=8
27672 @d XeTeX_math_char_def_code=9
27673
27674 @<Put each...@>=
27675 primitive("chardef",shorthand_def,char_def_code);@/
27676 @!@:char_def_}{\.{\\chardef} primitive@>
27677 primitive("mathchardef",shorthand_def,math_char_def_code);@/
27678 @!@:math_char_def_}{\.{\\mathchardef} primitive@>
27679 primitive("XeTeXmathcharnumdef",shorthand_def,XeTeX_math_char_num_def_code);@/
27680 primitive("Umathcharnumdef",shorthand_def,XeTeX_math_char_num_def_code);@/
27681 @!@:U_math_char_num_def_}{\.{\\Umathcharnumdef} primitive@>
27682 primitive("XeTeXmathchardef",shorthand_def,XeTeX_math_char_def_code);@/
27683 primitive("Umathchardef",shorthand_def,XeTeX_math_char_def_code);@/
27684 @!@:U_math_char_def_}{\.{\\Umathchardef} primitive@>
27685 primitive("countdef",shorthand_def,count_def_code);@/
27686 @!@:count_def_}{\.{\\countdef} primitive@>
27687 primitive("dimendef",shorthand_def,dimen_def_code);@/
27688 @!@:dimen_def_}{\.{\\dimendef} primitive@>
27689 primitive("skipdef",shorthand_def,skip_def_code);@/
27690 @!@:skip_def_}{\.{\\skipdef} primitive@>
27691 primitive("muskipdef",shorthand_def,mu_skip_def_code);@/
27692 @!@:mu_skip_def_}{\.{\\muskipdef} primitive@>
27693 primitive("toksdef",shorthand_def,toks_def_code);@/
27694 @!@:toks_def_}{\.{\\toksdef} primitive@>
27695
27696 @ @<Cases of |print_cmd_chr|...@>=
27697 shorthand_def: case chr_code of
27698 char_def_code: print_esc("chardef");
27699 math_char_def_code: print_esc("mathchardef");
27700 XeTeX_math_char_def_code: print_esc("Umathchardef");
27701 XeTeX_math_char_num_def_code: print_esc("Umathcharnumdef");
27702 count_def_code: print_esc("countdef");
27703 dimen_def_code: print_esc("dimendef");
27704 skip_def_code: print_esc("skipdef");
27705 mu_skip_def_code: print_esc("muskipdef");
27706 othercases print_esc("toksdef")
27707 endcases;
27708 char_given: begin print_esc("char"); print_hex(chr_code);
27709 end;
27710 math_given: begin print_esc("mathchar"); print_hex(chr_code);
27711 end;
27712 XeTeX_math_given: begin print_esc("Umathchar");
27713 print_hex(math_class_field(chr_code));
27714 print_hex(math_fam_field(chr_code));
27715 print_hex(math_char_field(chr_code));
27716 end;
27717
27718 @ We temporarily define |p| to be |relax|, so that an occurrence of |p|
27719 while scanning the definition will simply stop the scanning instead of
27720 producing an ``undefined control sequence'' error or expanding the
27721 previous meaning. This allows, for instance, `\.{\\chardef\\foo=123\\foo}'.
27722
27723 @<Assignments@>=
27724 shorthand_def: begin n:=cur_chr; get_r_token; p:=cur_cs; define(p,relax,256);
27725 scan_optional_equals;
27726 case n of
27727 char_def_code: begin scan_usv_num; define(p,char_given,cur_val);
27728 end;
27729 math_char_def_code: begin scan_fifteen_bit_int; define(p,math_given,cur_val);
27730 end;
27731 XeTeX_math_char_num_def_code: begin scan_xetex_math_char_int;
27732 define(p, XeTeX_math_given, cur_val);
27733 end;
27734 XeTeX_math_char_def_code: begin
27735 scan_math_class_int; n:=set_class_field(cur_val);
27736 scan_math_fam_int; n:=n + set_family_field(cur_val);
27737 scan_usv_num; n:=n + cur_val;
27738 define(p, XeTeX_math_given, n);
27739 end;
27740 othercases begin scan_register_num;
27741 if cur_val>255 then
27742 begin j:=n-count_def_code; {|int_val..box_val|}
27743 if j>mu_val then j:=tok_val; {|int_val..mu_val| or |tok_val|}
27744 find_sa_element(j,cur_val,true); add_sa_ref(cur_ptr);
27745 if j=tok_val then j:=toks_register@+else j:=register;
27746 define(p,j,cur_ptr);
27747 end
27748 else
27749 case n of
27750 count_def_code: define(p,assign_int,count_base+cur_val);
27751 dimen_def_code: define(p,assign_dimen,scaled_base+cur_val);
27752 skip_def_code: define(p,assign_glue,skip_base+cur_val);
27753 mu_skip_def_code: define(p,assign_mu_glue,mu_skip_base+cur_val);
27754 toks_def_code: define(p,assign_toks,toks_base+cur_val);
27755 end; {there are no other cases}
27756 end
27757 endcases;
27758 end;
27759
27760 @ @<Assignments@>=
27761 read_to_cs: begin j:=cur_chr; scan_int; n:=cur_val;
27762 if not scan_keyword("to") then
27763 @.to@>
27764 begin print_err("Missing `to' inserted");
27765 @.Missing `to'...@>
27766 help2("You should have said `\read<number> to \cs'.")@/
27767 ("I'm going to look for the \cs now."); error;
27768 end;
27769 get_r_token;
27770 p:=cur_cs; read_toks(n,p,j); define(p,call,cur_val);
27771 end;
27772
27773 @ The token-list parameters, \.{\\output} and \.{\\everypar}, etc., receive
27774 their values in the following way. (For safety's sake, we place an
27775 enclosing pair of braces around an \.{\\output} list.)
27776
27777 @<Assignments@>=
27778 toks_register,assign_toks: begin q:=cur_cs;
27779 e:=false; {just in case, will be set |true| for sparse array elements}
27780 if cur_cmd=toks_register then
27781 if cur_chr=mem_bot then
27782 begin scan_register_num;
27783 if cur_val>255 then
27784 begin find_sa_element(tok_val,cur_val,true);
27785 cur_chr:=cur_ptr; e:=true;
27786 end
27787 else cur_chr:=toks_base+cur_val;
27788 end
27789 else e:=true
27790 else if cur_chr=XeTeX_inter_char_loc then begin
27791 scan_char_class_not_ignored; cur_ptr:=cur_val;
27792 scan_char_class_not_ignored;
27793 find_sa_element(inter_char_val, cur_ptr*char_class_limit + cur_val, true);
27794 cur_chr:=cur_ptr; e:=true;
27795 end;
27796 p:=cur_chr; {|p=every_par_loc| or |output_routine_loc| or \dots}
27797 scan_optional_equals;
27798 @<Get the next non-blank non-relax non-call token@>;
27799 if cur_cmd<>left_brace then @<If the right-hand side is a token parameter
27800 or token register, finish the assignment and |goto done|@>;
27801 back_input; cur_cs:=q; q:=scan_toks(false,false);
27802 if link(def_ref)=null then {empty list: revert to the default}
27803 begin sa_define(p,null)(p,undefined_cs,null); free_avail(def_ref);
27804 end
27805 else begin if (p=output_routine_loc)and not e then {enclose in curlies}
27806 begin link(q):=get_avail; q:=link(q);
27807 info(q):=right_brace_token+"}";
27808 q:=get_avail; info(q):=left_brace_token+"{";
27809 link(q):=link(def_ref); link(def_ref):=q;
27810 end;
27811 sa_define(p,def_ref)(p,call,def_ref);
27812 end;
27813 end;
27814
27815 @ @<If the right-hand side is a token parameter...@>=
27816 if (cur_cmd=toks_register)or(cur_cmd=assign_toks) then
27817 begin if cur_cmd=toks_register then
27818 if cur_chr=mem_bot then
27819 begin scan_register_num;
27820 if cur_val<256 then q:=equiv(toks_base+cur_val)
27821 else begin find_sa_element(tok_val,cur_val,false);
27822 if cur_ptr=null then q:=null
27823 else q:=sa_ptr(cur_ptr);
27824 end;
27825 end
27826 else q:=sa_ptr(cur_chr)
27827 else if cur_chr=XeTeX_inter_char_loc then begin
27828 scan_char_class_not_ignored; cur_ptr:=cur_val;
27829 scan_char_class_not_ignored;
27830 find_sa_element(inter_char_val, cur_ptr*char_class_limit + cur_val, false);
27831 if cur_ptr=null then q:=null
27832 else q:=sa_ptr(cur_ptr);
27833 end else q:=equiv(cur_chr);
27834 if q=null then sa_define(p,null)(p,undefined_cs,null)
27835 else begin add_token_ref(q); sa_define(p,q)(p,call,q);
27836 end;
27837 goto done;
27838 end
27839
27840 @ Similar routines are used to assign values to the numeric parameters.
27841
27842 @<Assignments@>=
27843 assign_int: begin p:=cur_chr; scan_optional_equals; scan_int;
27844 word_define(p,cur_val);
27845 end;
27846 assign_dimen: begin p:=cur_chr; scan_optional_equals;
27847 scan_normal_dimen; word_define(p,cur_val);
27848 end;
27849 assign_glue,assign_mu_glue: begin p:=cur_chr; n:=cur_cmd; scan_optional_equals;
27850 if n=assign_mu_glue then scan_glue(mu_val)@+else scan_glue(glue_val);
27851 trap_zero_glue;
27852 define(p,glue_ref,cur_val);
27853 end;
27854
27855 @ When a glue register or parameter becomes zero, it will always point to
27856 |zero_glue| because of the following procedure. (Exception: The tabskip
27857 glue isn't trapped while preambles are being scanned.)
27858
27859 @<Declare subprocedures for |prefixed_command|@>=
27860 procedure trap_zero_glue;
27861 begin if (width(cur_val)=0)and(stretch(cur_val)=0)and(shrink(cur_val)=0) then
27862 begin add_glue_ref(zero_glue);
27863 delete_glue_ref(cur_val); cur_val:=zero_glue;
27864 end;
27865 end;
27866
27867 @ The various character code tables are changed by the |def_code| commands,
27868 and the font families are declared by |def_family|.
27869
27870 @<Put each...@>=
27871 primitive("catcode",def_code,cat_code_base);
27872 @!@:cat_code_}{\.{\\catcode} primitive@>
27873 primitive("mathcode",def_code,math_code_base);
27874 @!@:math_code_}{\.{\\mathcode} primitive@>
27875 primitive("XeTeXmathcodenum",XeTeX_def_code,math_code_base);
27876 primitive("Umathcodenum",XeTeX_def_code,math_code_base);
27877 @!@:U_math_code_num_}{\.{\\Umathcodenum} primitive@>
27878 primitive("XeTeXmathcode",XeTeX_def_code,math_code_base+1);
27879 primitive("Umathcode",XeTeX_def_code,math_code_base+1);
27880 @!@:U_math_code_}{\.{\\Umathcode} primitive@>
27881 primitive("lccode",def_code,lc_code_base);
27882 @!@:lc_code_}{\.{\\lccode} primitive@>
27883 primitive("uccode",def_code,uc_code_base);
27884 @!@:uc_code_}{\.{\\uccode} primitive@>
27885 primitive("sfcode",def_code,sf_code_base);
27886 @!@:sf_code_}{\.{\\sfcode} primitive@>
27887 primitive("XeTeXcharclass",XeTeX_def_code,sf_code_base);
27888 @!@:XeTeX_char_class_}{\.{\\XeTeXcharclass} primitive@>
27889 primitive("delcode",def_code,del_code_base);
27890 @!@:del_code_}{\.{\\delcode} primitive@>
27891 primitive("XeTeXdelcodenum",XeTeX_def_code,del_code_base);
27892 primitive("Udelcodenum",XeTeX_def_code,del_code_base);
27893 @!@:U_del_code_num_}{\.{\\Udelcodenum} primitive@>
27894 primitive("XeTeXdelcode",XeTeX_def_code,del_code_base+1);
27895 primitive("Udelcode",XeTeX_def_code,del_code_base+1);
27896 @!@:U_del_code_}{\.{\\Udelcode} primitive@>
27897 primitive("textfont",def_family,math_font_base);
27898 @!@:text_font_}{\.{\\textfont} primitive@>
27899 primitive("scriptfont",def_family,math_font_base+script_size);
27900 @!@:script_font_}{\.{\\scriptfont} primitive@>
27901 primitive("scriptscriptfont",def_family,math_font_base+script_script_size);
27902 @!@:script_script_font_}{\.{\\scriptscriptfont} primitive@>
27903
27904 @ @<Cases of |print_cmd_chr|...@>=
27905 def_code: if chr_code=cat_code_base then print_esc("catcode")
27906 else if chr_code=math_code_base then print_esc("mathcode")
27907 else if chr_code=lc_code_base then print_esc("lccode")
27908 else if chr_code=uc_code_base then print_esc("uccode")
27909 else if chr_code=sf_code_base then print_esc("sfcode")
27910 else print_esc("delcode");
27911 XeTeX_def_code:
27912 if chr_code=sf_code_base then print_esc("XeTeXcharclass")
27913 else if chr_code=math_code_base then print_esc("Umathcodenum")
27914 else if chr_code=math_code_base+1 then print_esc("Umathcode")
27915 else if chr_code=del_code_base then print_esc("Udelcodenum")
27916 else print_esc("Udelcode");
27917 def_family: print_size(chr_code-math_font_base);
27918
27919 @ The different types of code values have different legal ranges; the
27920 following program is careful to check each case properly.
27921
27922 @<Assignments@>=
27923 XeTeX_def_code: begin
27924 if cur_chr = sf_code_base then begin
27925 p:=cur_chr; scan_usv_num;
27926 p:=p+cur_val;
27927 n:=sf_code(cur_val) mod @"10000;
27928 scan_optional_equals;
27929 scan_char_class;
27930 define(p,data,cur_val*@"10000 + n);
27931 end
27932 else if cur_chr = math_code_base then begin
27933 p:=cur_chr; scan_usv_num;
27934 p:=p+cur_val;
27935 scan_optional_equals;
27936 scan_xetex_math_char_int;
27937 define(p,data,hi(cur_val));
27938 end
27939 else if cur_chr = math_code_base+1 then begin
27940 p:=cur_chr-1; scan_usv_num;
27941 p:=p+cur_val;
27942 scan_optional_equals;
27943 scan_math_class_int; n:=set_class_field(cur_val);
27944 scan_math_fam_int; n:=n + set_family_field(cur_val);
27945 scan_usv_num; n:=n + cur_val;
27946 define(p,data,hi(n));
27947 end
27948 else if cur_chr = del_code_base then begin
27949 p:=cur_chr; scan_usv_num;
27950 p:=p+cur_val;
27951 scan_optional_equals;
27952 scan_int; {|scan_xetex_del_code_int|; !!FIXME!!}
27953 word_define(p,hi(cur_val));
27954 end else begin
27955 p:=cur_chr-1; scan_usv_num;
27956 p:=p+cur_val;
27957 scan_optional_equals;
27958 n:=@"40000000; {extended delimiter code flag}
27959 scan_math_fam_int; n:=n + cur_val * @"200000; {extended delimiter code family}
27960 scan_usv_num; n:=n + cur_val; {extended delimiter code USV}
27961 word_define(p,hi(n));
27962 end;
27963 end;
27964 def_code: begin @<Let |n| be the largest legal code value, based on |cur_chr|@>;
27965 p:=cur_chr; scan_usv_num; p:=p+cur_val; scan_optional_equals;
27966 scan_int;
27967 if ((cur_val<0)and(p<del_code_base))or(cur_val>n) then
27968 begin print_err("Invalid code ("); print_int(cur_val);
27969 @.Invalid code@>
27970 if p<del_code_base then print("), should be in the range 0..")
27971 else print("), should be at most ");
27972 print_int(n);
27973 help1("I'm going to use 0 instead of that illegal code value.");@/
27974 error; cur_val:=0;
27975 end;
27976 if p<math_code_base then begin
27977 if p>=sf_code_base then begin
27978 n:=equiv(p) div @"10000;
27979 define(p,data,n*@"10000 + cur_val);
27980 end else
27981 define(p,data,cur_val)
27982 end else if p<del_code_base then begin
27983 if cur_val=@"8000 then cur_val:=active_math_char
27984 else cur_val:=set_class_field(cur_val div @"1000) +
27985 set_family_field((cur_val mod @"1000) div @"100) +
27986 (cur_val mod @"100); {!!FIXME!! check how this is used}
27987 define(p,data,hi(cur_val));
27988 end
27989 else word_define(p,cur_val);
27990 end;
27991
27992 @ @<Let |n| be the largest...@>=
27993 if cur_chr=cat_code_base then n:=max_char_code
27994 else if cur_chr=math_code_base then n:=@'100000
27995 else if cur_chr=sf_code_base then n:=@'77777
27996 else if cur_chr=del_code_base then n:=@'77777777
27997 else n:=biggest_usv
27998
27999 @ @<Assignments@>=
28000 def_family: begin p:=cur_chr; scan_math_fam_int; p:=p+cur_val;
28001 scan_optional_equals; scan_font_ident; define(p,data,cur_val);
28002 end;
28003
28004 @ Next we consider changes to \TeX's numeric registers.
28005
28006 @<Assignments@>=
28007 register,advance,multiply,divide: do_register_command(a);
28008
28009 @ We use the fact that |register<advance<multiply<divide|.
28010
28011 @<Declare subprocedures for |prefixed_command|@>=
28012 procedure do_register_command(@!a:small_number);
28013 label found,exit;
28014 var l,@!q,@!r,@!s:pointer; {for list manipulation}
28015 @!p:int_val..mu_val; {type of register involved}
28016 @!e:boolean; {does |l| refer to a sparse array element?}
28017 @!w:integer; {integer or dimen value of |l|}
28018 begin q:=cur_cmd;
28019 e:=false; {just in case, will be set |true| for sparse array elements}
28020 @<Compute the register location |l| and its type |p|; but |return| if invalid@>;
28021 if q=register then scan_optional_equals
28022 else if scan_keyword("by") then do_nothing; {optional `\.{by}'}
28023 @.by@>
28024 arith_error:=false;
28025 if q<multiply then @<Compute result of |register| or
28026 |advance|, put it in |cur_val|@>
28027 else @<Compute result of |multiply| or |divide|, put it in |cur_val|@>;
28028 if arith_error then
28029 begin print_err("Arithmetic overflow");
28030 @.Arithmetic overflow@>
28031 help2("I can't carry out that multiplication or division,")@/
28032 ("since the result is out of range.");
28033 if p>=glue_val then delete_glue_ref(cur_val);
28034 error; return;
28035 end;
28036 if p<glue_val then sa_word_define(l,cur_val)
28037 else begin trap_zero_glue; sa_define(l,cur_val)(l,glue_ref,cur_val);
28038 end;
28039 exit: end;
28040
28041 @ Here we use the fact that the consecutive codes |int_val..mu_val| and
28042 |assign_int..assign_mu_glue| correspond to each other nicely.
28043
28044 @<Compute the register location |l| and its type |p|...@>=
28045 begin if q<>register then
28046 begin get_x_token;
28047 if (cur_cmd>=assign_int)and(cur_cmd<=assign_mu_glue) then
28048 begin l:=cur_chr; p:=cur_cmd-assign_int; goto found;
28049 end;
28050 if cur_cmd<>register then
28051 begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
28052 @.You can't use x after ...@>
28053 print("' after "); print_cmd_chr(q,0);
28054 help1("I'm forgetting what you said and not changing anything.");
28055 error; return;
28056 end;
28057 end;
28058 if (cur_chr<mem_bot)or(cur_chr>lo_mem_stat_max) then
28059 begin l:=cur_chr; p:=sa_type(l); e:=true;
28060 end
28061 else begin p:=cur_chr-mem_bot; scan_register_num;
28062 if cur_val>255 then
28063 begin find_sa_element(p,cur_val,true); l:=cur_ptr; e:=true;
28064 end
28065 else
28066 case p of
28067 int_val: l:=cur_val+count_base;
28068 dimen_val: l:=cur_val+scaled_base;
28069 glue_val: l:=cur_val+skip_base;
28070 mu_val: l:=cur_val+mu_skip_base;
28071 end; {there are no other cases}
28072 end;
28073 end;
28074 found: if p<glue_val then@+if e then w:=sa_int(l)@+else w:=eqtb[l].int
28075 else if e then s:=sa_ptr(l)@+else s:=equiv(l)
28076
28077 @ @<Compute result of |register| or |advance|...@>=
28078 if p<glue_val then
28079 begin if p=int_val then scan_int@+else scan_normal_dimen;
28080 if q=advance then cur_val:=cur_val+w;
28081 end
28082 else begin scan_glue(p);
28083 if q=advance then @<Compute the sum of two glue specs@>;
28084 end
28085
28086 @ @<Compute the sum of two glue specs@>=
28087 begin q:=new_spec(cur_val); r:=s;
28088 delete_glue_ref(cur_val);
28089 width(q):=width(q)+width(r);
28090 if stretch(q)=0 then stretch_order(q):=normal;
28091 if stretch_order(q)=stretch_order(r) then stretch(q):=stretch(q)+stretch(r)
28092 else if (stretch_order(q)<stretch_order(r))and(stretch(r)<>0) then
28093 begin stretch(q):=stretch(r); stretch_order(q):=stretch_order(r);
28094 end;
28095 if shrink(q)=0 then shrink_order(q):=normal;
28096 if shrink_order(q)=shrink_order(r) then shrink(q):=shrink(q)+shrink(r)
28097 else if (shrink_order(q)<shrink_order(r))and(shrink(r)<>0) then
28098 begin shrink(q):=shrink(r); shrink_order(q):=shrink_order(r);
28099 end;
28100 cur_val:=q;
28101 end
28102
28103 @ @<Compute result of |multiply| or |divide|...@>=
28104 begin scan_int;
28105 if p<glue_val then
28106 if q=multiply then
28107 if p=int_val then cur_val:=mult_integers(w,cur_val)
28108 else cur_val:=nx_plus_y(w,cur_val,0)
28109 else cur_val:=x_over_n(w,cur_val)
28110 else begin r:=new_spec(s);
28111 if q=multiply then
28112 begin width(r):=nx_plus_y(width(s),cur_val,0);
28113 stretch(r):=nx_plus_y(stretch(s),cur_val,0);
28114 shrink(r):=nx_plus_y(shrink(s),cur_val,0);
28115 end
28116 else begin width(r):=x_over_n(width(s),cur_val);
28117 stretch(r):=x_over_n(stretch(s),cur_val);
28118 shrink(r):=x_over_n(shrink(s),cur_val);
28119 end;
28120 cur_val:=r;
28121 end;
28122 end
28123
28124 @ The processing of boxes is somewhat different, because we may need
28125 to scan and create an entire box before we actually change the value of the old
28126 one.
28127
28128 @<Assignments@>=
28129 set_box: begin scan_register_num;
28130 if global then n:=global_box_flag+cur_val@+else n:=box_flag+cur_val;
28131 scan_optional_equals;
28132 if set_box_allowed then scan_box(n)
28133 else begin print_err("Improper "); print_esc("setbox");
28134 @.Improper \\setbox@>
28135 help2("Sorry, \setbox is not allowed after \halign in a display,")@/
28136 ("or between \accent and an accented character."); error;
28137 end;
28138 end;
28139
28140 @ The |space_factor| or |prev_depth| settings are changed when a |set_aux|
28141 command is sensed. Similarly, |prev_graf| is changed in the presence of
28142 |set_prev_graf|, and |dead_cycles| or |insert_penalties| in the presence of
28143 |set_page_int|. These definitions are always global.
28144
28145 When some dimension of a box register is changed, the change isn't exactly
28146 global; but \TeX\ does not look at the \.{\\global} switch.
28147
28148 @<Assignments@>=
28149 set_aux:alter_aux;
28150 set_prev_graf:alter_prev_graf;
28151 set_page_dimen:alter_page_so_far;
28152 set_page_int:alter_integer;
28153 set_box_dimen:alter_box_dimen;
28154
28155 @ @<Declare subprocedures for |prefixed_command|@>=
28156 procedure alter_aux;
28157 var c:halfword; {|hmode| or |vmode|}
28158 begin if cur_chr<>abs(mode) then report_illegal_case
28159 else begin c:=cur_chr; scan_optional_equals;
28160 if c=vmode then
28161 begin scan_normal_dimen; prev_depth:=cur_val;
28162 end
28163 else begin scan_int;
28164 if (cur_val<=0)or(cur_val>32767) then
28165 begin print_err("Bad space factor");
28166 @.Bad space factor@>
28167 help1("I allow only values in the range 1..32767 here.");
28168 int_error(cur_val);
28169 end
28170 else space_factor:=cur_val;
28171 end;
28172 end;
28173 end;
28174
28175 @ @<Declare subprocedures for |prefixed_command|@>=
28176 procedure alter_prev_graf;
28177 var p:0..nest_size; {index into |nest|}
28178 begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
28179 while abs(nest[p].mode_field)<>vmode do decr(p);
28180 scan_optional_equals; scan_int;
28181 if cur_val<0 then
28182 begin print_err("Bad "); print_esc("prevgraf");
28183 @.Bad \\prevgraf@>
28184 help1("I allow only nonnegative values here.");
28185 int_error(cur_val);
28186 end
28187 else begin nest[p].pg_field:=cur_val; cur_list:=nest[nest_ptr];
28188 end;
28189 end;
28190
28191 @ @<Declare subprocedures for |prefixed_command|@>=
28192 procedure alter_page_so_far;
28193 var c:0..7; {index into |page_so_far|}
28194 begin c:=cur_chr; scan_optional_equals; scan_normal_dimen;
28195 page_so_far[c]:=cur_val;
28196 end;
28197
28198 @ @<Declare subprocedures for |prefixed_command|@>=
28199 procedure alter_integer;
28200 var c:small_number;
28201 {0 for \.{\\deadcycles}, 1 for \.{\\insertpenalties}, etc.}
28202 begin c:=cur_chr; scan_optional_equals; scan_int;
28203 if c=0 then dead_cycles:=cur_val
28204 @/@<Cases for |alter_integer|@>@/
28205 else insert_penalties:=cur_val;
28206 end;
28207
28208 @ @<Declare subprocedures for |prefixed_command|@>=
28209 procedure alter_box_dimen;
28210 var c:small_number; {|width_offset| or |height_offset| or |depth_offset|}
28211 @!b:pointer; {box register}
28212 begin c:=cur_chr; scan_register_num; fetch_box(b); scan_optional_equals;
28213 scan_normal_dimen;
28214 if b<>null then mem[b+c].sc:=cur_val;
28215 end;
28216
28217 @ Paragraph shapes are set up in the obvious way.
28218
28219 @<Assignments@>=
28220 set_shape: begin q:=cur_chr; scan_optional_equals; scan_int; n:=cur_val;
28221 if n<=0 then p:=null
28222 else if q>par_shape_loc then
28223 begin n:=(cur_val div 2)+1; p:=get_node(2*n+1); info(p):=n;
28224 n:=cur_val; mem[p+1].int:=n; {number of penalties}
28225 for j:=p+2 to p+n+1 do
28226 begin scan_int; mem[j].int:=cur_val; {penalty values}
28227 end;
28228 if not odd(n) then mem[p+n+2].int:=0; {unused}
28229 end
28230 else begin p:=get_node(2*n+1); info(p):=n;
28231 for j:=1 to n do
28232 begin scan_normal_dimen;
28233 mem[p+2*j-1].sc:=cur_val; {indentation}
28234 scan_normal_dimen;
28235 mem[p+2*j].sc:=cur_val; {width}
28236 end;
28237 end;
28238 define(q,shape_ref,p);
28239 end;
28240
28241 @ Here's something that isn't quite so obvious. It guarantees that
28242 |info(par_shape_ptr)| can hold any positive~|n| for which |get_node(2*n+1)|
28243 doesn't overflow the memory capacity.
28244
28245 @<Check the ``constant''...@>=
28246 if 2*max_halfword<mem_top-mem_min then bad:=41;
28247
28248 @ New hyphenation data is loaded by the |hyph_data| command.
28249
28250 @<Put each...@>=
28251 primitive("hyphenation",hyph_data,0);
28252 @!@:hyphenation_}{\.{\\hyphenation} primitive@>
28253 primitive("patterns",hyph_data,1);
28254 @!@:patterns_}{\.{\\patterns} primitive@>
28255
28256 @ @<Cases of |print_cmd_chr|...@>=
28257 hyph_data: if chr_code=1 then print_esc("patterns")
28258 else print_esc("hyphenation");
28259
28260 @ @<Assignments@>=
28261 hyph_data: if cur_chr=1 then
28262 begin @!init new_patterns; goto done;@;@+tini@/
28263 print_err("Patterns can be loaded only by INITEX");
28264 @.Patterns can be...@>
28265 help0; error;
28266 repeat get_token; until cur_cmd=right_brace; {flush the patterns}
28267 return;
28268 end
28269 else begin new_hyph_exceptions; goto done;
28270 end;
28271
28272 @ All of \TeX's parameters are kept in |eqtb| except the font information,
28273 the interaction mode, and the hyphenation tables; these are strictly global.
28274
28275 @<Assignments@>=
28276 assign_font_dimen: begin find_font_dimen(true); k:=cur_val;
28277 scan_optional_equals; scan_normal_dimen; font_info[k].sc:=cur_val;
28278 end;
28279 assign_font_int: begin n:=cur_chr; scan_font_ident; f:=cur_val;
28280 if n < lp_code_base then begin
28281 scan_optional_equals; scan_int;
28282 if n=0 then hyphen_char[f]:=cur_val@+else skew_char[f]:=cur_val;
28283 end else begin
28284 if is_native_font(f) then
28285 scan_glyph_number(f) {for native fonts, the value is a glyph id}
28286 else scan_char_num; {for |tfm| fonts it's the same like pdftex}
28287 p:=cur_val;
28288 scan_optional_equals; scan_int;
28289 case n of
28290 lp_code_base: set_cp_code(f, p, left_side, cur_val);
28291 rp_code_base: set_cp_code(f, p, right_side, cur_val);
28292 endcases;
28293 end;
28294 end;
28295
28296 @ @<Put each...@>=
28297 primitive("hyphenchar",assign_font_int,0);
28298 @!@:hyphen_char_}{\.{\\hyphenchar} primitive@>
28299 primitive("skewchar",assign_font_int,1);
28300 @!@:skew_char_}{\.{\\skewchar} primitive@>
28301 primitive("lpcode",assign_font_int,lp_code_base);
28302 @!@:lp_code_}{\.{\\lpcode} primitive@>
28303 primitive("rpcode",assign_font_int,rp_code_base);
28304 @!@:rp_code_}{\.{\\rpcode} primitive@>
28305
28306 @ @<Cases of |print_cmd_chr|...@>=
28307 assign_font_int: case chr_code of
28308 0: print_esc("hyphenchar");
28309 1: print_esc("skewchar");
28310 lp_code_base: print_esc("lpcode");
28311 rp_code_base: print_esc("rpcode");
28312 endcases;
28313
28314 @ Here is where the information for a new font gets loaded.
28315
28316 @<Assignments@>=
28317 def_font: new_font(a);
28318
28319 @ @<Declare subprocedures for |prefixed_command|@>=
28320 procedure new_font(@!a:small_number);
28321 label common_ending;
28322 var u:pointer; {user's font identifier}
28323 @!s:scaled; {stated ``at'' size, or negative of scaled magnification}
28324 @!f:internal_font_number; {runs through existing fonts}
28325 @!t:str_number; {name for the frozen font identifier}
28326 @!old_setting:0..max_selector; {holds |selector| setting}
28327 @!flushable_string:str_number; {string not yet referenced}
28328 begin if job_name=0 then open_log_file;
28329 {avoid confusing \.{texput} with the font name}
28330 @.texput@>
28331 get_r_token; u:=cur_cs;
28332 if u>=hash_base then t:=text(u)
28333 else if u>=single_base then
28334 if u=null_cs then t:="FONT"@+else t:=u-single_base
28335 else begin old_setting:=selector; selector:=new_string;
28336 print("FONT"); print(u-active_base); selector:=old_setting;
28337 @.FONTx@>
28338 str_room(1); t:=make_string;
28339 end;
28340 define(u,set_font,null_font); scan_optional_equals; scan_file_name;
28341 @<Scan the font size specification@>;
28342 @<If this font has already been loaded, set |f| to the internal
28343 font number and |goto common_ending|@>;
28344 f:=read_font_info(u,cur_name,cur_area,s);
28345 common_ending: define(u,set_font,f); eqtb[font_id_base+f]:=eqtb[u]; font_id_text(f):=t;
28346 end;
28347
28348 @ @<Scan the font size specification@>=
28349 name_in_progress:=true; {this keeps |cur_name| from being changed}
28350 if scan_keyword("at") then @<Put the \(p)(positive) `at' size into |s|@>
28351 @.at@>
28352 else if scan_keyword("scaled") then
28353 @.scaled@>
28354 begin scan_int; s:=-cur_val;
28355 if (cur_val<=0)or(cur_val>32768) then
28356 begin print_err("Illegal magnification has been changed to 1000");@/
28357 @.Illegal magnification...@>
28358 help1("The magnification ratio must be between 1 and 32768.");
28359 int_error(cur_val); s:=-1000;
28360 end;
28361 end
28362 else s:=-1000;
28363 name_in_progress:=false
28364
28365 @ @<Put the \(p)(positive) `at' size into |s|@>=
28366 begin scan_normal_dimen; s:=cur_val;
28367 if (s<=0)or(s>=@'1000000000) then
28368 begin print_err("Improper `at' size (");
28369 print_scaled(s); print("pt), replaced by 10pt");
28370 @.Improper `at' size...@>
28371 help2("I can only handle fonts at positive sizes that are")@/
28372 ("less than 2048pt, so I've changed what you said to 10pt.");
28373 error; s:=10*unity;
28374 end;
28375 end
28376
28377 @ When the user gives a new identifier to a font that was previously loaded,
28378 the new name becomes the font identifier of record. Font names `\.{xyz}' and
28379 `\.{XYZ}' are considered to be different.
28380
28381 @<If this font has already been loaded...@>=
28382 flushable_string:=str_ptr-1;
28383 for f:=font_base+1 to font_ptr do begin
28384 if str_eq_str(font_name[f],cur_name) and
28385 (((cur_area = "") and is_native_font(f)) or str_eq_str(font_area[f],cur_area)) then
28386 begin if cur_name=flushable_string then
28387 begin flush_string; cur_name:=font_name[f];
28388 end;
28389 if s>0 then
28390 begin if s=font_size[f] then goto common_ending;
28391 end
28392 else if font_size[f]=xn_over_d(font_dsize[f],-s,1000) then
28393 goto common_ending;
28394 end;
28395 { could be a native font whose "name" ended up partly in area or extension }
28396 append_str(cur_area); append_str(cur_name); append_str(cur_ext);
28397 if str_eq_str(font_name[f], make_string) then begin
28398 flush_string;
28399 if is_native_font(f) then
28400 begin if s>0 then
28401 begin if s=font_size[f] then goto common_ending;
28402 end
28403 else if font_size[f]=xn_over_d(font_dsize[f],-s,1000) then
28404 goto common_ending;
28405 end
28406 end
28407 else flush_string;
28408 end
28409
28410 @ @<Cases of |print_cmd_chr|...@>=
28411 set_font:begin print("select font ");
28412 font_name_str:=font_name[chr_code];
28413 if is_native_font(chr_code) then begin
28414 quote_char:="""";
28415 for n:=0 to length(font_name_str) - 1 do
28416 if str_pool[str_start_macro(font_name_str) + n] = """" then quote_char:="'";
28417 print_char(quote_char);
28418 slow_print(font_name_str);
28419 print_char(quote_char);
28420 end else
28421 slow_print(font_name_str);
28422 if font_size[chr_code]<>font_dsize[chr_code] then
28423 begin print(" at "); print_scaled(font_size[chr_code]);
28424 print("pt");
28425 end;
28426 end;
28427
28428 @ @<Put each...@>=
28429 primitive("batchmode",set_interaction,batch_mode);
28430 @!@:batch_mode_}{\.{\\batchmode} primitive@>
28431 primitive("nonstopmode",set_interaction,nonstop_mode);
28432 @!@:nonstop_mode_}{\.{\\nonstopmode} primitive@>
28433 primitive("scrollmode",set_interaction,scroll_mode);
28434 @!@:scroll_mode_}{\.{\\scrollmode} primitive@>
28435 primitive("errorstopmode",set_interaction,error_stop_mode);
28436 @!@:error_stop_mode_}{\.{\\errorstopmode} primitive@>
28437
28438 @ @<Cases of |print_cmd_chr|...@>=
28439 set_interaction: case chr_code of
28440 batch_mode: print_esc("batchmode");
28441 nonstop_mode: print_esc("nonstopmode");
28442 scroll_mode: print_esc("scrollmode");
28443 othercases print_esc("errorstopmode")
28444 endcases;
28445
28446 @ @<Assignments@>=
28447 set_interaction: new_interaction;
28448
28449 @ @<Declare subprocedures for |prefixed_command|@>=
28450 procedure new_interaction;
28451 begin print_ln;
28452 interaction:=cur_chr;
28453 @<Initialize the print |selector| based on |interaction|@>;
28454 if log_opened then selector:=selector+2;
28455 end;
28456
28457 @ The \.{\\afterassignment} command puts a token into the global
28458 variable |after_token|. This global variable is examined just after
28459 every assignment has been performed.
28460
28461 @<Glob...@>=
28462 @!after_token:halfword; {zero, or a saved token}
28463
28464 @ @<Set init...@>=
28465 after_token:=0;
28466
28467 @ @<Cases of |main_control| that don't...@>=
28468 any_mode(after_assignment):begin get_token; after_token:=cur_tok;
28469 end;
28470
28471 @ @<Insert a token saved by \.{\\afterassignment}, if any@>=
28472 if after_token<>0 then
28473 begin cur_tok:=after_token; back_input; after_token:=0;
28474 end
28475
28476 @ Here is a procedure that might be called `Get the next non-blank non-relax
28477 non-call non-assignment token'.
28478
28479 @<Declare act...@>=
28480 procedure do_assignments;
28481 label exit;
28482 begin loop begin @<Get the next non-blank non-relax...@>;
28483 if cur_cmd<=max_non_prefixed_command then return;
28484 set_box_allowed:=false; prefixed_command; set_box_allowed:=true;
28485 end;
28486 exit:end;
28487
28488 @ @<Cases of |main_control| that don't...@>=
28489 any_mode(after_group):begin get_token; save_for_after(cur_tok);
28490 end;
28491
28492 @ Files for \.{\\read} are opened and closed by the |in_stream| command.
28493
28494 @<Put each...@>=
28495 primitive("openin",in_stream,1);
28496 @!@:open_in_}{\.{\\openin} primitive@>
28497 primitive("closein",in_stream,0);
28498 @!@:close_in_}{\.{\\closein} primitive@>
28499
28500 @ @<Cases of |print_cmd_chr|...@>=
28501 in_stream: if chr_code=0 then print_esc("closein")
28502 else print_esc("openin");
28503
28504 @ @<Cases of |main_control| that don't...@>=
28505 any_mode(in_stream): open_or_close_in;
28506
28507 @ @<Declare act...@>=
28508 procedure open_or_close_in;
28509 var c:0..1; {1 for \.{\\openin}, 0 for \.{\\closein}}
28510 @!n:0..15; {stream number}
28511 begin c:=cur_chr; scan_four_bit_int; n:=cur_val;
28512 if read_open[n]<>closed then
28513 begin u_close(read_file[n]); read_open[n]:=closed;
28514 end;
28515 if c<>0 then
28516 begin scan_optional_equals; scan_file_name;
28517 if cur_ext="" then cur_ext:=".tex";
28518 pack_cur_name;
28519 if a_open_in(read_file[n]) then read_open[n]:=just_open;
28520 end;
28521 end;
28522
28523 @ The user can issue messages to the terminal, regardless of the
28524 current mode.
28525
28526 @<Cases of |main_control| that don't...@>=
28527 any_mode(message):issue_message;
28528
28529 @ @<Put each...@>=
28530 primitive("message",message,0);
28531 @!@:message_}{\.{\\message} primitive@>
28532 primitive("errmessage",message,1);
28533 @!@:err_message_}{\.{\\errmessage} primitive@>
28534
28535 @ @<Cases of |print_cmd_chr|...@>=
28536 message: if chr_code=0 then print_esc("message")
28537 else print_esc("errmessage");
28538
28539 @ @<Declare act...@>=
28540 procedure issue_message;
28541 var old_setting:0..max_selector; {holds |selector| setting}
28542 @!c:0..1; {identifies \.{\\message} and \.{\\errmessage}}
28543 @!s:str_number; {the message}
28544 begin c:=cur_chr; link(garbage):=scan_toks(false,true);
28545 old_setting:=selector; selector:=new_string;
28546 token_show(def_ref); selector:=old_setting;
28547 flush_list(def_ref);
28548 str_room(1); s:=make_string;
28549 if c=0 then @<Print string |s| on the terminal@>
28550 else @<Print string |s| as an error message@>;
28551 flush_string;
28552 end;
28553
28554 @ @<Print string |s| on the terminal@>=
28555 begin if term_offset+length(s)>max_print_line-2 then print_ln
28556 else if (term_offset>0)or(file_offset>0) then print_char(" ");
28557 slow_print(s); update_terminal;
28558 end
28559
28560 @ If \.{\\errmessage} occurs often in |scroll_mode|, without user-defined
28561 \.{\\errhelp}, we don't want to give a long help message each time. So we
28562 give a verbose explanation only once.
28563
28564 @<Glob...@>=
28565 @!long_help_seen:boolean; {has the long \.{\\errmessage} help been used?}
28566
28567 @ @<Set init...@>=long_help_seen:=false;
28568
28569 @ @<Print string |s| as an error message@>=
28570 begin print_err(""); slow_print(s);
28571 if err_help<>null then use_err_help:=true
28572 else if long_help_seen then help1("(That was another \errmessage.)")
28573 else begin if interaction<error_stop_mode then long_help_seen:=true;
28574 help4("This error message was generated by an \errmessage")@/
28575 ("command, so I can't give any explicit help.")@/
28576 ("Pretend that you're Hercule Poirot: Examine all clues,")@/
28577 @^Poirot, Hercule@>
28578 ("and deduce the truth by order and method.");
28579 end;
28580 error; use_err_help:=false;
28581 end
28582
28583 @ The |error| routine calls on |give_err_help| if help is requested from
28584 the |err_help| parameter.
28585
28586 @p procedure give_err_help;
28587 begin token_show(err_help);
28588 end;
28589
28590 @ The \.{\\uppercase} and \.{\\lowercase} commands are implemented by
28591 building a token list and then changing the cases of the letters in it.
28592
28593 @<Cases of |main_control| that don't...@>=
28594 any_mode(case_shift):shift_case;
28595
28596 @ @<Put each...@>=
28597 primitive("lowercase",case_shift,lc_code_base);
28598 @!@:lowercase_}{\.{\\lowercase} primitive@>
28599 primitive("uppercase",case_shift,uc_code_base);
28600 @!@:uppercase_}{\.{\\uppercase} primitive@>
28601
28602 @ @<Cases of |print_cmd_chr|...@>=
28603 case_shift:if chr_code=lc_code_base then print_esc("lowercase")
28604 else print_esc("uppercase");
28605
28606 @ @<Declare act...@>=
28607 procedure shift_case;
28608 var b:pointer; {|lc_code_base| or |uc_code_base|}
28609 @!p:pointer; {runs through the token list}
28610 @!t:halfword; {token}
28611 @!c:integer; {character code}
28612 begin b:=cur_chr; p:=scan_toks(false,false); p:=link(def_ref);
28613 while p<>null do
28614 begin @<Change the case of the token in |p|, if a change is appropriate@>;
28615 p:=link(p);
28616 end;
28617 back_list(link(def_ref)); free_avail(def_ref); {omit reference count}
28618 end;
28619
28620 @ When the case of a |chr_code| changes, we don't change the |cmd|.
28621 We also change active characters, using the fact that
28622 |cs_token_flag+active_base| is a multiple of~256.
28623 @^data structure assumptions@>
28624
28625 @<Change the case of the token in |p|, if a change is appropriate@>=
28626 t:=info(p);
28627 if t<cs_token_flag+single_base then
28628 begin c:=t mod max_char_val;
28629 if equiv(b+c)<>0 then info(p):=t-c+equiv(b+c);
28630 end
28631
28632 @ We come finally to the last pieces missing from |main_control|, namely the
28633 `\.{\\show}' commands that are useful when debugging.
28634
28635 @<Cases of |main_control| that don't...@>=
28636 any_mode(xray): show_whatever;
28637
28638 @ @d show_code=0 { \.{\\show} }
28639 @d show_box_code=1 { \.{\\showbox} }
28640 @d show_the_code=2 { \.{\\showthe} }
28641 @d show_lists_code=3 { \.{\\showlists} }
28642
28643 @<Put each...@>=
28644 primitive("show",xray,show_code);
28645 @!@:show_}{\.{\\show} primitive@>
28646 primitive("showbox",xray,show_box_code);
28647 @!@:show_box_}{\.{\\showbox} primitive@>
28648 primitive("showthe",xray,show_the_code);
28649 @!@:show_the_}{\.{\\showthe} primitive@>
28650 primitive("showlists",xray,show_lists_code);
28651 @!@:show_lists_code_}{\.{\\showlists} primitive@>
28652
28653 @ @<Cases of |print_cmd_chr|...@>=
28654 xray: case chr_code of
28655 show_box_code:print_esc("showbox");
28656 show_the_code:print_esc("showthe");
28657 show_lists_code:print_esc("showlists");
28658 @<Cases of |xray| for |print_cmd_chr|@>@;@/
28659 othercases print_esc("show")
28660 endcases;
28661
28662 @ @<Declare act...@>=
28663 procedure show_whatever;
28664 label common_ending;
28665 var p:pointer; {tail of a token list to show}
28666 @!t:small_number; {type of conditional being shown}
28667 @!m:normal..or_code; {upper bound on |fi_or_else| codes}
28668 @!l:integer; {line where that conditional began}
28669 @!n:integer; {level of \.{\\if...\\fi} nesting}
28670 begin case cur_chr of
28671 show_lists_code: begin begin_diagnostic; show_activities;
28672 end;
28673 show_box_code: @<Show the current contents of a box@>;
28674 show_code: @<Show the current meaning of a token, then |goto common_ending|@>;
28675 @<Cases for |show_whatever|@>@;@/
28676 othercases @<Show the current value of some parameter or register,
28677 then |goto common_ending|@>
28678 endcases;@/
28679 @<Complete a potentially long \.{\\show} command@>;
28680 common_ending: if interaction<error_stop_mode then
28681 begin help0; decr(error_count);
28682 end
28683 else if tracing_online>0 then
28684 begin@t@>@;@/
28685 help3("This isn't an error message; I'm just \showing something.")@/
28686 ("Type `I\show...' to show more (e.g., \show\cs,")@/
28687 ("\showthe\count10, \showbox255, \showlists).");
28688 end
28689 else begin@t@>@;@/
28690 help5("This isn't an error message; I'm just \showing something.")@/
28691 ("Type `I\show...' to show more (e.g., \show\cs,")@/
28692 ("\showthe\count10, \showbox255, \showlists).")@/
28693 ("And type `I\tracingonline=1\show...' to show boxes and")@/
28694 ("lists on your terminal as well as in the transcript file.");
28695 end;
28696 error;
28697 end;
28698
28699 @ @<Show the current meaning of a token...@>=
28700 begin get_token;
28701 if interaction=error_stop_mode then wake_up_terminal;
28702 print_nl("> ");
28703 if cur_cs<>0 then
28704 begin sprint_cs(cur_cs); print_char("=");
28705 end;
28706 print_meaning; goto common_ending;
28707 end
28708
28709 @ @<Cases of |print_cmd_chr|...@>=
28710 undefined_cs: print("undefined");
28711 call,long_call,outer_call,long_outer_call: begin n:=cmd-call;
28712 if info(link(chr_code))=protected_token then n:=n+4;
28713 if odd(n div 4) then print_esc("protected");
28714 if odd(n) then print_esc("long");
28715 if odd(n div 2) then print_esc("outer");
28716 if n>0 then print_char(" ");
28717 print("macro");
28718 end;
28719 end_template: print_esc("outer endtemplate");
28720
28721 @ @<Show the current contents of a box@>=
28722 begin scan_register_num; fetch_box(p); begin_diagnostic;
28723 print_nl("> \box"); print_int(cur_val); print_char("=");
28724 if p=null then print("void")@+else show_box(p);
28725 end
28726
28727 @ @<Show the current value of some parameter...@>=
28728 begin p:=the_toks;
28729 if interaction=error_stop_mode then wake_up_terminal;
28730 print_nl("> "); token_show(temp_head);
28731 flush_list(link(temp_head)); goto common_ending;
28732 end
28733
28734 @ @<Complete a potentially long \.{\\show} command@>=
28735 end_diagnostic(true); print_err("OK");
28736 @.OK@>
28737 if selector=term_and_log then if tracing_online<=0 then
28738 begin selector:=term_only; print(" (see the transcript file)");
28739 selector:=term_and_log;
28740 end
28741
28742 @* \[50] Dumping and undumping the tables.
28743 After \.{INITEX} has seen a collection of fonts and macros, it
28744 can write all the necessary information on an auxiliary file so
28745 that production versions of \TeX\ are able to initialize their
28746 memory at high speed. The present section of the program takes
28747 care of such output and input. We shall consider simultaneously
28748 the processes of storing and restoring,
28749 so that the inverse relation between them is clear.
28750 @.INITEX@>
28751
28752 The global variable |format_ident| is a string that is printed right
28753 after the |banner| line when \TeX\ is ready to start. For \.{INITEX} this
28754 string says simply `\.{ (INITEX)}'; for other versions of \TeX\ it says,
28755 for example, `\.{ (preloaded format=plain 1982.11.19)}', showing the year,
28756 month, and day that the format file was created. We have |format_ident=0|
28757 before \TeX's tables are loaded.
28758
28759 @<Glob...@>=
28760 @!format_ident:str_number;
28761
28762 @ @<Set init...@>=
28763 format_ident:=0;
28764
28765 @ @<Initialize table entries...@>=
28766 format_ident:=" (INITEX)";
28767
28768 @ @<Declare act...@>=
28769 @!init procedure store_fmt_file;
28770 label found1,found2,done1,done2;
28771 var j,@!k,@!l:integer; {all-purpose indices}
28772 @!p,@!q: pointer; {all-purpose pointers}
28773 @!x: integer; {something to dump}
28774 @!w: four_quarters; {four ASCII codes}
28775 begin @<If dumping is not allowed, abort@>;
28776 @<Create the |format_ident|, open the format file,
28777 and inform the user that dumping has begun@>;
28778 @<Dump constants for consistency check@>;
28779 @<Dump the string pool@>;
28780 @<Dump the dynamic memory@>;
28781 @<Dump the table of equivalents@>;
28782 @<Dump the font information@>;
28783 @<Dump the hyphenation tables@>;
28784 @<Dump a couple more things and the closing check word@>;
28785 @<Close the format file@>;
28786 end;
28787 tini
28788
28789 @ Corresponding to the procedure that dumps a format file, we have a function
28790 that reads one in. The function returns |false| if the dumped format is
28791 incompatible with the present \TeX\ table sizes, etc.
28792
28793 @d bad_fmt=6666 {go here if the format file is unacceptable}
28794 @d too_small(#)==begin wake_up_terminal;
28795 wterm_ln('---! Must increase the ',#);
28796 @.Must increase the x@>
28797 goto bad_fmt;
28798 end
28799
28800 @p @t\4@>@<Declare the function called |open_fmt_file|@>@;
28801 function load_fmt_file:boolean;
28802 label bad_fmt,exit;
28803 var j,@!k:integer; {all-purpose indices}
28804 @!p,@!q: pointer; {all-purpose pointers}
28805 @!x: integer; {something undumped}
28806 @!w: four_quarters; {four ASCII codes}
28807 begin @<Undump constants for consistency check@>;
28808 @<Undump the string pool@>;
28809 @<Undump the dynamic memory@>;
28810 @<Undump the table of equivalents@>;
28811 @<Undump the font information@>;
28812 @<Undump the hyphenation tables@>;
28813 @<Undump a couple more things and the closing check word@>;
28814 load_fmt_file:=true; return; {it worked!}
28815 bad_fmt: wake_up_terminal;
28816 wterm_ln('(Fatal format file error; I''m stymied)');
28817 @.Fatal format file error@>
28818 load_fmt_file:=false;
28819 exit:end;
28820
28821 @ The user is not allowed to dump a format file unless |save_ptr=0|.
28822 This condition implies that |cur_level=level_one|, hence
28823 the |xeq_level| array is constant and it need not be dumped.
28824
28825 @<If dumping is not allowed, abort@>=
28826 if save_ptr<>0 then
28827 begin print_err("You can't dump inside a group");
28828 @.You can't dump...@>
28829 help1("`{...\dump}' is a no-no."); succumb;
28830 end
28831
28832 @ Format files consist of |memory_word| items, and we use the following
28833 macros to dump words of different types:
28834
28835 @d dump_wd(#)==begin fmt_file^:=#; put(fmt_file);@+end
28836 @d dump_int(#)==begin fmt_file^.int:=#; put(fmt_file);@+end
28837 @d dump_hh(#)==begin fmt_file^.hh:=#; put(fmt_file);@+end
28838 @d dump_qqqq(#)==begin fmt_file^.qqqq:=#; put(fmt_file);@+end
28839
28840 @<Glob...@>=
28841 @!fmt_file:word_file; {for input or output of format information}
28842
28843 @ The inverse macros are slightly more complicated, since we need to check
28844 the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
28845 read an integer value |x| that is supposed to be in the range |a<=x<=b|.
28846 System error messages should be suppressed when undumping.
28847 @^system dependencies@>
28848
28849 @d undump_wd(#)==begin get(fmt_file); #:=fmt_file^;@+end
28850 @d undump_int(#)==begin get(fmt_file); #:=fmt_file^.int;@+end
28851 @d undump_hh(#)==begin get(fmt_file); #:=fmt_file^.hh;@+end
28852 @d undump_qqqq(#)==begin get(fmt_file); #:=fmt_file^.qqqq;@+end
28853 @d undump_end_end(#)==#:=x;@+end
28854 @d undump_end(#)==(x>#) then goto bad_fmt@+else undump_end_end
28855 @d undump(#)==begin undump_int(x); if (x<#) or undump_end
28856 @d undump_size_end_end(#)==too_small(#)@+else undump_end_end
28857 @d undump_size_end(#)==if x># then undump_size_end_end
28858 @d undump_size(#)==begin undump_int(x);
28859 if x<# then goto bad_fmt; undump_size_end
28860
28861 @ The next few sections of the program should make it clear how we use the
28862 dump/undump macros.
28863
28864 @<Dump constants for consistency check@>=
28865 dump_int(@$);@/
28866 @<Dump the \eTeX\ state@>@/
28867 dump_int(mem_bot);@/
28868 dump_int(mem_top);@/
28869 dump_int(eqtb_size);@/
28870 dump_int(hash_prime);@/
28871 dump_int(hyph_size)
28872
28873 @ Sections of a \.{WEB} program that are ``commented out'' still contribute
28874 strings to the string pool; therefore \.{INITEX} and \TeX\ will have
28875 the same strings. (And it is, of course, a good thing that they do.)
28876 @.WEB@>
28877 @^string pool@>
28878
28879 @<Undump constants for consistency check@>=
28880 x:=fmt_file^.int;
28881 if x<>@$ then goto bad_fmt; {check that strings are the same}
28882 @/@<Undump the \eTeX\ state@>@/
28883 undump_int(x);
28884 if x<>mem_bot then goto bad_fmt;
28885 undump_int(x);
28886 if x<>mem_top then goto bad_fmt;
28887 undump_int(x);
28888 if x<>eqtb_size then goto bad_fmt;
28889 undump_int(x);
28890 if x<>hash_prime then goto bad_fmt;
28891 undump_int(x);
28892 if x<>hyph_size then goto bad_fmt
28893
28894 @ @d dump_four_ASCII==
28895 w.b0:=qi(so(str_pool[k])); w.b1:=qi(so(str_pool[k+1]));
28896 w.b2:=qi(so(str_pool[k+2])); w.b3:=qi(so(str_pool[k+3]));
28897 dump_qqqq(w)
28898
28899 @<Dump the string pool@>=
28900 dump_int(pool_ptr);
28901 dump_int(str_ptr);
28902 for k:=0 to str_ptr do dump_int(str_start[k]);
28903 k:=0;
28904 while k+4<pool_ptr do
28905 begin dump_four_ASCII; k:=k+4;
28906 end;
28907 k:=pool_ptr-4; dump_four_ASCII;
28908 print_ln; print_int(str_ptr); print(" strings of total length ");
28909 print_int(pool_ptr)
28910
28911 @ @d undump_four_ASCII==
28912 undump_qqqq(w);
28913 str_pool[k]:=si(qo(w.b0)); str_pool[k+1]:=si(qo(w.b1));
28914 str_pool[k+2]:=si(qo(w.b2)); str_pool[k+3]:=si(qo(w.b3))
28915
28916 @<Undump the string pool@>=
28917 undump_size(0)(pool_size)('string pool size')(pool_ptr);
28918 undump_size(0)(max_strings)('max strings')(str_ptr);
28919 for k:=0 to str_ptr do undump(0)(pool_ptr)(str_start[k]);
28920 k:=0;
28921 while k+4<pool_ptr do
28922 begin undump_four_ASCII; k:=k+4;
28923 end;
28924 k:=pool_ptr-4; undump_four_ASCII;
28925 init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr
28926
28927 @ By sorting the list of available spaces in the variable-size portion of
28928 |mem|, we are usually able to get by without having to dump very much
28929 of the dynamic memory.
28930
28931 We recompute |var_used| and |dyn_used|, so that \.{INITEX} dumps valid
28932 information even when it has not been gathering statistics.
28933
28934 @<Dump the dynamic memory@>=
28935 sort_avail; var_used:=0;
28936 dump_int(lo_mem_max); dump_int(rover);
28937 if eTeX_ex then for k:=int_val to inter_char_val do dump_int(sa_root[k]);
28938 p:=mem_bot; q:=rover; x:=0;
28939 repeat for k:=p to q+1 do dump_wd(mem[k]);
28940 x:=x+q+2-p; var_used:=var_used+q-p;
28941 p:=q+node_size(q); q:=rlink(q);
28942 until q=rover;
28943 var_used:=var_used+lo_mem_max-p; dyn_used:=mem_end+1-hi_mem_min;@/
28944 for k:=p to lo_mem_max do dump_wd(mem[k]);
28945 x:=x+lo_mem_max+1-p;
28946 dump_int(hi_mem_min); dump_int(avail);
28947 for k:=hi_mem_min to mem_end do dump_wd(mem[k]);
28948 x:=x+mem_end+1-hi_mem_min;
28949 p:=avail;
28950 while p<>null do
28951 begin decr(dyn_used); p:=link(p);
28952 end;
28953 dump_int(var_used); dump_int(dyn_used);
28954 print_ln; print_int(x);
28955 print(" memory locations dumped; current usage is ");
28956 print_int(var_used); print_char("&"); print_int(dyn_used)
28957
28958 @ @<Undump the dynamic memory@>=
28959 undump(lo_mem_stat_max+1000)(hi_mem_stat_min-1)(lo_mem_max);
28960 undump(lo_mem_stat_max+1)(lo_mem_max)(rover);
28961 if eTeX_ex then for k:=int_val to inter_char_val do
28962 undump(null)(lo_mem_max)(sa_root[k]);
28963 p:=mem_bot; q:=rover;
28964 repeat for k:=p to q+1 do undump_wd(mem[k]);
28965 p:=q+node_size(q);
28966 if (p>lo_mem_max)or((q>=rlink(q))and(rlink(q)<>rover)) then goto bad_fmt;
28967 q:=rlink(q);
28968 until q=rover;
28969 for k:=p to lo_mem_max do undump_wd(mem[k]);
28970 if mem_min<mem_bot-2 then {make more low memory available}
28971 begin p:=llink(rover); q:=mem_min+1;
28972 link(mem_min):=null; info(mem_min):=null; {we don't use the bottom word}
28973 rlink(p):=q; llink(rover):=q;@/
28974 rlink(q):=rover; llink(q):=p; link(q):=empty_flag;
28975 node_size(q):=mem_bot-q;
28976 end;
28977 undump(lo_mem_max+1)(hi_mem_stat_min)(hi_mem_min);
28978 undump(null)(mem_top)(avail); mem_end:=mem_top;
28979 for k:=hi_mem_min to mem_end do undump_wd(mem[k]);
28980 undump_int(var_used); undump_int(dyn_used)
28981
28982 @ @<Dump the table of equivalents@>=
28983 @<Dump regions 1 to 4 of |eqtb|@>;
28984 @<Dump regions 5 and 6 of |eqtb|@>;
28985 dump_int(par_loc); dump_int(write_loc);@/
28986 @<Dump the hash table@>
28987
28988 @ @<Undump the table of equivalents@>=
28989 @<Undump regions 1 to 6 of |eqtb|@>;
28990 undump(hash_base)(frozen_control_sequence)(par_loc);
28991 par_token:=cs_token_flag+par_loc;@/
28992 undump(hash_base)(frozen_control_sequence)(write_loc);@/
28993 @<Undump the hash table@>
28994
28995 @ The table of equivalents usually contains repeated information, so we dump it
28996 in compressed form: The sequence of $n+2$ values $(n,x_1,\ldots,x_n,m)$ in the
28997 format file represents $n+m$ consecutive entries of |eqtb|, with |m| extra
28998 copies of $x_n$, namely $(x_1,\ldots,x_n,x_n,\ldots,x_n)$.
28999
29000 @<Dump regions 1 to 4 of |eqtb|@>=
29001 k:=active_base;
29002 repeat j:=k;
29003 while j<int_base-1 do
29004 begin if (equiv(j)=equiv(j+1))and(eq_type(j)=eq_type(j+1))and@|
29005 (eq_level(j)=eq_level(j+1)) then goto found1;
29006 incr(j);
29007 end;
29008 l:=int_base; goto done1; {|j=int_base-1|}
29009 found1: incr(j); l:=j;
29010 while j<int_base-1 do
29011 begin if (equiv(j)<>equiv(j+1))or(eq_type(j)<>eq_type(j+1))or@|
29012 (eq_level(j)<>eq_level(j+1)) then goto done1;
29013 incr(j);
29014 end;
29015 done1:dump_int(l-k);
29016 while k<l do
29017 begin dump_wd(eqtb[k]); incr(k);
29018 end;
29019 k:=j+1; dump_int(k-l);
29020 until k=int_base
29021
29022 @ @<Dump regions 5 and 6 of |eqtb|@>=
29023 repeat j:=k;
29024 while j<eqtb_size do
29025 begin if eqtb[j].int=eqtb[j+1].int then goto found2;
29026 incr(j);
29027 end;
29028 l:=eqtb_size+1; goto done2; {|j=eqtb_size|}
29029 found2: incr(j); l:=j;
29030 while j<eqtb_size do
29031 begin if eqtb[j].int<>eqtb[j+1].int then goto done2;
29032 incr(j);
29033 end;
29034 done2:dump_int(l-k);
29035 while k<l do
29036 begin dump_wd(eqtb[k]); incr(k);
29037 end;
29038 k:=j+1; dump_int(k-l);
29039 until k>eqtb_size
29040
29041 @ @<Undump regions 1 to 6 of |eqtb|@>=
29042 k:=active_base;
29043 repeat undump_int(x);
29044 if (x<1)or(k+x>eqtb_size+1) then goto bad_fmt;
29045 for j:=k to k+x-1 do undump_wd(eqtb[j]);
29046 k:=k+x;
29047 undump_int(x);
29048 if (x<0)or(k+x>eqtb_size+1) then goto bad_fmt;
29049 for j:=k to k+x-1 do eqtb[j]:=eqtb[k-1];
29050 k:=k+x;
29051 until k>eqtb_size
29052
29053 @ A different scheme is used to compress the hash table, since its lower
29054 region is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output
29055 two words, |p| and |hash[p]|. The hash table is, of course, densely packed
29056 for |p>=hash_used|, so the remaining entries are output in a~block.
29057
29058 @<Dump the hash table@>=
29059 for p:=0 to prim_size do dump_hh(prim[p]);
29060 dump_int(hash_used); cs_count:=frozen_control_sequence-1-hash_used;
29061 for p:=hash_base to hash_used do if text(p)<>0 then
29062 begin dump_int(p); dump_hh(hash[p]); incr(cs_count);
29063 end;
29064 for p:=hash_used+1 to undefined_control_sequence-1 do dump_hh(hash[p]);
29065 dump_int(cs_count);@/
29066 print_ln; print_int(cs_count); print(" multiletter control sequences")
29067
29068 @ @<Undump the hash table@>=
29069 for p:=0 to prim_size do undump_hh(prim[p]);
29070 undump(hash_base)(frozen_control_sequence)(hash_used); p:=hash_base-1;
29071 repeat undump(p+1)(hash_used)(p); undump_hh(hash[p]);
29072 until p=hash_used;
29073 for p:=hash_used+1 to undefined_control_sequence-1 do undump_hh(hash[p]);
29074 undump_int(cs_count)
29075
29076 @ @<Dump the font information@>=
29077 dump_int(fmem_ptr);
29078 for k:=0 to fmem_ptr-1 do dump_wd(font_info[k]);
29079 dump_int(font_ptr);
29080 for k:=null_font to font_ptr do
29081 @<Dump the array info for internal font number |k|@>;
29082 print_ln; print_int(fmem_ptr-7); print(" words of font info for ");
29083 print_int(font_ptr-font_base); print(" preloaded font");
29084 if font_ptr<>font_base+1 then print_char("s")
29085
29086 @ @<Undump the font information@>=
29087 undump_size(7)(font_mem_size)('font mem size')(fmem_ptr);
29088 for k:=0 to fmem_ptr-1 do undump_wd(font_info[k]);
29089 undump_size(font_base)(font_max)('font max')(font_ptr);
29090 for k:=null_font to font_ptr do
29091 @<Undump the array info for internal font number |k|@>
29092
29093 @ @<Dump the array info for internal font number |k|@>=
29094 begin dump_qqqq(font_check[k]);
29095 dump_int(font_size[k]);
29096 dump_int(font_dsize[k]);
29097 dump_int(font_params[k]);@/
29098 dump_int(hyphen_char[k]);
29099 dump_int(skew_char[k]);@/
29100 dump_int(font_name[k]);
29101 dump_int(font_area[k]);@/
29102 dump_int(font_bc[k]);
29103 dump_int(font_ec[k]);@/
29104 dump_int(char_base[k]);
29105 dump_int(width_base[k]);
29106 dump_int(height_base[k]);@/
29107 dump_int(depth_base[k]);
29108 dump_int(italic_base[k]);
29109 dump_int(lig_kern_base[k]);@/
29110 dump_int(kern_base[k]);
29111 dump_int(exten_base[k]);
29112 dump_int(param_base[k]);@/
29113 dump_int(font_glue[k]);@/
29114 dump_int(bchar_label[k]);
29115 dump_int(font_bchar[k]);
29116 dump_int(font_false_bchar[k]);@/
29117 print_nl("\font"); print_esc(font_id_text(k)); print_char("=");
29118 print_file_name(font_name[k],font_area[k],"");
29119 if font_size[k]<>font_dsize[k] then
29120 begin print(" at "); print_scaled(font_size[k]); print("pt");
29121 end;
29122 end
29123
29124 @ @<Undump the array info for internal font number |k|@>=
29125 begin undump_qqqq(font_check[k]);@/
29126 undump_int(font_size[k]);
29127 undump_int(font_dsize[k]);
29128 undump(min_halfword)(max_halfword)(font_params[k]);@/
29129 undump_int(hyphen_char[k]);
29130 undump_int(skew_char[k]);@/
29131 undump(0)(str_ptr)(font_name[k]);
29132 undump(0)(str_ptr)(font_area[k]);@/
29133 undump(0)(255)(font_bc[k]);
29134 undump(0)(255)(font_ec[k]);@/
29135 undump_int(char_base[k]);
29136 undump_int(width_base[k]);
29137 undump_int(height_base[k]);@/
29138 undump_int(depth_base[k]);
29139 undump_int(italic_base[k]);
29140 undump_int(lig_kern_base[k]);@/
29141 undump_int(kern_base[k]);
29142 undump_int(exten_base[k]);
29143 undump_int(param_base[k]);@/
29144 undump(min_halfword)(lo_mem_max)(font_glue[k]);@/
29145 undump(0)(fmem_ptr-1)(bchar_label[k]);
29146 undump(min_quarterword)(non_char)(font_bchar[k]);
29147 undump(min_quarterword)(non_char)(font_false_bchar[k]);
29148 end
29149
29150 @ @<Dump the hyphenation tables@>=
29151 dump_int(hyph_count);
29152 for k:=0 to hyph_size do if hyph_word[k]<>0 then
29153 begin dump_int(k); dump_int(hyph_word[k]); dump_int(hyph_list[k]);
29154 end;
29155 print_ln; print_int(hyph_count); print(" hyphenation exception");
29156 if hyph_count<>1 then print_char("s");
29157 if trie_not_ready then init_trie;
29158 dump_int(trie_max);
29159 dump_int(hyph_start);
29160 for k:=0 to trie_max do dump_hh(trie[k]);
29161 dump_int(max_hyph_char);
29162 dump_int(trie_op_ptr);
29163 for k:=1 to trie_op_ptr do
29164 begin dump_int(hyf_distance[k]);
29165 dump_int(hyf_num[k]);
29166 dump_int(hyf_next[k]);
29167 end;
29168 print_nl("Hyphenation trie of length "); print_int(trie_max);
29169 @.Hyphenation trie...@>
29170 print(" has "); print_int(trie_op_ptr); print(" op");
29171 if trie_op_ptr<>1 then print_char("s");
29172 print(" out of "); print_int(trie_op_size);
29173 for k:=biggest_lang downto 0 do if trie_used[k]>min_quarterword then
29174 begin print_nl(" "); print_int(qo(trie_used[k]));
29175 print(" for language "); print_int(k);
29176 dump_int(k); dump_int(qo(trie_used[k]));
29177 end
29178
29179 @ Only ``nonempty'' parts of |op_start| need to be restored.
29180
29181 @<Undump the hyphenation tables@>=
29182 undump(0)(hyph_size)(hyph_count);
29183 for k:=1 to hyph_count do
29184 begin undump(0)(hyph_size)(j);
29185 undump(0)(str_ptr)(hyph_word[j]);
29186 undump(min_halfword)(max_halfword)(hyph_list[j]);
29187 end;
29188 undump_size(0)(trie_size)('trie size')(j); @+init trie_max:=j;@+tini
29189 undump(0)(j)(hyph_start);
29190 for k:=0 to j do undump_hh(trie[k]);
29191 undump_int(max_hyph_char);
29192 undump_size(0)(trie_op_size)('trie op size')(j); @+init trie_op_ptr:=j;@+tini
29193 for k:=1 to j do
29194 begin undump(0)(63)(hyf_distance[k]); {a |small_number|}
29195 undump(0)(63)(hyf_num[k]);
29196 undump(min_quarterword)(max_quarterword)(hyf_next[k]);
29197 end;
29198 init for k:=0 to biggest_lang do trie_used[k]:=min_quarterword;@+tini@;@/
29199 k:=biggest_lang+1;
29200 while j>0 do
29201 begin undump(0)(k-1)(k); undump(1)(j)(x);@+init trie_used[k]:=qi(x);@+tini@;@/
29202 j:=j-x; op_start[k]:=qo(j);
29203 end;
29204 @!init trie_not_ready:=false @+tini
29205
29206 @ We have already printed a lot of statistics, so we set |tracing_stats:=0|
29207 to prevent them from appearing again.
29208
29209 @<Dump a couple more things and the closing check word@>=
29210 dump_int(interaction); dump_int(format_ident); dump_int(69069);
29211 tracing_stats:=0
29212
29213 @ @<Undump a couple more things and the closing check word@>=
29214 undump(batch_mode)(error_stop_mode)(interaction);
29215 undump(0)(str_ptr)(format_ident);
29216 undump_int(x);
29217 if (x<>69069)or eof(fmt_file) then goto bad_fmt
29218
29219 @ @<Create the |format_ident|...@>=
29220 selector:=new_string;
29221 print(" (preloaded format="); print(job_name); print_char(" ");
29222 print_int(year); print_char(".");
29223 print_int(month); print_char("."); print_int(day); print_char(")");
29224 if interaction=batch_mode then selector:=log_only
29225 else selector:=term_and_log;
29226 str_room(1);
29227 format_ident:=make_string;
29228 pack_job_name(format_extension);
29229 while not w_open_out(fmt_file) do
29230 prompt_file_name("format file name",format_extension);
29231 print_nl("Beginning to dump on file ");
29232 @.Beginning to dump...@>
29233 slow_print(w_make_name_string(fmt_file)); flush_string;
29234 print_nl(""); slow_print(format_ident)
29235
29236 @ @<Close the format file@>=
29237 w_close(fmt_file)
29238
29239 @* \[51] The main program.
29240 This is it: the part of \TeX\ that executes all those procedures we have
29241 written.
29242
29243 Well---almost. Let's leave space for a few more routines that we may
29244 have forgotten.
29245
29246 @p @<Last-minute procedures@>
29247
29248 @ We have noted that there are two versions of \TeX82. One, called \.{INITEX},
29249 @.INITEX@>
29250 has to be run first; it initializes everything from scratch, without
29251 reading a format file, and it has the capability of dumping a format file.
29252 The other one is called `\.{VIRTEX}'; it is a ``virgin'' program that needs
29253 @.VIRTEX@>
29254 to input a format file in order to get started. \.{VIRTEX} typically has
29255 more memory capacity than \.{INITEX}, because it does not need the space
29256 consumed by the auxiliary hyphenation tables and the numerous calls on
29257 |primitive|, etc.
29258
29259 The \.{VIRTEX} program cannot read a format file instantaneously, of course;
29260 the best implementations therefore allow for production versions of \TeX\ that
29261 not only avoid the loading routine for \PASCAL\ object code, they also have
29262 a format file pre-loaded. This is impossible to do if we stick to standard
29263 \PASCAL; but there is a simple way to fool many systems into avoiding the
29264 initialization, as follows:\quad(1)~We declare a global integer variable
29265 called |ready_already|. The probability is negligible that this
29266 variable holds any particular value like 314159 when \.{VIRTEX} is first
29267 loaded.\quad(2)~After we have read in a format file and initialized
29268 everything, we set |ready_already:=314159|.\quad(3)~Soon \.{VIRTEX}
29269 will print `\.*', waiting for more input; and at this point we
29270 interrupt the program and save its core image in some form that the
29271 operating system can reload speedily.\quad(4)~When that core image is
29272 activated, the program starts again at the beginning; but now
29273 |ready_already=314159| and all the other global variables have
29274 their initial values too. The former chastity has vanished!
29275
29276 In other words, if we allow ourselves to test the condition
29277 |ready_already=314159|, before |ready_already| has been
29278 assigned a value, we can avoid the lengthy initialization. Dirty tricks
29279 rarely pay off so handsomely.
29280 @^dirty \PASCAL@>
29281 @^system dependencies@>
29282
29283 On systems that allow such preloading, the standard program called \.{TeX}
29284 should be the one that has \.{plain} format preloaded, since that agrees
29285 with {\sl The \TeX book}. Other versions, e.g., \.{AmSTeX}, should also
29286 @:TeXbook}{\sl The \TeX book@>
29287 @.AmSTeX@>
29288 @.plain@>
29289 be provided for commonly used formats.
29290
29291 @<Glob...@>=
29292 @!ready_already:integer; {a sacrifice of purity for economy}
29293
29294 @ Now this is really it: \TeX\ starts and ends here.
29295
29296 The initial test involving |ready_already| should be deleted if the
29297 \PASCAL\ runtime system is smart enough to detect such a ``mistake.''
29298 @^system dependencies@>
29299
29300 @p begin @!{|start_here|}
29301 history:=fatal_error_stop; {in case we quit during initialization}
29302 t_open_out; {open the terminal for output}
29303 if ready_already=314159 then goto start_of_TEX;
29304 @<Check the ``constant'' values...@>@;
29305 if bad>0 then
29306 begin wterm_ln('Ouch---my internal constants have been clobbered!',
29307 '---case ',bad:1);
29308 @.Ouch...clobbered@>
29309 goto final_end;
29310 end;
29311 initialize; {set global variables to their starting values}
29312 @!init if not get_strings_started then goto final_end;
29313 init_prim; {call |primitive| for each primitive}
29314 init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr; fix_date_and_time;
29315 tini@/
29316 ready_already:=314159;
29317 start_of_TEX: @<Initialize the output routines@>;
29318 @<Get the first line of input and prepare to start@>;
29319 history:=spotless; {ready to go!}
29320 main_control; {come to life}
29321 final_cleanup; {prepare for death}
29322 end_of_TEX: close_files_and_terminate;
29323 final_end: ready_already:=0;
29324 end.
29325
29326 @ Here we do whatever is needed to complete \TeX's job gracefully on the
29327 local operating system. The code here might come into play after a fatal
29328 error; it must therefore consist entirely of ``safe'' operations that
29329 cannot produce error messages. For example, it would be a mistake to call
29330 |str_room| or |make_string| at this time, because a call on |overflow|
29331 might lead to an infinite loop.
29332 @^system dependencies@>
29333 (Actually there's one way to get error messages, via |prepare_mag|;
29334 but that can't cause infinite recursion.)
29335 @^recursion@>
29336
29337 If |final_cleanup| is bypassed, this program doesn't bother to close
29338 the input files that may still be open.
29339
29340 @<Last-minute...@>=
29341 procedure close_files_and_terminate;
29342 var k:integer; {all-purpose index}
29343 begin @<Finish the extensions@>; new_line_char:=-1;
29344 @!stat if tracing_stats>0 then @<Output statistics about this job@>;@;@+tats@/
29345 wake_up_terminal; @<Finish the \.{DVI} file@>;
29346 if log_opened then
29347 begin wlog_cr; a_close(log_file); selector:=selector-2;
29348 if selector=term_only then
29349 begin print_nl("Transcript written on ");
29350 @.Transcript written...@>
29351 slow_print(log_name); print_char(".");
29352 end;
29353 end;
29354 end;
29355
29356 @ The present section goes directly to the log file instead of using
29357 |print| commands, because there's no need for these strings to take
29358 up |str_pool| memory when a non-{\bf stat} version of \TeX\ is being used.
29359
29360 @<Output statistics...@>=
29361 if log_opened then
29362 begin wlog_ln(' ');
29363 wlog_ln('Here is how much of TeX''s memory',' you used:');
29364 @.Here is how much...@>
29365 wlog(' ',str_ptr-init_str_ptr:1,' string');
29366 if str_ptr<>init_str_ptr+1 then wlog('s');
29367 wlog_ln(' out of ', max_strings-init_str_ptr:1);@/
29368 wlog_ln(' ',pool_ptr-init_pool_ptr:1,' string characters out of ',
29369 pool_size-init_pool_ptr:1);@/
29370 wlog_ln(' ',lo_mem_max-mem_min+mem_end-hi_mem_min+2:1,@|
29371 ' words of memory out of ',mem_end+1-mem_min:1);@/
29372 wlog_ln(' ',cs_count:1,' multiletter control sequences out of ',
29373 hash_size:1);@/
29374 wlog(' ',fmem_ptr:1,' words of font info for ',
29375 font_ptr-font_base:1,' font');
29376 if font_ptr<>font_base+1 then wlog('s');
29377 wlog_ln(', out of ',font_mem_size:1,' for ',font_max-font_base:1);@/
29378 wlog(' ',hyph_count:1,' hyphenation exception');
29379 if hyph_count<>1 then wlog('s');
29380 wlog_ln(' out of ',hyph_size:1);@/
29381 wlog_ln(' ',max_in_stack:1,'i,',max_nest_stack:1,'n,',@|
29382 max_param_stack:1,'p,',@|
29383 max_buf_stack+1:1,'b,',@|
29384 max_save_stack+6:1,'s stack positions out of ',@|
29385 stack_size:1,'i,',
29386 nest_size:1,'n,',
29387 param_size:1,'p,',
29388 buf_size:1,'b,',
29389 save_size:1,'s');
29390 end
29391
29392 @ We get to the |final_cleanup| routine when \.{\\end} or \.{\\dump} has
29393 been scanned and |its_all_over|\kern-2pt.
29394
29395 @<Last-minute...@>=
29396 procedure final_cleanup;
29397 label exit;
29398 var c:small_number; {0 for \.{\\end}, 1 for \.{\\dump}}
29399 begin c:=cur_chr; if c<>1 then new_line_char:=-1;
29400 if job_name=0 then open_log_file;
29401 while input_ptr>0 do
29402 if state=token_list then end_token_list@+else end_file_reading;
29403 while open_parens>0 do
29404 begin print(" )"); decr(open_parens);
29405 end;
29406 if cur_level>level_one then
29407 begin print_nl("("); print_esc("end occurred ");
29408 print("inside a group at level ");
29409 @:end_}{\.{(\\end occurred...)}@>
29410 print_int(cur_level-level_one); print_char(")");
29411 if eTeX_ex then show_save_groups;
29412 end;
29413 while cond_ptr<>null do
29414 begin print_nl("("); print_esc("end occurred ");
29415 print("when "); print_cmd_chr(if_test,cur_if);
29416 if if_line<>0 then
29417 begin print(" on line "); print_int(if_line);
29418 end;
29419 print(" was incomplete)");
29420 if_line:=if_line_field(cond_ptr);
29421 cur_if:=subtype(cond_ptr); temp_ptr:=cond_ptr;
29422 cond_ptr:=link(cond_ptr); free_node(temp_ptr,if_node_size);
29423 end;
29424 if history<>spotless then
29425 if ((history=warning_issued)or(interaction<error_stop_mode)) then
29426 if selector=term_and_log then
29427 begin selector:=term_only;
29428 print_nl("(see the transcript file for additional information)");
29429 @.see the transcript file...@>
29430 selector:=term_and_log;
29431 end;
29432 if c=1 then
29433 begin @!init for c:=top_mark_code to split_bot_mark_code do
29434 if cur_mark[c]<>null then delete_token_ref(cur_mark[c]);
29435 if sa_mark<>null then
29436 if do_marks(destroy_marks,0,sa_mark) then sa_mark:=null;
29437 for c:=last_box_code to vsplit_code do flush_node_list(disc_ptr[c]);
29438 if last_glue<>max_halfword then delete_glue_ref(last_glue);
29439 store_fmt_file; return;@+tini@/
29440 print_nl("(\dump is performed only by INITEX)"); return;
29441 @:dump_}{\.{\\dump...only by INITEX}@>
29442 end;
29443 exit:end;
29444
29445 @ @<Last-minute...@>=
29446 @!init procedure init_prim; {initialize all the primitives}
29447 begin no_new_control_sequence:=false;
29448 first:=0;
29449 @<Put each...@>;
29450 no_new_control_sequence:=true;
29451 end;
29452 tini
29453
29454 @ When we begin the following code, \TeX's tables may still contain garbage;
29455 the strings might not even be present. Thus we must proceed cautiously to get
29456 bootstrapped in.
29457
29458 But when we finish this part of the program, \TeX\ is ready to call on the
29459 |main_control| routine to do its work.
29460
29461 @<Get the first line...@>=
29462 begin @<Initialize the input routines@>;
29463 @<Enable \eTeX, if requested@>@;@/
29464 if (format_ident=0)or(buffer[loc]="&") then
29465 begin if format_ident<>0 then initialize; {erase preloaded format}
29466 if not open_fmt_file then goto final_end;
29467 if not load_fmt_file then
29468 begin w_close(fmt_file); goto final_end;
29469 end;
29470 w_close(fmt_file);
29471 while (loc<limit)and(buffer[loc]=" ") do incr(loc);
29472 end;
29473 if eTeX_ex then wterm_ln('entering extended mode');
29474 if end_line_char_inactive then decr(limit)
29475 else buffer[limit]:=end_line_char;
29476 fix_date_and_time;@/
29477 random_seed :=(microseconds*1000)+(epochseconds mod 1000000);@/
29478 init_randoms(random_seed);@/
29479 @<Compute the magic offset@>;
29480 @<Initialize the print |selector|...@>;
29481 if (loc<limit)and(cat_code(buffer[loc])<>escape) then start_input;
29482 {\.{\\input} assumed}
29483 end
29484
29485 @* \[52] Debugging.
29486 Once \TeX\ is working, you should be able to diagnose most errors with
29487 the \.{\\show} commands and other diagnostic features. But for the initial
29488 stages of debugging, and for the revelation of really deep mysteries, you
29489 can compile \TeX\ with a few more aids, including the \PASCAL\ runtime
29490 checks and its debugger. An additional routine called |debug_help|
29491 will also come into play when you type `\.D' after an error message;
29492 |debug_help| also occurs just before a fatal error causes \TeX\ to succumb.
29493 @^debugging@>
29494 @^system dependencies@>
29495
29496 The interface to |debug_help| is primitive, but it is good enough when used
29497 with a \PASCAL\ debugger that allows you to set breakpoints and to read
29498 variables and change their values. After getting the prompt `\.{debug \#}', you
29499 type either a negative number (this exits |debug_help|), or zero (this
29500 goes to a location where you can set a breakpoint, thereby entering into
29501 dialog with the \PASCAL\ debugger), or a positive number |m| followed by
29502 an argument |n|. The meaning of |m| and |n| will be clear from the
29503 program below. (If |m=13|, there is an additional argument, |l|.)
29504 @.debug \#@>
29505
29506 @d breakpoint=888 {place where a breakpoint is desirable}
29507
29508 @<Last-minute...@>=
29509 @!debug procedure debug_help; {routine to display various things}
29510 label breakpoint,exit;
29511 var k,@!l,@!m,@!n:integer;
29512 begin clear_terminal;
29513 loop begin wake_up_terminal;
29514 print_nl("debug # (-1 to exit):"); update_terminal;
29515 @.debug \#@>
29516 read(term_in,m);
29517 if m<0 then return
29518 else if m=0 then
29519 begin goto breakpoint;@/ {go to every declared label at least once}
29520 breakpoint: m:=0; @{'BREAKPOINT'@}@/
29521 end
29522 else begin read(term_in,n);
29523 case m of
29524 @t\4@>@<Numbered cases for |debug_help|@>@;
29525 othercases print("?")
29526 endcases;
29527 end;
29528 end;
29529 exit:end;
29530 gubed
29531
29532 @ @<Numbered cases...@>=
29533 1: print_word(mem[n]); {display |mem[n]| in all forms}
29534 2: print_int(info(n));
29535 3: print_int(link(n));
29536 4: print_word(eqtb[n]);
29537 5: print_word(font_info[n]);
29538 6: print_word(save_stack[n]);
29539 7: show_box(n);
29540 {show a box, abbreviated by |show_box_depth| and |show_box_breadth|}
29541 8: begin breadth_max:=10000; depth_threshold:=pool_size-pool_ptr-10;
29542 show_node_list(n); {show a box in its entirety}
29543 end;
29544 9: show_token_list(n,null,1000);
29545 10: slow_print(n);
29546 11: check_mem(n>0); {check wellformedness; print new busy locations if |n>0|}
29547 12: search_mem(n); {look for pointers to |n|}
29548 13: begin read(term_in,l); print_cmd_chr(n,l);
29549 end;
29550 14: for k:=0 to n do print(buffer[k]);
29551 15: begin font_in_short_display:=null_font; short_display(n);
29552 end;
29553 16: panicking:=not panicking;
29554
29555 @* \[53] Extensions.
29556 The program above includes a bunch of ``hooks'' that allow further
29557 capabilities to be added without upsetting \TeX's basic structure.
29558 Most of these hooks are concerned with ``whatsit'' nodes, which are
29559 intended to be used for special purposes; whenever a new extension to
29560 \TeX\ involves a new kind of whatsit node, a corresponding change needs
29561 to be made to the routines below that deal with such nodes,
29562 but it will usually be unnecessary to make many changes to the
29563 other parts of this program.
29564
29565 In order to demonstrate how extensions can be made, we shall treat
29566 `\.{\\write}', `\.{\\openout}', `\.{\\closeout}', `\.{\\immediate}',
29567 `\.{\\special}', and `\.{\\setlanguage}' as if they were extensions.
29568 These commands are actually primitives of \TeX, and they should
29569 appear in all implementations of the system; but let's try to imagine
29570 that they aren't. Then the program below illustrates how a person
29571 could add them.
29572
29573 Sometimes, of course, an extension will require changes to \TeX\ itself;
29574 no system of hooks could be complete enough for all conceivable extensions.
29575 The features associated with `\.{\\write}' are almost all confined to the
29576 following paragraphs, but there are small parts of the |print_ln| and
29577 |print_char| procedures that were introduced specifically to \.{\\write}
29578 characters. Furthermore one of the token lists recognized by the scanner
29579 is a |write_text|; and there are a few other miscellaneous places where we
29580 have already provided for some aspect of \.{\\write}. The goal of a \TeX\
29581 extender should be to minimize alterations to the standard parts of the
29582 program, and to avoid them completely if possible. He or she should also
29583 be quite sure that there's no easy way to accomplish the desired goals
29584 with the standard features that \TeX\ already has. ``Think thrice before
29585 extending,'' because that may save a lot of work, and it will also keep
29586 incompatible extensions of \TeX\ from proliferating.
29587 @^system dependencies@>
29588 @^extensions to \TeX@>
29589
29590 @ First let's consider the format of whatsit nodes that are used to represent
29591 the data associated with \.{\\write} and its relatives. Recall that a whatsit
29592 has |type=whatsit_node|, and the |subtype| is supposed to distinguish
29593 different kinds of whatsits. Each node occupies two or more words; the
29594 exact number is immaterial, as long as it is readily determined from the
29595 |subtype| or other data.
29596
29597 We shall introduce five |subtype| values here, corresponding to the
29598 control sequences \.{\\openout}, \.{\\write}, \.{\\closeout}, \.{\\special}, and
29599 \.{\\setlanguage}. The second word of I/O whatsits has a |write_stream| field
29600 that identifies the write-stream number (0 to 15, or 16 for out-of-range and
29601 positive, or 17 for out-of-range and negative).
29602 In the case of \.{\\write} and \.{\\special}, there is also a field that
29603 points to the reference count of a token list that should be sent. In the
29604 case of \.{\\openout}, we need three words and three auxiliary subfields
29605 to hold the string numbers for name, area, and extension.
29606
29607 @d write_node_size=2 {number of words in a write/whatsit node}
29608 @d open_node_size=3 {number of words in an open/whatsit node}
29609 @d open_node=0 {|subtype| in whatsits that represent files to \.{\\openout}}
29610 @d write_node=1 {|subtype| in whatsits that represent things to \.{\\write}}
29611 @d close_node=2 {|subtype| in whatsits that represent streams to \.{\\closeout}}
29612 @d special_node=3 {|subtype| in whatsits that represent \.{\\special} things}
29613 @d latespecial_node=4 {|subtype| in whatsits that represent \.{\\special} things}
29614 @d language_node=5 {|subtype| in whatsits that change the current language}
29615 @d what_lang(#)==link(#+1) {language number, in the range |0..255|}
29616 @d what_lhm(#)==type(#+1) {minimum left fragment, in the range |1..63|}
29617 @d what_rhm(#)==subtype(#+1) {minimum right fragment, in the range |1..63|}
29618 @d write_tokens(#) == link(#+1) {reference count of token list to write}
29619 @d write_stream(#) == info(#+1) {stream number (0 to 17)}
29620 @d open_name(#) == link(#+1) {string number of file name to open}
29621 @d open_area(#) == info(#+2) {string number of file area for |open_name|}
29622 @d open_ext(#) == link(#+2) {string number of file extension for |open_name|}
29623
29624 @ The sixteen possible \.{\\write} streams are represented by the |write_file|
29625 array. The |j|th file is open if and only if |write_open[j]=true|. The last
29626 two streams are special; |write_open[16]| represents a stream number
29627 greater than 15, while |write_open[17]| represents a negative stream number,
29628 and both of these variables are always |false|.
29629
29630 @<Glob...@>=
29631 @!write_file:array[0..15] of alpha_file;
29632 @!write_open:array[0..17] of boolean;
29633
29634 @ @<Set init...@>=
29635 for k:=0 to 17 do write_open[k]:=false;
29636
29637 @ Extensions might introduce new command codes; but it's best to use
29638 |extension| with a modifier, whenever possible, so that |main_control|
29639 stays the same.
29640
29641 @d immediate_code=5 {command modifier for \.{\\immediate}}
29642 @d set_language_code=6 {command modifier for \.{\\setlanguage}}
29643
29644 @d pdftex_first_extension_code = 7
29645 @d pdf_save_pos_node == pdftex_first_extension_code + 16
29646 @d reset_timer_code == pdftex_first_extension_code + 26
29647 @d set_random_seed_code == pdftex_first_extension_code + 28
29648
29649 @d pic_file_code=41 { command modifier for \.{\\XeTeXpicfile}, skipping codes pdfTeX might use }
29650 @d pdf_file_code=42 { command modifier for \.{\\XeTeXpdffile} }
29651 @d glyph_code=43 { command modifier for \.{\\XeTeXglyph} }
29652
29653 @d XeTeX_input_encoding_extension_code=44
29654 @d XeTeX_default_encoding_extension_code=45
29655 @d XeTeX_linebreak_locale_extension_code=46
29656
29657 @<Put each...@>=
29658 primitive("openout",extension,open_node);@/
29659 @!@:open_out_}{\.{\\openout} primitive@>
29660 primitive("write",extension,write_node); write_loc:=cur_val;@/
29661 @!@:write_}{\.{\\write} primitive@>
29662 primitive("closeout",extension,close_node);@/
29663 @!@:close_out_}{\.{\\closeout} primitive@>
29664 primitive("special",extension,special_node);@/
29665 @!@:special_}{\.{\\special} primitive@>
29666 primitive("immediate",extension,immediate_code);@/
29667 @!@:immediate_}{\.{\\immediate} primitive@>
29668 primitive("setlanguage",extension,set_language_code);@/
29669 @!@:set_language_}{\.{\\setlanguage} primitive@>
29670 primitive("resettimer",extension,reset_timer_code);@/
29671 @!@:reset_timer_}{\.{\\resettimer} primitive@>
29672 primitive("setrandomseed",extension,set_random_seed_code);@/
29673 @!@:set_random_seed_code}{\.{\\setrandomseed} primitive@>
29674
29675 @ The \.{\\XeTeXpicfile} and \.{\\XeTeXpdffile} primitives are only defined in extended mode.
29676
29677 @<Generate all \eTeX\ primitives@>=
29678 primitive("XeTeXpicfile",extension,pic_file_code);@/
29679 @!@:XeTeX_pic_file_}{\.{\\XeTeXpicfile} primitive@>
29680 primitive("XeTeXpdffile",extension,pdf_file_code);@/
29681 @!@:XeTeX_pdf_file_}{\.{\\XeTeXpdffile} primitive@>
29682 primitive("XeTeXglyph",extension,glyph_code);@/
29683 @!@:XeTeX_glyph_}{\.{\\XeTeXglyph} primitive@>
29684 primitive("XeTeXlinebreaklocale", extension, XeTeX_linebreak_locale_extension_code);@/
29685 @!@:XeTeX_linebreak_locale_}{\.{\\XeTeXlinebreaklocale} primitive@>
29686 primitive("XeTeXinterchartoks",assign_toks,XeTeX_inter_char_loc);
29687 @!@:XeTeX_inter_char_toks_}{\.{\\XeTeXinterchartoks} primitive@>
29688 @#
29689 primitive("pdfsavepos",extension,pdf_save_pos_node);@/
29690 @!@:pdf_save_pos_}{\.{\\pdfsavepos} primitive@>
29691
29692 @ The variable |write_loc| just introduced is used to provide an
29693 appropriate error message in case of ``runaway'' write texts.
29694
29695 @<Glob...@>=
29696 @!write_loc:pointer; {|eqtb| address of \.{\\write}}
29697
29698 @ @<Cases of |print_cmd_chr|...@>=
29699 extension: case chr_code of
29700 open_node:print_esc("openout");
29701 write_node:print_esc("write");
29702 close_node:print_esc("closeout");
29703 special_node:print_esc("special");
29704 immediate_code:print_esc("immediate");
29705 set_language_code:print_esc("setlanguage");
29706 pdf_save_pos_node: print_esc("pdfsavepos");
29707 reset_timer_code: print_esc("resettimer");
29708 set_random_seed_code: print_esc("setrandomseed");
29709 pic_file_code:print_esc("XeTeXpicfile");
29710 pdf_file_code:print_esc("XeTeXpdffile");
29711 glyph_code:print_esc("XeTeXglyph");
29712 XeTeX_linebreak_locale_extension_code:print_esc("XeTeXlinebreaklocale");
29713 XeTeX_input_encoding_extension_code:print_esc("XeTeXinputencoding");
29714 XeTeX_default_encoding_extension_code:print_esc("XeTeXdefaultencoding");
29715 othercases print("[unknown extension!]")
29716 endcases;
29717
29718 @ When an |extension| command occurs in |main_control|, in any mode,
29719 the |do_extension| routine is called.
29720
29721 @<Cases of |main_control| that are for extensions...@>=
29722 any_mode(extension):do_extension;
29723
29724 @ @<Declare act...@>=
29725 @t\4@>@<Declare procedures needed in |do_extension|@>@;
29726 procedure do_extension;
29727 var i,@!j,@!k:integer; {all-purpose integers}
29728 @!p,@!q,@!r:pointer; {all-purpose pointers}
29729 begin case cur_chr of
29730 open_node:@<Implement \.{\\openout}@>;
29731 write_node:@<Implement \.{\\write}@>;
29732 close_node:@<Implement \.{\\closeout}@>;
29733 special_node:@<Implement \.{\\special}@>;
29734 immediate_code:@<Implement \.{\\immediate}@>;
29735 set_language_code:@<Implement \.{\\setlanguage}@>;
29736 pdf_save_pos_node: @<Implement \.{\\pdfsavepos}@>;
29737 reset_timer_code: @<Implement \.{\\resettimer}@>;
29738 set_random_seed_code: @<Implement \.{\\setrandomseed}@>;
29739 pic_file_code:@<Implement \.{\\XeTeXpicfile}@>;
29740 pdf_file_code:@<Implement \.{\\XeTeXpdffile}@>;
29741 glyph_code:@<Implement \.{\\XeTeXglyph}@>;
29742 XeTeX_input_encoding_extension_code:@<Implement \.{\\XeTeXinputencoding}@>;
29743 XeTeX_default_encoding_extension_code:@<Implement \.{\\XeTeXdefaultencoding}@>;
29744 XeTeX_linebreak_locale_extension_code:@<Implement \.{\\XeTeXlinebreaklocale}@>;
29745 othercases confusion("ext1")
29746 @:this can't happen ext1}{\quad ext1@>
29747 endcases;
29748 end;
29749
29750 @ Here is a subroutine that creates a whatsit node having a given |subtype|
29751 and a given number of words. It initializes only the first word of the whatsit,
29752 and appends it to the current list.
29753
29754 @<Declare procedures needed in |do_extension|@>=
29755 procedure new_whatsit(@!s:small_number;@!w:small_number);
29756 var p:pointer; {the new node}
29757 begin p:=get_node(w); type(p):=whatsit_node; subtype(p):=s;
29758 link(tail):=p; tail:=p;
29759 end;
29760
29761 @ The next subroutine uses |cur_chr| to decide what sort of whatsit is
29762 involved, and also inserts a |write_stream| number.
29763
29764 @<Declare procedures needed in |do_ext...@>=
29765 procedure new_write_whatsit(@!w:small_number);
29766 begin new_whatsit(cur_chr,w);
29767 if w<>write_node_size then scan_four_bit_int
29768 else begin scan_int;
29769 if cur_val<0 then cur_val:=17
29770 else if cur_val>15 then cur_val:=16;
29771 end;
29772 write_stream(tail):=cur_val;
29773 end;
29774
29775 @ @<Implement \.{\\openout}@>=
29776 begin new_write_whatsit(open_node_size);
29777 scan_optional_equals; scan_file_name;@/
29778 open_name(tail):=cur_name; open_area(tail):=cur_area; open_ext(tail):=cur_ext;
29779 end
29780
29781 @ When `\.{\\write 12\{...\}}' appears, we scan the token list `\.{\{...\}}'
29782 without expanding its macros; the macros will be expanded later when this
29783 token list is rescanned.
29784
29785 @<Implement \.{\\write}@>=
29786 begin k:=cur_cs; new_write_whatsit(write_node_size);@/
29787 cur_cs:=k; p:=scan_toks(false,false); write_tokens(tail):=def_ref;
29788 end
29789
29790 @ @<Implement \.{\\closeout}@>=
29791 begin new_write_whatsit(write_node_size); write_tokens(tail):=null;
29792 end
29793
29794 @ When `\.{\\special\{...\}}' appears, we expand the macros in the token
29795 list as in \.{\\xdef} and \.{\\mark}. When marked with \.{shipout}, we keep
29796 tokens unexpanded for now.
29797
29798 @<Implement \.{\\special}@>=
29799 begin if scan_keyword("shipout") then
29800 begin new_whatsit(latespecial_node,write_node_size); write_stream(tail):=null;
29801 p:=scan_toks(false,false); write_tokens(tail):=def_ref;
29802 end else
29803 begin new_whatsit(special_node,write_node_size); write_stream(tail):=null;
29804 p:=scan_toks(false,true); write_tokens(tail):=def_ref;
29805 end; end
29806
29807 @ @d call_func(#) == begin if # <> 0 then do_nothing end
29808 @d flushable(#) == (# = str_ptr - 1)
29809 @d max_integer == @"7FFFFFFF {$2^{31}-1$}
29810
29811 @p procedure flush_str(s: str_number); {flush a string if possible}
29812 begin
29813 if flushable(s) then
29814 flush_string;
29815 end;
29816
29817 function tokens_to_string(p: pointer): str_number; {return a string from tokens
29818 list}
29819 begin
29820 if selector = new_string then
29821 pdf_error("tokens", "tokens_to_string() called while selector = new_string");
29822 old_setting:=selector; selector:=new_string;
29823 show_token_list(link(p),null,pool_size-pool_ptr);
29824 selector:=old_setting;
29825 tokens_to_string:=make_string;
29826 end;
29827
29828 procedure scan_pdf_ext_toks;
29829 begin
29830 call_func(scan_toks(false, true)); {like \.{\\special}}
29831 end;
29832
29833 procedure compare_strings; {to implement \.{\\strcmp}}
29834 label done;
29835 var s1, s2: str_number;
29836 i1, i2, j1, j2: pool_pointer;
29837 save_cur_cs: pointer;
29838 begin
29839 save_cur_cs:=cur_cs; call_func(scan_toks(false, true));
29840 s1:=tokens_to_string(def_ref);
29841 delete_token_ref(def_ref);
29842 cur_cs:=save_cur_cs; call_func(scan_toks(false, true));
29843 s2:=tokens_to_string(def_ref);
29844 delete_token_ref(def_ref);
29845 i1:=str_start_macro(s1);
29846 j1:=str_start_macro(s1 + 1);
29847 i2:=str_start_macro(s2);
29848 j2:=str_start_macro(s2 + 1);
29849 while (i1 < j1) and (i2 < j2) do begin
29850 if str_pool[i1] < str_pool[i2] then begin
29851 cur_val:=-1;
29852 goto done;
29853 end;
29854 if str_pool[i1] > str_pool[i2] then begin
29855 cur_val:=1;
29856 goto done;
29857 end;
29858 incr(i1);
29859 incr(i2);
29860 end;
29861 if (i1 = j1) and (i2 = j2) then
29862 cur_val:=0
29863 else if i1 < j1 then
29864 cur_val:=1
29865 else
29866 cur_val:=-1;
29867 done:
29868 flush_str(s2);
29869 flush_str(s1);
29870 cur_val_level:=int_val;
29871 end;
29872
29873 @ @<Declare procedures that need to be declared forward for \pdfTeX@>=
29874 function get_microinterval:integer;
29875 var s,@!m:integer; {seconds and microseconds}
29876 begin
29877 seconds_and_micros(s,m);
29878 if (s-epochseconds)>32767 then
29879 get_microinterval := max_integer
29880 else if (microseconds>m) then
29881 get_microinterval := ((s-1-epochseconds)*65536)+ (((m+1000000-microseconds)/100)*65536)/10000
29882 else
29883 get_microinterval := ((s-epochseconds)*65536) + (((m-microseconds)/100)*65536)/10000;
29884 end;
29885
29886 @ @<Set initial values of key variables@>=
29887 seconds_and_micros(epochseconds,microseconds);
29888 init_start_time;
29889
29890 @ Negative random seed values are silently converted to positive ones
29891
29892 @<Implement \.{\\setrandomseed}@>=
29893 begin
29894 scan_int;
29895 if cur_val<0 then negate(cur_val);
29896 random_seed := cur_val;
29897 init_randoms(random_seed);
29898 end
29899
29900 @ @<Implement \.{\\resettimer}@>=
29901 begin
29902 seconds_and_micros(epochseconds,microseconds);
29903 end
29904
29905 @ Each new type of node that appears in our data structure must be capable
29906 of being displayed, copied, destroyed, and so on. The routines that we
29907 need for write-oriented whatsits are somewhat like those for mark nodes;
29908 other extensions might, of course, involve more subtlety here.
29909
29910 @<Basic printing...@>=
29911 procedure print_write_whatsit(@!s:str_number;@!p:pointer);
29912 begin print_esc(s);
29913 if write_stream(p)<16 then print_int(write_stream(p))
29914 else if write_stream(p)=16 then print_char("*")
29915 @.*\relax@>
29916 else print_char("-");
29917 end;
29918
29919 procedure print_native_word(@!p:pointer);
29920 var i,c,cc:integer;
29921 begin
29922 for i:=0 to native_length(p) - 1 do begin
29923 c:=get_native_char(p,i);
29924 if (c >= @"D800) and (c <= @"DBFF) then begin
29925 if i < native_length(p) - 1 then begin
29926 cc:=get_native_char(p, i+1);
29927 if (cc >= @"DC00) and (cc <= @"DFFF) then begin
29928 c:=@"10000 + (c - @"D800) * @"400 + (cc - @"DC00);
29929 print_char(c);
29930 incr(i);
29931 end else
29932 print(".");
29933 end else
29934 print(".");
29935 end else
29936 print_char(c);
29937 end
29938 end;
29939
29940 @ @<Display the whatsit...@>=
29941 case subtype(p) of
29942 open_node:begin print_write_whatsit("openout",p);
29943 print_char("="); print_file_name(open_name(p),open_area(p),open_ext(p));
29944 end;
29945 write_node:begin print_write_whatsit("write",p);
29946 print_mark(write_tokens(p));
29947 end;
29948 close_node:print_write_whatsit("closeout",p);
29949 special_node:begin print_esc("special");
29950 print_mark(write_tokens(p));
29951 end;
29952 latespecial_node:begin print_esc("special"); print(" shipout");
29953 print_mark(write_tokens(p));
29954 end;
29955 language_node:begin print_esc("setlanguage");
29956 print_int(what_lang(p)); print(" (hyphenmin ");
29957 print_int(what_lhm(p)); print_char(",");
29958 print_int(what_rhm(p)); print_char(")");
29959 end;
29960 pdf_save_pos_node: print_esc("pdfsavepos");
29961 native_word_node, native_word_node_AT:begin print_esc(font_id_text(native_font(p)));
29962 print_char(" ");
29963 print_native_word(p);
29964 end;
29965 glyph_node:begin print_esc(font_id_text(native_font(p)));
29966 print(" glyph#");
29967 print_int(native_glyph(p));
29968 end;
29969 pic_node,pdf_node: begin
29970 if subtype(p) = pic_node then print_esc("XeTeXpicfile")
29971 else print_esc("XeTeXpdffile");
29972 print(" """);
29973 for i:=0 to pic_path_length(p)-1 do
29974 print_visible_char(pic_path_byte(p, i));
29975 print("""");
29976 end;
29977 othercases print("whatsit?")
29978 endcases
29979
29980 @ Picture nodes are tricky in that they are variable size.
29981 @d total_pic_node_size(#) == (pic_node_size + (pic_path_length(#) + sizeof(memory_word) - 1) div sizeof(memory_word))
29982
29983 @<Make a partial copy of the whatsit...@>=
29984 case subtype(p) of
29985 open_node: begin r:=get_node(open_node_size); words:=open_node_size;
29986 end;
29987 write_node,special_node,latespecial_node: begin r:=get_node(write_node_size);
29988 add_token_ref(write_tokens(p)); words:=write_node_size;
29989 end;
29990 close_node,language_node: begin r:=get_node(small_node_size);
29991 words:=small_node_size;
29992 end;
29993 native_word_node, native_word_node_AT: begin words:=native_size(p);
29994 r:=get_node(words);
29995 while words > 0 do
29996 begin decr(words); mem[r+words]:=mem[p+words]; end;
29997 native_glyph_info_ptr(r):=null_ptr; native_glyph_count(r):=0;
29998 copy_native_glyph_info(p, r);
29999 end;
30000 glyph_node: begin r:=get_node(glyph_node_size);
30001 words:=glyph_node_size;
30002 end;
30003 pic_node,pdf_node: begin words:=total_pic_node_size(p);
30004 r:=get_node(words);
30005 end;
30006 pdf_save_pos_node:
30007 r:=get_node(small_node_size);
30008 othercases confusion("ext2")
30009 @:this can't happen ext2}{\quad ext2@>
30010 endcases
30011
30012 @ @<Wipe out the whatsit...@>=
30013 begin case subtype(p) of
30014 open_node: free_node(p,open_node_size);
30015 write_node,special_node,latespecial_node: begin delete_token_ref(write_tokens(p));
30016 free_node(p,write_node_size); goto done;
30017 end;
30018 close_node,language_node: free_node(p,small_node_size);
30019 native_word_node, native_word_node_AT: begin free_native_glyph_info(p); free_node(p,native_size(p)); end;
30020 glyph_node: free_node(p,glyph_node_size);
30021 pic_node,pdf_node: free_node(p,total_pic_node_size(p));
30022 pdf_save_pos_node:
30023 free_node(p, small_node_size);
30024 othercases confusion("ext3")
30025 @:this can't happen ext3}{\quad ext3@>
30026 endcases;@/
30027 goto done;
30028 end
30029
30030 @ @<Incorporate a whatsit node into a vbox@>=
30031 begin
30032 if (subtype(p)=pic_node)
30033 or (subtype(p)=pdf_node)
30034 then begin
30035 x:=x + d + height(p);
30036 d:=depth(p);
30037 if width(p) > w then w:=width(p);
30038 end;
30039 end
30040
30041 @ @<Incorporate a whatsit node into an hbox@>=
30042 begin
30043 case subtype(p) of
30044 native_word_node, native_word_node_AT: begin
30045 { merge with any following word fragments in same font, discarding discretionary breaks }
30046 if (q <> r+list_offset) and (type(q) = disc_node) then k:=replace_count(q) else k:=0;
30047 while (link(q) <> p) do begin
30048 decr(k);
30049 q:=link(q); { bring q up in preparation for deletion of nodes starting at p }
30050 if type(q) = disc_node then k:=replace_count(q);
30051 end;
30052 pp:=link(p);
30053 restart:
30054 if (k <= 0) and (pp <> null) and (not is_char_node(pp)) then begin
30055 if (type(pp) = whatsit_node)
30056 and (is_native_word_subtype(pp))
30057 and (native_font(pp) = native_font(p)) then begin
30058 pp:=link(pp);
30059 goto restart;
30060 end
30061 else if (type(pp) = disc_node) then begin
30062 ppp:=link(pp);
30063 if is_native_word_node(ppp) and (native_font(ppp) = native_font(p)) then begin
30064 pp:=link(ppp);
30065 goto restart;
30066 end
30067 end
30068 end;
30069
30070 { now pp points to the non-|native_word| node that ended the chain, or null }
30071
30072 { we can just check type(p)=|whatsit_node| below, as we know that the chain
30073 contains only discretionaries and |native_word| nodes, no other whatsits or |char_node|s }
30074
30075 if (pp <> link(p)) then begin
30076 { found a chain of at least two pieces starting at p }
30077 total_chars:=0;
30078 p:=link(q); { the first fragment }
30079 while (p <> pp) do begin
30080 if (type(p) = whatsit_node) then
30081 total_chars:=total_chars + native_length(p); { accumulate char count }
30082 ppp:=p; { remember last node seen }
30083 p:=link(p); { point to next fragment or discretionary or terminator }
30084 end;
30085
30086 p:=link(q); { the first fragment again }
30087 pp:=new_native_word_node(native_font(p), total_chars); { make new node for merged word }
30088 subtype(pp):=subtype(p);
30089 link(q):=pp; { link to preceding material }
30090 link(pp):=link(ppp); { attach remainder of hlist to it }
30091 link(ppp):=null; { and detach from the old fragments }
30092
30093 { copy the chars into new node }
30094 total_chars:=0;
30095 ppp:=p;
30096 repeat
30097 if (type(ppp) = whatsit_node) then
30098 for k:=0 to native_length(ppp)-1 do begin
30099 set_native_char(pp, total_chars, get_native_char(ppp, k));
30100 incr(total_chars);
30101 end;
30102 ppp:=link(ppp);
30103 until (ppp = null);
30104
30105 flush_node_list(p); { delete the fragments }
30106 p:=link(q); { update p to point to the new node }
30107 set_native_metrics(p, XeTeX_use_glyph_metrics); { and measure it (i.e., re-do the OT layout) }
30108 end;
30109
30110 { now incorporate the |native_word| node measurements into the box we're packing }
30111 if height(p) > h then
30112 h:=height(p);
30113 if depth(p) > d then
30114 d:=depth(p);
30115 x:=x + width(p);
30116 end;
30117 glyph_node, pic_node, pdf_node: begin
30118 if height(p) > h then
30119 h:=height(p);
30120 if depth(p) > d then
30121 d:=depth(p);
30122 x:=x + width(p);
30123 end;
30124 othercases do_nothing
30125 endcases;
30126 end
30127
30128 @ @<Let |d| be the width of the whatsit |p|, and |goto found| if ``visible''@>=
30129 if (is_native_word_subtype(p))
30130 or (subtype(p)=glyph_node)
30131 or (subtype(p)=pic_node)
30132 or (subtype(p)=pdf_node)
30133 then begin
30134 d:=width(p);
30135 goto found;
30136 end else
30137 d:=0
30138
30139 @ @d adv_past_linebreak(#)==@+if subtype(#)=language_node then
30140 begin cur_lang:=what_lang(#); l_hyf:=what_lhm(#); r_hyf:=what_rhm(#);
30141 set_hyph_index;
30142 end
30143 else if (is_native_word_subtype(#))
30144 or (subtype(#)=glyph_node)
30145 or (subtype(#)=pic_node)
30146 or (subtype(#)=pdf_node)
30147 then
30148 begin act_width:=act_width+width(#); end
30149
30150 @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>=@+
30151 adv_past_linebreak(cur_p)
30152
30153 @ @d adv_past_prehyph(#)==@+if subtype(#)=language_node then
30154 begin cur_lang:=what_lang(#); l_hyf:=what_lhm(#); r_hyf:=what_rhm(#);
30155 set_hyph_index;
30156 end
30157
30158 @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>=@+
30159 adv_past_prehyph(s)
30160
30161 @ @<Prepare to move whatsit |p| to the current page, then |goto contribute|@>=
30162 begin
30163 if (subtype(p)=pic_node)
30164 or (subtype(p)=pdf_node)
30165 then begin
30166 page_total:=page_total + page_depth + height(p);
30167 page_depth:=depth(p);
30168 end;
30169 goto contribute;
30170 end
30171
30172 @ @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>=
30173 begin
30174 if (subtype(p)=pic_node)
30175 or (subtype(p)=pdf_node)
30176 then begin
30177 cur_height:=cur_height + prev_dp + height(p); prev_dp:=depth(p);
30178 end;
30179 goto not_found;
30180 end
30181
30182 @ @<Output the whatsit node |p| in a vlist@>=
30183 begin
30184 case subtype(p) of
30185 glyph_node: begin
30186 cur_v:=cur_v+height(p);
30187 cur_h:=left_edge;
30188 synch_h; synch_v; {Sync DVI state to TeX state}
30189 f:=native_font(p);
30190 if f<>dvi_f then @<Change font |dvi_f| to |f|@>;
30191 dvi_out(set_glyphs);
30192 dvi_four(0); { width }
30193 dvi_two(1); { glyph count }
30194 dvi_four(0); { x-offset as fixed point }
30195 dvi_four(0); { y-offset as fixed point }
30196 dvi_two(native_glyph(p));
30197 cur_v:=cur_v+depth(p);
30198 cur_h:=left_edge;
30199 end;
30200 pic_node, pdf_node: begin
30201 save_h:=dvi_h; save_v:=dvi_v;
30202 cur_v:=cur_v+height(p);
30203 pic_out(p);
30204 dvi_h:=save_h; dvi_v:=save_v;
30205 cur_v:=save_v+depth(p); cur_h:=left_edge;
30206 end;
30207 pdf_save_pos_node: @<Save current position to |pdf_last_x_pos|, |pdf_last_y_pos|@>;
30208 othercases out_what(p)
30209 endcases
30210 end
30211
30212 @ @<Save current position to |pdf_last_x_pos|, |pdf_last_y_pos|@>=
30213 begin
30214 pdf_last_x_pos:=cur_h + 4736286;
30215 pdf_last_y_pos:=cur_page_height - cur_v - 4736286;
30216 end
30217
30218 @ @<Calculate page dimensions and margins@>=
30219 cur_h_offset:=h_offset + (unity * 7227) / 100;
30220 cur_v_offset:=v_offset + (unity * 7227) / 100;
30221 if pdf_page_width <> 0 then
30222 cur_page_width:=pdf_page_width
30223 else
30224 cur_page_width:=width(p) + 2*cur_h_offset;
30225 if pdf_page_height <> 0 then
30226 cur_page_height:=pdf_page_height
30227 else
30228 cur_page_height:=height(p) + depth(p) + 2*cur_v_offset
30229
30230 @ @<Glob...@>=
30231 @!cur_page_width: scaled; {width of page being shipped}
30232 @!cur_page_height: scaled; {height of page being shipped}
30233 @!cur_h_offset: scaled; {horizontal offset of page being shipped}
30234 @!cur_v_offset: scaled; {vertical offset of page being shipped}
30235
30236 @ @<Output the whatsit node |p| in an hlist@>=
30237 begin
30238 case subtype(p) of
30239 native_word_node, native_word_node_AT, glyph_node: begin
30240 synch_h; synch_v; {Sync DVI state to TeX state}
30241 f:=native_font(p);
30242 if f<>dvi_f then @<Change font |dvi_f| to |f|@>;
30243 if subtype(p) = glyph_node then begin
30244 dvi_out(set_glyphs);
30245 dvi_four(width(p));
30246 dvi_two(1); { glyph count }
30247 dvi_four(0); { x-offset as fixed point }
30248 dvi_four(0); { y-offset as fixed point }
30249 dvi_two(native_glyph(p));
30250 cur_h:=cur_h + width(p);
30251 end else begin
30252 if subtype(p)=native_word_node_AT then begin
30253 if (native_length(p) > 0) or (native_glyph_info_ptr(p) <> null_ptr) then begin
30254 dvi_out(set_text_and_glyphs);
30255 len:=native_length(p);
30256 dvi_two(len);
30257 for k:=0 to len-1 do begin
30258 dvi_two(get_native_char(p, k));
30259 end;
30260 len:=make_xdv_glyph_array_data(p);
30261 for k:=0 to len-1 do
30262 dvi_out(xdv_buffer_byte(k));
30263 end
30264 end else begin
30265 if native_glyph_info_ptr(p) <> null_ptr then begin
30266 dvi_out(set_glyphs);
30267 len:=make_xdv_glyph_array_data(p);
30268 for k:=0 to len-1 do
30269 dvi_out(xdv_buffer_byte(k));
30270 end
30271 end;
30272 cur_h:=cur_h + width(p);
30273 end;
30274 dvi_h:=cur_h;
30275 end;
30276 pic_node, pdf_node: begin
30277 save_h:=dvi_h; save_v:=dvi_v;
30278 cur_v:=base_line;
30279 edge:=cur_h+width(p);
30280 pic_out(p);
30281 dvi_h:=save_h; dvi_v:=save_v;
30282 cur_h:=edge; cur_v:=base_line;
30283 end;
30284 pdf_save_pos_node: @<Save current position to |pdf_last_x_pos|, |pdf_last_y_pos|@>;
30285 othercases out_what(p)
30286 endcases
30287 end
30288
30289 @ After all this preliminary shuffling, we come finally to the routines
30290 that actually send out the requested data. Let's do \.{\\special} first
30291 (it's easier).
30292
30293 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
30294 procedure special_out(@!p:pointer);
30295 var old_setting:0..max_selector; {holds print |selector|}
30296 @!k:pool_pointer; {index into |str_pool|}
30297 @!h:halfword;
30298 @!q,@!r:pointer; {temporary variables for list manipulation}
30299 @!old_mode:integer; {saved |mode|}
30300 begin synch_h; synch_v;@/
30301 doing_special:=true;
30302 old_setting:=selector;
30303 if subtype(p)=latespecial_node then
30304 begin @<Expand macros in the token list
30305 and make |link(def_ref)| point to the result@>;
30306 h:=def_ref;
30307 end
30308 else h:=write_tokens(p);
30309 selector:=new_string;
30310 show_token_list(link(h),null,pool_size-pool_ptr);
30311 selector:=old_setting;
30312 str_room(1);
30313 if cur_length<256 then
30314 begin dvi_out(xxx1); dvi_out(cur_length);
30315 end
30316 else begin dvi_out(xxx4); dvi_four(cur_length);
30317 end;
30318 for k:=str_start_macro(str_ptr) to pool_ptr-1 do dvi_out(so(str_pool[k]));
30319 pool_ptr:=str_start_macro(str_ptr); {erase the string}
30320 if subtype(p)=latespecial_node then
30321 flush_list(def_ref);
30322 doing_special:=false;
30323 end;
30324
30325 @ To write a token list, we must run it through \TeX's scanner, expanding
30326 macros and \.{\\the} and \.{\\number}, etc. This might cause runaways,
30327 if a delimited macro parameter isn't matched, and runaways would be
30328 extremely confusing since we are calling on \TeX's scanner in the middle
30329 of a \.{\\shipout} command. Therefore we will put a dummy control sequence as
30330 a ``stopper,'' right after the token list. This control sequence is
30331 artificially defined to be \.{\\outer}.
30332 @:end_write_}{\.{\\endwrite}@>
30333
30334 @<Initialize table...@>=
30335 text(end_write):="endwrite"; eq_level(end_write):=level_one;
30336 eq_type(end_write):=outer_call; equiv(end_write):=null;
30337
30338 @ @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
30339 procedure write_out(@!p:pointer);
30340 var old_setting:0..max_selector; {holds print |selector|}
30341 @!old_mode:integer; {saved |mode|}
30342 @!j:small_number; {write stream number}
30343 @!k:integer;
30344 @!q,@!r:pointer; {temporary variables for list manipulation}
30345 begin @<Expand macros in the token list
30346 and make |link(def_ref)| point to the result@>;
30347 old_setting:=selector; j:=write_stream(p);
30348 if write_open[j] then selector:=j
30349 else begin {write to the terminal if file isn't open}
30350 if (j=17)and(selector=term_and_log) then selector:=log_only;
30351 print_nl("");
30352 end;
30353 token_show(def_ref); print_ln;
30354 flush_list(def_ref); selector:=old_setting;
30355 end;
30356
30357 @ The final line of this routine is slightly subtle; at least, the author
30358 didn't think about it until getting burnt! There is a used-up token list
30359 @^Knuth, Donald Ervin@>
30360 on the stack, namely the one that contained |end_write_token|. (We
30361 insert this artificial `\.{\\endwrite}' to prevent runaways, as explained
30362 above.) If it were not removed, and if there were numerous writes on a
30363 single page, the stack would overflow.
30364
30365 @d end_write_token==cs_token_flag+end_write
30366
30367 @<Expand macros in the token list and...@>=
30368 q:=get_avail; info(q):=right_brace_token+"}";@/
30369 r:=get_avail; link(q):=r; info(r):=end_write_token; ins_list(q);@/
30370 begin_token_list(write_tokens(p),write_text);@/
30371 q:=get_avail; info(q):=left_brace_token+"{"; ins_list(q);
30372 {now we're ready to scan
30373 `\.\{$\langle\,$token list$\,\rangle$\.{\} \\endwrite}'}
30374 old_mode:=mode; mode:=0;
30375 {disable \.{\\prevdepth}, \.{\\spacefactor}, \.{\\lastskip}, \.{\\prevgraf}}
30376 cur_cs:=write_loc; q:=scan_toks(false,true); {expand macros, etc.}
30377 get_token;@+if cur_tok<>end_write_token then
30378 @<Recover from an unbalanced write command@>;
30379 mode:=old_mode;
30380 end_token_list {conserve stack space}
30381
30382 @ @<Recover from an unbalanced write command@>=
30383 begin print_err("Unbalanced write command");
30384 @.Unbalanced write...@>
30385 help2("On this page there's a \write with fewer real {'s than }'s.")@/
30386 ("I can't handle that very well; good luck."); error;
30387 repeat get_token;
30388 until cur_tok=end_write_token;
30389 end
30390
30391 @ The |out_what| procedure takes care of outputting whatsit nodes for
30392 |vlist_out| and |hlist_out|\kern-.3pt.
30393
30394 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
30395 procedure pic_out(@!p:pointer);
30396 var old_setting:0..max_selector; {holds print |selector|}
30397 i:integer;
30398 k:pool_pointer; {index into |str_pool|}
30399 begin
30400 synch_h; synch_v;
30401 old_setting:=selector; selector:=new_string;
30402 print("pdf:image ");
30403 print("matrix ");
30404 print_scaled(pic_transform1(p)); print(" ");
30405 print_scaled(pic_transform2(p)); print(" ");
30406 print_scaled(pic_transform3(p)); print(" ");
30407 print_scaled(pic_transform4(p)); print(" ");
30408 print_scaled(pic_transform5(p)); print(" ");
30409 print_scaled(pic_transform6(p)); print(" ");
30410 print("page "); print_int(pic_page(p)); print(" ");
30411 case pic_pdf_box(p) of
30412 pdfbox_crop: print("pagebox cropbox ");
30413 pdfbox_media: print("pagebox mediabox ");
30414 pdfbox_bleed: print("pagebox bleedbox ");
30415 pdfbox_art: print("pagebox artbox ");
30416 pdfbox_trim: print("pagebox trimbox ");
30417 others: do_nothing;
30418 endcases;
30419 print("(");
30420 for i:=0 to pic_path_length(p)-1 do
30421 print_visible_char(pic_path_byte(p, i));
30422 print(")");
30423 selector:=old_setting;
30424 if cur_length<256 then
30425 begin dvi_out(xxx1); dvi_out(cur_length);
30426 end
30427 else begin dvi_out(xxx4); dvi_four(cur_length);
30428 end;
30429 for k:=str_start_macro(str_ptr) to pool_ptr-1 do dvi_out(so(str_pool[k]));
30430 pool_ptr:=str_start_macro(str_ptr); {erase the string}
30431 end;
30432
30433 procedure out_what(@!p:pointer);
30434 var j:small_number; {write stream number}
30435 begin case subtype(p) of
30436 open_node,write_node,close_node:@<Do some work that has been queued up
30437 for \.{\\write}@>;
30438 special_node,latespecial_node:special_out(p);
30439 language_node:do_nothing;
30440 othercases confusion("ext4")
30441 @:this can't happen ext4}{\quad ext4@>
30442 endcases;
30443 end;
30444
30445 @ We don't implement \.{\\write} inside of leaders. (The reason is that
30446 the number of times a leader box appears might be different in different
30447 implementations, due to machine-dependent rounding in the glue calculations.)
30448 @^leaders@>
30449
30450 @<Do some work that has been queued up...@>=
30451 if not doing_leaders then
30452 begin j:=write_stream(p);
30453 if subtype(p)=write_node then write_out(p)
30454 else begin if write_open[j] then a_close(write_file[j]);
30455 if subtype(p)=close_node then write_open[j]:=false
30456 else if j<16 then
30457 begin cur_name:=open_name(p); cur_area:=open_area(p);
30458 cur_ext:=open_ext(p);
30459 if cur_ext="" then cur_ext:=".tex";
30460 pack_cur_name;
30461 while not a_open_out(write_file[j]) do
30462 prompt_file_name("output file name",".tex");
30463 write_open[j]:=true;
30464 end;
30465 end;
30466 end
30467
30468 @ The presence of `\.{\\immediate}' causes the |do_extension| procedure
30469 to descend to one level of recursion. Nothing happens unless \.{\\immediate}
30470 is followed by `\.{\\openout}', `\.{\\write}', or `\.{\\closeout}'.
30471 @^recursion@>
30472
30473 @<Implement \.{\\immediate}@>=
30474 begin get_x_token;
30475 if (cur_cmd=extension)and(cur_chr<=close_node) then
30476 begin p:=tail; do_extension; {append a whatsit node}
30477 out_what(tail); {do the action immediately}
30478 flush_node_list(tail); tail:=p; link(p):=null;
30479 end
30480 else back_input;
30481 end
30482
30483 @ The \.{\\language} extension is somewhat different.
30484 We need a subroutine that comes into play when a character of
30485 a non-|clang| language is being appended to the current paragraph.
30486
30487 @<Declare action...@>=
30488 procedure fix_language;
30489 var @!l:ASCII_code; {the new current language}
30490 begin if language<=0 then l:=0
30491 else if language>255 then l:=0
30492 else l:=language;
30493 if l<>clang then
30494 begin new_whatsit(language_node,small_node_size);
30495 what_lang(tail):=l; clang:=l;@/
30496 what_lhm(tail):=norm_min(left_hyphen_min);
30497 what_rhm(tail):=norm_min(right_hyphen_min);
30498 end;
30499 end;
30500
30501 @ @<Implement \.{\\setlanguage}@>=
30502 if abs(mode)<>hmode then report_illegal_case
30503 else begin new_whatsit(language_node,small_node_size);
30504 scan_int;
30505 if cur_val<=0 then clang:=0
30506 else if cur_val>255 then clang:=0
30507 else clang:=cur_val;
30508 what_lang(tail):=clang;
30509 what_lhm(tail):=norm_min(left_hyphen_min);
30510 what_rhm(tail):=norm_min(right_hyphen_min);
30511 end
30512
30513 @ @<Finish the extensions@>=
30514 terminate_font_manager;
30515 for k:=0 to 15 do if write_open[k] then a_close(write_file[k])
30516
30517 @ @<Implement \.{\\XeTeXpicfile}@>=
30518 if abs(mode)=mmode then report_illegal_case
30519 else load_picture(false)
30520
30521 @ @<Implement \.{\\XeTeXpdffile}@>=
30522 if abs(mode)=mmode then report_illegal_case
30523 else load_picture(true)
30524
30525 @ @<Implement \.{\\XeTeXglyph}@>=
30526 begin
30527 if abs(mode)=vmode then begin
30528 back_input;
30529 new_graf(true);
30530 end else if abs(mode)=mmode then report_illegal_case
30531 else begin
30532 if is_native_font(cur_font) then begin
30533 new_whatsit(glyph_node,glyph_node_size);
30534 scan_int;
30535 if (cur_val<0)or(cur_val>65535) then
30536 begin print_err("Bad glyph number");
30537 help2("A glyph number must be between 0 and 65535.")@/
30538 ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
30539 end;
30540 native_font(tail):=cur_font;
30541 native_glyph(tail):=cur_val;
30542 set_native_glyph_metrics(tail, XeTeX_use_glyph_metrics);
30543 end else not_native_font_error(extension, glyph_code, cur_font);
30544 end
30545 end
30546
30547 @ Load a picture file and handle following keywords.
30548
30549 @d calc_min_and_max==
30550 begin
30551 xmin:=1000000.0;
30552 xmax:=-xmin;
30553 ymin:=xmin;
30554 ymax:=xmax;
30555 for i:=0 to 3 do begin
30556 if xCoord(corners[i]) < xmin then xmin:=xCoord(corners[i]);
30557 if xCoord(corners[i]) > xmax then xmax:=xCoord(corners[i]);
30558 if yCoord(corners[i]) < ymin then ymin:=yCoord(corners[i]);
30559 if yCoord(corners[i]) > ymax then ymax:=yCoord(corners[i]);
30560 end;
30561 end
30562
30563 @d update_corners==
30564 for i:=0 to 3 do
30565 transform_point(addressof(corners[i]), addressof(t2))
30566
30567 @d do_size_requests==begin
30568 { calculate current width and height }
30569 calc_min_and_max;
30570 if x_size_req = 0.0 then begin
30571 make_scale(addressof(t2), y_size_req / (ymax - ymin), y_size_req / (ymax - ymin));
30572 end else if y_size_req = 0.0 then begin
30573 make_scale(addressof(t2), x_size_req / (xmax - xmin), x_size_req / (xmax - xmin));
30574 end else begin
30575 make_scale(addressof(t2), x_size_req / (xmax - xmin), y_size_req / (ymax - ymin));
30576 end;
30577 update_corners;
30578 x_size_req:=0.0;
30579 y_size_req:=0.0;
30580 transform_concat(addressof(t), addressof(t2));
30581 end
30582
30583 @<Declare procedures needed in |do_extension|@>=
30584 procedure load_picture(@!is_pdf:boolean);
30585 var
30586 pic_path: ^char;
30587 bounds: real_rect;
30588 t, t2: transform;
30589 corners: array[0..3] of real_point;
30590 x_size_req,y_size_req: real;
30591 check_keywords: boolean;
30592 xmin,xmax,ymin,ymax: real;
30593 i: small_number;
30594 page: integer;
30595 pdf_box_type: integer;
30596 result: integer;
30597 begin
30598 { scan the filename and pack into |name_of_file| }
30599 scan_file_name;
30600 pack_cur_name;
30601
30602 pdf_box_type:=0;
30603 page:=0;
30604 if is_pdf then begin
30605 if scan_keyword("page") then begin
30606 scan_int;
30607 page:=cur_val;
30608 end;
30609 pdf_box_type:=pdfbox_none;
30610 if scan_keyword("crop") then pdf_box_type:=pdfbox_crop
30611 else if scan_keyword("media") then pdf_box_type:=pdfbox_media
30612 else if scan_keyword("bleed") then pdf_box_type:=pdfbox_bleed
30613 else if scan_keyword("trim") then pdf_box_type:=pdfbox_trim
30614 else if scan_keyword("art") then pdf_box_type:=pdfbox_art;
30615 end;
30616
30617 { access the picture file and check its size }
30618 if pdf_box_type=pdfbox_none then
30619 result:=find_pic_file(addressof(pic_path), addressof(bounds), pdfbox_crop, page)
30620 else
30621 result:=find_pic_file(addressof(pic_path), addressof(bounds), pdf_box_type, page);
30622
30623 setPoint(corners[0], xField(bounds), yField(bounds));
30624 setPoint(corners[1], xField(corners[0]), yField(bounds) + htField(bounds));
30625 setPoint(corners[2], xField(bounds) + wdField(bounds), yField(corners[1]));
30626 setPoint(corners[3], xField(corners[2]), yField(corners[0]));
30627
30628 x_size_req:=0.0;
30629 y_size_req:=0.0;
30630
30631 { look for any scaling requests for this picture }
30632 make_identity(addressof(t));
30633
30634 check_keywords:=true;
30635 while check_keywords do begin
30636 if scan_keyword("scaled") then begin
30637 scan_int;
30638 if (x_size_req = 0.0) and (y_size_req = 0.0) then begin
30639 make_scale(addressof(t2), float(cur_val) / 1000.0, float(cur_val) / 1000.0);
30640 update_corners;
30641 transform_concat(addressof(t), addressof(t2));
30642 end
30643 end else if scan_keyword("xscaled") then begin
30644 scan_int;
30645 if (x_size_req = 0.0) and (y_size_req = 0.0) then begin
30646 make_scale(addressof(t2), float(cur_val) / 1000.0, 1.0);
30647 update_corners;
30648 transform_concat(addressof(t), addressof(t2));
30649 end
30650 end else if scan_keyword("yscaled") then begin
30651 scan_int;
30652 if (x_size_req = 0.0) and (y_size_req = 0.0) then begin
30653 make_scale(addressof(t2), 1.0, float(cur_val) / 1000.0);
30654 update_corners;
30655 transform_concat(addressof(t), addressof(t2));
30656 end
30657 end else if scan_keyword("width") then begin
30658 scan_normal_dimen;
30659 if cur_val <= 0 then begin
30660 print_err("Improper image ");
30661 print("size (");
30662 print_scaled(cur_val);
30663 print("pt) will be ignored");
30664 help2("I can't scale images to zero or negative sizes,")@/
30665 ("so I'm ignoring this.");
30666 error;
30667 end else
30668 x_size_req:=Fix2D(cur_val);
30669 end else if scan_keyword("height") then begin
30670 scan_normal_dimen;
30671 if cur_val <= 0 then begin
30672 print_err("Improper image ");
30673 print("size (");
30674 print_scaled(cur_val);
30675 print("pt) will be ignored");
30676 help2("I can't scale images to zero or negative sizes,")@/
30677 ("so I'm ignoring this.");
30678 error;
30679 end else
30680 y_size_req:=Fix2D(cur_val);
30681 end else if scan_keyword("rotated") then begin
30682 scan_decimal;
30683 if (x_size_req <> 0.0) or (y_size_req <> 0.0) then do_size_requests;
30684 make_rotation(addressof(t2), Fix2D(cur_val) * 3.141592653589793 / 180.0);
30685 update_corners;
30686 calc_min_and_max;
30687 setPoint(corners[0], xmin, ymin);
30688 setPoint(corners[1], xmin, ymax);
30689 setPoint(corners[2], xmax, ymax);
30690 setPoint(corners[3], xmax, ymin);
30691 transform_concat(addressof(t), addressof(t2));
30692 end else
30693 check_keywords:=false;
30694 end;
30695
30696 if (x_size_req <> 0.0) or (y_size_req <> 0.0) then do_size_requests;
30697
30698 calc_min_and_max;
30699 make_translation(addressof(t2), -xmin * 72 / 72.27, -ymin * 72 / 72.27);
30700 transform_concat(addressof(t), addressof(t2));
30701
30702 if result = 0 then begin
30703 new_whatsit(pic_node, pic_node_size + (strlen(pic_path) + sizeof(memory_word) - 1) div sizeof(memory_word));
30704 if is_pdf then begin
30705 subtype(tail):=pdf_node;
30706 end;
30707 pic_path_length(tail):=strlen(pic_path);
30708 pic_page(tail):=page;
30709 pic_pdf_box(tail):=pdf_box_type;
30710
30711 width(tail):=D2Fix(xmax - xmin);
30712 height(tail):=D2Fix(ymax - ymin);
30713 depth(tail):=0;
30714
30715 pic_transform1(tail):=D2Fix(aField(t));
30716 pic_transform2(tail):=D2Fix(bField(t));
30717 pic_transform3(tail):=D2Fix(cField(t));
30718 pic_transform4(tail):=D2Fix(dField(t));
30719 pic_transform5(tail):=D2Fix(xField(t));
30720 pic_transform6(tail):=D2Fix(yField(t));
30721
30722 memcpy(addressof(mem[tail + pic_node_size]), pic_path, strlen(pic_path));
30723 libc_free(pic_path);
30724 end else begin
30725 print_err("Unable to load picture or PDF file '");
30726 print_file_name(cur_name,cur_area,cur_ext); print("'");
30727 if result = -43 then begin { Mac OS file not found error }
30728 help2("The requested image couldn't be read because")@/
30729 ("the file was not found.");
30730 end
30731 else begin { otherwise assume GraphicImport failed }
30732 help2("The requested image couldn't be read because")@/
30733 ("it was not a recognized image format.");
30734 end;
30735 error;
30736 end;
30737 end;
30738
30739 @ @<Implement \.{\\XeTeXinputencoding}@>=
30740 begin
30741 scan_and_pack_name; {scan a filename-like arg for the input encoding}
30742
30743 i:=get_encoding_mode_and_info(addressof(j)); {convert it to |mode| and |encoding| values}
30744 if i = XeTeX_input_mode_auto then begin
30745 print_err("Encoding mode `auto' is not valid for \XeTeXinputencoding");
30746 help2("You can't use `auto' encoding here, only for \XeTeXdefaultencoding.")@/
30747 ("I'll ignore this and leave the current encoding unchanged.");@/
30748 error;
30749 end else set_input_file_encoding(input_file[in_open], i, j); {apply them to the current input file}
30750 end
30751
30752 @ @<Implement \.{\\XeTeXdefaultencoding}@>=
30753 begin
30754 scan_and_pack_name; {scan a filename-like arg for the input encoding}
30755
30756 i:=get_encoding_mode_and_info(addressof(j)); {convert it to |mode| and |encoding| values}
30757 XeTeX_default_input_mode:=i; {store them as defaults for new input files}
30758 XeTeX_default_input_encoding:=j;
30759 end
30760
30761 @ @<Implement \.{\\XeTeXlinebreaklocale}@>=
30762 begin
30763 scan_file_name; {scan a filename-like arg for the locale name}
30764 if length(cur_name) = 0 then XeTeX_linebreak_locale:=0
30765 else XeTeX_linebreak_locale:=cur_name; {we ignore the area and extension!}
30766 end
30767
30768 @ @<Glob...@>=
30769 @!pdf_last_x_pos: integer;
30770 @!pdf_last_y_pos: integer;
30771
30772 @ @<Implement \.{\\pdfsavepos}@>=
30773 begin
30774 new_whatsit(pdf_save_pos_node, small_node_size);
30775 end
30776
30777
30778 @* \[53a] The extended features of \eTeX.
30779 The program has two modes of operation: (1)~In \TeX\ compatibility mode
30780 it fully deserves the name \TeX\ and there are neither extended features
30781 nor additional primitive commands. There are, however, a few
30782 modifications that would be legitimate in any implementation of \TeX\
30783 such as, e.g., preventing inadequate results of the glue to \.{DVI}
30784 unit conversion during |ship_out|. (2)~In extended mode there are
30785 additional primitive commands and the extended features of \eTeX\ are
30786 available.
30787
30788 The distinction between these two modes of operation initially takes
30789 place when a `virgin' \.{eINITEX} starts without reading a format file.
30790 Later on the values of all \eTeX\ state variables are inherited when
30791 \.{eVIRTEX} (or \.{eINITEX}) reads a format file.
30792
30793 The code below is designed to work for cases where `$|init|\ldots|tini|$'
30794 is a run-time switch.
30795
30796 @<Enable \eTeX, if requested@>=
30797 @!init if (buffer[loc]="*")and(format_ident=" (INITEX)") then
30798 begin no_new_control_sequence:=false;
30799 @<Generate all \eTeX\ primitives@>@;
30800 incr(loc); eTeX_mode:=1; {enter extended mode}
30801 @<Initialize variables for \eTeX\ extended mode@>@;
30802 end;
30803 tini@;@/
30804 if not no_new_control_sequence then {just entered extended mode ?}
30805 no_new_control_sequence:=true@+else
30806
30807 @ The \eTeX\ features available in extended mode are grouped into two
30808 categories: (1)~Some of them are permanently enabled and have no
30809 semantic effect as long as none of the additional primitives are
30810 executed. (2)~The remaining \eTeX\ features are optional and can be
30811 individually enabled and disabled. For each optional feature there is
30812 an \eTeX\ state variable named \.{\\...state}; the feature is enabled,
30813 resp.\ disabled by assigning a positive, resp.\ non-positive value to
30814 that integer.
30815
30816 @d eTeX_state_base=int_base+eTeX_state_code
30817 @d eTeX_state(#)==eqtb[eTeX_state_base+#].int {an \eTeX\ state variable}
30818 @#
30819 @d eTeX_version_code=eTeX_int {code for \.{\\eTeXversion}}
30820
30821 @<Generate all \eTeX...@>=
30822 primitive("lastnodetype",last_item,last_node_type_code);
30823 @!@:last_node_type_}{\.{\\lastnodetype} primitive@>
30824 primitive("eTeXversion",last_item,eTeX_version_code);
30825 @!@:eTeX_version_}{\.{\\eTeXversion} primitive@>
30826 primitive("eTeXrevision",convert,eTeX_revision_code);@/
30827 @!@:eTeX_revision_}{\.{\\eTeXrevision} primitive@>
30828
30829 primitive("XeTeXversion",last_item,XeTeX_version_code);
30830 @!@:XeTeX_version_}{\.{\\XeTeXversion} primitive@>
30831 primitive("XeTeXrevision",convert,XeTeX_revision_code);@/
30832 @!@:XeTeXrevision_}{\.{\\XeTeXrevision} primitive@>
30833
30834 primitive("XeTeXcountglyphs",last_item,XeTeX_count_glyphs_code);
30835
30836 primitive("XeTeXcountvariations",last_item,XeTeX_count_variations_code);
30837 primitive("XeTeXvariation",last_item,XeTeX_variation_code);
30838 primitive("XeTeXfindvariationbyname",last_item,XeTeX_find_variation_by_name_code);
30839 primitive("XeTeXvariationmin",last_item,XeTeX_variation_min_code);
30840 primitive("XeTeXvariationmax",last_item,XeTeX_variation_max_code);
30841 primitive("XeTeXvariationdefault",last_item,XeTeX_variation_default_code);
30842
30843 primitive("XeTeXcountfeatures",last_item,XeTeX_count_features_code);
30844 primitive("XeTeXfeaturecode",last_item,XeTeX_feature_code_code);
30845 primitive("XeTeXfindfeaturebyname",last_item,XeTeX_find_feature_by_name_code);
30846 primitive("XeTeXisexclusivefeature",last_item,XeTeX_is_exclusive_feature_code);
30847 primitive("XeTeXcountselectors",last_item,XeTeX_count_selectors_code);
30848 primitive("XeTeXselectorcode",last_item,XeTeX_selector_code_code);
30849 primitive("XeTeXfindselectorbyname",last_item,XeTeX_find_selector_by_name_code);
30850 primitive("XeTeXisdefaultselector",last_item,XeTeX_is_default_selector_code);
30851
30852 primitive("XeTeXvariationname",convert,XeTeX_variation_name_code);
30853 primitive("XeTeXfeaturename",convert,XeTeX_feature_name_code);
30854 primitive("XeTeXselectorname",convert,XeTeX_selector_name_code);
30855
30856 primitive("XeTeXOTcountscripts",last_item,XeTeX_OT_count_scripts_code);
30857 primitive("XeTeXOTcountlanguages",last_item,XeTeX_OT_count_languages_code);
30858 primitive("XeTeXOTcountfeatures",last_item,XeTeX_OT_count_features_code);
30859 primitive("XeTeXOTscripttag",last_item,XeTeX_OT_script_code);
30860 primitive("XeTeXOTlanguagetag",last_item,XeTeX_OT_language_code);
30861 primitive("XeTeXOTfeaturetag",last_item,XeTeX_OT_feature_code);
30862
30863 primitive("XeTeXcharglyph", last_item, XeTeX_map_char_to_glyph_code);
30864 primitive("XeTeXglyphindex", last_item, XeTeX_glyph_index_code);
30865 primitive("XeTeXglyphbounds", last_item, XeTeX_glyph_bounds_code);
30866
30867 primitive("XeTeXglyphname",convert,XeTeX_glyph_name_code);
30868
30869 primitive("XeTeXfonttype", last_item, XeTeX_font_type_code);
30870
30871 primitive("XeTeXfirstfontchar", last_item, XeTeX_first_char_code);
30872 primitive("XeTeXlastfontchar", last_item, XeTeX_last_char_code);
30873
30874 primitive("XeTeXpdfpagecount",last_item,XeTeX_pdf_page_count_code);
30875
30876 @ @<Cases of |last_item| for |print_cmd_chr|@>=
30877 last_node_type_code: print_esc("lastnodetype");
30878 eTeX_version_code: print_esc("eTeXversion");
30879 XeTeX_version_code: print_esc("XeTeXversion");
30880
30881 XeTeX_count_glyphs_code: print_esc("XeTeXcountglyphs");
30882
30883 XeTeX_count_variations_code: print_esc("XeTeXcountvariations");
30884 XeTeX_variation_code: print_esc("XeTeXvariation");
30885 XeTeX_find_variation_by_name_code: print_esc("XeTeXfindvariationbyname");
30886 XeTeX_variation_min_code: print_esc("XeTeXvariationmin");
30887 XeTeX_variation_max_code: print_esc("XeTeXvariationmax");
30888 XeTeX_variation_default_code: print_esc("XeTeXvariationdefault");
30889
30890 XeTeX_count_features_code: print_esc("XeTeXcountfeatures");
30891 XeTeX_feature_code_code: print_esc("XeTeXfeaturecode");
30892 XeTeX_find_feature_by_name_code: print_esc("XeTeXfindfeaturebyname");
30893 XeTeX_is_exclusive_feature_code: print_esc("XeTeXisexclusivefeature");
30894 XeTeX_count_selectors_code: print_esc("XeTeXcountselectors");
30895 XeTeX_selector_code_code: print_esc("XeTeXselectorcode");
30896 XeTeX_find_selector_by_name_code: print_esc("XeTeXfindselectorbyname");
30897 XeTeX_is_default_selector_code: print_esc("XeTeXisdefaultselector");
30898
30899 XeTeX_OT_count_scripts_code: print_esc("XeTeXOTcountscripts");
30900 XeTeX_OT_count_languages_code: print_esc("XeTeXOTcountlanguages");
30901 XeTeX_OT_count_features_code: print_esc("XeTeXOTcountfeatures");
30902 XeTeX_OT_script_code: print_esc("XeTeXOTscripttag");
30903 XeTeX_OT_language_code: print_esc("XeTeXOTlanguagetag");
30904 XeTeX_OT_feature_code: print_esc("XeTeXOTfeaturetag");
30905
30906 XeTeX_map_char_to_glyph_code: print_esc("XeTeXcharglyph");
30907 XeTeX_glyph_index_code: print_esc("XeTeXglyphindex");
30908 XeTeX_glyph_bounds_code: print_esc("XeTeXglyphbounds");
30909
30910 XeTeX_font_type_code: print_esc("XeTeXfonttype");
30911
30912 XeTeX_first_char_code: print_esc("XeTeXfirstfontchar");
30913 XeTeX_last_char_code: print_esc("XeTeXlastfontchar");
30914
30915 XeTeX_pdf_page_count_code: print_esc("XeTeXpdfpagecount");
30916
30917 @ @<Cases for fetching an integer value@>=
30918 eTeX_version_code: cur_val:=eTeX_version;
30919 XeTeX_version_code: cur_val:=XeTeX_version;
30920
30921 XeTeX_count_glyphs_code:
30922 begin
30923 scan_font_ident; n:=cur_val;
30924 if is_aat_font(n) then
30925 cur_val:=aat_font_get(m - XeTeX_int, font_layout_engine[n])
30926 else if is_otgr_font(n) then
30927 cur_val:=ot_font_get(m - XeTeX_int, font_layout_engine[n])
30928 else
30929 cur_val:=0;
30930 end;
30931
30932 XeTeX_count_features_code:
30933 begin
30934 scan_font_ident; n:=cur_val;
30935 if is_aat_font(n) then
30936 cur_val:=aat_font_get(m - XeTeX_int, font_layout_engine[n])
30937 else if is_gr_font(n) then
30938 cur_val:=ot_font_get(m - XeTeX_int, font_layout_engine[n])
30939 else
30940 cur_val:=0;
30941 end;
30942
30943 XeTeX_variation_code,
30944 XeTeX_variation_min_code,
30945 XeTeX_variation_max_code,
30946 XeTeX_variation_default_code,
30947 XeTeX_count_variations_code:
30948 begin
30949 scan_font_ident; n:=cur_val;
30950 cur_val:=0; {Deprecated}
30951 end;
30952
30953 XeTeX_feature_code_code,
30954 XeTeX_is_exclusive_feature_code,
30955 XeTeX_count_selectors_code:
30956 begin
30957 scan_font_ident; n:=cur_val;
30958 if is_aat_font(n) then begin
30959 scan_int; k:=cur_val;
30960 cur_val:=aat_font_get_1(m - XeTeX_int, font_layout_engine[n], k);
30961 end else if is_gr_font(n) then begin
30962 scan_int; k:=cur_val;
30963 cur_val:=ot_font_get_1(m - XeTeX_int, font_layout_engine[n], k);
30964 end else begin
30965 not_aat_gr_font_error(last_item, m, n); cur_val:=-1;
30966 end;
30967 end;
30968
30969 XeTeX_selector_code_code,
30970 XeTeX_is_default_selector_code:
30971 begin
30972 scan_font_ident; n:=cur_val;
30973 if is_aat_font(n) then begin
30974 scan_int; k:=cur_val; scan_int;
30975 cur_val:=aat_font_get_2(m - XeTeX_int, font_layout_engine[n], k, cur_val);
30976 end else if is_gr_font(n) then begin
30977 scan_int; k:=cur_val; scan_int;
30978 cur_val:=ot_font_get_2(m - XeTeX_int, font_layout_engine[n], k, cur_val);
30979 end else begin
30980 not_aat_gr_font_error(last_item, m, n); cur_val:=-1;
30981 end;
30982 end;
30983
30984 XeTeX_find_variation_by_name_code:
30985 begin
30986 scan_font_ident; n:=cur_val;
30987 if is_aat_font(n) then begin
30988 scan_and_pack_name;
30989 cur_val:=aat_font_get_named(m - XeTeX_int, font_layout_engine[n]);
30990 end else begin
30991 not_aat_font_error(last_item, m, n); cur_val:=-1;
30992 end;
30993 end;
30994
30995 XeTeX_find_feature_by_name_code:
30996 begin
30997 scan_font_ident; n:=cur_val;
30998 if is_aat_font(n) then begin
30999 scan_and_pack_name;
31000 cur_val:=aat_font_get_named(m - XeTeX_int, font_layout_engine[n]);
31001 end else if is_gr_font(n) then begin
31002 scan_and_pack_name;
31003 cur_val:=gr_font_get_named(m - XeTeX_int, font_layout_engine[n]);
31004 end else begin
31005 not_aat_gr_font_error(last_item, m, n); cur_val:=-1;
31006 end;
31007 end;
31008
31009 XeTeX_find_selector_by_name_code:
31010 begin
31011 scan_font_ident; n:=cur_val;
31012 if is_aat_font(n) then begin
31013 scan_int; k:=cur_val; scan_and_pack_name;
31014 cur_val:=aat_font_get_named_1(m - XeTeX_int, font_layout_engine[n], k);
31015 end else if is_gr_font(n) then begin
31016 scan_int; k:=cur_val; scan_and_pack_name;
31017 cur_val:=gr_font_get_named_1(m - XeTeX_int, font_layout_engine[n], k);
31018 end else begin
31019 not_aat_gr_font_error(last_item, m, n); cur_val:=-1;
31020 end;
31021 end;
31022
31023 XeTeX_OT_count_scripts_code:
31024 begin
31025 scan_font_ident; n:=cur_val;
31026 if is_ot_font(n) then
31027 cur_val:=ot_font_get(m - XeTeX_int, font_layout_engine[n])
31028 else begin
31029 cur_val:=0;
31030 end;
31031 end;
31032
31033 XeTeX_OT_count_languages_code,
31034 XeTeX_OT_script_code:
31035 begin
31036 scan_font_ident; n:=cur_val;
31037 if is_ot_font(n) then begin
31038 scan_int;
31039 cur_val:=ot_font_get_1(m - XeTeX_int, font_layout_engine[n], cur_val);
31040 end else begin
31041 not_ot_font_error(last_item, m, n); cur_val:=-1;
31042 end;
31043 end;
31044
31045 XeTeX_OT_count_features_code,
31046 XeTeX_OT_language_code:
31047 begin
31048 scan_font_ident; n:=cur_val;
31049 if is_ot_font(n) then begin
31050 scan_int; k:=cur_val; scan_int;
31051 cur_val:=ot_font_get_2(m - XeTeX_int, font_layout_engine[n], k, cur_val);
31052 end else begin
31053 not_ot_font_error(last_item, m, n); cur_val:=-1;
31054 end;
31055 end;
31056
31057 XeTeX_OT_feature_code:
31058 begin
31059 scan_font_ident; n:=cur_val;
31060 if is_ot_font(n) then begin
31061 scan_int; k:=cur_val; scan_int; kk:=cur_val; scan_int;
31062 cur_val:=ot_font_get_3(m - XeTeX_int, font_layout_engine[n], k, kk, cur_val);
31063 end else begin
31064 not_ot_font_error(last_item, m, n); cur_val:=-1;
31065 end;
31066 end;
31067
31068 XeTeX_map_char_to_glyph_code:
31069 begin
31070 if is_native_font(cur_font) then begin
31071 scan_int; n:=cur_val; cur_val:=map_char_to_glyph(cur_font, n)
31072 end else begin
31073 not_native_font_error(last_item, m, cur_font); cur_val:=0
31074 end
31075 end;
31076
31077 XeTeX_glyph_index_code:
31078 begin
31079 if is_native_font(cur_font) then begin
31080 scan_and_pack_name;
31081 cur_val:=map_glyph_to_index(cur_font)
31082 end else begin
31083 not_native_font_error(last_item, m, cur_font); cur_val:=0
31084 end
31085 end;
31086
31087 XeTeX_font_type_code:
31088 begin
31089 scan_font_ident; n:=cur_val;
31090 if is_aat_font(n) then cur_val:=1
31091 else if is_ot_font(n) then cur_val:=2
31092 else if is_gr_font(n) then cur_val:=3
31093 else cur_val:=0;
31094 end;
31095
31096 XeTeX_first_char_code,XeTeX_last_char_code:
31097 begin
31098 scan_font_ident; n:=cur_val;
31099 if is_native_font(n) then
31100 cur_val:=get_font_char_range(n, m = XeTeX_first_char_code)
31101 else begin
31102 if m = XeTeX_first_char_code then cur_val:=font_bc[n]
31103 else cur_val:=font_ec[n];
31104 end
31105 end;
31106
31107 pdf_last_x_pos_code: cur_val:=pdf_last_x_pos;
31108 pdf_last_y_pos_code: cur_val:=pdf_last_y_pos;
31109
31110 XeTeX_pdf_page_count_code:
31111 begin
31112 scan_and_pack_name;
31113 cur_val:=count_pdf_file_pages;
31114 end;
31115
31116 @ Slip in an extra procedure here and there....
31117
31118 @<Error hand...@>=
31119 procedure scan_and_pack_name; forward;
31120
31121 @ @<Declare procedures needed in |do_extension|@>=
31122 procedure scan_and_pack_name;
31123 begin
31124 scan_file_name; pack_cur_name;
31125 end;
31126
31127 @ @<Declare the procedure called |print_cmd_chr|@>=
31128 procedure not_aat_font_error(cmd, c: integer; f: integer);
31129 begin
31130 print_err("Cannot use "); print_cmd_chr(cmd, c);
31131 print(" with "); print(font_name[f]);
31132 print("; not an AAT font");
31133 error;
31134 end;
31135
31136 procedure not_aat_gr_font_error(cmd, c: integer; f: integer);
31137 begin
31138 print_err("Cannot use "); print_cmd_chr(cmd, c);
31139 print(" with "); print(font_name[f]);
31140 print("; not an AAT or Graphite font");
31141 error;
31142 end;
31143
31144 procedure not_ot_font_error(cmd, c: integer; f: integer);
31145 begin
31146 print_err("Cannot use "); print_cmd_chr(cmd, c);
31147 print(" with "); print(font_name[f]);
31148 print("; not an OpenType Layout font");
31149 error;
31150 end;
31151
31152 procedure not_native_font_error(cmd, c: integer; f: integer);
31153 begin
31154 print_err("Cannot use "); print_cmd_chr(cmd, c);
31155 print(" with "); print(font_name[f]);
31156 print("; not a native platform font");
31157 error;
31158 end;
31159
31160 @ @<Cases for fetching a dimension value@>=
31161 XeTeX_glyph_bounds_code:
31162 begin
31163 if is_native_font(cur_font) then begin
31164 scan_int; n:=cur_val; { which edge: 1=left, 2=top, 3=right, 4=bottom }
31165 if (n < 1) or (n > 4) then begin
31166 print_err("\\XeTeXglyphbounds requires an edge index from 1 to 4;");
31167 print_nl("I don't know anything about edge "); print_int(n);
31168 error;
31169 cur_val:=0;
31170 end else begin
31171 scan_int; { glyph number }
31172 cur_val:=get_glyph_bounds(cur_font, n, cur_val);
31173 end
31174 end else begin
31175 not_native_font_error(last_item, m, cur_font); cur_val:=0
31176 end
31177 end;
31178
31179 @ @<Cases of |convert| for |print_cmd_chr|@>=
31180 XeTeX_revision_code: print_esc("XeTeXrevision");
31181
31182 XeTeX_variation_name_code: print_esc("XeTeXvariationname");
31183 XeTeX_feature_name_code: print_esc("XeTeXfeaturename");
31184 XeTeX_selector_name_code: print_esc("XeTeXselectorname");
31185 XeTeX_glyph_name_code: print_esc("XeTeXglyphname");
31186
31187 XeTeX_Uchar_code: print_esc("Uchar");
31188 XeTeX_Ucharcat_code: print_esc("Ucharcat");
31189
31190 @ @<Cases of `Scan the argument for command |c|'@>=
31191 XeTeX_revision_code: do_nothing;
31192
31193 XeTeX_variation_name_code:
31194 begin
31195 scan_font_ident; fnt:=cur_val;
31196 if is_aat_font(fnt) then begin
31197 scan_int; arg1:=cur_val; arg2:=0;
31198 end else
31199 not_aat_font_error(convert, c, fnt);
31200 end;
31201
31202 XeTeX_feature_name_code:
31203 begin
31204 scan_font_ident; fnt:=cur_val;
31205 if is_aat_font(fnt) or is_gr_font(fnt) then begin
31206 scan_int; arg1:=cur_val; arg2:=0;
31207 end else
31208 not_aat_gr_font_error(convert, c, fnt);
31209 end;
31210
31211 XeTeX_selector_name_code:
31212 begin
31213 scan_font_ident; fnt:=cur_val;
31214 if is_aat_font(fnt) or is_gr_font(fnt) then begin
31215 scan_int; arg1:=cur_val; scan_int; arg2:=cur_val;
31216 end else
31217 not_aat_gr_font_error(convert, c, fnt);
31218 end;
31219
31220 XeTeX_glyph_name_code:
31221 begin
31222 scan_font_ident; fnt:=cur_val;
31223 if is_native_font(fnt) then begin
31224 scan_int; arg1:=cur_val;
31225 end else
31226 not_native_font_error(convert, c, fnt);
31227 end;
31228
31229 @ @<Cases of `Print the result of command |c|'@>=
31230 XeTeX_revision_code: print(XeTeX_revision);
31231
31232 XeTeX_variation_name_code:
31233 if is_aat_font(fnt) then
31234 aat_print_font_name(c, font_layout_engine[fnt], arg1, arg2);
31235
31236 XeTeX_feature_name_code,
31237 XeTeX_selector_name_code:
31238 if is_aat_font(fnt) then
31239 aat_print_font_name(c, font_layout_engine[fnt], arg1, arg2)
31240 else if is_gr_font(fnt) then
31241 gr_print_font_name(c, font_layout_engine[fnt], arg1, arg2);
31242
31243 XeTeX_glyph_name_code:
31244 if is_native_font(fnt) then print_glyph_name(fnt, arg1);
31245
31246 @ @d eTeX_ex==(eTeX_mode=1) {is this extended mode?}
31247
31248 @<Glob...@>=
31249 @!eTeX_mode: 0..1; {identifies compatibility and extended mode}
31250
31251 @ @<Initialize table entries...@>=
31252 eTeX_mode:=0; {initially we are in compatibility mode}
31253 @<Initialize variables for \eTeX\ compatibility mode@>@;
31254
31255 @ @<Dump the \eTeX\ state@>=
31256 dump_int(eTeX_mode);
31257 { in a deliberate change from e-TeX, we allow non-zero state variables to be dumped }
31258
31259 @ @<Undump the \eTeX\ state@>=
31260 undump(0)(1)(eTeX_mode);
31261 if eTeX_ex then
31262 begin @<Initialize variables for \eTeX\ extended mode@>@;
31263 end
31264 else begin @<Initialize variables for \eTeX\ compatibility mode@>@;
31265 end;
31266
31267 @ The |eTeX_enabled| function simply returns its first argument as
31268 result. This argument is |true| if an optional \eTeX\ feature is
31269 currently enabled; otherwise, if the argument is |false|, the function
31270 gives an error message.
31271
31272 @<Declare \eTeX\ procedures for use...@>=
31273 function eTeX_enabled(@!b:boolean;@!j:quarterword;@!k:halfword):boolean;
31274 begin if not b then
31275 begin print_err("Improper "); print_cmd_chr(j,k);
31276 help1("Sorry, this optional e-TeX feature has been disabled."); error;
31277 end;
31278 eTeX_enabled:=b;
31279 end;
31280
31281 @ First we implement the additional \eTeX\ parameters in the table of
31282 equivalents.
31283
31284 @<Generate all \eTeX...@>=
31285 primitive("everyeof",assign_toks,every_eof_loc);
31286 @!@:every_eof_}{\.{\\everyeof} primitive@>
31287 primitive("tracingassigns",assign_int,int_base+tracing_assigns_code);@/
31288 @!@:tracing_assigns_}{\.{\\tracingassigns} primitive@>
31289 primitive("tracinggroups",assign_int,int_base+tracing_groups_code);@/
31290 @!@:tracing_groups_}{\.{\\tracinggroups} primitive@>
31291 primitive("tracingifs",assign_int,int_base+tracing_ifs_code);@/
31292 @!@:tracing_ifs_}{\.{\\tracingifs} primitive@>
31293 primitive("tracingscantokens",assign_int,int_base+tracing_scan_tokens_code);@/
31294 @!@:tracing_scan_tokens_}{\.{\\tracingscantokens} primitive@>
31295 primitive("tracingnesting",assign_int,int_base+tracing_nesting_code);@/
31296 @!@:tracing_nesting_}{\.{\\tracingnesting} primitive@>
31297 primitive("predisplaydirection",
31298 assign_int,int_base+pre_display_direction_code);@/
31299 @!@:pre_display_direction_}{\.{\\predisplaydirection} primitive@>
31300 primitive("lastlinefit",assign_int,int_base+last_line_fit_code);@/
31301 @!@:last_line_fit_}{\.{\\lastlinefit} primitive@>
31302 primitive("savingvdiscards",assign_int,int_base+saving_vdiscards_code);@/
31303 @!@:saving_vdiscards_}{\.{\\savingvdiscards} primitive@>
31304 primitive("savinghyphcodes",assign_int,int_base+saving_hyph_codes_code);@/
31305 @!@:saving_hyph_codes_}{\.{\\savinghyphcodes} primitive@>
31306 primitive("ignoreprimitiveerror",assign_int,int_base+ignore_primitive_error_code);@/
31307 @!@:ignore_primitive_error_}{\.{\\ignoreprimitiveerror} primitive@>
31308
31309 @ @d every_eof==equiv(every_eof_loc)
31310
31311 @<Cases of |assign_toks| for |print_cmd_chr|@>=
31312 every_eof_loc: print_esc("everyeof");
31313 XeTeX_inter_char_loc: print_esc("XeTeXinterchartoks");
31314
31315 @ @<Cases for |print_param|@>=
31316 tracing_assigns_code:print_esc("tracingassigns");
31317 tracing_groups_code:print_esc("tracinggroups");
31318 tracing_ifs_code:print_esc("tracingifs");
31319 tracing_scan_tokens_code:print_esc("tracingscantokens");
31320 tracing_nesting_code:print_esc("tracingnesting");
31321 pre_display_direction_code:print_esc("predisplaydirection");
31322 last_line_fit_code:print_esc("lastlinefit");
31323 saving_vdiscards_code:print_esc("savingvdiscards");
31324 saving_hyph_codes_code:print_esc("savinghyphcodes");
31325 ignore_primitive_error_code:print_esc("ignoreprimitiveerror");
31326
31327 @ In order to handle \.{\\everyeof} we need an array |eof_seen| of
31328 boolean variables.
31329
31330 @<Glob...@>=
31331 @!eof_seen : array[1..max_in_open] of boolean; {has eof been seen?}
31332
31333 @ The |print_group| procedure prints the current level of grouping and
31334 the name corresponding to |cur_group|.
31335
31336 @<Declare \eTeX\ procedures for tr...@>=
31337 procedure print_group(@!e:boolean);
31338 label exit;
31339 begin case cur_group of
31340 bottom_level: begin print("bottom level"); return;
31341 end;
31342 simple_group,semi_simple_group:
31343 begin if cur_group=semi_simple_group then print("semi ");
31344 print("simple");
31345 end;
31346 hbox_group,adjusted_hbox_group:
31347 begin if cur_group=adjusted_hbox_group then print("adjusted ");
31348 print("hbox");
31349 end;
31350 vbox_group: print("vbox");
31351 vtop_group: print("vtop");
31352 align_group,no_align_group:
31353 begin if cur_group=no_align_group then print("no ");
31354 print("align");
31355 end;
31356 output_group: print("output");
31357 disc_group: print("disc");
31358 insert_group: print("insert");
31359 vcenter_group: print("vcenter");
31360 math_group,math_choice_group,math_shift_group,math_left_group:
31361 begin print("math");
31362 if cur_group=math_choice_group then print(" choice")
31363 else if cur_group=math_shift_group then print(" shift")
31364 else if cur_group=math_left_group then print(" left");
31365 end;
31366 end; {there are no other cases}
31367 print(" group (level "); print_int(qo(cur_level)); print_char(")");
31368 if saved(-1)<>0 then
31369 begin if e then print(" entered at line ") else print(" at line ");
31370 print_int(saved(-1));
31371 end;
31372 exit:end;
31373
31374 @ The |group_trace| procedure is called when a new level of grouping
31375 begins (|e=false|) or ends (|e=true|) with |saved(-1)| containing the
31376 line number.
31377
31378 @<Declare \eTeX\ procedures for tr...@>=
31379 @!stat procedure group_trace(@!e:boolean);
31380 begin begin_diagnostic; print_char("{");
31381 if e then print("leaving ") else print("entering ");
31382 print_group(e); print_char("}"); end_diagnostic(false);
31383 end;
31384 tats
31385
31386 @ The \.{\\currentgrouplevel} and \.{\\currentgrouptype} commands return
31387 the current level of grouping and the type of the current group
31388 respectively.
31389
31390 @d current_group_level_code=eTeX_int+1 {code for \.{\\currentgrouplevel}}
31391 @d current_group_type_code=eTeX_int+2 {code for \.{\\currentgrouptype}}
31392
31393 @<Generate all \eTeX...@>=
31394 primitive("currentgrouplevel",last_item,current_group_level_code);
31395 @!@:current_group_level_}{\.{\\currentgrouplevel} primitive@>
31396 primitive("currentgrouptype",last_item,current_group_type_code);
31397 @!@:current_group_type_}{\.{\\currentgrouptype} primitive@>
31398
31399 @ @<Cases of |last_item| for |print_cmd_chr|@>=
31400 current_group_level_code: print_esc("currentgrouplevel");
31401 current_group_type_code: print_esc("currentgrouptype");
31402
31403 @ @<Cases for fetching an integer value@>=
31404 current_group_level_code: cur_val:=cur_level-level_one;
31405 current_group_type_code: cur_val:=cur_group;
31406
31407 @ The \.{\\currentiflevel}, \.{\\currentiftype}, and
31408 \.{\\currentifbranch} commands return the current level of conditionals
31409 and the type and branch of the current conditional.
31410
31411 @d current_if_level_code=eTeX_int+3 {code for \.{\\currentiflevel}}
31412 @d current_if_type_code=eTeX_int+4 {code for \.{\\currentiftype}}
31413 @d current_if_branch_code=eTeX_int+5 {code for \.{\\currentifbranch}}
31414
31415 @<Generate all \eTeX...@>=
31416 primitive("currentiflevel",last_item,current_if_level_code);
31417 @!@:current_if_level_}{\.{\\currentiflevel} primitive@>
31418 primitive("currentiftype",last_item,current_if_type_code);
31419 @!@:current_if_type_}{\.{\\currentiftype} primitive@>
31420 primitive("currentifbranch",last_item,current_if_branch_code);
31421 @!@:current_if_branch_}{\.{\\currentifbranch} primitive@>
31422
31423 @ @<Cases of |last_item| for |print_cmd_chr|@>=
31424 current_if_level_code: print_esc("currentiflevel");
31425 current_if_type_code: print_esc("currentiftype");
31426 current_if_branch_code: print_esc("currentifbranch");
31427
31428 @ @<Cases for fetching an integer value@>=
31429 current_if_level_code: begin q:=cond_ptr; cur_val:=0;
31430 while q<>null do
31431 begin incr(cur_val); q:=link(q);
31432 end;
31433 end;
31434 current_if_type_code: if cond_ptr=null then cur_val:=0
31435 else if cur_if<unless_code then cur_val:=cur_if+1
31436 else cur_val:=-(cur_if-unless_code+1);
31437 current_if_branch_code:
31438 if (if_limit=or_code)or(if_limit=else_code) then cur_val:=1
31439 else if if_limit=fi_code then cur_val:=-1
31440 else cur_val:=0;
31441
31442 @ The \.{\\fontcharwd}, \.{\\fontcharht}, \.{\\fontchardp}, and
31443 \.{\\fontcharic} commands return information about a character in a
31444 font.
31445
31446 @d font_char_wd_code=eTeX_dim {code for \.{\\fontcharwd}}
31447 @d font_char_ht_code=eTeX_dim+1 {code for \.{\\fontcharht}}
31448 @d font_char_dp_code=eTeX_dim+2 {code for \.{\\fontchardp}}
31449 @d font_char_ic_code=eTeX_dim+3 {code for \.{\\fontcharic}}
31450
31451 @<Generate all \eTeX...@>=
31452 primitive("fontcharwd",last_item,font_char_wd_code);
31453 @!@:font_char_wd_}{\.{\\fontcharwd} primitive@>
31454 primitive("fontcharht",last_item,font_char_ht_code);
31455 @!@:font_char_ht_}{\.{\\fontcharht} primitive@>
31456 primitive("fontchardp",last_item,font_char_dp_code);
31457 @!@:font_char_dp_}{\.{\\fontchardp} primitive@>
31458 primitive("fontcharic",last_item,font_char_ic_code);
31459 @!@:font_char_ic_}{\.{\\fontcharic} primitive@>
31460
31461 @ @<Cases of |last_item| for |print_cmd_chr|@>=
31462 font_char_wd_code: print_esc("fontcharwd");
31463 font_char_ht_code: print_esc("fontcharht");
31464 font_char_dp_code: print_esc("fontchardp");
31465 font_char_ic_code: print_esc("fontcharic");
31466
31467 @ @<Cases for fetching a dimension value@>=
31468 font_char_wd_code,
31469 font_char_ht_code,
31470 font_char_dp_code,
31471 font_char_ic_code: begin scan_font_ident; q:=cur_val; scan_usv_num;
31472 if is_native_font(q) then begin
31473 case m of
31474 font_char_wd_code: cur_val:=getnativecharwd(q, cur_val);
31475 font_char_ht_code: cur_val:=getnativecharht(q, cur_val);
31476 font_char_dp_code: cur_val:=getnativechardp(q, cur_val);
31477 font_char_ic_code: cur_val:=getnativecharic(q, cur_val);
31478 end; {there are no other cases}
31479 end else begin
31480 if (font_bc[q]<=cur_val)and(font_ec[q]>=cur_val) then
31481 begin i:=char_info(q)(qi(cur_val));
31482 case m of
31483 font_char_wd_code: cur_val:=char_width(q)(i);
31484 font_char_ht_code: cur_val:=char_height(q)(height_depth(i));
31485 font_char_dp_code: cur_val:=char_depth(q)(height_depth(i));
31486 font_char_ic_code: cur_val:=char_italic(q)(i);
31487 end; {there are no other cases}
31488 end
31489 else cur_val:=0;
31490 end
31491 end;
31492
31493 @ The \.{\\parshapedimen}, \.{\\parshapeindent}, and \.{\\parshapelength}
31494 commands return the indent and length parameters of the current
31495 \.{\\parshape} specification.
31496
31497 @d par_shape_length_code=eTeX_dim+4 {code for \.{\\parshapelength}}
31498 @d par_shape_indent_code=eTeX_dim+5 {code for \.{\\parshapeindent}}
31499 @d par_shape_dimen_code=eTeX_dim+6 {code for \.{\\parshapedimen}}
31500
31501 @<Generate all \eTeX...@>=
31502 primitive("parshapelength",last_item,par_shape_length_code);
31503 @!@:par_shape_length_}{\.{\\parshapelength} primitive@>
31504 primitive("parshapeindent",last_item,par_shape_indent_code);
31505 @!@:par_shape_indent_}{\.{\\parshapeindent} primitive@>
31506 primitive("parshapedimen",last_item,par_shape_dimen_code);
31507 @!@:par_shape_dimen_}{\.{\\parshapedimen} primitive@>
31508
31509 @ @<Cases of |last_item| for |print_cmd_chr|@>=
31510 par_shape_length_code: print_esc("parshapelength");
31511 par_shape_indent_code: print_esc("parshapeindent");
31512 par_shape_dimen_code: print_esc("parshapedimen");
31513
31514 @ @<Cases for fetching a dimension value@>=
31515 par_shape_length_code,
31516 par_shape_indent_code,
31517 par_shape_dimen_code: begin q:=cur_chr-par_shape_length_code; scan_int;
31518 if (par_shape_ptr=null)or(cur_val<=0) then cur_val:=0
31519 else begin if q=2 then
31520 begin q:=cur_val mod 2; cur_val:=(cur_val+q)div 2;
31521 end;
31522 if cur_val>info(par_shape_ptr) then cur_val:=info(par_shape_ptr);
31523 cur_val:=mem[par_shape_ptr+2*cur_val-q].sc;
31524 end;
31525 cur_val_level:=dimen_val;
31526 end;
31527
31528 @ The \.{\\showgroups} command displays all currently active grouping
31529 levels.
31530
31531 @d show_groups=4 { \.{\\showgroups} }
31532
31533 @<Generate all \eTeX...@>=
31534 primitive("showgroups",xray,show_groups);
31535 @!@:show_groups_}{\.{\\showgroups} primitive@>
31536
31537 @ @<Cases of |xray| for |print_cmd_chr|@>=
31538 show_groups:print_esc("showgroups");
31539
31540 @ @<Cases for |show_whatever|@>=
31541 show_groups: begin begin_diagnostic; show_save_groups;
31542 end;
31543
31544 @ @<Types...@>=
31545 @!save_pointer=0..save_size; {index into |save_stack|}
31546
31547 @ The modifications of \TeX\ required for the display produced by the
31548 |show_save_groups| procedure were first discussed by Donald~E. Knuth in
31549 {\sl TUGboat\/} {\bf 11}, 165--170 and 499--511, 1990.
31550 @^Knuth, Donald Ervin@>
31551
31552 In order to understand a group type we also have to know its mode.
31553 Since unrestricted horizontal modes are not associated with grouping,
31554 they are skipped when traversing the semantic nest.
31555
31556 @<Declare \eTeX\ procedures for use...@>=
31557 procedure show_save_groups;
31558 label found1,found2,found,done;
31559 var p:0..nest_size; {index into |nest|}
31560 @!m:-mmode..mmode; {mode}
31561 @!v:save_pointer; {saved value of |save_ptr|}
31562 @!l:quarterword; {saved value of |cur_level|}
31563 @!c:group_code; {saved value of |cur_group|}
31564 @!a:-1..1; {to keep track of alignments}
31565 @!i:integer;
31566 @!j:quarterword;
31567 @!s:str_number;
31568 begin p:=nest_ptr; nest[p]:=cur_list; {put the top level into the array}
31569 v:=save_ptr; l:=cur_level; c:=cur_group;
31570 save_ptr:=cur_boundary; decr(cur_level);@/
31571 a:=1;
31572 print_nl(""); print_ln;
31573 loop@+begin print_nl("### "); print_group(true);
31574 if cur_group=bottom_level then goto done;
31575 repeat m:=nest[p].mode_field;
31576 if p>0 then decr(p) else m:=vmode;
31577 until m<>hmode;
31578 print(" (");
31579 case cur_group of
31580 simple_group: begin incr(p); goto found2;
31581 end;
31582 hbox_group,adjusted_hbox_group: s:="hbox";
31583 vbox_group: s:="vbox";
31584 vtop_group: s:="vtop";
31585 align_group: if a=0 then
31586 begin if m=-vmode then s:="halign" else s:="valign";
31587 a:=1; goto found1;
31588 end
31589 else begin if a=1 then print("align entry") else print_esc("cr");
31590 if p>=a then p:=p-a;
31591 a:=0; goto found;
31592 end;
31593 no_align_group:
31594 begin incr(p); a:=-1; print_esc("noalign"); goto found2;
31595 end;
31596 output_group:
31597 begin print_esc("output"); goto found;
31598 end;
31599 math_group: goto found2;
31600 disc_group,math_choice_group:
31601 begin if cur_group=disc_group then print_esc("discretionary")
31602 else print_esc("mathchoice");
31603 for i:=1 to 3 do if i<=saved(-2) then print("{}");
31604 goto found2;
31605 end;
31606 insert_group:
31607 begin if saved(-2)=255 then print_esc("vadjust")
31608 else begin print_esc("insert"); print_int(saved(-2));
31609 end;
31610 goto found2;
31611 end;
31612 vcenter_group: begin s:="vcenter"; goto found1;
31613 end;
31614 semi_simple_group: begin incr(p); print_esc("begingroup"); goto found;
31615 end;
31616 math_shift_group:
31617 begin if m=mmode then print_char("$")
31618 else if nest[p].mode_field=mmode then
31619 begin print_cmd_chr(eq_no,saved(-2)); goto found;
31620 end;
31621 print_char("$"); goto found;
31622 end;
31623 math_left_group:
31624 begin if type(nest[p+1].eTeX_aux_field)=left_noad then print_esc("left")
31625 else print_esc("middle");
31626 goto found;
31627 end;
31628 end; {there are no other cases}
31629 @<Show the box context@>;
31630 found1: print_esc(s); @<Show the box packaging info@>;
31631 found2: print_char("{");
31632 found: print_char(")"); decr(cur_level);
31633 cur_group:=save_level(save_ptr); save_ptr:=save_index(save_ptr)
31634 end;
31635 done: save_ptr:=v; cur_level:=l; cur_group:=c;
31636 end;
31637
31638 @ @<Show the box packaging info@>=
31639 if saved(-2)<>0 then
31640 begin print_char(" ");
31641 if saved(-3)=exactly then print("to") else print("spread");
31642 print_scaled(saved(-2)); print("pt");
31643 end
31644
31645 @ @<Show the box context@>=
31646 i:=saved(-4);
31647 if i<>0 then
31648 if i<box_flag then
31649 begin if abs(nest[p].mode_field)=vmode then j:=hmove else j:=vmove;
31650 if i>0 then print_cmd_chr(j,0) else print_cmd_chr(j,1);
31651 print_scaled(abs(i)); print("pt");
31652 end
31653 else if i<ship_out_flag then
31654 begin if i>=global_box_flag then
31655 begin print_esc("global"); i:=i-(global_box_flag-box_flag);
31656 end;
31657 print_esc("setbox"); print_int(i-box_flag); print_char("=");
31658 end
31659 else print_cmd_chr(leader_ship,i-(leader_flag-a_leaders))
31660
31661 @ The |scan_general_text| procedure is much like |scan_toks(false,false)|,
31662 but will be invoked via |expand|, i.e., recursively.
31663 @^recursion@>
31664
31665 @<Declare \eTeX\ procedures for sc...@>=
31666 procedure@?scan_general_text; forward;@t\2@>
31667
31668 @ The token list (balanced text) created by |scan_general_text| begins
31669 at |link(temp_head)| and ends at |cur_val|. (If |cur_val=temp_head|,
31670 the list is empty.)
31671
31672 @<Declare \eTeX\ procedures for tok...@>=
31673 procedure scan_general_text;
31674 label found;
31675 var s:normal..absorbing; {to save |scanner_status|}
31676 @!w:pointer; {to save |warning_index|}
31677 @!d:pointer; {to save |def_ref|}
31678 @!p:pointer; {tail of the token list being built}
31679 @!q:pointer; {new node being added to the token list via |store_new_token|}
31680 @!unbalance:halfword; {number of unmatched left braces}
31681 begin s:=scanner_status; w:=warning_index; d:=def_ref;
31682 scanner_status:=absorbing; warning_index:=cur_cs;
31683 def_ref:=get_avail; token_ref_count(def_ref):=null; p:=def_ref;
31684 scan_left_brace; {remove the compulsory left brace}
31685 unbalance:=1;
31686 loop@+ begin get_token;
31687 if cur_tok<right_brace_limit then
31688 if cur_cmd<right_brace then incr(unbalance)
31689 else begin decr(unbalance);
31690 if unbalance=0 then goto found;
31691 end;
31692 store_new_token(cur_tok);
31693 end;
31694 found: q:=link(def_ref); free_avail(def_ref); {discard reference count}
31695 if q=null then cur_val:=temp_head @+ else cur_val:=p;
31696 link(temp_head):=q;
31697 scanner_status:=s; warning_index:=w; def_ref:=d;
31698 end;
31699
31700 @ The \.{\\showtokens} command displays a token list.
31701
31702 @d show_tokens=5 { \.{\\showtokens} , must be odd! }
31703
31704 @<Generate all \eTeX...@>=
31705 primitive("showtokens",xray,show_tokens);
31706 @!@:show_tokens_}{\.{\\showtokens} primitive@>
31707
31708 @ @<Cases of |xray| for |print_cmd_chr|@>=
31709 show_tokens:print_esc("showtokens");
31710
31711 @ The \.{\\unexpanded} primitive prevents expansion of tokens much as
31712 the result from \.{\\the} applied to a token variable. The
31713 \.{\\detokenize} primitive converts a token list into a list of
31714 character tokens much as if the token list were written to a file. We
31715 use the fact that the command modifiers for \.{\\unexpanded} and
31716 \.{\\detokenize} are odd whereas those for \.{\\the} and \.{\\showthe}
31717 are even.
31718
31719 @<Generate all \eTeX...@>=
31720 primitive("unexpanded",the,1);@/
31721 @!@:unexpanded_}{\.{\\unexpanded} primitive@>
31722 primitive("detokenize",the,show_tokens);@/
31723 @!@:detokenize_}{\.{\\detokenize} primitive@>
31724
31725 @ @<Cases of |the| for |print_cmd_chr|@>=
31726 else if chr_code=1 then print_esc("unexpanded")
31727 else print_esc("detokenize")
31728
31729 @ @<Handle \.{\\unexpanded} or \.{\\detokenize} and |return|@>=
31730 if odd(cur_chr) then
31731 begin c:=cur_chr; scan_general_text;
31732 if c=1 then the_toks:=cur_val
31733 else begin old_setting:=selector; selector:=new_string; b:=pool_ptr;
31734 p:=get_avail; link(p):=link(temp_head);
31735 token_show(p); flush_list(p);
31736 selector:=old_setting; the_toks:=str_toks(b);
31737 end;
31738 return;
31739 end
31740
31741 @ The \.{\\showifs} command displays all currently active conditionals.
31742
31743 @d show_ifs=6 { \.{\\showifs} }
31744
31745 @<Generate all \eTeX...@>=
31746 primitive("showifs",xray,show_ifs);
31747 @!@:show_ifs_}{\.{\\showifs} primitive@>
31748
31749 @ @<Cases of |xray| for |print_cmd_chr|@>=
31750 show_ifs:print_esc("showifs");
31751
31752 @
31753 @d print_if_line(#)==if #<>0 then
31754 begin print(" entered on line "); print_int(#);
31755 end
31756
31757 @<Cases for |show_whatever|@>=
31758 show_ifs: begin begin_diagnostic; print_nl(""); print_ln;
31759 if cond_ptr=null then
31760 begin print_nl("### "); print("no active conditionals");
31761 end
31762 else begin p:=cond_ptr; n:=0;
31763 repeat incr(n); p:=link(p);@+until p=null;
31764 p:=cond_ptr; t:=cur_if; l:=if_line; m:=if_limit;
31765 repeat print_nl("### level "); print_int(n); print(": ");
31766 print_cmd_chr(if_test,t);
31767 if m=fi_code then print_esc("else");
31768 print_if_line(l);
31769 decr(n); t:=subtype(p); l:=if_line_field(p); m:=type(p); p:=link(p);
31770 until p=null;
31771 end;
31772 end;
31773
31774 @ The \.{\\interactionmode} primitive allows to query and set the
31775 interaction mode.
31776
31777 @<Generate all \eTeX...@>=
31778 primitive("interactionmode",set_page_int,2);
31779 @!@:interaction_mode_}{\.{\\interactionmode} primitive@>
31780
31781 @ @<Cases of |set_page_int| for |print_cmd_chr|@>=
31782 else if chr_code=2 then print_esc("interactionmode")
31783
31784 @ @<Cases for `Fetch the |dead_cycles| or the |insert_penalties|'@>=
31785 else if m=2 then cur_val:=interaction
31786
31787 @ @<Declare \eTeX\ procedures for use...@>=
31788 procedure@?new_interaction; forward;@t\2@>
31789
31790 @ @<Cases for |alter_integer|@>=
31791 else if c=2 then
31792 begin if (cur_val<batch_mode)or(cur_val>error_stop_mode) then
31793 begin print_err("Bad interaction mode");
31794 @.Bad interaction mode@>
31795 help2("Modes are 0=batch, 1=nonstop, 2=scroll, and")@/
31796 ("3=errorstop. Proceed, and I'll ignore this case.");
31797 int_error(cur_val);
31798 end
31799 else begin cur_chr:=cur_val; new_interaction;
31800 end;
31801 end
31802
31803 @ The |middle| feature of \eTeX\ allows one ore several \.{\\middle}
31804 delimiters to appear between \.{\\left} and \.{\\right}.
31805
31806 @<Generate all \eTeX...@>=
31807 primitive("middle",left_right,middle_noad);
31808 @!@:middle_}{\.{\\middle} primitive@>
31809
31810 @ @<Cases of |left_right| for |print_cmd_chr|@>=
31811 else if chr_code=middle_noad then print_esc("middle")
31812
31813 @ In constructions such as
31814 $$\vbox{\halign{\.{#}\hfil\cr
31815 {}\\hbox to \\hsize\{\cr
31816 \hskip 25pt \\hskip 0pt plus 0.0001fil\cr
31817 \hskip 25pt ...\cr
31818 \hskip 25pt \\hfil\\penalty-200\\hfilneg\cr
31819 \hskip 25pt ...\}\cr}}$$
31820 the stretch components of \.{\\hfil} and \.{\\hfilneg} compensate; they may,
31821 however, get modified in order to prevent arithmetic overflow during
31822 |hlist_out| when each of them is multiplied by a large |glue_set| value.
31823
31824 Since this ``glue rounding'' depends on state variables |cur_g| and
31825 |cur_glue| and \TeXXeT\ is supposed to emulate the behaviour of \TeXeT\
31826 (plus a suitable postprocessor) as close as possible the glue rounding
31827 cannot be postponed until (segments of) an hlist has been reversed.
31828
31829 The code below is invoked after the effective width, |rule_wd|, of a glue
31830 node has been computed. The glue node is either converted into a kern node
31831 or, for leaders, the glue specification is replaced by an equivalent rigid
31832 one; the subtype of the glue node remains unchanged.
31833
31834 @<Handle a glue node for mixed...@>=
31835 if (((g_sign=stretching) and (stretch_order(g)=g_order)) or
31836 ((g_sign=shrinking) and (shrink_order(g)=g_order))) then
31837 begin fast_delete_glue_ref(g);
31838 if subtype(p)<a_leaders then
31839 begin type(p):=kern_node; width(p):=rule_wd;
31840 end
31841 else begin g:=get_node(glue_spec_size);@/
31842 stretch_order(g):=filll+1; shrink_order(g):=filll+1; {will never match}
31843 width(g):=rule_wd; stretch(g):=0; shrink(g):=0; glue_ptr(p):=g;
31844 end;
31845 end
31846
31847 @ The optional |TeXXeT| feature of \eTeX\ contains the code for mixed
31848 left-to-right and right-to-left typesetting. This code is inspired by
31849 but different from \TeXeT\ as presented by Donald~E. Knuth and Pierre
31850 MacKay in {\sl TUGboat\/} {\bf 8}, 14--25, 1987.
31851 @^Knuth, Donald Ervin@>
31852 @^MacKay, Pierre@>
31853
31854 In order to avoid confusion with \TeXeT\ the present implementation of
31855 mixed direction typesetting is called \TeXXeT. It differs from \TeXeT\
31856 in several important aspects: (1)~Right-to-left text is reversed
31857 explicitly by the |ship_out| routine and is written to a normal \.{DVI}
31858 file without any |begin_reflect| or |end_reflect| commands; (2)~a
31859 |math_node| is (ab)used instead of a |whatsit_node| to record the
31860 \.{\\beginL}, \.{\\endL}, \.{\\beginR}, and \.{\\endR} text direction
31861 primitives in order to keep the influence on the line breaking algorithm
31862 for pure left-to-right text as small as possible; (3)~right-to-left text
31863 interrupted by a displayed equation is automatically resumed after that
31864 equation; and (4)~the |valign| command code with a non-zero command
31865 modifier is (ab)used for the text direction primitives.
31866
31867 Nevertheless there is a subtle difference between \TeX\ and \TeXXeT\
31868 that may influence the line breaking algorithm for pure left-to-right
31869 text. When a paragraph containing math mode material is broken into
31870 lines \TeX\ may generate lines where math mode material is not enclosed
31871 by properly nested \.{\\mathon} and \.{\\mathoff} nodes. Unboxing such
31872 lines as part of a new paragraph may have the effect that hyphenation is
31873 attempted for `words' originating from math mode or that hyphenation is
31874 inhibited for words originating from horizontal mode.
31875
31876 In \TeXXeT\ additional \.{\\beginM}, resp.\ \.{\\endM} math nodes are
31877 supplied at the start, resp.\ end of lines such that math mode material
31878 inside a horizontal list always starts with either \.{\\mathon} or
31879 \.{\\beginM} and ends with \.{\\mathoff} or \.{\\endM}. These
31880 additional nodes are transparent to operations such as \.{\\unskip},
31881 \.{\\lastpenalty}, or \.{\\lastbox} but they do have the effect that
31882 hyphenation is never attempted for `words' originating from math mode
31883 and is never inhibited for words originating from horizontal mode.
31884
31885 @d TeXXeT_state==eTeX_state(TeXXeT_code)
31886 @d TeXXeT_en==(TeXXeT_state>0) {is \TeXXeT\ enabled?}
31887
31888 @d XeTeX_upwards_state==eTeX_state(XeTeX_upwards_code)
31889 @d XeTeX_upwards==(XeTeX_upwards_state>0)
31890
31891 @d XeTeX_use_glyph_metrics_state==eTeX_state(XeTeX_use_glyph_metrics_code)
31892 @d XeTeX_use_glyph_metrics==(XeTeX_use_glyph_metrics_state>0)
31893
31894 @d XeTeX_inter_char_tokens_state==eTeX_state(XeTeX_inter_char_tokens_code)
31895 @d XeTeX_inter_char_tokens_en==(XeTeX_inter_char_tokens_state>0)
31896
31897 @d XeTeX_dash_break_state == eTeX_state(XeTeX_dash_break_code)
31898 @d XeTeX_dash_break_en == (XeTeX_dash_break_state>0)
31899
31900 @d XeTeX_input_normalization_state == eTeX_state(XeTeX_input_normalization_code)
31901 @d XeTeX_tracing_fonts_state == eTeX_state(XeTeX_tracing_fonts_code)
31902
31903 @d XeTeX_interword_space_shaping_state==eTeX_state(XeTeX_interword_space_shaping_code)
31904
31905 @d XeTeX_generate_actual_text_state == eTeX_state(XeTeX_generate_actual_text_code)
31906 @d XeTeX_generate_actual_text_en == (XeTeX_generate_actual_text_state>0)
31907
31908 @d XeTeX_default_input_mode == eTeX_state(XeTeX_default_input_mode_code)
31909 @d XeTeX_default_input_encoding == eTeX_state(XeTeX_default_input_encoding_code)
31910
31911 @d XeTeX_hyphenatable_length == eTeX_state(XeTeX_hyphenatable_length_code)
31912
31913 @<Cases for |print_param|@>=
31914 suppress_fontnotfound_error_code:print_esc("suppressfontnotfounderror");
31915 eTeX_state_code+TeXXeT_code:print_esc("TeXXeTstate");
31916 eTeX_state_code+XeTeX_upwards_code:print_esc("XeTeXupwardsmode");
31917 eTeX_state_code+XeTeX_use_glyph_metrics_code:print_esc("XeTeXuseglyphmetrics");
31918 eTeX_state_code+XeTeX_inter_char_tokens_code:print_esc("XeTeXinterchartokenstate");
31919 eTeX_state_code+XeTeX_dash_break_code:print_esc("XeTeXdashbreakstate");
31920 eTeX_state_code+XeTeX_input_normalization_code:print_esc("XeTeXinputnormalization");
31921 eTeX_state_code+XeTeX_tracing_fonts_code:print_esc("XeTeXtracingfonts");
31922 eTeX_state_code+XeTeX_interword_space_shaping_code:print_esc("XeTeXinterwordspaceshaping");
31923 eTeX_state_code+XeTeX_generate_actual_text_code:print_esc("XeTeXgenerateactualtext");
31924 eTeX_state_code+XeTeX_hyphenatable_length_code:print_esc("XeTeXhyphenatablelength");
31925
31926 @ @<Generate all \eTeX...@>=
31927 primitive("suppressfontnotfounderror",assign_int,int_base+suppress_fontnotfound_error_code);@/
31928 primitive("TeXXeTstate",assign_int,eTeX_state_base+TeXXeT_code);
31929 @!@:TeXXeT_state_}{\.{\\TeXXeT_state} primitive@>
31930 primitive("XeTeXupwardsmode",assign_int,eTeX_state_base+XeTeX_upwards_code);
31931 @!@:XeTeX_upwards_mode_}{\.{\\XeTeXupwardsmode} primitive@>
31932 primitive("XeTeXuseglyphmetrics",assign_int,eTeX_state_base+XeTeX_use_glyph_metrics_code);
31933 @!@:XeTeX_use_glyph_metrics_}{\.{\\XeTeXuseglyphmetrics} primitive@>
31934 primitive("XeTeXinterchartokenstate",assign_int,eTeX_state_base+XeTeX_inter_char_tokens_code);
31935 @!@:XeTeX_use_inter_char_tokens_}{\.{\\XeTeXinterchartokenstate} primitive@>
31936
31937 primitive("XeTeXdashbreakstate",assign_int,eTeX_state_base+XeTeX_dash_break_code);
31938 @!@:XeTeX_dash_break_state_}{\.{\\XeTeXdashbreakstate} primitive@>
31939
31940 primitive("XeTeXinputnormalization",assign_int,eTeX_state_base+XeTeX_input_normalization_code);
31941 @!@:XeTeX_input_normalization_}{\.{\\XeTeXinputnormalization} primitive@>
31942
31943 primitive("XeTeXtracingfonts",assign_int,eTeX_state_base+XeTeX_tracing_fonts_code);
31944
31945 primitive("XeTeXinterwordspaceshaping",assign_int,eTeX_state_base+XeTeX_interword_space_shaping_code);
31946 @!@:XeTeX_interword_space_shaping_}{\.{\\XeTeXinterwordspaceshaping} primitive@>
31947
31948 primitive("XeTeXgenerateactualtext",assign_int,eTeX_state_base+XeTeX_generate_actual_text_code);
31949 @!@:XeTeX_generate_actual_text_}{\.{\\XeTeXgenerateactualtext} primitive@>
31950
31951 primitive("XeTeXhyphenatablelength",assign_int,eTeX_state_base+XeTeX_hyphenatable_length_code);
31952 @!@:XeTeX_hyphenatable_length_}{\.{\\XeTeXhyphenatablelength} primitive@>
31953
31954 primitive("XeTeXinputencoding",extension,XeTeX_input_encoding_extension_code);
31955 primitive("XeTeXdefaultencoding",extension,XeTeX_default_encoding_extension_code);
31956 primitive("beginL",valign,begin_L_code);
31957 @!@:beginL_}{\.{\\beginL} primitive@>
31958 primitive("endL",valign,end_L_code);
31959 @!@:endL_}{\.{\\endL} primitive@>
31960 primitive("beginR",valign,begin_R_code);
31961 @!@:beginR_}{\.{\\beginR} primitive@>
31962 primitive("endR",valign,end_R_code);
31963 @!@:endR_}{\.{\\endR} primitive@>
31964
31965 @ @<Cases of |valign| for |print_cmd_chr|@>=
31966 else case chr_code of
31967 begin_L_code: print_esc("beginL");
31968 end_L_code: print_esc("endL");
31969 begin_R_code: print_esc("beginR");
31970 othercases print_esc("endR")
31971 endcases
31972
31973 @ @<Cases of |main_control| for |hmode+valign|@>=
31974 if cur_chr>0 then
31975 begin if eTeX_enabled(TeXXeT_en,cur_cmd,cur_chr) then
31976 @.Improper \\beginL@>
31977 @.Improper \\endL@>
31978 @.Improper \\beginR@>
31979 @.Improper \\endR@>
31980 tail_append(new_math(0,cur_chr));
31981 end
31982 else
31983
31984 @ An hbox with subtype dlist will never be reversed, even when embedded
31985 in right-to-left text.
31986
31987 @<Display if this box is never to be reversed@>=
31988 if (type(p)=hlist_node)and(box_lr(p)=dlist) then print(", display")
31989
31990 @ A number of routines are based on a stack of one-word nodes whose
31991 |info| fields contain |end_M_code|, |end_L_code|, or |end_R_code|. The
31992 top of the stack is pointed to by |LR_ptr|.
31993
31994 When the stack manipulation macros of this section are used below,
31995 variable |LR_ptr| might be the global variable declared here for |hpack|
31996 and |ship_out|, or might be local to |post_line_break|.
31997
31998 @d put_LR(#)==begin temp_ptr:=get_avail; info(temp_ptr):=#;
31999 link(temp_ptr):=LR_ptr; LR_ptr:=temp_ptr;
32000 end
32001 @#
32002 @d push_LR(#)==put_LR(end_LR_type(#))
32003 @#
32004 @d pop_LR==begin temp_ptr:=LR_ptr; LR_ptr:=link(temp_ptr);
32005 free_avail(temp_ptr);
32006 end
32007
32008 @<Glob...@>=
32009 @!LR_ptr:pointer; {stack of LR codes for |hpack|, |ship_out|, and |init_math|}
32010 @!LR_problems:integer; {counts missing begins and ends}
32011 @!cur_dir:small_number; {current text direction}
32012
32013 @ @<Set init...@>=
32014 LR_ptr:=null; LR_problems:=0; cur_dir:=left_to_right;
32015
32016 @ @<Insert LR nodes at the beg...@>=
32017 begin q:=link(temp_head);
32018 if LR_ptr<>null then
32019 begin temp_ptr:=LR_ptr; r:=q;
32020 repeat s:=new_math(0,begin_LR_type(info(temp_ptr))); link(s):=r; r:=s;
32021 temp_ptr:=link(temp_ptr);
32022 until temp_ptr=null;
32023 link(temp_head):=r;
32024 end;
32025 while q<>cur_break(cur_p) do
32026 begin if not is_char_node(q) then
32027 if type(q)=math_node then @<Adjust \(t)the LR stack for the |p...@>;
32028 q:=link(q);
32029 end;
32030 end
32031
32032 @ @<Adjust \(t)the LR stack for the |p...@>=
32033 if end_LR(q) then
32034 begin if LR_ptr<>null then if info(LR_ptr)=end_LR_type(q) then pop_LR;
32035 end
32036 else push_LR(q)
32037
32038 @ We use the fact that |q| now points to the node with \.{\\rightskip} glue.
32039
32040 @<Insert LR nodes at the end...@>=
32041 if LR_ptr<>null then
32042 begin s:=temp_head; r:=link(s);
32043 while r<>q do
32044 begin s:=r; r:=link(s);
32045 end;
32046 r:=LR_ptr;
32047 while r<>null do
32048 begin temp_ptr:=new_math(0,info(r));
32049 link(s):=temp_ptr; s:=temp_ptr; r:=link(r);
32050 end;
32051 link(s):=q;
32052 end
32053
32054 @ @<Initialize the LR stack@>=
32055 put_LR(before) {this will never match}
32056
32057 @ @<Adjust \(t)the LR stack for the |hp...@>=
32058 if end_LR(p) then
32059 if info(LR_ptr)=end_LR_type(p) then pop_LR
32060 else begin incr(LR_problems); type(p):=kern_node; subtype(p):=explicit;
32061 end
32062 else push_LR(p)
32063
32064 @ @<Check for LR anomalies at the end of |hp...@>=
32065 begin if info(LR_ptr)<>before then
32066 begin while link(q)<>null do q:=link(q);
32067 repeat temp_ptr:=q; q:=new_math(0,info(LR_ptr)); link(temp_ptr):=q;
32068 LR_problems:=LR_problems+10000; pop_LR;
32069 until info(LR_ptr)=before;
32070 end;
32071 if LR_problems>0 then
32072 begin @<Report LR problems@>; goto common_ending;
32073 end;
32074 pop_LR;
32075 if LR_ptr<>null then confusion("LR1");
32076 @:this can't happen LR1}{\quad LR1@>
32077 end
32078
32079 @ @<Report LR problems@>=
32080 begin print_ln; print_nl("\endL or \endR problem (");@/
32081 print_int(LR_problems div 10000); print(" missing, ");@/
32082 print_int(LR_problems mod 10000); print(" extra");@/
32083 LR_problems:=0;
32084 end
32085
32086 @ @<Initialize |hlist_out| for mixed...@>=
32087 if eTeX_ex then
32088 begin @<Initialize the LR stack@>;
32089 if box_lr(this_box)=dlist then
32090 if cur_dir=right_to_left then
32091 begin cur_dir:=left_to_right; cur_h:=cur_h-width(this_box);
32092 end
32093 else set_box_lr(this_box)(0);
32094 if (cur_dir=right_to_left)and(box_lr(this_box)<>reversed) then
32095 @<Reverse the complete hlist and set the subtype to |reversed|@>;
32096 end
32097
32098 @ @<Finish |hlist_out| for mixed...@>=
32099 if eTeX_ex then
32100 begin @<Check for LR anomalies at the end of |hlist_out|@>;
32101 if box_lr(this_box)=dlist then cur_dir:=right_to_left;
32102 end
32103
32104 @ @<Handle a math node in |hlist_out|@>=
32105 begin if eTeX_ex then
32106 @<Adjust \(t)the LR stack for the |hlist_out| routine; if necessary
32107 reverse an hlist segment and |goto reswitch|@>;
32108 cur_h:=cur_h+width(p);
32109 end
32110
32111 @ Breaking a paragraph into lines while \TeXXeT\ is disabled may result
32112 in lines whith unpaired math nodes. Such hlists are silently accepted
32113 in the absence of text direction directives.
32114
32115 @d LR_dir(#)==(subtype(#) div R_code) {text direction of a `math node'}
32116
32117 @<Adjust \(t)the LR stack for the |hl...@>=
32118 begin if end_LR(p) then
32119 if info(LR_ptr)=end_LR_type(p) then pop_LR
32120 else begin if subtype(p)>L_code then incr(LR_problems);
32121 end
32122 else begin push_LR(p);
32123 if LR_dir(p)<>cur_dir then
32124 @<Reverse an hlist segment and |goto reswitch|@>;
32125 end;
32126 type(p):=kern_node;
32127 end
32128
32129 @ @<Check for LR anomalies at the end of |hl...@>=
32130 begin while info(LR_ptr)<>before do
32131 begin if info(LR_ptr)>L_code then LR_problems:=LR_problems+10000;
32132 pop_LR;
32133 end;
32134 pop_LR;
32135 end
32136
32137 @ @d edge_node=style_node {a |style_node| does not occur in hlists}
32138 @d edge_node_size=style_node_size {number of words in an edge node}
32139 @d edge_dist(#)==depth(#) {new |left_edge| position relative to |cur_h|
32140 (after |width| has been taken into account)}
32141
32142 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
32143 function new_edge(@!s:small_number;@!w:scaled):pointer;
32144 {create an edge node}
32145 var p:pointer; {the new node}
32146 begin p:=get_node(edge_node_size); type(p):=edge_node; subtype(p):=s;
32147 width(p):=w; edge_dist(p):=0; {the |edge_dist| field will be set later}
32148 new_edge:=p;
32149 end;
32150
32151 @ @<Cases of |hlist_out| that arise...@>=
32152 edge_node: begin cur_h:=cur_h+width(p);
32153 left_edge:=cur_h+edge_dist(p); cur_dir:=subtype(p);
32154 end;
32155
32156 @ We detach the hlist, start a new one consisting of just one kern node,
32157 append the reversed list, and set the width of the kern node.
32158
32159 @<Reverse the complete hlist...@>=
32160 begin save_h:=cur_h; temp_ptr:=p; p:=new_kern(0); link(prev_p):=p;
32161 cur_h:=0; link(p):=reverse(this_box,null,cur_g,cur_glue); width(p):=-cur_h;
32162 cur_h:=save_h; set_box_lr(this_box)(reversed);
32163 end
32164
32165 @ We detach the remainder of the hlist, replace the math node by
32166 an edge node, and append the reversed hlist segment to it; the tail of
32167 the reversed segment is another edge node and the remainder of the
32168 original list is attached to it.
32169
32170 @<Reverse an hlist segment...@>=
32171 begin save_h:=cur_h; temp_ptr:=link(p); rule_wd:=width(p);
32172 free_node(p,small_node_size);
32173 cur_dir:=reflected; p:=new_edge(cur_dir,rule_wd); link(prev_p):=p;
32174 cur_h:=cur_h-left_edge+rule_wd;
32175 link(p):=reverse(this_box,new_edge(reflected,0),cur_g,cur_glue);
32176 edge_dist(p):=cur_h; cur_dir:=reflected; cur_h:=save_h;
32177 goto reswitch;
32178 end
32179
32180 @ The |reverse| function defined here is responsible to reverse the
32181 nodes of an hlist (segment). The first parameter |this_box| is the enclosing
32182 hlist node, the second parameter |t| is to become the tail of the reversed
32183 list, and the global variable |temp_ptr| is the head of the list to be
32184 reversed. Finally |cur_g| and |cur_glue| are the current glue rounding state
32185 variables, to be updated by this function. We remove nodes from the original
32186 list and add them to the head of the new one.
32187
32188 @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
32189 function reverse(@!this_box,@!t:pointer; var cur_g:scaled;
32190 var cur_glue:real):pointer;
32191 label reswitch,next_p,done;
32192 var l:pointer; {the new list}
32193 @!p:pointer; {the current node}
32194 @!q:pointer; {the next node}
32195 @!g_order: glue_ord; {applicable order of infinity for glue}
32196 @!g_sign: normal..shrinking; {selects type of glue}
32197 @!glue_temp:real; {glue value before rounding}
32198 @!m,@!n:halfword; {count of unmatched math nodes}
32199 begin g_order:=glue_order(this_box); g_sign:=glue_sign(this_box);
32200 l:=t; p:=temp_ptr; m:=min_halfword; n:=min_halfword;
32201 loop@+ begin while p<>null do
32202 @<Move node |p| to the new list and go to the next node;
32203 or |goto done| if the end of the reflected segment has been reached@>;
32204 if (t=null)and(m=min_halfword)and(n=min_halfword) then goto done;
32205 p:=new_math(0,info(LR_ptr)); LR_problems:=LR_problems+10000;
32206 {manufacture one missing math node}
32207 end;
32208 done:reverse:=l;
32209 end;
32210
32211 @ @<Move node |p| to the new list...@>=
32212 reswitch: if is_char_node(p) then
32213 repeat f:=font(p); c:=character(p);
32214 cur_h:=cur_h+char_width(f)(char_info(f)(c));
32215 q:=link(p); link(p):=l; l:=p; p:=q;
32216 until not is_char_node(p)
32217 else @<Move the non-|char_node| |p| to the new list@>
32218
32219 @ @<Move the non-|char_node| |p| to the new list@>=
32220 begin q:=link(p);
32221 case type(p) of
32222 hlist_node,vlist_node,rule_node,kern_node: rule_wd:=width(p);
32223 @t\4@>@<Cases of |reverse| that need special treatment@>@;
32224 edge_node: confusion("LR2");
32225 @:this can't happen LR2}{\quad LR2@>
32226 othercases goto next_p
32227 endcases;@/
32228 cur_h:=cur_h+rule_wd;
32229 next_p: link(p):=l;
32230 if type(p)=kern_node then if (rule_wd=0)or(l=null) then
32231 begin free_node(p,small_node_size); p:=l;
32232 end;
32233 l:=p; p:=q;
32234 end
32235
32236 @ Need to measure |native_word| and picture nodes when reversing!
32237 @<Cases of |reverse|...@>=
32238 whatsit_node:
32239 if (is_native_word_subtype(p))
32240 or (subtype(p)=glyph_node)
32241 or (subtype(p)=pic_node)
32242 or (subtype(p)=pdf_node)
32243 then
32244 rule_wd:=width(p)
32245 else
32246 goto next_p;
32247
32248 @ Here we compute the effective width of a glue node as in |hlist_out|.
32249
32250 @<Cases of |reverse|...@>=
32251 glue_node: begin round_glue;
32252 @<Handle a glue node for mixed...@>;
32253 end;
32254
32255 @ A ligature node is replaced by a char node.
32256
32257 @<Cases of |reverse|...@>=
32258 ligature_node: begin flush_node_list(lig_ptr(p));
32259 temp_ptr:=p; p:=get_avail; mem[p]:=mem[lig_char(temp_ptr)]; link(p):=q;
32260 free_node(temp_ptr,small_node_size); goto reswitch;
32261 end;
32262
32263 @ Math nodes in an inner reflected segment are modified, those at the
32264 outer level are changed into kern nodes.
32265
32266 @<Cases of |reverse|...@>=
32267 math_node: begin rule_wd:=width(p);
32268 if end_LR(p) then
32269 if info(LR_ptr)<>end_LR_type(p) then
32270 begin type(p):=kern_node; incr(LR_problems);
32271 end
32272 else begin pop_LR;
32273 if n>min_halfword then
32274 begin decr(n); decr(subtype(p)); {change |after| into |before|}
32275 end
32276 else begin type(p):=kern_node;
32277 if m>min_halfword then decr(m)
32278 else @<Finish the reversed hlist segment and |goto done|@>;
32279 end;
32280 end
32281 else begin push_LR(p);
32282 if (n>min_halfword)or(LR_dir(p)<>cur_dir) then
32283 begin incr(n); incr(subtype(p)); {change |before| into |after|}
32284 end
32285 else begin type(p):=kern_node; incr(m);
32286 end;
32287 end;
32288 end;
32289
32290 @ Finally we have found the end of the hlist segment to be reversed; the
32291 final math node is released and the remaining list attached to the
32292 edge node terminating the reversed segment.
32293
32294 @<Finish the reversed...@>=
32295 begin free_node(p,small_node_size);
32296 link(t):=q; width(t):=rule_wd; edge_dist(t):=-cur_h-rule_wd; goto done;
32297 end
32298
32299 @ @<Check for LR anomalies at the end of |s...@>=
32300 begin if LR_problems>0 then
32301 begin @<Report LR problems@>; print_char(")"); print_ln;
32302 end;
32303 if (LR_ptr<>null)or(cur_dir<>left_to_right) then confusion("LR3");
32304 @:this can't happen LR3}{\quad LR3@>
32305 end
32306
32307 @ Some special actions are required for displayed equation in paragraphs
32308 with mixed direction texts. First of all we have to set the text
32309 direction preceding the display.
32310
32311 @<Set the value of |x| to the text direction before the display@>=
32312 if LR_save=null then x:=0
32313 else if info(LR_save)>=R_code then x:=-1@+else x:=1
32314
32315 @ @<Prepare for display after an empty...@>=
32316 begin pop_nest; @<Set the value of |x|...@>;
32317 end
32318
32319 @ When calculating the natural width, |w|, of the final line preceding
32320 the display, we may have to copy all or part of its hlist. We copy,
32321 however, only those parts of the original list that are relevant for the
32322 computation of |pre_display_size|.
32323 @^data structure assumptions@>
32324
32325 @<Declare subprocedures for |init_math|@>=
32326 procedure just_copy(@!p,@!h,@!t:pointer);
32327 label found,not_found;
32328 var @!r:pointer; {current node being fabricated for new list}
32329 @!words:0..5; {number of words remaining to be copied}
32330 begin while p<>null do
32331 begin words:=1; {this setting occurs in more branches than any other}
32332 if is_char_node(p) then r:=get_avail
32333 else case type(p) of
32334 hlist_node,vlist_node: begin r:=get_node(box_node_size);
32335 mem[r+6]:=mem[p+6]; mem[r+5]:=mem[p+5]; {copy the last two words}
32336 words:=5; list_ptr(r):=null; {this affects |mem[r+5]|}
32337 end;
32338 rule_node: begin r:=get_node(rule_node_size); words:=rule_node_size;
32339 end;
32340 ligature_node: begin r:=get_avail; {only |font| and |character| are needed}
32341 mem[r]:=mem[lig_char(p)]; goto found;
32342 end;
32343 kern_node,math_node: begin r:=get_node(small_node_size);
32344 words:=small_node_size;
32345 end;
32346 glue_node: begin r:=get_node(small_node_size); add_glue_ref(glue_ptr(p));
32347 glue_ptr(r):=glue_ptr(p); leader_ptr(r):=null;
32348 end;
32349 whatsit_node:@<Make a partial copy of the whatsit...@>;
32350 othercases goto not_found
32351 endcases;
32352 while words>0 do
32353 begin decr(words); mem[r+words]:=mem[p+words];
32354 end;
32355 found: link(h):=r; h:=r;
32356 not_found: p:=link(p);
32357 end;
32358 link(h):=t;
32359 end;
32360
32361 @ When the final line ends with R-text, the value |w| refers to the line
32362 reflected with respect to the left edge of the enclosing vertical list.
32363
32364 @<Prepare for display after a non-empty...@>=
32365 if eTeX_ex then @<Let |j| be the prototype box for the display@>;
32366 v:=shift_amount(just_box);
32367 @<Set the value of |x|...@>;
32368 if x>=0 then
32369 begin p:=list_ptr(just_box); link(temp_head):=null;
32370 end
32371 else begin v:=-v-width(just_box);
32372 p:=new_math(0,begin_L_code); link(temp_head):=p;
32373 just_copy(list_ptr(just_box),p,new_math(0,end_L_code));
32374 cur_dir:=right_to_left;
32375 end;
32376 v:=v+2*quad(cur_font);
32377 if TeXXeT_en then @<Initialize the LR stack@>
32378
32379 @ @<Finish the natural width computation@>=
32380 if TeXXeT_en then
32381 begin while LR_ptr<>null do pop_LR;
32382 if LR_problems<>0 then
32383 begin w:=max_dimen; LR_problems:=0;
32384 end;
32385 end;
32386 cur_dir:=left_to_right; flush_node_list(link(temp_head))
32387
32388 @ In the presence of text direction directives we assume that any LR
32389 problems have been fixed by the |hpack| routine. If the final line
32390 contains, however, text direction directives while \TeXXeT\ is disabled,
32391 then we set |w:=max_dimen|.
32392
32393 @<Cases of `Let |d| be the natural...@>=
32394 math_node: begin d:=width(p);
32395 if TeXXeT_en then @<Adjust \(t)the LR stack for the |init_math| routine@>
32396 else if subtype(p)>=L_code then
32397 begin w:=max_dimen; goto done;
32398 end;
32399 end;
32400 edge_node: begin d:=width(p); cur_dir:=subtype(p);
32401 end;
32402
32403 @ @<Adjust \(t)the LR stack for the |i...@>=
32404 if end_LR(p) then
32405 begin if info(LR_ptr)=end_LR_type(p) then pop_LR
32406 else if subtype(p)>L_code then
32407 begin w:=max_dimen; goto done;
32408 end
32409 end
32410 else begin push_LR(p);
32411 if LR_dir(p)<>cur_dir then
32412 begin just_reverse(p); p:=temp_head;
32413 end;
32414 end
32415
32416 @ @<Declare subprocedures for |init_math|@>=
32417 procedure just_reverse(@!p:pointer);
32418 label found,done;
32419 var l:pointer; {the new list}
32420 @!t:pointer; {tail of reversed segment}
32421 @!q:pointer; {the next node}
32422 @!m,@!n:halfword; {count of unmatched math nodes}
32423 begin m:=min_halfword; n:=min_halfword;
32424 if link(temp_head)=null then
32425 begin just_copy(link(p),temp_head,null); q:=link(temp_head);
32426 end
32427 else begin q:=link(p); link(p):=null; flush_node_list(link(temp_head));
32428 end;
32429 t:=new_edge(cur_dir,0); l:=t; cur_dir:=reflected;
32430 while q<>null do
32431 if is_char_node(q) then
32432 repeat p:=q; q:=link(p); link(p):=l; l:=p;
32433 until not is_char_node(q)
32434 else begin p:=q; q:=link(p);
32435 if type(p)=math_node then
32436 @<Adjust \(t)the LR stack for the |just_reverse| routine@>;
32437 link(p):=l; l:=p;
32438 end;
32439 goto done;
32440 found:width(t):=width(p); link(t):=q; free_node(p,small_node_size);
32441 done:link(temp_head):=l;
32442 end;
32443
32444 @ @<Adjust \(t)the LR stack for the |j...@>=
32445 if end_LR(p) then
32446 if info(LR_ptr)<>end_LR_type(p) then
32447 begin type(p):=kern_node; incr(LR_problems);
32448 end
32449 else begin pop_LR;
32450 if n>min_halfword then
32451 begin decr(n); decr(subtype(p)); {change |after| into |before|}
32452 end
32453 else begin if m>min_halfword then decr(m)@+else goto found;
32454 type(p):=kern_node;
32455 end;
32456 end
32457 else begin push_LR(p);
32458 if (n>min_halfword)or(LR_dir(p)<>cur_dir) then
32459 begin incr(n); incr(subtype(p)); {change |before| into |after|}
32460 end
32461 else begin type(p):=kern_node; incr(m);
32462 end;
32463 end
32464
32465 @ The prototype box is an hlist node with the width, glue set, and shift
32466 amount of |just_box|, i.e., the last line preceding the display. Its
32467 hlist reflects the current \.{\\leftskip} and \.{\\rightskip}.
32468
32469 @<Let |j| be the prototype box for the display@>=
32470 begin if right_skip=zero_glue then j:=new_kern(0)
32471 else j:=new_param_glue(right_skip_code);
32472 if left_skip=zero_glue then p:=new_kern(0)
32473 else p:=new_param_glue(left_skip_code);
32474 link(p):=j; j:=new_null_box; width(j):=width(just_box);
32475 shift_amount(j):=shift_amount(just_box); list_ptr(j):=p;
32476 glue_order(j):=glue_order(just_box); glue_sign(j):=glue_sign(just_box);
32477 glue_set(j):=glue_set(just_box);
32478 end
32479
32480 @ At the end of a displayed equation we retrieve the prototype box.
32481
32482 @<Local variables for finishing...@>=
32483 @!j:pointer; {prototype box}
32484
32485 @ @<Retrieve the prototype box@>=
32486 if mode=mmode then j:=LR_box
32487
32488 @ @<Flush the prototype box@>=
32489 flush_node_list(j)
32490
32491 @ The |app_display| procedure used to append the displayed equation
32492 and\slash or equation number to the current vertical list has three
32493 parameters: the prototype box, the hbox to be appended, and the
32494 displacement of the hbox in the display line.
32495
32496 @<Declare subprocedures for |after_math|@>=
32497 procedure app_display(@!j,@!b:pointer;@!d:scaled);
32498 var z:scaled; {width of the line}
32499 @!s:scaled; {move the line right this much}
32500 @!e:scaled; {distance from right edge of box to end of line}
32501 @!x:integer; {|pre_display_direction|}
32502 @!p,@!q,@!r,@!t,@!u:pointer; {for list manipulation}
32503 begin s:=display_indent; x:=pre_display_direction;
32504 if x=0 then shift_amount(b):=s+d
32505 else begin z:=display_width; p:=b;
32506 @<Set up the hlist for the display line@>;
32507 @<Package the display line@>;
32508 end;
32509 append_to_vlist(b);
32510 end;
32511
32512 @ Here we construct the hlist for the display, starting with node |p|
32513 and ending with node |q|. We also set |d| and |e| to the amount of
32514 kerning to be added before and after the hlist (adjusted for the
32515 prototype box).
32516
32517 @<Set up the hlist for the display line@>=
32518 if x>0 then e:=z-d-width(p)
32519 else begin e:=d; d:=z-e-width(p);
32520 end;
32521 if j<>null then
32522 begin b:=copy_node_list(j); height(b):=height(p); depth(b):=depth(p);
32523 s:=s-shift_amount(b); d:=d+s; e:=e+width(b)-z-s;
32524 end;
32525 if box_lr(p)=dlist then q:=p {display or equation number}
32526 else begin {display and equation number}
32527 r:=list_ptr(p); free_node(p,box_node_size);
32528 if r=null then confusion("LR4");
32529 if x>0 then
32530 begin p:=r;
32531 repeat q:=r; r:=link(r); {find tail of list}
32532 until r=null;
32533 end
32534 else begin p:=null; q:=r;
32535 repeat t:=link(r); link(r):=p; p:=r; r:=t; {reverse list}
32536 until r=null;
32537 end;
32538 end
32539
32540 @ In the presence of a prototype box we use its shift amount and width
32541 to adjust the values of kerning and add these values to the glue nodes
32542 inserted to cancel the \.{\\leftskip} and \.{\\rightskip}. If there is
32543 no prototype box (because the display is preceded by an empty
32544 paragraph), or if the skip parameters are zero, we just add kerns.
32545
32546 The |cancel_glue| macro creates and links a glue node that is, together
32547 with another glue node, equivalent to a given amount of kerning. We can
32548 use |j| as temporary pointer, since all we need is |j<>null|.
32549
32550 @d cancel_glue(#)==j:=new_skip_param(#); cancel_glue_cont
32551 @d cancel_glue_cont(#)==link(#):=j; cancel_glue_cont_cont
32552 @d cancel_glue_cont_cont(#)==link(j):=#; cancel_glue_end
32553 @d cancel_glue_end(#)==j:=glue_ptr(#); cancel_glue_end_end
32554 @d cancel_glue_end_end(#)==
32555 stretch_order(temp_ptr):=stretch_order(j);
32556 shrink_order(temp_ptr):=shrink_order(j); width(temp_ptr):=#-width(j);
32557 stretch(temp_ptr):=-stretch(j); shrink(temp_ptr):=-shrink(j)
32558
32559 @<Package the display line@>=
32560 if j=null then
32561 begin r:=new_kern(0); t:=new_kern(0); {the widths will be set later}
32562 end
32563 else begin r:=list_ptr(b); t:=link(r);
32564 end;
32565 u:=new_math(0,end_M_code);
32566 if type(t)=glue_node then {|t| is \.{\\rightskip} glue}
32567 begin cancel_glue(right_skip_code)(q)(u)(t)(e); link(u):=t;
32568 end
32569 else begin width(t):=e; link(t):=u; link(q):=t;
32570 end;
32571 u:=new_math(0,begin_M_code);
32572 if type(r)=glue_node then {|r| is \.{\\leftskip} glue}
32573 begin cancel_glue(left_skip_code)(u)(p)(r)(d); link(r):=u;
32574 end
32575 else begin width(r):=d; link(r):=p; link(u):=r;
32576 if j=null then
32577 begin b:=hpack(u,natural); shift_amount(b):=s;
32578 end
32579 else list_ptr(b):=u;
32580 end
32581
32582 @ The |scan_tokens| feature of \eTeX\ defines the \.{\\scantokens}
32583 primitive.
32584
32585 @<Generate all \eTeX...@>=
32586 primitive("scantokens",input,2);
32587 @!@:scan_tokens_}{\.{\\scantokens} primitive@>
32588
32589 @ @<Cases of |input| for |print_cmd_chr|@>=
32590 else if chr_code=2 then print_esc("scantokens")
32591
32592 @ @<Cases for |input|@>=
32593 else if cur_chr=2 then pseudo_start
32594
32595 @ The global variable |pseudo_files| is used to maintain a stack of
32596 pseudo files. The |info| field of each pseudo file points to a linked
32597 list of variable size nodes representing lines not yet processed: the
32598 |info| field of the first word contains the size of this node, all the
32599 following words contain ASCII codes.
32600
32601 @<Glob...@>=
32602 @!pseudo_files:pointer; {stack of pseudo files}
32603
32604 @ @<Set init...@>=
32605 pseudo_files:=null;
32606
32607 @ The |pseudo_start| procedure initiates reading from a pseudo file.
32608
32609 @<Declare \eTeX\ procedures for ex...@>=
32610 procedure@?pseudo_start; forward;@t\2@>
32611
32612 @ @<Declare \eTeX\ procedures for tok...@>=
32613 procedure pseudo_start;
32614 var old_setting:0..max_selector; {holds |selector| setting}
32615 @!s:str_number; {string to be converted into a pseudo file}
32616 @!l,@!m:pool_pointer; {indices into |str_pool|}
32617 @!p,@!q,@!r:pointer; {for list construction}
32618 @!w: four_quarters; {four ASCII codes}
32619 @!nl,@!sz:integer;
32620 begin scan_general_text;
32621 old_setting:=selector; selector:=new_string;
32622 token_show(temp_head); selector:=old_setting;
32623 flush_list(link(temp_head));
32624 str_room(1); s:=make_string;
32625 @<Convert string |s| into a new pseudo file@>;
32626 flush_string;
32627 @<Initiate input from new pseudo file@>;
32628 end;
32629
32630 @ @<Convert string |s| into a new pseudo file@>=
32631 str_pool[pool_ptr]:=si(" "); l:=str_start_macro(s);
32632 nl:=si(new_line_char);
32633 p:=get_avail; q:=p;
32634 while l<pool_ptr do
32635 begin m:=l;
32636 while (l<pool_ptr)and(str_pool[l]<>nl) do incr(l);
32637 sz:=(l-m+7)div 4;
32638 if sz=1 then sz:=2;
32639 r:=get_node(sz); link(q):=r; q:=r; info(q):=hi(sz);
32640 while sz>2 do
32641 begin decr(sz); incr(r);
32642 w.b0:=qi(so(str_pool[m])); w.b1:=qi(so(str_pool[m+1]));
32643 w.b2:=qi(so(str_pool[m+2])); w.b3:=qi(so(str_pool[m+3]));
32644 mem[r].qqqq:=w; m:=m+4;
32645 end;
32646 w.b0:=qi(" "); w.b1:=qi(" "); w.b2:=qi(" "); w.b3:=qi(" ");
32647 if l>m then
32648 begin w.b0:=qi(so(str_pool[m]));
32649 if l>m+1 then
32650 begin w.b1:=qi(so(str_pool[m+1]));
32651 if l>m+2 then
32652 begin w.b2:=qi(so(str_pool[m+2]));
32653 if l>m+3 then w.b3:=qi(so(str_pool[m+3]));
32654 end;
32655 end;
32656 end;
32657 mem[r+1].qqqq:=w;
32658 if str_pool[l]=nl then incr(l);
32659 end;
32660 info(p):=link(p); link(p):=pseudo_files; pseudo_files:=p
32661
32662 @ @<Initiate input from new pseudo file@>=
32663 begin_file_reading; {set up |cur_file| and new level of input}
32664 line:=0; limit:=start; loc:=limit+1; {force line read}
32665 if tracing_scan_tokens>0 then
32666 begin if term_offset>max_print_line-3 then print_ln
32667 else if (term_offset>0)or(file_offset>0) then print_char(" ");
32668 name:=19; print("( "); incr(open_parens); update_terminal;
32669 end
32670 else name:=18
32671
32672 @ Here we read a line from the current pseudo file into |buffer|.
32673
32674 @<Declare \eTeX\ procedures for tr...@>=
32675 function pseudo_input: boolean; {inputs the next line or returns |false|}
32676 var p:pointer; {current line from pseudo file}
32677 @!sz:integer; {size of node |p|}
32678 @!w:four_quarters; {four ASCII codes}
32679 @!r:pointer; {loop index}
32680 begin last:=first; {cf.\ Matthew 19\thinspace:\thinspace30}
32681 p:=info(pseudo_files);
32682 if p=null then pseudo_input:=false
32683 else begin info(pseudo_files):=link(p); sz:=ho(info(p));
32684 if 4*sz-3>=buf_size-last then
32685 @<Report overflow of the input buffer, and abort@>;
32686 last:=first;
32687 for r:=p+1 to p+sz-1 do
32688 begin w:=mem[r].qqqq;
32689 buffer[last]:=w.b0; buffer[last+1]:=w.b1;
32690 buffer[last+2]:=w.b2; buffer[last+3]:=w.b3;
32691 last:=last+4;
32692 end;
32693 if last>=max_buf_stack then max_buf_stack:=last+1;
32694 while (last>first)and(buffer[last-1]=" ") do decr(last);
32695 free_node(p,sz);
32696 pseudo_input:=true;
32697 end;
32698 end;
32699
32700 @ When we are done with a pseudo file we `close' it.
32701
32702 @<Declare \eTeX\ procedures for tr...@>=
32703 procedure pseudo_close; {close the top level pseudo file}
32704 var p,@!q: pointer;
32705 begin p:=link(pseudo_files); q:=info(pseudo_files);
32706 free_avail(pseudo_files); pseudo_files:=p;
32707 while q<>null do
32708 begin p:=q; q:=link(p); free_node(p,ho(info(p)));
32709 end;
32710 end;
32711
32712 @ @<Dump the \eTeX\ state@>=
32713 while pseudo_files<>null do pseudo_close; {flush pseudo files}
32714
32715 @ @<Generate all \eTeX...@>=
32716 primitive("readline",read_to_cs,1);@/
32717 @!@:read_line_}{\.{\\readline} primitive@>
32718
32719 @ @<Cases of |read| for |print_cmd_chr|@>=
32720 else print_esc("readline")
32721
32722 @ @<Handle \.{\\readline} and |goto done|@>=
32723 if j=1 then
32724 begin while loc<=limit do {current line not yet finished}
32725 begin cur_chr:=buffer[loc]; incr(loc);
32726 if cur_chr=" " then cur_tok:=space_token
32727 @+else cur_tok:=cur_chr+other_token;
32728 store_new_token(cur_tok);
32729 end;
32730 goto done;
32731 end
32732
32733 @ Here we define the additional conditionals of \eTeX\ as well as the
32734 \.{\\unless} prefix.
32735
32736 @d if_def_code=17 { `\.{\\ifdefined}' }
32737 @d if_cs_code=18 { `\.{\\ifcsname}' }
32738 @d if_font_char_code=19 { `\.{\\iffontchar}' }
32739 @d if_in_csname_code=20 { `\.{\\ifincsname}' }
32740
32741 @<Generate all \eTeX...@>=
32742 primitive("unless",expand_after,1);@/
32743 @!@:unless_}{\.{\\unless} primitive@>
32744 primitive("ifdefined",if_test,if_def_code);
32745 @!@:if_defined_}{\.{\\ifdefined} primitive@>
32746 primitive("ifcsname",if_test,if_cs_code);
32747 @!@:if_cs_name_}{\.{\\ifcsname} primitive@>
32748 primitive("iffontchar",if_test,if_font_char_code);
32749 @!@:if_font_char_}{\.{\\iffontchar} primitive@>
32750 primitive("ifincsname",if_test,if_in_csname_code);
32751 @!@:if_in_csname_}{\.{\\ifincsname} primitive@>
32752
32753 @ @<Cases of |expandafter| for |print_cmd_chr|@>=
32754 else print_esc("unless")
32755
32756 @ @<Cases of |if_test| for |print_cmd_chr|@>=
32757 if_def_code:print_esc("ifdefined");
32758 if_cs_code:print_esc("ifcsname");
32759 if_font_char_code:print_esc("iffontchar");
32760 if_in_csname_code:print_esc("ifincsname");
32761
32762 @ The result of a boolean condition is reversed when the conditional is
32763 preceded by \.{\\unless}.
32764
32765 @<Negate a boolean conditional and |goto reswitch|@>=
32766 begin get_token;
32767 if (cur_cmd=if_test)and(cur_chr<>if_case_code) then
32768 begin cur_chr:=cur_chr+unless_code; goto reswitch;
32769 end;
32770 print_err("You can't use `"); print_esc("unless"); print("' before `");
32771 @.You can't use \\unless...@>
32772 print_cmd_chr(cur_cmd,cur_chr); print_char("'");
32773 help1("Continue, and I'll forget that it ever happened.");
32774 back_error;
32775 end
32776
32777 @ The conditional \.{\\ifdefined} tests if a control sequence is
32778 defined.
32779
32780 We need to reset |scanner_status|, since \.{\\outer} control sequences
32781 are allowed, but we might be scanning a macro definition or preamble.
32782
32783 @<Cases for |conditional|@>=
32784 if_def_code:begin save_scanner_status:=scanner_status;
32785 scanner_status:=normal;
32786 get_next; b:=(cur_cmd<>undefined_cs);
32787 scanner_status:=save_scanner_status;
32788 end;
32789
32790 @ The conditional \.{\\ifcsname} is equivalent to \.{\{\\expandafter}
32791 \.{\}\\expandafter} \.{\\ifdefined} \.{\\csname}, except that no new
32792 control sequence will be entered into the hash table (once all tokens
32793 preceding the mandatory \.{\\endcsname} have been expanded).
32794
32795 @<Cases for |conditional|@>=
32796 if_cs_code:begin n:=get_avail; p:=n; {head of the list of characters}
32797 e:=is_in_csname; is_in_csname:=true;
32798 repeat get_x_token;
32799 if cur_cs=0 then store_new_token(cur_tok);
32800 until cur_cs<>0;
32801 if cur_cmd<>end_cs_name then @<Complain about missing \.{\\endcsname}@>;
32802 @<Look up the characters of list |n| in the hash table, and set |cur_cs|@>;
32803 flush_list(n);
32804 b:=(eq_type(cur_cs)<>undefined_cs);
32805 is_in_csname:=e;
32806 end;
32807
32808 @ @<Look up the characters of list |n| in the hash table...@>=
32809 m:=first; p:=link(n);
32810 while p<>null do
32811 begin if m>=max_buf_stack then
32812 begin max_buf_stack:=m+1;
32813 if max_buf_stack=buf_size then
32814 overflow("buffer size",buf_size);
32815 @:TeX capacity exceeded buffer size}{\quad buffer size@>
32816 end;
32817 buffer[m]:=info(p) mod max_char_val; incr(m); p:=link(p);
32818 end;
32819 if m>first+1 then
32820 cur_cs:=id_lookup(first,m-first) {|no_new_control_sequence| is |true|}
32821 else if m=first then cur_cs:=null_cs {the list is empty}
32822 else cur_cs:=single_base+buffer[first] {the list has length one}
32823
32824 @ The conditional \.{\\iffontchar} tests the existence of a character in
32825 a font.
32826
32827 @<Cases for |conditional|@>=
32828 if_in_csname_code: b:=is_in_csname;
32829 if_font_char_code:begin scan_font_ident; n:=cur_val; scan_usv_num;
32830 if is_native_font(n) then
32831 b:=(map_char_to_glyph(n, cur_val) > 0)
32832 else begin
32833 if (font_bc[n]<=cur_val)and(font_ec[n]>=cur_val) then
32834 b:=char_exists(char_info(n)(qi(cur_val)))
32835 else b:=false;
32836 end;
32837 end;
32838
32839 @ The |protected| feature of \eTeX\ defines the \.{\\protected} prefix
32840 command for macro definitions. Such macros are protected against
32841 expansions when lists of expanded tokens are built, e.g., for \.{\\edef}
32842 or during \.{\\write}.
32843
32844 @<Generate all \eTeX...@>=
32845 primitive("protected",prefix,8);
32846 @!@:protected_}{\.{\\protected} primitive@>
32847
32848 @ @<Cases of |prefix| for |print_cmd_chr|@>=
32849 else if chr_code=8 then print_esc("protected")
32850
32851 @ The |get_x_or_protected| procedure is like |get_x_token| except that
32852 protected macros are not expanded.
32853
32854 @<Declare \eTeX\ procedures for sc...@>=
32855 procedure get_x_or_protected; {sets |cur_cmd|, |cur_chr|, |cur_tok|,
32856 and expands non-protected macros}
32857 label exit;
32858 begin loop@+begin get_token;
32859 if cur_cmd<=max_command then return;
32860 if (cur_cmd>=call)and(cur_cmd<end_template) then
32861 if info(link(cur_chr))=protected_token then return;
32862 expand;
32863 end;
32864 exit:end;
32865
32866 @ A group entered (or a conditional started) in one file may end in a
32867 different file. Such slight anomalies, although perfectly legitimate,
32868 may cause errors that are difficult to locate. In order to be able to
32869 give a warning message when such anomalies occur, \eTeX\ uses the
32870 |grp_stack| and |if_stack| arrays to record the initial |cur_boundary|
32871 and |cond_ptr| values for each input file.
32872
32873 @<Glob...@>=
32874 @!grp_stack : array[0..max_in_open] of save_pointer; {initial |cur_boundary|}
32875 @!if_stack : array[0..max_in_open] of pointer; {initial |cond_ptr|}
32876
32877 @ When a group ends that was apparently entered in a different input
32878 file, the |group_warning| procedure is invoked in order to update the
32879 |grp_stack|. If moreover \.{\\tracingnesting} is positive we want to
32880 give a warning message. The situation is, however, somewhat complicated
32881 by two facts: (1)~There may be |grp_stack| elements without a
32882 corresponding \.{\\input} file or \.{\\scantokens} pseudo file (e.g.,
32883 error insertions from the terminal); and (2)~the relevant information is
32884 recorded in the |name_field| of the |input_stack| only loosely
32885 synchronized with the |in_open| variable indexing |grp_stack|.
32886
32887 @<Declare \eTeX\ procedures for tr...@>=
32888 procedure group_warning;
32889 var i:0..max_in_open; {index into |grp_stack|}
32890 @!w:boolean; {do we need a warning?}
32891 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
32892 {store current state}
32893 i:=in_open; w:=false;
32894 while (grp_stack[i]=cur_boundary)and(i>0) do
32895 begin @<Set variable |w| to indicate if this case should be reported@>;
32896 grp_stack[i]:=save_index(save_ptr); decr(i);
32897 end;
32898 if w then
32899 begin print_nl("Warning: end of "); print_group(true);
32900 @.Warning: end of...@>
32901 print(" of a different file"); print_ln;
32902 if tracing_nesting>1 then show_context;
32903 if history=spotless then history:=warning_issued;
32904 end;
32905 end;
32906
32907 @ This code scans the input stack in order to determine the type of the
32908 current input file.
32909
32910 @<Set variable |w| to...@>=
32911 if tracing_nesting>0 then
32912 begin while (input_stack[base_ptr].state_field=token_list)or@|
32913 (input_stack[base_ptr].index_field>i) do decr(base_ptr);
32914 if input_stack[base_ptr].name_field>17 then w:=true;
32915 end
32916
32917 @ When a conditional ends that was apparently started in a different
32918 input file, the |if_warning| procedure is invoked in order to update the
32919 |if_stack|. If moreover \.{\\tracingnesting} is positive we want to
32920 give a warning message (with the same complications as above).
32921
32922 @<Declare \eTeX\ procedures for tr...@>=
32923 procedure if_warning;
32924 var i:0..max_in_open; {index into |if_stack|}
32925 @!w:boolean; {do we need a warning?}
32926 begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
32927 {store current state}
32928 i:=in_open; w:=false;
32929 while if_stack[i]=cond_ptr do
32930 begin @<Set variable |w| to...@>;
32931 if_stack[i]:=link(cond_ptr); decr(i);
32932 end;
32933 if w then
32934 begin print_nl("Warning: end of "); print_cmd_chr(if_test,cur_if);
32935 @.Warning: end of...@>
32936 print_if_line(if_line); print(" of a different file"); print_ln;
32937 if tracing_nesting>1 then show_context;
32938 if history=spotless then history:=warning_issued;
32939 end;
32940 end;
32941
32942 @ Conversely, the |file_warning| procedure is invoked when a file ends
32943 and some groups entered or conditionals started while reading from that
32944 file are still incomplete.
32945
32946 @<Declare \eTeX\ procedures for tr...@>=
32947 procedure file_warning;
32948 var p:pointer; {saved value of |save_ptr| or |cond_ptr|}
32949 @!l:quarterword; {saved value of |cur_level| or |if_limit|}
32950 @!c:quarterword; {saved value of |cur_group| or |cur_if|}
32951 @!i:integer; {saved value of |if_line|}
32952 begin p:=save_ptr; l:=cur_level; c:=cur_group; save_ptr:=cur_boundary;
32953 while grp_stack[in_open]<>save_ptr do
32954 begin decr(cur_level);
32955 print_nl("Warning: end of file when ");
32956 @.Warning: end of file when...@>
32957 print_group(true); print(" is incomplete");@/
32958 cur_group:=save_level(save_ptr); save_ptr:=save_index(save_ptr)
32959 end;
32960 save_ptr:=p; cur_level:=l; cur_group:=c; {restore old values}
32961 p:=cond_ptr; l:=if_limit; c:=cur_if; i:=if_line;
32962 while if_stack[in_open]<>cond_ptr do
32963 begin print_nl("Warning: end of file when ");
32964 @.Warning: end of file when...@>
32965 print_cmd_chr(if_test,cur_if);
32966 if if_limit=fi_code then print_esc("else");
32967 print_if_line(if_line); print(" is incomplete");@/
32968 if_line:=if_line_field(cond_ptr); cur_if:=subtype(cond_ptr);
32969 if_limit:=type(cond_ptr); cond_ptr:=link(cond_ptr);
32970 end;
32971 cond_ptr:=p; if_limit:=l; cur_if:=c; if_line:=i; {restore old values}
32972 print_ln;
32973 if tracing_nesting>1 then show_context;
32974 if history=spotless then history:=warning_issued;
32975 end;
32976
32977 @ Here are the additional \eTeX\ primitives for expressions.
32978
32979 @<Generate all \eTeX...@>=
32980 primitive("numexpr",last_item,eTeX_expr-int_val+int_val);
32981 @!@:num_expr_}{\.{\\numexpr} primitive@>
32982 primitive("dimexpr",last_item,eTeX_expr-int_val+dimen_val);
32983 @!@:dim_expr_}{\.{\\dimexpr} primitive@>
32984 primitive("glueexpr",last_item,eTeX_expr-int_val+glue_val);
32985 @!@:glue_expr_}{\.{\\glueexpr} primitive@>
32986 primitive("muexpr",last_item,eTeX_expr-int_val+mu_val);
32987 @!@:mu_expr_}{\.{\\muexpr} primitive@>
32988
32989 @ @<Cases of |last_item| for |print_cmd_chr|@>=
32990 eTeX_expr-int_val+int_val: print_esc("numexpr");
32991 eTeX_expr-int_val+dimen_val: print_esc("dimexpr");
32992 eTeX_expr-int_val+glue_val: print_esc("glueexpr");
32993 eTeX_expr-int_val+mu_val: print_esc("muexpr");
32994
32995 @ This code for reducing |cur_val_level| and\slash or negating the
32996 result is similar to the one for all the other cases of
32997 |scan_something_internal|, with the difference that |scan_expr| has
32998 already increased the reference count of a glue specification.
32999
33000 @<Process an expression and |return|@>=
33001 begin if m<eTeX_mu then
33002 begin case m of
33003 @/@<Cases for fetching a glue value@>@/
33004 end; {there are no other cases}
33005 cur_val_level:=glue_val;
33006 end
33007 else if m<eTeX_expr then
33008 begin case m of
33009 @/@<Cases for fetching a mu value@>@/
33010 end; {there are no other cases}
33011 cur_val_level:=mu_val;
33012 end
33013 else begin cur_val_level:=m-eTeX_expr+int_val; scan_expr;
33014 end;
33015 while cur_val_level>level do
33016 begin if cur_val_level=glue_val then
33017 begin m:=cur_val; cur_val:=width(m); delete_glue_ref(m);
33018 end
33019 else if cur_val_level=mu_val then mu_error;
33020 decr(cur_val_level);
33021 end;
33022 if negative then
33023 if cur_val_level>=glue_val then
33024 begin m:=cur_val; cur_val:=new_spec(m); delete_glue_ref(m);
33025 @<Negate all three glue components of |cur_val|@>;
33026 end
33027 else negate(cur_val);
33028 return;
33029 end
33030
33031 @ @<Declare \eTeX\ procedures for sc...@>=
33032 procedure@?scan_expr; forward;@t\2@>
33033
33034 @ The |scan_expr| procedure scans and evaluates an expression.
33035
33036 @<Declare procedures needed for expressions@>=
33037 @t\4@>@<Declare subprocedures for |scan_expr|@>
33038 procedure scan_expr; {scans and evaluates an expression}
33039 label restart, continue, found;
33040 var a,@!b:boolean; {saved values of |arith_error|}
33041 @!l:small_number; {type of expression}
33042 @!r:small_number; {state of expression so far}
33043 @!s:small_number; {state of term so far}
33044 @!o:small_number; {next operation or type of next factor}
33045 @!e:integer; {expression so far}
33046 @!t:integer; {term so far}
33047 @!f:integer; {current factor}
33048 @!n:integer; {numerator of combined multiplication and division}
33049 @!p:pointer; {top of expression stack}
33050 @!q:pointer; {for stack manipulations}
33051 begin l:=cur_val_level; a:=arith_error; b:=false; p:=null;
33052 incr(expand_depth_count);
33053 if expand_depth_count>=expand_depth then overflow("expansion depth",expand_depth);
33054 @<Scan and evaluate an expression |e| of type |l|@>;
33055 decr(expand_depth_count);
33056 if b then
33057 begin print_err("Arithmetic overflow");
33058 @.Arithmetic overflow@>
33059 help2("I can't evaluate this expression,")@/
33060 ("since the result is out of range.");
33061 error;
33062 if l>=glue_val then
33063 begin delete_glue_ref(e); e:=zero_glue; add_glue_ref(e);
33064 end
33065 else e:=0;
33066 end;
33067 arith_error:=a; cur_val:=e; cur_val_level:=l;
33068 end;
33069
33070 @ Evaluating an expression is a recursive process: When the left
33071 parenthesis of a subexpression is scanned we descend to the next level
33072 of recursion; the previous level is resumed with the matching right
33073 parenthesis.
33074
33075 @d expr_none=0 {\.( seen, or \.( $\langle\it expr\rangle$ \.) seen}
33076 @d expr_add=1 {\.( $\langle\it expr\rangle$ \.+ seen}
33077 @d expr_sub=2 {\.( $\langle\it expr\rangle$ \.- seen}
33078 @d expr_mult=3 {$\langle\it term\rangle$ \.* seen}
33079 @d expr_div=4 {$\langle\it term\rangle$ \./ seen}
33080 @d expr_scale=5 {$\langle\it term\rangle$ \.*
33081 $\langle\it factor\rangle$ \./ seen}
33082
33083 @<Scan and eval...@>=
33084 restart: r:=expr_none; e:=0; s:=expr_none; t:=0; n:=0;
33085 continue: if s=expr_none then o:=l@+else o:=int_val;
33086 @<Scan a factor |f| of type |o| or start a subexpression@>;
33087 found: @<Scan the next operator and set |o|@>;
33088 arith_error:=b;
33089 @<Make sure that |f| is in the proper range@>;
33090 case s of @<Cases for evaluation of the current term@>@;
33091 end; {there are no other cases}
33092 if o>expr_sub then s:=o@+else @<Evaluate the current expression@>;
33093 b:=arith_error;
33094 if o<>expr_none then goto continue;
33095 if p<>null then @<Pop the expression stack and |goto found|@>
33096
33097 @ @<Scan the next op...@>=
33098 @<Get the next non-blank non-call token@>;
33099 if cur_tok=other_token+"+" then o:=expr_add
33100 else if cur_tok=other_token+"-" then o:=expr_sub
33101 else if cur_tok=other_token+"*" then o:=expr_mult
33102 else if cur_tok=other_token+"/" then o:=expr_div
33103 else begin o:=expr_none;
33104 if p=null then
33105 begin if cur_cmd<>relax then back_input;
33106 end
33107 else if cur_tok<>other_token+")" then
33108 begin print_err("Missing ) inserted for expression");
33109 @.Missing ) inserted@>
33110 help1("I was expecting to see `+', `-', `*', `/', or `)'. Didn't.");
33111 back_error;
33112 end;
33113 end
33114
33115 @ @<Scan a factor...@>=
33116 @<Get the next non-blank non-call token@>;
33117 if cur_tok=other_token+"(" then
33118 @<Push the expression stack and |goto restart|@>;
33119 back_input;
33120 if o=int_val then scan_int
33121 else if o=dimen_val then scan_normal_dimen
33122 else if o=glue_val then scan_normal_glue
33123 else scan_mu_glue;
33124 f:=cur_val
33125
33126 @ @<Declare \eTeX\ procedures for sc...@>=
33127 procedure@?scan_normal_glue; forward;@t\2@>@/
33128 procedure@?scan_mu_glue; forward;@t\2@>
33129
33130 @ Here we declare two trivial procedures in order to avoid mutually
33131 recursive procedures with parameters.
33132
33133 @<Declare procedures needed for expressions@>=
33134 procedure scan_normal_glue;
33135 begin scan_glue(glue_val);
33136 end;
33137 @#
33138 procedure scan_mu_glue;
33139 begin scan_glue(mu_val);
33140 end;
33141
33142 @ Parenthesized subexpressions can be inside expressions, and this
33143 nesting has a stack. Seven local variables represent the top of the
33144 expression stack: |p| points to pushed-down entries, if any; |l|
33145 specifies the type of expression currently being evaluated; |e| is the
33146 expression so far and |r| is the state of its evaluation; |t| is the
33147 term so far and |s| is the state of its evaluation; finally |n| is the
33148 numerator for a combined multiplication and division, if any.
33149
33150 @d expr_node_size=4 {number of words in stack entry for subexpressions}
33151 @d expr_e_field(#)==mem[#+1].int {saved expression so far}
33152 @d expr_t_field(#)==mem[#+2].int {saved term so far}
33153 @d expr_n_field(#)==mem[#+3].int {saved numerator}
33154
33155 @<Push the expression...@>=
33156 begin q:=get_node(expr_node_size); link(q):=p; type(q):=l;
33157 subtype(q):=4*s+r;
33158 expr_e_field(q):=e; expr_t_field(q):=t; expr_n_field(q):=n;
33159 p:=q; l:=o; goto restart;
33160 end
33161
33162 @ @<Pop the expression...@>=
33163 begin f:=e; q:=p;
33164 e:=expr_e_field(q); t:=expr_t_field(q); n:=expr_n_field(q);
33165 s:=subtype(q) div 4; r:=subtype(q) mod 4;
33166 l:=type(q); p:=link(q); free_node(q,expr_node_size);
33167 goto found;
33168 end
33169
33170 @ We want to make sure that each term and (intermediate) result is in
33171 the proper range. Integer values must not exceed |infinity|
33172 ($2^{31}-1$) in absolute value, dimensions must not exceed |max_dimen|
33173 ($2^{30}-1$). We avoid the absolute value of an integer, because this
33174 might fail for the value $-2^{31}$ using 32-bit arithmetic.
33175
33176 @d num_error(#)== {clear a number or dimension and set |arith_error|}
33177 begin arith_error:=true; #:=0;
33178 end
33179 @d glue_error(#)== {clear a glue spec and set |arith_error|}
33180 begin arith_error:=true; delete_glue_ref(#); #:=new_spec(zero_glue);
33181 end
33182
33183 @<Make sure that |f|...@>=
33184 if (l=int_val)or(s>expr_sub) then
33185 begin if (f>infinity)or(f<-infinity) then num_error(f);
33186 end
33187 else if l=dimen_val then
33188 begin if abs(f)>max_dimen then num_error(f);
33189 end
33190 else begin if (abs(width(f))>max_dimen)or@|
33191 (abs(stretch(f))>max_dimen)or@|
33192 (abs(shrink(f))>max_dimen) then glue_error(f);
33193 end
33194
33195 @ Applying the factor |f| to the partial term |t| (with the operator
33196 |s|) is delayed until the next operator |o| has been scanned. Here we
33197 handle the first factor of a partial term. A glue spec has to be copied
33198 unless the next operator is a right parenthesis; this allows us later on
33199 to simply modify the glue components.
33200
33201 @d normalize_glue(#)==
33202 if stretch(#)=0 then stretch_order(#):=normal;
33203 if shrink(#)=0 then shrink_order(#):=normal
33204
33205 @<Cases for evaluation of the current term@>=
33206 expr_none: if (l>=glue_val)and(o<>expr_none) then
33207 begin t:=new_spec(f); delete_glue_ref(f); normalize_glue(t);
33208 end
33209 else t:=f;
33210
33211 @ When a term |t| has been completed it is copied to, added to, or
33212 subtracted from the expression |e|.
33213
33214 @d expr_add_sub(#)==add_or_sub(#,r=expr_sub)
33215 @d expr_a(#)==expr_add_sub(#,max_dimen)
33216
33217 @<Evaluate the current expression@>=
33218 begin s:=expr_none;
33219 if r=expr_none then e:=t
33220 else if l=int_val then e:=expr_add_sub(e,t,infinity)
33221 else if l=dimen_val then e:=expr_a(e,t)
33222 else @<Compute the sum or difference of two glue specs@>;
33223 r:=o;
33224 end
33225
33226 @ The function |add_or_sub(x,y,max_answer,negative)| computes the sum
33227 (for |negative=false|) or difference (for |negative=true|) of |x| and
33228 |y|, provided the absolute value of the result does not exceed
33229 |max_answer|.
33230
33231 @<Declare subprocedures for |scan_expr|@>=
33232 function add_or_sub(@!x,@!y,@!max_answer:integer;@!negative:boolean):integer;
33233 var a:integer; {the answer}
33234 begin if negative then negate(y);
33235 if x>=0 then
33236 if y<=max_answer-x then a:=x+y@+else num_error(a)
33237 else if y>=-max_answer-x then a:=x+y@+else num_error(a);
33238 add_or_sub:=a;
33239 end;
33240
33241 @ We know that |stretch_order(e)>normal| implies |stretch(e)<>0| and
33242 |shrink_order(e)>normal| implies |shrink(e)<>0|.
33243
33244 @<Compute the sum or diff...@>=
33245 begin width(e):=expr_a(width(e),width(t));
33246 if stretch_order(e)=stretch_order(t) then
33247 stretch(e):=expr_a(stretch(e),stretch(t))
33248 else if (stretch_order(e)<stretch_order(t))and(stretch(t)<>0) then
33249 begin stretch(e):=stretch(t); stretch_order(e):=stretch_order(t);
33250 end;
33251 if shrink_order(e)=shrink_order(t) then
33252 shrink(e):=expr_a(shrink(e),shrink(t))
33253 else if (shrink_order(e)<shrink_order(t))and(shrink(t)<>0) then
33254 begin shrink(e):=shrink(t); shrink_order(e):=shrink_order(t);
33255 end;
33256 delete_glue_ref(t); normalize_glue(e);
33257 end
33258
33259 @ If a multiplication is followed by a division, the two operations are
33260 combined into a `scaling' operation. Otherwise the term |t| is
33261 multiplied by the factor |f|.
33262
33263 @d expr_m(#)==#:=nx_plus_y(#,f,0)
33264
33265 @<Cases for evaluation of the current term@>=
33266 expr_mult: if o=expr_div then
33267 begin n:=f; o:=expr_scale;
33268 end
33269 else if l=int_val then t:=mult_integers(t,f)
33270 else if l=dimen_val then expr_m(t)
33271 else begin expr_m(width(t)); expr_m(stretch(t)); expr_m(shrink(t));
33272 end;
33273
33274 @ Here we divide the term |t| by the factor |f|.
33275
33276 @d expr_d(#)==#:=quotient(#,f)
33277
33278 @<Cases for evaluation of the current term@>=
33279 expr_div: if l<glue_val then expr_d(t)
33280 else begin expr_d(width(t)); expr_d(stretch(t)); expr_d(shrink(t));
33281 end;
33282
33283 @ The function |quotient(n,d)| computes the rounded quotient
33284 $q=\lfloor n/d+{1\over2}\rfloor$, when $n$ and $d$ are positive.
33285
33286 @<Declare subprocedures for |scan_expr|@>=
33287 function quotient(@!n,@!d:integer):integer;
33288 var negative:boolean; {should the answer be negated?}
33289 @!a:integer; {the answer}
33290 begin if d=0 then num_error(a)
33291 else begin if d>0 then negative:=false
33292 else begin negate(d); negative:=true;
33293 end;
33294 if n<0 then
33295 begin negate(n); negative:=not negative;
33296 end;
33297 a:=n div d; n:=n-a*d; d:=n-d; {avoid certain compiler optimizations!}
33298 if d+n>=0 then incr(a);
33299 if negative then negate(a);
33300 end;
33301 quotient:=a;
33302 end;
33303
33304 @ Here the term |t| is multiplied by the quotient $n/f$.
33305
33306 @d expr_s(#)==#:=fract(#,n,f,max_dimen)
33307
33308 @<Cases for evaluation of the current term@>=
33309 expr_scale: if l=int_val then t:=fract(t,n,f,infinity)
33310 else if l=dimen_val then expr_s(t)
33311 else begin expr_s(width(t)); expr_s(stretch(t)); expr_s(shrink(t));
33312 end;
33313
33314 @ Finally, the function |fract(x,n,d,max_answer)| computes the integer
33315 $q=\lfloor xn/d+{1\over2}\rfloor$, when $x$, $n$, and $d$ are positive
33316 and the result does not exceed |max_answer|. We can't use floating
33317 point arithmetic since the routine must produce identical results in all
33318 cases; and it would be too dangerous to multiply by~|n| and then divide
33319 by~|d|, in separate operations, since overflow might well occur. Hence
33320 this subroutine simulates double precision arithmetic, somewhat
33321 analogous to \MF's |make_fraction| and |take_fraction| routines.
33322
33323 @d too_big=88 {go here when the result is too big}
33324
33325 @<Declare subprocedures for |scan_expr|@>=
33326 function fract(@!x,@!n,@!d,@!max_answer:integer):integer;
33327 label found, found1, too_big, done;
33328 var negative:boolean; {should the answer be negated?}
33329 @!a:integer; {the answer}
33330 @!f:integer; {a proper fraction}
33331 @!h:integer; {smallest integer such that |2*h>=d|}
33332 @!r:integer; {intermediate remainder}
33333 @!t:integer; {temp variable}
33334 begin if d=0 then goto too_big;
33335 a:=0;
33336 if d>0 then negative:=false
33337 else begin negate(d); negative:=true;
33338 end;
33339 if x<0 then
33340 begin negate(x); negative:=not negative;
33341 end
33342 else if x=0 then goto done;
33343 if n<0 then
33344 begin negate(n); negative:=not negative;
33345 end;
33346 t:=n div d;
33347 if t>max_answer div x then goto too_big;
33348 a:=t*x; n:=n-t*d;
33349 if n=0 then goto found;
33350 t:=x div d;
33351 if t>(max_answer-a) div n then goto too_big;
33352 a:=a+t*n; x:=x-t*d;
33353 if x=0 then goto found;
33354 if x<n then
33355 begin t:=x; x:=n; n:=t;
33356 end; {now |0<n<=x<d|}
33357 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>@;
33358 if f>(max_answer-a) then goto too_big;
33359 a:=a+f;
33360 found: if negative then negate(a);
33361 goto done;
33362 too_big: num_error(a);
33363 done: fract:=a;
33364 end;
33365
33366 @ The loop here preserves the following invariant relations
33367 between |f|, |x|, |n|, and~|r|:
33368 (i)~$f+\lfloor(xn+(r+d))/d\rfloor=\lfloor x_0n_0/d+{1\over2}\rfloor$;
33369 (ii)~|-d<=r<0<n<=x<d|, where $x_0$, $n_0$ are the original values of~$x$
33370 and $n$.
33371
33372 Notice that the computation specifies |(x-d)+x| instead of |(x+x)-d|,
33373 because the latter could overflow.
33374
33375 @<Compute \(f)$f=\lfloor xn/d+{1\over2}\rfloor$@>=
33376 f:=0; r:=(d div 2)-d; h:=-r;
33377 loop@+begin if odd(n) then
33378 begin r:=r+x;
33379 if r>=0 then
33380 begin r:=r-d; incr(f);
33381 end;
33382 end;
33383 n:=n div 2;
33384 if n=0 then goto found1;
33385 if x<h then x:=x+x
33386 else begin t:=x-d; x:=t+x; f:=f+n;
33387 if x<n then
33388 begin if x=0 then goto found1;
33389 t:=x; x:=n; n:=t;
33390 end;
33391 end;
33392 end;
33393 found1:
33394
33395 @ The \.{\\gluestretch}, \.{\\glueshrink}, \.{\\gluestretchorder}, and
33396 \.{\\glueshrinkorder} commands return the stretch and shrink components
33397 and their orders of ``infinity'' of a glue specification.
33398
33399 @d glue_stretch_order_code=eTeX_int+6 {code for \.{\\gluestretchorder}}
33400 @d glue_shrink_order_code=eTeX_int+7 {code for \.{\\glueshrinkorder}}
33401 @d glue_stretch_code=eTeX_dim+7 {code for \.{\\gluestretch}}
33402 @d glue_shrink_code=eTeX_dim+8 {code for \.{\\glueshrink}}
33403
33404 @<Generate all \eTeX...@>=
33405 primitive("gluestretchorder",last_item,glue_stretch_order_code);
33406 @!@:glue_stretch_order_}{\.{\\gluestretchorder} primitive@>
33407 primitive("glueshrinkorder",last_item,glue_shrink_order_code);
33408 @!@:glue_shrink_order_}{\.{\\glueshrinkorder} primitive@>
33409 primitive("gluestretch",last_item,glue_stretch_code);
33410 @!@:glue_stretch_}{\.{\\gluestretch} primitive@>
33411 primitive("glueshrink",last_item,glue_shrink_code);
33412 @!@:glue_shrink_}{\.{\\glueshrink} primitive@>
33413
33414 @ @<Cases of |last_item| for |print_cmd_chr|@>=
33415 glue_stretch_order_code: print_esc("gluestretchorder");
33416 glue_shrink_order_code: print_esc("glueshrinkorder");
33417 glue_stretch_code: print_esc("gluestretch");
33418 glue_shrink_code: print_esc("glueshrink");
33419
33420 @ @<Cases for fetching an integer value@>=
33421 glue_stretch_order_code, glue_shrink_order_code:
33422 begin scan_normal_glue; q:=cur_val;
33423 if m=glue_stretch_order_code then cur_val:=stretch_order(q)
33424 else cur_val:=shrink_order(q);
33425 delete_glue_ref(q);
33426 end;
33427
33428 @ @<Cases for fetching a dimension value@>=
33429 glue_stretch_code, glue_shrink_code:
33430 begin scan_normal_glue; q:=cur_val;
33431 if m=glue_stretch_code then cur_val:=stretch(q)
33432 else cur_val:=shrink(q);
33433 delete_glue_ref(q);
33434 end;
33435
33436 @ The \.{\\mutoglue} and \.{\\gluetomu} commands convert ``math'' glue
33437 into normal glue and vice versa; they allow to manipulate math glue with
33438 \.{\\gluestretch} etc.
33439
33440 @d mu_to_glue_code=eTeX_glue {code for \.{\\mutoglue}}
33441 @d glue_to_mu_code=eTeX_mu {code for \.{\\gluetomu}}
33442
33443 @<Generate all \eTeX...@>=
33444 primitive("mutoglue",last_item,mu_to_glue_code);
33445 @!@:mu_to_glue_}{\.{\\mutoglue} primitive@>
33446 primitive("gluetomu",last_item,glue_to_mu_code);
33447 @!@:glue_to_mu_}{\.{\\gluetomu} primitive@>
33448
33449 @ @<Cases of |last_item| for |print_cmd_chr|@>=
33450 mu_to_glue_code: print_esc("mutoglue");
33451 glue_to_mu_code: print_esc("gluetomu");
33452
33453 @ @<Cases for fetching a glue value@>=
33454 mu_to_glue_code: scan_mu_glue;
33455
33456 @ @<Cases for fetching a mu value@>=
33457 glue_to_mu_code: scan_normal_glue;
33458
33459 @ \eTeX\ (in extended mode) supports 32768 (i.e., $2^{15}$) count,
33460 dimen, skip, muskip, box, and token registers. As in \TeX\ the first
33461 256 registers of each kind are realized as arrays in the table of
33462 equivalents; the additional registers are realized as tree structures
33463 built from variable-size nodes with individual registers existing only
33464 when needed. Default values are used for nonexistent registers: zero
33465 for count and dimen values, |zero_glue| for glue (skip and muskip)
33466 values, void for boxes, and |null| for token lists (and current marks
33467 discussed below).
33468
33469 Similarly there are 32768 mark classes; the command \.{\\marks}|n|
33470 creates a mark node for a given mark class |0<=n<=32767| (where
33471 \.{\\marks0} is synonymous to \.{\\mark}). The page builder (actually
33472 the |fire_up| routine) and the |vsplit| routine maintain the current
33473 values of |top_mark|, |first_mark|, |bot_mark|, |split_first_mark|, and
33474 |split_bot_mark| for each mark class. They are accessed as
33475 \.{\\topmarks}|n| etc., and \.{\\topmarks0} is again synonymous to
33476 \.{\\topmark}. As in \TeX\ the five current marks for mark class zero
33477 are realized as |cur_mark| array. The additional current marks are
33478 again realized as tree structure with individual mark classes existing
33479 only when needed.
33480
33481 @<Generate all \eTeX...@>=
33482 primitive("marks",mark,marks_code);
33483 @!@:marks_}{\.{\\marks} primitive@>
33484 primitive("topmarks",top_bot_mark,top_mark_code+marks_code);
33485 @!@:top_marks_}{\.{\\topmarks} primitive@>
33486 primitive("firstmarks",top_bot_mark,first_mark_code+marks_code);
33487 @!@:first_marks_}{\.{\\firstmarks} primitive@>
33488 primitive("botmarks",top_bot_mark,bot_mark_code+marks_code);
33489 @!@:bot_marks_}{\.{\\botmarks} primitive@>
33490 primitive("splitfirstmarks",top_bot_mark,split_first_mark_code+marks_code);
33491 @!@:split_first_marks_}{\.{\\splitfirstmarks} primitive@>
33492 primitive("splitbotmarks",top_bot_mark,split_bot_mark_code+marks_code);
33493 @!@:split_bot_marks_}{\.{\\splitbotmarks} primitive@>
33494
33495 @ The |scan_register_num| procedure scans a register number that must
33496 not exceed 255 in compatibility mode resp.\ 32767 in extended mode.
33497
33498 @<Declare \eTeX\ procedures for ex...@>=
33499 procedure@?scan_register_num; forward;@t\2@>
33500
33501 @ @<Declare procedures that scan restricted classes of integers@>=
33502 procedure scan_register_num;
33503 begin scan_int;
33504 if (cur_val<0)or(cur_val>max_reg_num) then
33505 begin print_err("Bad register code");
33506 @.Bad register code@>
33507 help2(max_reg_help_line)("I changed this one to zero.");
33508 int_error(cur_val); cur_val:=0;
33509 end;
33510 end;
33511
33512 @ @<Initialize variables for \eTeX\ comp...@>=
33513 max_reg_num:=255;
33514 max_reg_help_line:="A register number must be between 0 and 255.";
33515
33516 @ @<Initialize variables for \eTeX\ ext...@>=
33517 max_reg_num:=32767;
33518 max_reg_help_line:="A register number must be between 0 and 32767.";
33519
33520 @ @<Glob...@>=
33521 @!max_reg_num: halfword; {largest allowed register number}
33522 @!max_reg_help_line: str_number; {first line of help message}
33523
33524 @ There are eight almost identical doubly linked trees, one for the
33525 sparse array of the up to 32512 additional registers of each kind,
33526 one for inter-character token lists at specified class transitions, and
33527 one for the sparse array of the up to 32767 additional mark classes.
33528 The root of each such tree, if it exists, is an index node containing 64
33529 pointers to subtrees for $64^4$ consecutive array elements. Similar index
33530 nodes are the starting points for all nonempty subtrees for $64^3$, $64^2$,
33531 and 64 consecutive array elements. These four levels of index nodes are
33532 followed by a fifth level with nodes for the individual array elements.
33533
33534 Each index node is 33 words long. The pointers to the 64 possible
33535 subtrees or nodes are kept in the |info| and |link| fields of the last 32
33536 words. (It would be both elegant and efficient to declare them as
33537 array, unfortunately \PASCAL\ doesn't allow this.)
33538
33539 The fields in the first word of each index node and in the nodes for the
33540 array elements are closely related. The |link| field points to the next
33541 lower index node and the |sa_index| field contains four bits (one
33542 hexadecimal digit) of the register number or mark class. For the lowest
33543 index node the |link| field is |null| and the |sa_index| field indicates
33544 the type of quantity (|int_val|, |dimen_val|, |glue_val|, |mu_val|,
33545 |box_val|, |tok_val|, |inter_char_val| or |mark_val|). The |sa_used| field in the index
33546 nodes counts how many of the 64 pointers are non-null.
33547
33548 The |sa_index| field in the nodes for array elements contains the six
33549 bits plus 64 times the type. Therefore such a node represents a count
33550 or dimen register if and only if |sa_index<dimen_val_limit|; it
33551 represents a skip or muskip register if and only if
33552 |dimen_val_limit<=sa_index<mu_val_limit|; it represents a box register
33553 if and only if |mu_val_limit<=sa_index<box_val_limit|; it represents a
33554 token list register if and only if
33555 |box_val_limit<=sa_index<tok_val_limit|; finally it represents a mark
33556 class if and only if |tok_val_limit<=sa_index|.
33557
33558 The |new_index| procedure creates an index node (returned in |cur_ptr|)
33559 having given contents of the |sa_index| and |link| fields.
33560
33561 @d box_val==4 {the additional box registers}
33562 @d mark_val=7 {the additional mark classes}
33563 @#
33564 @d dimen_val_limit=@"80 {$2^6\cdot(|dimen_val|+1)$}
33565 @d mu_val_limit=@"100 {$2^6\cdot(|mu_val|+1)$}
33566 @d box_val_limit=@"140 {$2^6\cdot(|box_val|+1)$}
33567 @d tok_val_limit=@"180 {$2^6\cdot(|tok_val|+1)$}
33568 @#
33569 @d index_node_size=33 {size of an index node}
33570 @d sa_index==type {a four-bit address or a type or both}
33571 @d sa_used==subtype {count of non-null pointers}
33572
33573 @<Declare \eTeX\ procedures for ex...@>=
33574 procedure new_index(@!i:quarterword; @!q:pointer);
33575 var k:small_number; {loop index}
33576 begin cur_ptr:=get_node(index_node_size); sa_index(cur_ptr):=i;
33577 sa_used(cur_ptr):=0; link(cur_ptr):=q;
33578 for k:=1 to index_node_size-1 do {clear all 64 pointers}
33579 mem[cur_ptr+k]:=sa_null;
33580 end;
33581
33582 @ The roots of the eight trees for the additional registers and mark
33583 classes are kept in the |sa_root| array. The first seven locations must
33584 be dumped and undumped; the last one is also known as |sa_mark|.
33585
33586 @d sa_mark==sa_root[mark_val] {root for mark classes}
33587
33588 @<Glob...@>=
33589 @!sa_root:array[int_val..mark_val] of pointer; {roots of sparse arrays}
33590 @!cur_ptr:pointer; {value returned by |new_index| and |find_sa_element|}
33591 @!sa_null:memory_word; {two |null| pointers}
33592
33593 @ @<Set init...@>=
33594 sa_mark:=null; sa_null.hh.lh:=null; sa_null.hh.rh:=null;
33595
33596 @ @<Initialize table...@>=
33597 for i:=int_val to inter_char_val do sa_root[i]:=null;
33598
33599 @ Given a type |t| and a twenty-four-bit number |n|, the |find_sa_element|
33600 procedure returns (in |cur_ptr|) a pointer to the node for the
33601 corresponding array element, or |null| when no such element exists. The
33602 third parameter |w| is set |true| if the element must exist, e.g.,
33603 because it is about to be modified. The procedure has two main
33604 branches: one follows the existing tree structure, the other (only used
33605 when |w| is |true|) creates the missing nodes.
33606
33607 We use macros to extract the six-bit pieces from a twenty-four-bit register
33608 number or mark class and to fetch or store one of the 64 pointers from
33609 an index node. (Note that the |hex_dig| macros are mis-named since the conversion
33610 from 4-bit to 6-bit fields for \XeTeX!)
33611
33612 @d if_cur_ptr_is_null_then_return_or_goto(#)== {some tree element is missing}
33613 begin if cur_ptr=null then
33614 if w then goto #@+else return;
33615 end
33616 @#
33617 @d hex_dig1(#)==# div @"40000 {the fourth lowest 6-bit field}
33618 @d hex_dig2(#)==(# div @"1000) mod @"40 {the third lowest 6-bit field}
33619 @d hex_dig3(#)==(# div @"40) mod @"40 {the second lowest 6-bit field}
33620 @d hex_dig4(#)==# mod @"40 {the lowest 6-bit field}
33621 @#
33622 @d get_sa_ptr==if odd(i) then cur_ptr:=link(q+(i div 2)+1)
33623 else cur_ptr:=info(q+(i div 2)+1)
33624 {set |cur_ptr| to the pointer indexed by |i| from index node |q|}
33625 @d put_sa_ptr(#)==if odd(i) then link(q+(i div 2)+1):=#
33626 else info(q+(i div 2)+1):=#
33627 {store the pointer indexed by |i| in index node |q|}
33628 @d add_sa_ptr==begin put_sa_ptr(cur_ptr); incr(sa_used(q));
33629 end {add |cur_ptr| as the pointer indexed by |i| in index node |q|}
33630 @d delete_sa_ptr==begin put_sa_ptr(null); decr(sa_used(q));
33631 end {delete the pointer indexed by |i| in index node |q|}
33632
33633 @<Declare \eTeX\ procedures for ex...@>=
33634 procedure find_sa_element(@!t:small_number;@!n:halfword;@!w:boolean);
33635 {sets |cur_val| to sparse array element location or |null|}
33636 label not_found,not_found1,not_found2,not_found3,not_found4,exit;
33637 var q:pointer; {for list manipulations}
33638 @!i:small_number; {a six bit index}
33639 begin cur_ptr:=sa_root[t];
33640 if_cur_ptr_is_null_then_return_or_goto(not_found);@/
33641 q:=cur_ptr; i:=hex_dig1(n); get_sa_ptr;
33642 if_cur_ptr_is_null_then_return_or_goto(not_found1);@/
33643 q:=cur_ptr; i:=hex_dig2(n); get_sa_ptr;
33644 if_cur_ptr_is_null_then_return_or_goto(not_found2);@/
33645 q:=cur_ptr; i:=hex_dig3(n); get_sa_ptr;
33646 if_cur_ptr_is_null_then_return_or_goto(not_found3);@/
33647 q:=cur_ptr; i:=hex_dig4(n); get_sa_ptr;
33648 if (cur_ptr=null)and w then goto not_found4;
33649 return;
33650 not_found: new_index(t,null); {create first level index node}
33651 sa_root[t]:=cur_ptr; q:=cur_ptr; i:=hex_dig1(n);
33652 not_found1: new_index(i,q); {create second level index node}
33653 add_sa_ptr; q:=cur_ptr; i:=hex_dig2(n);
33654 not_found2: new_index(i,q); {create third level index node}
33655 add_sa_ptr; q:=cur_ptr; i:=hex_dig3(n);
33656 not_found3: new_index(i,q); {create fourth level index node}
33657 add_sa_ptr; q:=cur_ptr; i:=hex_dig4(n);
33658 not_found4: @<Create a new array element of type |t| with index |i|@>;
33659 link(cur_ptr):=q; add_sa_ptr;
33660 exit:end;
33661
33662 @ The array elements for registers are subject to grouping and have an
33663 |sa_lev| field (quite analogous to |eq_level|) instead of |sa_used|.
33664 Since saved values as well as shorthand definitions (created by e.g.,
33665 \.{\\countdef}) refer to the location of the respective array element,
33666 we need a reference count that is kept in the |sa_ref| field. An array
33667 element can be deleted (together with all references to it) when its
33668 |sa_ref| value is |null| and its value is the default value.
33669 @^reference counts@>
33670
33671 Skip, muskip, box, and token registers use two word nodes, their values
33672 are stored in the |sa_ptr| field.
33673 Count and dimen registers use three word nodes, their
33674 values are stored in the |sa_int| resp.\ |sa_dim| field in the third
33675 word; the |sa_ptr| field is used under the name |sa_num| to store
33676 the register number. Mark classes use four word nodes. The last three
33677 words contain the five types of current marks
33678
33679 @d sa_lev==sa_used {grouping level for the current value}
33680 @d pointer_node_size=2 {size of an element with a pointer value}
33681 @d sa_type(#)==(sa_index(#) div 64) {type part of combined type/index}
33682 @d sa_ref(#)==info(#+1) {reference count of a sparse array element}
33683 @d sa_ptr(#)==link(#+1) {a pointer value}
33684 @#
33685 @d word_node_size=3 {size of an element with a word value}
33686 @d sa_num==sa_ptr {the register number}
33687 @d sa_int(#)==mem[#+2].int {an integer}
33688 @d sa_dim(#)==mem[#+2].sc {a dimension (a somewhat esotheric distinction)}
33689 @#
33690 @d mark_class_node_size=4 {size of an element for a mark class}
33691 @#
33692 @d fetch_box(#)== {fetch |box(cur_val)|}
33693 if cur_val<256 then #:=box(cur_val)
33694 else begin find_sa_element(box_val,cur_val,false);
33695 if cur_ptr=null then #:=null@+else #:=sa_ptr(cur_ptr);
33696 end
33697
33698 @<Create a new array element...@>=
33699 if t=mark_val then {a mark class}
33700 begin cur_ptr:=get_node(mark_class_node_size);
33701 mem[cur_ptr+1]:=sa_null; mem[cur_ptr+2]:=sa_null; mem[cur_ptr+3]:=sa_null;
33702 end
33703 else begin if t<=dimen_val then {a count or dimen register}
33704 begin cur_ptr:=get_node(word_node_size); sa_int(cur_ptr):=0;
33705 sa_num(cur_ptr):=n;
33706 end
33707 else begin cur_ptr:=get_node(pointer_node_size);
33708 if t<=mu_val then {a skip or muskip register}
33709 begin sa_ptr(cur_ptr):=zero_glue; add_glue_ref(zero_glue);
33710 end
33711 else sa_ptr(cur_ptr):=null; {a box or token list register}
33712 end;
33713 sa_ref(cur_ptr):=null; {all registers have a reference count}
33714 end;
33715 sa_index(cur_ptr):=64*t+i; sa_lev(cur_ptr):=level_one
33716
33717 @ The |delete_sa_ref| procedure is called when a pointer to an array
33718 element representing a register is being removed; this means that the
33719 reference count should be decreased by one. If the reduced reference
33720 count is |null| and the register has been (globally) assigned its
33721 default value the array element should disappear, possibly together with
33722 some index nodes. This procedure will never be used for mark class
33723 nodes.
33724 @^reference counts@>
33725
33726 @d add_sa_ref(#)==incr(sa_ref(#)) {increase reference count}
33727 @#
33728 @d change_box(#)== {change |box(cur_val)|, the |eq_level| stays the same}
33729 if cur_val<256 then box(cur_val):=#@+else set_sa_box(#)
33730 @#
33731 @d set_sa_box(#)==begin find_sa_element(box_val,cur_val,false);
33732 if cur_ptr<>null then
33733 begin sa_ptr(cur_ptr):=#; add_sa_ref(cur_ptr); delete_sa_ref(cur_ptr);
33734 end;
33735 end
33736
33737 @<Declare \eTeX\ procedures for tr...@>=
33738 procedure delete_sa_ref(@!q:pointer); {reduce reference count}
33739 label exit;
33740 var p:pointer; {for list manipulations}
33741 @!i:small_number; {a four bit index}
33742 @!s:small_number; {size of a node}
33743 begin decr(sa_ref(q));
33744 if sa_ref(q)<>null then return;
33745 if sa_index(q)<dimen_val_limit then
33746 if sa_int(q)=0 then s:=word_node_size
33747 else return
33748 else begin if sa_index(q)<mu_val_limit then
33749 if sa_ptr(q)=zero_glue then delete_glue_ref(zero_glue)
33750 else return
33751 else if sa_ptr(q)<>null then return;
33752 s:=pointer_node_size;
33753 end;
33754 repeat i:=hex_dig4(sa_index(q)); p:=q; q:=link(p); free_node(p,s);
33755 if q=null then {the whole tree has been freed}
33756 begin sa_root[i]:=null; return;
33757 end;
33758 delete_sa_ptr; s:=index_node_size; {node |q| is an index node}
33759 until sa_used(q)>0;
33760 exit:end;
33761
33762 @ The |print_sa_num| procedure prints the register number corresponding
33763 to an array element.
33764
33765 @<Basic print...@>=
33766 procedure print_sa_num(@!q:pointer); {print register number}
33767 var @!n:halfword; {the register number}
33768 begin if sa_index(q)<dimen_val_limit then n:=sa_num(q) {the easy case}
33769 else begin n:=hex_dig4(sa_index(q)); q:=link(q); n:=n+64*sa_index(q);
33770 q:=link(q); n:=n+64*64*(sa_index(q)+64*sa_index(link(q)));
33771 end;
33772 print_int(n);
33773 end;
33774
33775 @ Here is a procedure that displays the contents of an array element
33776 symbolically. It is used under similar circumstances as is
33777 |restore_trace| (together with |show_eqtb|) for the quantities kept in
33778 the |eqtb| array.
33779
33780 @<Declare \eTeX\ procedures for tr...@>=
33781 @!stat procedure show_sa(@!p:pointer;@!s:str_number);
33782 var t:small_number; {the type of element}
33783 begin begin_diagnostic; print_char("{"); print(s); print_char(" ");
33784 if p=null then print_char("?") {this can't happen}
33785 else begin t:=sa_type(p);
33786 if t<box_val then print_cmd_chr(register,p)
33787 else if t=box_val then
33788 begin print_esc("box"); print_sa_num(p);
33789 end
33790 else if t=tok_val then print_cmd_chr(toks_register,p)
33791 else print_char("?"); {this can't happen either}
33792 print_char("=");
33793 if t=int_val then print_int(sa_int(p))
33794 else if t=dimen_val then
33795 begin print_scaled(sa_dim(p)); print("pt");
33796 end
33797 else begin p:=sa_ptr(p);
33798 if t=glue_val then print_spec(p,"pt")
33799 else if t=mu_val then print_spec(p,"mu")
33800 else if t=box_val then
33801 if p=null then print("void")
33802 else begin depth_threshold:=0; breadth_max:=1; show_node_list(p);
33803 end
33804 else if t=tok_val then
33805 begin if p<>null then show_token_list(link(p),null,32);
33806 end
33807 else print_char("?"); {this can't happen either}
33808 end;
33809 end;
33810 print_char("}"); end_diagnostic(false);
33811 end;
33812 tats
33813
33814 @ Here we compute the pointer to the current mark of type |t| and mark
33815 class |cur_val|.
33816
33817 @<Compute the mark pointer...@>=
33818 begin find_sa_element(mark_val,cur_val,false);
33819 if cur_ptr<>null then
33820 if odd(t) then cur_ptr:=link(cur_ptr+(t div 2)+1)
33821 else cur_ptr:=info(cur_ptr+(t div 2)+1);
33822 end
33823
33824 @ The current marks for all mark classes are maintained by the |vsplit|
33825 and |fire_up| routines and are finally destroyed (for \.{INITEX} only)
33826 @.INITEX@>
33827 by the |final_cleanup| routine. Apart from updating the current marks
33828 when mark nodes are encountered, these routines perform certain actions
33829 on all existing mark classes. The recursive |do_marks| procedure walks
33830 through the whole tree or a subtree of existing mark class nodes and
33831 preforms certain actions indicted by its first parameter |a|, the action
33832 code. The second parameter |l| indicates the level of recursion (at
33833 most four); the third parameter points to a nonempty tree or subtree.
33834 The result is |true| if the complete tree or subtree has been deleted.
33835
33836 @d vsplit_init==0 {action code for |vsplit| initialization}
33837 @d fire_up_init==1 {action code for |fire_up| initialization}
33838 @d fire_up_done==2 {action code for |fire_up| completion}
33839 @d destroy_marks==3 {action code for |final_cleanup|}
33840 @#
33841 @d sa_top_mark(#)==info(#+1) {\.{\\topmarks}|n|}
33842 @d sa_first_mark(#)==link(#+1) {\.{\\firstmarks}|n|}
33843 @d sa_bot_mark(#)==info(#+2) {\.{\\botmarks}|n|}
33844 @d sa_split_first_mark(#)==link(#+2) {\.{\\splitfirstmarks}|n|}
33845 @d sa_split_bot_mark(#)==info(#+3) {\.{\\splitbotmarks}|n|}
33846
33847 @<Declare the function called |do_marks|@>=
33848 function do_marks(@!a,@!l:small_number;@!q:pointer):boolean;
33849 var i:small_number; {a four bit index}
33850 begin if l<4 then {|q| is an index node}
33851 begin for i:=0 to 15 do
33852 begin get_sa_ptr;
33853 if cur_ptr<>null then if do_marks(a,l+1,cur_ptr) then delete_sa_ptr;
33854 end;
33855 if sa_used(q)=0 then
33856 begin free_node(q,index_node_size); q:=null;
33857 end;
33858 end
33859 else {|q| is the node for a mark class}
33860 begin case a of
33861 @<Cases for |do_marks|@>@;
33862 end; {there are no other cases}
33863 if sa_bot_mark(q)=null then if sa_split_bot_mark(q)=null then
33864 begin free_node(q,mark_class_node_size); q:=null;
33865 end;
33866 end;
33867 do_marks:=(q=null);
33868 end;
33869
33870 @ At the start of the |vsplit| routine the existing |split_fist_mark|
33871 and |split_bot_mark| are discarded.
33872
33873 @<Cases for |do_marks|@>=
33874 vsplit_init: if sa_split_first_mark(q)<>null then
33875 begin delete_token_ref(sa_split_first_mark(q)); sa_split_first_mark(q):=null;
33876 delete_token_ref(sa_split_bot_mark(q)); sa_split_bot_mark(q):=null;
33877 end;
33878
33879 @ We use again the fact that |split_first_mark=null| if and only if
33880 |split_bot_mark=null|.
33881
33882 @<Update the current marks for |vsplit|@>=
33883 begin find_sa_element(mark_val,mark_class(p),true);
33884 if sa_split_first_mark(cur_ptr)=null then
33885 begin sa_split_first_mark(cur_ptr):=mark_ptr(p);
33886 add_token_ref(mark_ptr(p));
33887 end
33888 else delete_token_ref(sa_split_bot_mark(cur_ptr));
33889 sa_split_bot_mark(cur_ptr):=mark_ptr(p);
33890 add_token_ref(mark_ptr(p));
33891 end
33892
33893 @ At the start of the |fire_up| routine the old |top_mark| and
33894 |first_mark| are discarded, whereas the old |bot_mark| becomes the new
33895 |top_mark|. An empty new |top_mark| token list is, however, discarded
33896 as well in order that mark class nodes can eventually be released. We
33897 use again the fact that |bot_mark<>null| implies |first_mark<>null|; it
33898 also knows that |bot_mark=null| implies |top_mark=first_mark=null|.
33899
33900 @<Cases for |do_marks|@>=
33901 fire_up_init: if sa_bot_mark(q)<>null then
33902 begin if sa_top_mark(q)<>null then delete_token_ref(sa_top_mark(q));
33903 delete_token_ref(sa_first_mark(q)); sa_first_mark(q):=null;
33904 if link(sa_bot_mark(q))=null then {an empty token list}
33905 begin delete_token_ref(sa_bot_mark(q)); sa_bot_mark(q):=null;
33906 end
33907 else add_token_ref(sa_bot_mark(q));
33908 sa_top_mark(q):=sa_bot_mark(q);
33909 end;
33910
33911 @ @<Cases for |do_marks|@>=
33912 fire_up_done: if (sa_top_mark(q)<>null)and(sa_first_mark(q)=null) then
33913 begin sa_first_mark(q):=sa_top_mark(q); add_token_ref(sa_top_mark(q));
33914 end;
33915
33916 @ @<Update the current marks for |fire_up|@>=
33917 begin find_sa_element(mark_val,mark_class(p),true);
33918 if sa_first_mark(cur_ptr)=null then
33919 begin sa_first_mark(cur_ptr):=mark_ptr(p);
33920 add_token_ref(mark_ptr(p));
33921 end;
33922 if sa_bot_mark(cur_ptr)<>null then delete_token_ref(sa_bot_mark(cur_ptr));
33923 sa_bot_mark(cur_ptr):=mark_ptr(p); add_token_ref(mark_ptr(p));
33924 end
33925
33926 @ Here we use the fact that the five current mark pointers in a mark
33927 class node occupy the same locations as the the first five pointers of
33928 an index node. For systems using a run-time switch to distinguish
33929 between \.{VIRTEX} and \.{INITEX}, the codewords `$|init|\ldots|tini|$'
33930 surrounding the following piece of code should be removed.
33931 @.INITEX@>
33932 @^system dependencies@>
33933
33934 @<Cases for |do_marks|@>=
33935 @!init destroy_marks: for i:=top_mark_code to split_bot_mark_code do
33936 begin get_sa_ptr;
33937 if cur_ptr<>null then
33938 begin delete_token_ref(cur_ptr); put_sa_ptr(null);
33939 end;
33940 end;
33941 tini
33942
33943 @ The command code |register| is used for `\.{\\count}', `\.{\\dimen}',
33944 etc., as well as for references to sparse array elements defined by
33945 `\.{\\countdef}', etc.
33946
33947 @<Cases of |register| for |print_cmd_chr|@>=
33948 begin if (chr_code<mem_bot)or(chr_code>lo_mem_stat_max) then
33949 cmd:=sa_type(chr_code)
33950 else begin cmd:=chr_code-mem_bot; chr_code:=null;
33951 end;
33952 if cmd=int_val then print_esc("count")
33953 else if cmd=dimen_val then print_esc("dimen")
33954 else if cmd=glue_val then print_esc("skip")
33955 else print_esc("muskip");
33956 if chr_code<>null then print_sa_num(chr_code);
33957 end
33958
33959 @ Similarly the command code |toks_register| is used for `\.{\\toks}' as
33960 well as for references to sparse array elements defined by
33961 `\.{\\toksdef}'.
33962
33963 @<Cases of |toks_register| for |print_cmd_chr|@>=
33964 begin print_esc("toks");
33965 if chr_code<>mem_bot then print_sa_num(chr_code);
33966 end
33967
33968 @ When a shorthand definition for an element of one of the sparse arrays
33969 is destroyed, we must reduce the reference count.
33970
33971 @<Cases for |eq_destroy|@>=
33972 toks_register,register:
33973 if (equiv_field(w)<mem_bot)or(equiv_field(w)>lo_mem_stat_max) then
33974 delete_sa_ref(equiv_field(w));
33975
33976 @ The task to maintain (change, save, and restore) register values is
33977 essentially the same when the register is realized as sparse array
33978 element or entry in |eqtb|. The global variable |sa_chain| is the head
33979 of a linked list of entries saved at the topmost level |sa_level|; the
33980 lists for lowel levels are kept in special save stack entries.
33981
33982 @<Glob...@>=
33983 @!sa_chain: pointer; {chain of saved sparse array entries}
33984 @!sa_level: quarterword; {group level for |sa_chain|}
33985
33986 @ @<Set init...@>=
33987 sa_chain:=null; sa_level:=level_zero;
33988
33989 @ The individual saved items are kept in pointer or word nodes similar
33990 to those used for the array elements: a word node with value zero is,
33991 however, saved as pointer node with the otherwise impossible |sa_index|
33992 value |tok_val_limit|.
33993
33994 @d sa_loc==sa_ref {location of saved item}
33995
33996 @<Declare \eTeX\ procedures for tr...@>=
33997 procedure sa_save(@!p:pointer); {saves value of |p|}
33998 var q:pointer; {the new save node}
33999 @!i:quarterword; {index field of node}
34000 begin if cur_level<>sa_level then
34001 begin check_full_save_stack; save_type(save_ptr):=restore_sa;
34002 save_level(save_ptr):=sa_level; save_index(save_ptr):=sa_chain;
34003 incr(save_ptr); sa_chain:=null; sa_level:=cur_level;
34004 end;
34005 i:=sa_index(p);
34006 if i<dimen_val_limit then
34007 begin if sa_int(p)=0 then
34008 begin q:=get_node(pointer_node_size); i:=tok_val_limit;
34009 end
34010 else begin q:=get_node(word_node_size); sa_int(q):=sa_int(p);
34011 end;
34012 sa_ptr(q):=null;
34013 end
34014 else begin q:=get_node(pointer_node_size); sa_ptr(q):=sa_ptr(p);
34015 end;
34016 sa_loc(q):=p; sa_index(q):=i; sa_lev(q):=sa_lev(p);
34017 link(q):=sa_chain; sa_chain:=q; add_sa_ref(p);
34018 end;
34019
34020 @ @<Declare \eTeX\ procedures for tr...@>=
34021 procedure sa_destroy(@!p:pointer); {destroy value of |p|}
34022 begin if sa_index(p)<mu_val_limit then delete_glue_ref(sa_ptr(p))
34023 else if sa_ptr(p)<>null then
34024 if sa_index(p)<box_val_limit then flush_node_list(sa_ptr(p))
34025 else delete_token_ref(sa_ptr(p));
34026 end;
34027
34028 @ The procedure |sa_def| assigns a new value to sparse array elements,
34029 and saves the former value if appropriate. This procedure is used only
34030 for skip, muskip, box, and token list registers. The counterpart of
34031 |sa_def| for count and dimen registers is called |sa_w_def|.
34032
34033 @d sa_define(#)==if e then
34034 if global then gsa_def(#)@+else sa_def(#)
34035 else define
34036 @#
34037 @d sa_def_box== {assign |cur_box| to |box(cur_val)|}
34038 begin find_sa_element(box_val,cur_val,true);
34039 if global then gsa_def(cur_ptr,cur_box)@+else sa_def(cur_ptr,cur_box);
34040 end
34041 @#
34042 @d sa_word_define(#)==if e then
34043 if global then gsa_w_def(#)@+else sa_w_def(#)
34044 else word_define(#)
34045
34046 @<Declare \eTeX\ procedures for tr...@>=
34047 procedure sa_def(@!p:pointer;@!e:halfword);
34048 {new data for sparse array elements}
34049 begin add_sa_ref(p);
34050 if sa_ptr(p)=e then
34051 begin @!stat if tracing_assigns>0 then show_sa(p,"reassigning");@+tats@;@/
34052 sa_destroy(p);
34053 end
34054 else begin @!stat if tracing_assigns>0 then show_sa(p,"changing");@+tats@;@/
34055 if sa_lev(p)=cur_level then sa_destroy(p)@+else sa_save(p);
34056 sa_lev(p):=cur_level; sa_ptr(p):=e;
34057 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
34058 end;
34059 delete_sa_ref(p);
34060 end;
34061 @#
34062 procedure sa_w_def(@!p:pointer;@!w:integer);
34063 begin add_sa_ref(p);
34064 if sa_int(p)=w then
34065 begin @!stat if tracing_assigns>0 then show_sa(p,"reassigning");@+tats@;@/
34066 end
34067 else begin @!stat if tracing_assigns>0 then show_sa(p,"changing");@+tats@;@/
34068 if sa_lev(p)<>cur_level then sa_save(p);
34069 sa_lev(p):=cur_level; sa_int(p):=w;
34070 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
34071 end;
34072 delete_sa_ref(p);
34073 end;
34074
34075 @ The |sa_def| and |sa_w_def| routines take care of local definitions.
34076 @^global definitions@>
34077 Global definitions are done in almost the same way, but there is no need
34078 to save old values, and the new value is associated with |level_one|.
34079
34080 @<Declare \eTeX\ procedures for tr...@>=
34081 procedure gsa_def(@!p:pointer;@!e:halfword); {global |sa_def|}
34082 begin add_sa_ref(p);
34083 @!stat if tracing_assigns>0 then show_sa(p,"globally changing");@+tats@;@/
34084 sa_destroy(p); sa_lev(p):=level_one; sa_ptr(p):=e;
34085 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
34086 delete_sa_ref(p);
34087 end;
34088 @#
34089 procedure gsa_w_def(@!p:pointer;@!w:integer); {global |sa_w_def|}
34090 begin add_sa_ref(p);
34091 @!stat if tracing_assigns>0 then show_sa(p,"globally changing");@+tats@;@/
34092 sa_lev(p):=level_one; sa_int(p):=w;
34093 @!stat if tracing_assigns>0 then show_sa(p,"into");@+tats@;@/
34094 delete_sa_ref(p);
34095 end;
34096
34097 @ The |sa_restore| procedure restores the sparse array entries pointed
34098 at by |sa_chain|
34099
34100 @<Declare \eTeX\ procedures for tr...@>=
34101 procedure sa_restore;
34102 var p:pointer; {sparse array element}
34103 begin repeat p:=sa_loc(sa_chain);
34104 if sa_lev(p)=level_one then
34105 begin if sa_index(p)>=dimen_val_limit then sa_destroy(sa_chain);
34106 @!stat if tracing_restores>0 then show_sa(p,"retaining");@+tats@;@/
34107 end
34108 else begin if sa_index(p)<dimen_val_limit then
34109 if sa_index(sa_chain)<dimen_val_limit then sa_int(p):=sa_int(sa_chain)
34110 else sa_int(p):=0
34111 else begin sa_destroy(p); sa_ptr(p):=sa_ptr(sa_chain);
34112 end;
34113 sa_lev(p):=sa_lev(sa_chain);
34114 @!stat if tracing_restores>0 then show_sa(p,"restoring");@+tats@;@/
34115 end;
34116 delete_sa_ref(p);
34117 p:=sa_chain; sa_chain:=link(p);
34118 if sa_index(p)<dimen_val_limit then free_node(p,word_node_size)
34119 else free_node(p,pointer_node_size);
34120 until sa_chain=null;
34121 end;
34122
34123 @ When the value of |last_line_fit| is positive, the last line of a
34124 (partial) paragraph is treated in a special way and we need additional
34125 fields in the active nodes.
34126
34127 @d active_node_size_extended=5 {number of words in extended active nodes}
34128 @d active_short(#)==mem[#+3].sc {|shortfall| of this line}
34129 @d active_glue(#)==mem[#+4].sc {corresponding glue stretch or shrink}
34130
34131 @<Glob...@>=
34132 @!last_line_fill:pointer; {the |par_fill_skip| glue node of the new paragraph}
34133 @!do_last_line_fit:boolean; {special algorithm for last line of paragraph?}
34134 @!active_node_size:small_number; {number of words in active nodes}
34135 @!fill_width:array[0..2] of scaled; {infinite stretch components of
34136 |par_fill_skip|}
34137 @!best_pl_short:array[very_loose_fit..tight_fit] of scaled; {|shortfall|
34138 corresponding to |minimal_demerits|}
34139 @!best_pl_glue:array[very_loose_fit..tight_fit] of scaled; {corresponding
34140 glue stretch or shrink}
34141
34142 @ The new algorithm for the last line requires that the stretchability of
34143 |par_fill_skip| is infinite and the stretchability of |left_skip| plus
34144 |right_skip| is finite.
34145
34146 @<Check for special...@>=
34147 do_last_line_fit:=false; active_node_size:=active_node_size_normal;
34148 {just in case}
34149 if last_line_fit>0 then
34150 begin q:=glue_ptr(last_line_fill);
34151 if (stretch(q)>0)and(stretch_order(q)>normal) then
34152 if (background[3]=0)and(background[4]=0)and(background[5]=0) then
34153 begin do_last_line_fit:=true;
34154 active_node_size:=active_node_size_extended;
34155 fill_width[0]:=0; fill_width[1]:=0; fill_width[2]:=0;
34156 fill_width[stretch_order(q)-1]:=stretch(q);
34157 end;
34158 end
34159
34160 @ @<Other local variables for |try_break|@>=
34161 @!g:scaled; {glue stretch or shrink of test line, adjustment for last line}
34162
34163 @ Here we initialize the additional fields of the first active node
34164 representing the beginning of the paragraph.
34165
34166 @<Initialize additional fields of the first active node@>=
34167 begin active_short(q):=0; active_glue(q):=0;
34168 end
34169
34170 @ Here we compute the adjustment |g| and badness |b| for a line from |r|
34171 to the end of the paragraph. When any of the criteria for adjustment is
34172 violated we fall through to the normal algorithm.
34173
34174 The last line must be too short, and have infinite stretch entirely due
34175 to |par_fill_skip|.
34176
34177 @<Perform computations for last line and |goto found|@>=
34178 begin if (active_short(r)=0)or(active_glue(r)<=0) then goto not_found;
34179 {previous line was neither stretched nor shrunk, or was infinitely bad}
34180 if (cur_active_width[3]<>fill_width[0])or@|
34181 (cur_active_width[4]<>fill_width[1])or@|
34182 (cur_active_width[5]<>fill_width[2]) then goto not_found;
34183 {infinite stretch of this line not entirely due to |par_fill_skip|}
34184 if active_short(r)>0 then g:=cur_active_width[2]
34185 else g:=cur_active_width[6];
34186 if g<=0 then goto not_found; {no finite stretch resp.\ no shrink}
34187 arith_error:=false; g:=fract(g,active_short(r),active_glue(r),max_dimen);
34188 if last_line_fit<1000 then g:=fract(g,last_line_fit,1000,max_dimen);
34189 if arith_error then
34190 if active_short(r)>0 then g:=max_dimen@+else g:=-max_dimen;
34191 if g>0 then
34192 @<Set the value of |b| to the badness of the last line for stretching,
34193 compute the corresponding |fit_class|, and |goto found|@>
34194 else if g<0 then
34195 @<Set the value of |b| to the badness of the last line for shrinking,
34196 compute the corresponding |fit_class|, and |goto found|@>;
34197 not_found:end
34198
34199 @ These badness computations are rather similar to those of the standard
34200 algorithm, with the adjustment amount |g| replacing the |shortfall|.
34201
34202 @<Set the value of |b| to the badness of the last line for str...@>=
34203 begin if g>shortfall then g:=shortfall;
34204 if g>7230584 then if cur_active_width[2]<1663497 then
34205 begin b:=inf_bad; fit_class:=very_loose_fit; goto found;
34206 end;
34207 b:=badness(g,cur_active_width[2]);
34208 if b>12 then
34209 if b>99 then fit_class:=very_loose_fit
34210 else fit_class:=loose_fit
34211 else fit_class:=decent_fit;
34212 goto found;
34213 end
34214
34215 @ @<Set the value of |b| to the badness of the last line for shr...@>=
34216 begin if -g>cur_active_width[6] then g:=-cur_active_width[6];
34217 b:=badness(-g,cur_active_width[6]);
34218 if b>12 then fit_class:=tight_fit@+else fit_class:=decent_fit;
34219 goto found;
34220 end
34221
34222 @ Vanishing values of |shortfall| and |g| indicate that the last line is
34223 not adjusted.
34224
34225 @<Adjust \(t)the additional data for last line@>=
34226 begin if cur_p=null then shortfall:=0;
34227 if shortfall>0 then g:=cur_active_width[2]
34228 else if shortfall<0 then g:=cur_active_width[6]
34229 else g:=0;
34230 end
34231
34232 @ For each feasible break we record the shortfall and glue stretch or
34233 shrink (or adjustment).
34234
34235 @<Store \(a)additional data for this feasible break@>=
34236 begin best_pl_short[fit_class]:=shortfall; best_pl_glue[fit_class]:=g;
34237 end
34238
34239 @ Here we save these data in the active node representing a potential
34240 line break.
34241
34242 @<Store \(a)additional data in the new active node@>=
34243 begin active_short(q):=best_pl_short[fit_class];
34244 active_glue(q):=best_pl_glue[fit_class];
34245 end
34246
34247 @ @<Print additional data in the new active node@>=
34248 begin print(" s="); print_scaled(active_short(q));
34249 if cur_p=null then print(" a=")@+else print(" g=");
34250 print_scaled(active_glue(q));
34251 end
34252
34253 @ Here we either reset |do_last_line_fit| or adjust the |par_fill_skip|
34254 glue.
34255
34256 @<Adjust \(t)the final line of the paragraph@>=
34257 if active_short(best_bet)=0 then do_last_line_fit:=false
34258 else begin q:=new_spec(glue_ptr(last_line_fill));
34259 delete_glue_ref(glue_ptr(last_line_fill));
34260 width(q):=width(q)+active_short(best_bet)-active_glue(best_bet);
34261 stretch(q):=0; glue_ptr(last_line_fill):=q;
34262 end
34263
34264 @ When reading \.{\\patterns} while \.{\\savinghyphcodes} is positive
34265 the current |lc_code| values are stored together with the hyphenation
34266 patterns for the current language. They will later be used instead of
34267 the |lc_code| values for hyphenation purposes.
34268
34269 The |lc_code| values are stored in the linked trie analogous to patterns
34270 $p_1$ of length~1, with |hyph_root=trie_r[0]| replacing |trie_root| and
34271 |lc_code(p_1)| replacing the |trie_op| code. This allows to compress
34272 and pack them together with the patterns with minimal changes to the
34273 existing code.
34274
34275 @d hyph_root==trie_r[0] {root of the linked trie for |hyph_codes|}
34276
34277 @<Initialize table entries...@>=
34278 XeTeX_hyphenatable_length:=63; {for backward compatibility with standard TeX by default}
34279
34280 @ @<Store hyphenation codes for current language@>=
34281 begin c:=cur_lang; first_child:=false; p:=0;
34282 repeat q:=p; p:=trie_r[q];
34283 until (p=0)or(c<=so(trie_c[p]));
34284 if (p=0)or(c<so(trie_c[p])) then
34285 @<Insert a new trie node between |q| and |p|, and
34286 make |p| point to it@>;
34287 q:=p; {now node |q| represents |cur_lang|}
34288 @<Store all current |lc_code| values@>;
34289 end
34290
34291 @ We store all nonzero |lc_code| values, overwriting any previously
34292 stored values (and possibly wasting a few trie nodes that were used
34293 previously and are not needed now). We always store at least one
34294 |lc_code| value such that |hyph_index| (defined below) will not be zero.
34295
34296 @<Store all current |lc_code| values@>=
34297 p:=trie_l[q]; first_child:=true;
34298 for c:=0 to 255 do
34299 if (lc_code(c)>0)or((c=255)and first_child) then
34300 begin if p=0 then
34301 @<Insert a new trie node between |q| and |p|, and
34302 make |p| point to it@>
34303 else trie_c[p]:=si(c);
34304 trie_o[p]:=qi(lc_code(c));
34305 q:=p; p:=trie_r[q]; first_child:=false;
34306 end;
34307 if first_child then trie_l[q]:=0@+else trie_r[q]:=0
34308
34309 @ We must avoid to ``take'' location~1, in order to distinguish between
34310 |lc_code| values and patterns.
34311
34312 @<Pack all stored |hyph_codes|@>=
34313 begin if trie_root=0 then for p:=0 to 255 do trie_min[p]:=p+2;
34314 first_fit(hyph_root); trie_pack(hyph_root);
34315 hyph_start:=trie_ref[hyph_root];
34316 end
34317
34318 @ The global variable |hyph_index| will point to the hyphenation codes
34319 for the current language.
34320
34321 @d set_hyph_index== {set |hyph_index| for current language}
34322 if trie_char(hyph_start+cur_lang)<>qi(cur_lang)
34323 then hyph_index:=0 {no hyphenation codes for |cur_lang|}
34324 else hyph_index:=trie_link(hyph_start+cur_lang)
34325 @#
34326 @d set_lc_code(#)== {set |hc[0]| to hyphenation or lc code for |#|}
34327 if (hyph_index=0) or ((#)>255) then hc[0]:=lc_code(#)
34328 else if trie_char(hyph_index+#)<>qi(#) then hc[0]:=0
34329 else hc[0]:=qo(trie_op(hyph_index+#))
34330
34331 @<Glob...@>=
34332 @!hyph_start:trie_pointer; {root of the packed trie for |hyph_codes|}
34333 @!hyph_index:trie_pointer; {pointer to hyphenation codes for |cur_lang|}
34334
34335 @ When |saving_vdiscards| is positive then the glue, kern, and penalty
34336 nodes removed by the page builder or by \.{\\vsplit} from the top of a
34337 vertical list are saved in special lists instead of being discarded.
34338
34339 @d tail_page_disc==disc_ptr[copy_code] {last item removed by page builder}
34340 @d page_disc==disc_ptr[last_box_code] {first item removed by page builder}
34341 @d split_disc==disc_ptr[vsplit_code] {first item removed by \.{\\vsplit}}
34342
34343 @<Glob...@>=
34344 @!disc_ptr:array[copy_code..vsplit_code] of pointer; {list pointers}
34345
34346 @ @<Set init...@>=
34347 page_disc:=null; split_disc:=null;
34348
34349 @ The \.{\\pagediscards} and \.{\\splitdiscards} commands share the
34350 command code |un_vbox| with \.{\\unvbox} and \.{\\unvcopy}, they are
34351 distinguished by their |chr_code| values |last_box_code| and
34352 |vsplit_code|. These |chr_code| values are larger than |box_code| and
34353 |copy_code|.
34354
34355 @<Generate all \eTeX...@>=
34356 primitive("pagediscards",un_vbox,last_box_code);@/
34357 @!@:page_discards_}{\.{\\pagediscards} primitive@>
34358 primitive("splitdiscards",un_vbox,vsplit_code);@/
34359 @!@:split_discards_}{\.{\\splitdiscards} primitive@>
34360
34361 @ @<Cases of |un_vbox| for |print_cmd_chr|@>=
34362 else if chr_code=last_box_code then print_esc("pagediscards")
34363 else if chr_code=vsplit_code then print_esc("splitdiscards")
34364
34365 @ @<Handle saved items and |goto done|@>=
34366 begin link(tail):=disc_ptr[cur_chr]; disc_ptr[cur_chr]:=null;
34367 goto done;
34368 end
34369
34370 @ The \.{\\interlinepenalties}, \.{\\clubpenalties}, \.{\\widowpenalties},
34371 and \.{\\displaywidowpenalties} commands allow to define arrays of
34372 penalty values to be used instead of the corresponding single values.
34373
34374 @d inter_line_penalties_ptr==equiv(inter_line_penalties_loc)
34375 @d club_penalties_ptr==equiv(club_penalties_loc)
34376 @d widow_penalties_ptr==equiv(widow_penalties_loc)
34377 @d display_widow_penalties_ptr==equiv(display_widow_penalties_loc)
34378
34379 @<Generate all \eTeX...@>=
34380 primitive("interlinepenalties",set_shape,inter_line_penalties_loc);@/
34381 @!@:inter_line_penalties_}{\.{\\interlinepenalties} primitive@>
34382 primitive("clubpenalties",set_shape,club_penalties_loc);@/
34383 @!@:club_penalties_}{\.{\\clubpenalties} primitive@>
34384 primitive("widowpenalties",set_shape,widow_penalties_loc);@/
34385 @!@:widow_penalties_}{\.{\\widowpenalties} primitive@>
34386 primitive("displaywidowpenalties",set_shape,display_widow_penalties_loc);@/
34387 @!@:display_widow_penalties_}{\.{\\displaywidowpenalties} primitive@>
34388
34389 @ @<Cases of |set_shape| for |print_cmd_chr|@>=
34390 inter_line_penalties_loc: print_esc("interlinepenalties");
34391 club_penalties_loc: print_esc("clubpenalties");
34392 widow_penalties_loc: print_esc("widowpenalties");
34393 display_widow_penalties_loc: print_esc("displaywidowpenalties");
34394
34395 @ @<Fetch a penalties array element@>=
34396 begin scan_int;
34397 if (equiv(m)=null)or(cur_val<0) then cur_val:=0
34398 else begin if cur_val>penalty(equiv(m)) then cur_val:=penalty(equiv(m));
34399 cur_val:=penalty(equiv(m)+cur_val);
34400 end;
34401 end
34402
34403 @* \[54] System-dependent changes.
34404 This section should be replaced, if necessary, by any special
34405 modifications of the program
34406 that are necessary to make \TeX\ work at a particular installation.
34407 It is usually best to design your change file so that all changes to
34408 previous sections preserve the section numbering; then everybody's version
34409 will be consistent with the published program. More extensive changes,
34410 which introduce new sections, can be inserted here; then only the index
34411 itself will get a new section number.
34412 @^system dependencies@>
34413
34414 @* \[55] Index.
34415 Here is where you can find all uses of each identifier in the program,
34416 with underlined entries pointing to where the identifier was defined.
34417 If the identifier is only one letter long, however, you get to see only
34418 the underlined entries. {\sl All references are to section numbers instead of
34419 page numbers.}
34420
34421 This index also lists error messages and other aspects of the program
34422 that you might want to look up some day. For example, the entry
34423 for ``system dependencies'' lists all sections that should receive
34424 special attention from people who are installing \TeX\ in a new
34425 operating environment. A list of various things that can't happen appears
34426 under ``this can't happen''. Approximately 40 sections are listed under
34427 ``inner loop''; these account for about 60\pct! of \TeX's running time,
34428 exclusive of input and output.