home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / unixtex-6.1b-src.tgz / tar.out / contrib / unixtex / web2c / tex / tex.web (.txt) < prev    next >
LaTeX Document  |  1996-09-28  |  1MB  |  21,424 lines

  1. % This program is copyright (C) 1982 by D. E. Knuth; all rights are reserved.
  2. % Copying of this file is authorized only if (1) you are D. E. Knuth, or if
  3. % (2) you make absolutely no changes to your copy. (The WEB system provides
  4. % for alterations via an auxiliary file; the master file should stay intact.)
  5. % See Appendix H of the WEB manual for hints on how to install this program.
  6. % And see Appendix A of the TRIP manual for details about how to validate it.
  7. % TeX is a trademark of the American Mathematical Society.
  8. % METAFONT is a trademark of Addison-Wesley Publishing Company.
  9. % Version 0 was released in September 1982 after it passed a variety of tests.
  10. % Version 1 was released in November 1983 after thorough testing.
  11. % Version 1.1 fixed ``disappearing font identifiers'' et alia (July 1984).
  12. % Version 1.2 allowed `0' in response to an error, et alia (October 1984).
  13. % Version 1.3 made memory allocation more flexible and local (November 1984).
  14. % Version 1.4 fixed accents right after line breaks, et alia (April 1985).
  15. % Version 1.5 fixed \the\toks after other expansion in \edefs (August 1985).
  16. % Version 2.0 (almost identical to 1.5) corresponds to "Volume B" (April 1986).
  17. % Version 2.1 corrected anomalies in discretionary breaks (January 1987).
  18. % Version 2.2 corrected "(Please type...)" with null \endlinechar (April 1987).
  19. % Version 2.3 avoided incomplete page in premature termination (August 1987).
  20. % Version 2.4 fixed \noaligned rules in indented displays (August 1987).
  21. % Version 2.5 saved cur_order when expanding tokens (September 1987).
  22. % Version 2.6 added 10sp slop when shipping leaders (November 1987).
  23. % Version 2.7 improved rounding of negative-width characters (November 1987).
  24. % Version 2.8 fixed weird bug if no \patterns are used (December 1987).
  25. % Version 2.9 made \csname\endcsname's "relax" local (December 1987).
  26. % Version 2.91 fixed \outer\def\a0{}\a\a bug (April 1988).
  27. % Version 2.92 fixed \patterns, also file names with complex macros (May 1988).
  28. % Version 2.93 fixed negative halving in allocator when mem_min<0 (June 1988).
  29. % Version 2.94 kept open_log_file from calling fatal_error (November 1988).
  30. % Version 2.95 solved that problem a better way (December 1988).
  31. % Version 2.96 corrected bug in "Infinite shrinkage" recovery (January 1989).
  32. % Version 2.97 corrected blunder in creating 2.95 (February 1989).
  33. % Version 2.98 omitted save_for_after at outer level (March 1989).
  34. % Version 2.99 caught $$\begingroup\halign..$$ (June 1989).
  35. % Version 2.991 caught .5\ifdim.6... (June 1989).
  36. % Version 2.992 introduced major changes for 8-bit extensions (September 1989).
  37. % Version 2.993 fixed a save_stack synchronization bug et alia (December 1989).
  38. % Version 3.0 fixed unusual displays; was more \output robust (March 1990).
  39. % Version 3.1 fixed nullfont, disabled \write{\the\prevgraf} (September 1990).
  40. % Version 3.14 fixed unprintable font names and corrected typos (March 1991).
  41. % Version 3.141 more of same; reconstituted ligatures better (March 1992).
  42. % Version 3.1415 preserved nonexplicit kerns, tidied up (February 1993).
  43. % A reward of $327.68 will be paid to the first finder of any remaining bug,
  44. % not counting changes introduced after August 1989.
  45. % Although considerable effort has been expended to make the TeX program
  46. % correct and reliable, no warranty is implied; the author disclaims any
  47. % obligation or liability for damages, including but not limited to
  48. % special, indirect, or consequential damages arising out of or in
  49. % connection with the use or performance of this software. This work has
  50. % been a ``labor of love'' and the author hopes that users enjoy it.
  51. % Here is TeX material that gets inserted after \input webmac
  52. \def\hang{\hangindent 3em\noindent\ignorespaces}
  53. \def\textindent#1{\hangindent2.5em\noindent\hbox to2.5em{\hss#1 }\ignorespaces}
  54. \font\ninerm=cmr9
  55. \let\mc=\ninerm % medium caps for names like SAIL
  56. \def\PASCAL{Pascal}
  57. \def\ph{\hbox{Pascal-H}}
  58. \def\pct!{{\char`\%}} % percent sign in ordinary text
  59. \font\logo=logo10 % font used for the METAFONT logo
  60. \def\MF{{\logo META}\-{\logo FONT}}
  61. \def\<#1>{$\langle#1\rangle$}
  62. \def\section{\mathhexbox278}
  63. \def\(#1){} % this is used to make section names sort themselves better
  64. \def\9#1{} % this is used for sort keys in the index via @@:sort key}{entry@@>
  65. \outer\def\N#1. \[#2]#3.{\MN#1.\vfil\eject % begin starred section
  66.   \def\rhead{PART #2:\uppercase{#3}} % define running headline
  67.   \message{*\modno} % progress report
  68.   \edef\next{\write\cont{\Z{\?#2]#3}{\modno}{\the\pageno}}}\next
  69.   \ifon\startsection{\bf\ignorespaces#3.\quad}\ignorespaces}
  70. \let\?=\relax % we want to be able to \write a \?
  71. \def\title{\TeX82}
  72. \def\topofcontents{\hsize 5.5in
  73.   \vglue 0pt plus 1fil minus 1.5in
  74.   \def\?##1]{\hbox to 1in{\hfil##1.\ }}
  75. \def\botofcontents{\vskip 0pt plus 1fil minus 1.5in}
  76. \pageno=3
  77. \def\glob{13} % this should be the section number of "<Global...>"
  78. \def\gglob{20, 26} % this should be the next two sections of "<Global...>"
  79. @* \[1] Introduction.
  80. This is \TeX, a document compiler intended to produce typesetting of high
  81. quality.
  82. The \PASCAL\ program that follows is the definition of \TeX82, a standard
  83. @:PASCAL}{\PASCAL@>
  84. @!@:TeX82}{\TeX82@>
  85. version of \TeX\ that is designed to be highly portable so that identical output
  86. will be obtainable on a great variety of computers.
  87. The main purpose of the following program is to explain the algorithms of \TeX\
  88. as clearly as possible. As a result, the program will not necessarily be very
  89. efficient when a particular \PASCAL\ compiler has translated it into a
  90. particular machine language. However, the program has been written so that it
  91. can be tuned to run efficiently in a wide variety of operating environments
  92. by making comparatively few changes. Such flexibility is possible because
  93. the documentation that follows is written in the \.{WEB} language, which is
  94. at a higher level than \PASCAL; the preprocessing step that converts \.{WEB}
  95. to \PASCAL\ is able to introduce most of the necessary refinements.
  96. Semi-automatic translation to other languages is also feasible, because the
  97. program below does not make extensive use of features that are peculiar to
  98. \PASCAL.
  99. A large piece of software like \TeX\ has inherent complexity that cannot
  100. be reduced below a certain level of difficulty, although each individual
  101. part is fairly simple by itself. The \.{WEB} language is intended to make
  102. the algorithms as readable as possible, by reflecting the way the
  103. individual program pieces fit together and by providing the
  104. cross-references that connect different parts. Detailed comments about
  105. what is going on, and about why things were done in certain ways, have
  106. been liberally sprinkled throughout the program.  These comments explain
  107. features of the implementation, but they rarely attempt to explain the
  108. \TeX\ language itself, since the reader is supposed to be familiar with
  109. {\sl The \TeX book}.
  110. @.WEB@>
  111. @:TeXbook}{\sl The \TeX book@>
  112. @ The present implementation has a long ancestry, beginning in the summer
  113. of~1977, when Michael~F. Plass and Frank~M. Liang designed and coded
  114. a prototype
  115. @^Plass, Michael Frederick@>
  116. @^Liang, Franklin Mark@>
  117. @^Knuth, Donald Ervin@>
  118. based on some specifications that the author had made in May of that year.
  119. This original proto\TeX\ included macro definitions and elementary
  120. manipulations on boxes and glue, but it did not have line-breaking,
  121. page-breaking, mathematical formulas, alignment routines, error recovery,
  122. or the present semantic nest; furthermore,
  123. it used character lists instead of token lists, so that a control sequence
  124. like \.{\\halign} was represented by a list of seven characters. A
  125. complete version of \TeX\ was designed and coded by the author in late
  126. 1977 and early 1978; that program, like its prototype, was written in the
  127. {\mc SAIL} language, for which an excellent debugging system was
  128. available. Preliminary plans to convert the {\mc SAIL} code into a form
  129. somewhat like the present ``web'' were developed by Luis Trabb~Pardo and
  130. the author at the beginning of 1979, and a complete implementation was
  131. created by Ignacio~A. Zabala in 1979 and 1980. The \TeX82 program, which
  132. @^Zabala Salelles, Ignacio Andres@>
  133. was written by the author during the latter part of 1981 and the early
  134. part of 1982, also incorporates ideas from the 1979 implementation of
  135. @^Guibas, Leonidas Ioannis@>
  136. @^Sedgewick, Robert@>
  137. @^Wyatt, Douglas Kirk@>
  138. \TeX\ in {\mc MESA} that was written by Leonidas Guibas, Robert Sedgewick,
  139. and Douglas Wyatt at the Xerox Palo Alto Research Center.  Several hundred
  140. refinements were introduced into \TeX82 based on the experiences gained with
  141. the original implementations, so that essentially every part of the system
  142. has been substantially improved. After the appearance of ``Version 0'' in
  143. September 1982, this program benefited greatly from the comments of
  144. many other people, notably David~R. Fuchs and Howard~W. Trickey.
  145. A final revision in September 1989 extended the input character set to
  146. eight-bit codes and introduced the ability to hyphenate words from
  147. different languages, based on some ideas of Michael~J. Ferguson.
  148. @^Fuchs, David Raymond@>
  149. @^Trickey, Howard Wellington@>
  150. @^Ferguson, Michael John@>
  151. No doubt there still is plenty of room for improvement, but the author
  152. is firmly committed to keeping \TeX82 ``frozen'' from now on; stability
  153. and reliability are to be its main virtues.
  154. On the other hand, the \.{WEB} description can be extended without changing
  155. the core of \TeX82 itself, and the program has been designed so that such
  156. extensions are not extremely difficult to make.
  157. The |banner| string defined here should be changed whenever \TeX\
  158. undergoes any modifications, so that it will be clear which version of
  159. \TeX\ might be the guilty party when a problem arises.
  160. @^extensions to \TeX@>
  161. @^system dependencies@>
  162. If this program is changed, the resulting system should not be called
  163. `\TeX'; the official name `\TeX' by itself is reserved
  164. for software systems that are fully compatible with each other.
  165. A special test suite called the ``\.{TRIP} test'' is available for
  166. helping to determine whether a particular implementation deserves to be
  167. known as `\TeX' [cf.~Stanford Computer Science report CS1027,
  168. November 1984].
  169. @d banner=='This is TeX, Version 3.1415' {printed when \TeX\ starts}
  170. @ Different \PASCAL s have slightly different conventions, and the present
  171. @!@:PASCAL H}{\ph@>
  172. program expresses \TeX\ in terms of the \PASCAL\ that was
  173. available to the author in 1982. Constructions that apply to
  174. this particular compiler, which we shall call \ph, should help the
  175. reader see how to make an appropriate interface for other systems
  176. if necessary. (\ph\ is Charles Hedrick's modification of a compiler
  177. @^Hedrick, Charles Locke@>
  178. for the DECsystem-10 that was originally developed at the University of
  179. Hamburg; cf.\ {\sl SOFTWARE---Practice \AM\ Experience \bf6} (1976),
  180. 29--42. The \TeX\ program below is intended to be adaptable, without
  181. extensive changes, to most other versions of \PASCAL, so it does not fully
  182. use the admirable features of \ph. Indeed, a conscious effort has been
  183. made here to avoid using several idiosyncratic features of standard
  184. \PASCAL\ itself, so that most of the code can be translated mechanically
  185. into other high-level languages. For example, the `\&{with}' and `\\{new}'
  186. features are not used, nor are pointer types, set types, or enumerated
  187. scalar types; there are no `\&{var}' parameters, except in the case of files;
  188. there are no tag fields on variant records; there are no assignments
  189. |real:=integer|; no procedures are declared local to other procedures.)
  190. The portions of this program that involve system-dependent code, where
  191. changes might be necessary because of differences between \PASCAL\ compilers
  192. and/or differences between
  193. operating systems, can be identified by looking at the sections whose
  194. numbers are listed under `system dependencies' in the index. Furthermore,
  195. the index entries for `dirty \PASCAL' list all places where the restrictions
  196. of \PASCAL\ have not been followed perfectly, for one reason or another.
  197. @!@^system dependencies@>
  198. @!@^dirty \PASCAL@>
  199. @ The program begins with a normal \PASCAL\ program heading, whose
  200. components will be filled in later, using the conventions of \.{WEB}.
  201. @.WEB@>
  202. For example, the portion of the program called `\X\glob:Global
  203. variables\X' below will be replaced by a sequence of variable declarations
  204. that starts in $\section\glob$ of this documentation. In this way, we are able
  205. to define each individual global variable when we are prepared to
  206. understand what it means; we do not have to define all of the globals at
  207. once.  Cross references in $\section\glob$, where it says ``See also
  208. sections \gglob, \dots,'' also make it possible to look at the set of
  209. all global variables, if desired.  Similar remarks apply to the other
  210. portions of the program heading.
  211. Actually the heading shown here is not quite normal: The |program| line
  212. does not mention any |output| file, because \ph\ would ask the \TeX\ user
  213. to specify a file name if |output| were specified here.
  214. @^system dependencies@>
  215. @d mtype==t@&y@&p@&e {this is a \.{WEB} coding trick:}
  216. @f mtype==type {`\&{mtype}' will be equivalent to `\&{type}'}
  217. @f type==true {but `|type|' will not be treated as a reserved word}
  218. @p @t\4@>@<Compiler directives@>@/
  219. program TEX; {all file names are defined dynamically}
  220. label @<Labels in the outer block@>@/
  221. const @<Constants in the outer block@>@/
  222. mtype @<Types in the outer block@>@/
  223. var @<Global variables@>@/
  224. procedure initialize; {this procedure gets things started properly}
  225.   var @<Local variables for initialization@>@/
  226.   begin @<Initialize whatever \TeX\ might access@>@;
  227.   end;@#
  228. @t\4@>@<Basic printing procedures@>@/
  229. @t\4@>@<Error handling procedures@>@/
  230. @ The overall \TeX\ program begins with the heading just shown, after which
  231. comes a bunch of procedure declarations and function declarations.
  232. Finally we will get to the main program, which begins with the
  233. comment `|start_here|'. If you want to skip down to the
  234. main program now, you can look up `|start_here|' in the index.
  235. But the author suggests that the best way to understand this program
  236. is to follow pretty much the order of \TeX's components as they appear in the
  237. \.{WEB} description you are now reading, since the present ordering is
  238. intended to combine the advantages of the ``bottom up'' and ``top down''
  239. approaches to the problem of understanding a somewhat complicated system.
  240. @ Three labels must be declared in the main program, so we give them
  241. symbolic names.
  242. @d start_of_TEX=1 {go here when \TeX's variables are initialized}
  243. @d end_of_TEX=9998 {go here to close files and terminate gracefully}
  244. @d final_end=9999 {this label marks the ending of the program}
  245. @<Labels in the out...@>=
  246. start_of_TEX@t\hskip-2pt@>, end_of_TEX@t\hskip-2pt@>,@,final_end;
  247.   {key control points}
  248. @ Some of the code below is intended to be used only when diagnosing the
  249. strange behavior that sometimes occurs when \TeX\ is being installed or
  250. when system wizards are fooling around with \TeX\ without quite knowing
  251. what they are doing. Such code will not normally be compiled; it is
  252. delimited by the codewords `$|debug|\ldots|gubed|$', with apologies
  253. to people who wish to preserve the purity of English.
  254. Similarly, there is some conditional code delimited by
  255. `$|stat|\ldots|tats|$' that is intended for use when statistics are to be
  256. kept about \TeX's memory usage.  The |stat| $\ldots$ |tats| code also
  257. implements diagnostic information for \.{\\tracingparagraphs} and
  258. \.{\\tracingpages}.
  259. @^debugging@>
  260. @d debug==@{ {change this to `$\\{debug}\equiv\null$' when debugging}
  261. @d gubed==@t@>@} {change this to `$\\{gubed}\equiv\null$' when debugging}
  262. @f debug==begin
  263. @f gubed==end
  264. @d stat==@{ {change this to `$\\{stat}\equiv\null$' when gathering
  265.   usage statistics}
  266. @d tats==@t@>@} {change this to `$\\{tats}\equiv\null$' when gathering
  267.   usage statistics}
  268. @f stat==begin
  269. @f tats==end
  270. @ This program has two important variations: (1) There is a long and slow
  271. version called \.{INITEX}, which does the extra calculations needed to
  272. @.INITEX@>
  273. initialize \TeX's internal tables; and (2)~there is a shorter and faster
  274. production version, which cuts the initialization to a bare minimum.
  275. Parts of the program that are needed in (1) but not in (2) are delimited by
  276. the codewords `$|init|\ldots|tini|$'.
  277. @d init== {change this to `$\\{init}\equiv\.{@@\{}$' in the production version}
  278. @d tini== {change this to `$\\{tini}\equiv\.{@@\}}$' in the production version}
  279. @f init==begin
  280. @f tini==end
  281. @<Initialize whatever...@>=
  282. @<Set initial values of key variables@>@/
  283. @!init @<Initialize table entries (done by \.{INITEX} only)@>@;@+tini
  284. @ If the first character of a \PASCAL\ comment is a dollar sign,
  285. \ph\ treats the comment as a list of ``compiler directives'' that will
  286. affect the translation of this program into machine language.  The
  287. directives shown below specify full checking and inclusion of the \PASCAL\
  288. debugger when \TeX\ is being debugged, but they cause range checking and other
  289. redundant code to be eliminated when the production system is being generated.
  290. Arithmetic overflow will be detected in all cases.
  291. @^system dependencies@>
  292. @^Overflow in arithmetic@>
  293. @<Compiler directives@>=
  294. @{@&$C-,A+,D-@} {no range check, catch arithmetic overflow, no debug overhead}
  295. @!debug @{@&$C+,D+@}@+ gubed {but turn everything on when debugging}
  296. @ This \TeX\ implementation conforms to the rules of the {\sl Pascal User
  297. @:PASCAL}{\PASCAL@>
  298. @^system dependencies@>
  299. Manual} published by Jensen and Wirth in 1975, except where system-dependent
  300. @^Wirth, Niklaus@>
  301. @^Jensen, Kathleen@>
  302. code is necessary to make a useful system program, and except in another
  303. respect where such conformity would unnecessarily obscure the meaning
  304. and clutter up the code: We assume that |case| statements may include a
  305. default case that applies if no matching label is found. Thus, we shall use
  306. constructions like
  307. $$\vbox{\halign{\ignorespaces#\hfil\cr
  308. |case x of|\cr
  309. 1: $\langle\,$code for $x=1\,\rangle$;\cr
  310. 3: $\langle\,$code for $x=3\,\rangle$;\cr
  311. |othercases| $\langle\,$code for |x<>1| and |x<>3|$\,\rangle$\cr
  312. |endcases|\cr}}$$
  313. since most \PASCAL\ compilers have plugged this hole in the language by
  314. incorporating some sort of default mechanism. For example, the \ph\
  315. compiler allows `|others|:' as a default label, and other \PASCAL s allow
  316. syntaxes like `\&{else}' or `\&{otherwise}' or `\\{otherwise}:', etc. The
  317. definitions of |othercases| and |endcases| should be changed to agree with
  318. local conventions.  Note that no semicolon appears before |endcases| in
  319. this program, so the definition of |endcases| should include a semicolon
  320. if the compiler wants one. (Of course, if no default mechanism is
  321. available, the |case| statements of \TeX\ will have to be laboriously
  322. extended by listing all remaining cases. People who are stuck with such
  323. \PASCAL s have, in fact, done this, successfully but not happily!)
  324. @d othercases == others: {default for cases not listed explicitly}
  325. @d endcases == @+end {follows the default case in an extended |case| statement}
  326. @f othercases == else
  327. @f endcases == end
  328. @ The following parameters can be changed at compile time to extend or
  329. reduce \TeX's capacity. They may have different values in \.{INITEX} and
  330. in production versions of \TeX.
  331. @.INITEX@>
  332. @^system dependencies@>
  333. @<Constants...@>=
  334. @!mem_max=30000; {greatest index in \TeX's internal |mem| array;
  335.   must be strictly less than |max_halfword|;
  336.   must be equal to |mem_top| in \.{INITEX}, otherwise |>=mem_top|}
  337. @!mem_min=0; {smallest index in \TeX's internal |mem| array;
  338.   must be |min_halfword| or more;
  339.   must be equal to |mem_bot| in \.{INITEX}, otherwise |<=mem_bot|}
  340. @!buf_size=500; {maximum number of characters simultaneously present in
  341.   current lines of open files and in control sequences between
  342.   \.{\\csname} and \.{\\endcsname}; must not exceed |max_halfword|}
  343. @!error_line=72; {width of context lines on terminal error messages}
  344. @!half_error_line=42; {width of first lines of contexts in terminal
  345.   error messages; should be between 30 and |error_line-15|}
  346. @!max_print_line=79; {width of longest text lines output; should be at least 60}
  347. @!stack_size=200; {maximum number of simultaneous input sources}
  348. @!max_in_open=6; {maximum number of input files and error insertions that
  349.   can be going on simultaneously}
  350. @!font_max=75; {maximum internal font number; must not exceed |max_quarterword|
  351.   and must be at most |font_base+256|}
  352. @!font_mem_size=20000; {number of words of |font_info| for all fonts}
  353. @!param_size=60; {maximum number of simultaneous macro parameters}
  354. @!nest_size=40; {maximum number of semantic levels simultaneously active}
  355. @!max_strings=3000; {maximum number of strings; must not exceed |max_halfword|}
  356. @!string_vacancies=8000; {the minimum number of characters that should be
  357.   available for the user's control sequences and font names,
  358.   after \TeX's own error messages are stored}
  359. @!pool_size=32000; {maximum number of characters in strings, including all
  360.   error messages and help texts, and the names of all fonts and
  361.   control sequences; must exceed |string_vacancies| by the total
  362.   length of \TeX's own strings, which is currently about 23000}
  363. @!save_size=600; {space for saving values outside of current group; must be
  364.   at most |max_halfword|}
  365. @!trie_size=8000; {space for hyphenation patterns; should be larger for
  366.   \.{INITEX} than it is in production versions of \TeX}
  367. @!trie_op_size=500; {space for ``opcodes'' in the hyphenation patterns}
  368. @!dvi_buf_size=800; {size of the output buffer; must be a multiple of 8}
  369. @!file_name_size=40; {file names shouldn't be longer than this}
  370. @!pool_name='TeXformats:TEX.POOL                     ';
  371.   {string of length |file_name_size|; tells where the string pool appears}
  372. @.TeXformats@>
  373. @ Like the preceding parameters, the following quantities can be changed
  374. at compile time to extend or reduce \TeX's capacity. But if they are changed,
  375. it is necessary to rerun the initialization program \.{INITEX}
  376. @.INITEX@>
  377. to generate new tables for the production \TeX\ program.
  378. One can't simply make helter-skelter changes to the following constants,
  379. since certain rather complex initialization
  380. numbers are computed from them. They are defined here using
  381. \.{WEB} macros, instead of being put into \PASCAL's |const| list, in order to
  382. emphasize this distinction.
  383. @d mem_bot=0 {smallest index in the |mem| array dumped by \.{INITEX};
  384.   must not be less than |mem_min|}
  385. @d mem_top==30000 {largest index in the |mem| array dumped by \.{INITEX};
  386.   must be substantially larger than |mem_bot|
  387.   and not greater than |mem_max|}
  388. @d font_base=0 {smallest internal font number; must not be less
  389.   than |min_quarterword|}
  390. @d hash_size=2100 {maximum number of control sequences; it should be at most
  391.   about |(mem_max-mem_min)/10|}
  392. @d hash_prime=1777 {a prime number equal to about 85\pct! of |hash_size|}
  393. @d hyph_size=307 {another prime; the number of \.{\\hyphenation} exceptions}
  394. @^system dependencies@>
  395. @ In case somebody has inadvertently made bad settings of the ``constants,''
  396. \TeX\ checks them using a global variable called |bad|.
  397. This is the first of many sections of \TeX\ where global variables are
  398. defined.
  399. @<Glob...@>=
  400. @!bad:integer; {is some ``constant'' wrong?}
  401. @ Later on we will say `\ignorespaces|if mem_max>=max_halfword then bad:=14|',
  402. or something similar. (We can't do that until |max_halfword| has been defined.)
  403. @<Check the ``constant'' values for consistency@>=
  404. bad:=0;
  405. if (half_error_line<30)or(half_error_line>error_line-15) then bad:=1;
  406. if max_print_line<60 then bad:=2;
  407. if dvi_buf_size mod 8<>0 then bad:=3;
  408. if mem_bot+1100>mem_top then bad:=4;
  409. if hash_prime>hash_size then bad:=5;
  410. if max_in_open>=128 then bad:=6;
  411. if mem_top<256+11 then bad:=7; {we will want |null_list>255|}
  412. @ Labels are given symbolic names by the following definitions, so that
  413. occasional |goto| statements will be meaningful. We insert the label
  414. `|exit|:' just before the `\ignorespaces|end|\unskip' of a procedure in
  415. which we have used the `|return|' statement defined below; the label
  416. `|restart|' is occasionally used at the very beginning of a procedure; and
  417. the label `|reswitch|' is occasionally used just prior to a |case|
  418. statement in which some cases change the conditions and we wish to branch
  419. to the newly applicable case.  Loops that are set up with the |loop|
  420. construction defined below are commonly exited by going to `|done|' or to
  421. `|found|' or to `|not_found|', and they are sometimes repeated by going to
  422. `|continue|'.  If two or more parts of a subroutine start differently but
  423. end up the same, the shared code may be gathered together at
  424. `|common_ending|'.
  425. Incidentally, this program never declares a label that isn't actually used,
  426. because some fussy \PASCAL\ compilers will complain about redundant labels.
  427. @d exit=10 {go here to leave a procedure}
  428. @d restart=20 {go here to start a procedure again}
  429. @d reswitch=21 {go here to start a case statement again}
  430. @d continue=22 {go here to resume a loop}
  431. @d done=30 {go here to exit a loop}
  432. @d done1=31 {like |done|, when there is more than one loop}
  433. @d done2=32 {for exiting the second loop in a long block}
  434. @d done3=33 {for exiting the third loop in a very long block}
  435. @d done4=34 {for exiting the fourth loop in an extremely long block}
  436. @d done5=35 {for exiting the fifth loop in an immense block}
  437. @d done6=36 {for exiting the sixth loop in a block}
  438. @d found=40 {go here when you've found it}
  439. @d found1=41 {like |found|, when there's more than one per routine}
  440. @d found2=42 {like |found|, when there's more than two per routine}
  441. @d not_found=45 {go here when you've found nothing}
  442. @d common_ending=50 {go here when you want to merge with another branch}
  443. @ Here are some macros for common programming idioms.
  444. @d incr(#) == #:=#+1 {increase a variable by unity}
  445. @d decr(#) == #:=#-1 {decrease a variable by unity}
  446. @d negate(#) == #:=-# {change the sign of a variable}
  447. @d loop == @+ while true do@+ {repeat over and over until a |goto| happens}
  448. @f loop == xclause
  449.   {\.{WEB}'s |xclause| acts like `\ignorespaces|while true do|\unskip'}
  450. @d do_nothing == {empty statement}
  451. @d return == goto exit {terminate a procedure call}
  452. @f return == nil
  453. @d empty=0 {symbolic name for a null constant}
  454. @* \[2] The character set.
  455. In order to make \TeX\ readily portable to a wide variety of
  456. computers, all of its input text is converted to an internal eight-bit
  457. code that includes standard ASCII, the ``American Standard Code for
  458. Information Interchange.''  This conversion is done immediately when each
  459. character is read in. Conversely, characters are converted from ASCII to
  460. the user's external representation just before they are output to a
  461. text file.
  462. Such an internal code is relevant to users of \TeX\ primarily because it
  463. governs the positions of characters in the fonts. For example, the
  464. character `\.A' has ASCII code $65=@'101$, and when \TeX\ typesets
  465. this letter it specifies character number 65 in the current font.
  466. If that font actually has `\.A' in a different position, \TeX\ doesn't
  467. know what the real position is; the program that does the actual printing from
  468. \TeX's device-independent files is responsible for converting from ASCII to
  469. a particular font encoding.
  470. @^ASCII code@>
  471. \TeX's internal code also defines the value of constants
  472. that begin with a reverse apostrophe; and it provides an index to the
  473. \.{\\catcode}, \.{\\mathcode}, \.{\\uccode}, \.{\\lccode}, and \.{\\delcode}
  474. tables.
  475. @ Characters of text that have been converted to \TeX's internal form
  476. are said to be of type |ASCII_code|, which is a subrange of the integers.
  477. @<Types...@>=
  478. @!ASCII_code=0..255; {eight-bit numbers}
  479. @ The original \PASCAL\ compiler was designed in the late 60s, when six-bit
  480. character sets were common, so it did not make provision for lowercase
  481. letters. Nowadays, of course, we need to deal with both capital and small
  482. letters in a convenient way, especially in a program for typesetting;
  483. so the present specification of \TeX\ has been written under the assumption
  484. that the \PASCAL\ compiler and run-time system permit the use of text files
  485. with more than 64 distinguishable characters. More precisely, we assume that
  486. the character set contains at least the letters and symbols associated
  487. with ASCII codes @'40 through @'176; all of these characters are now
  488. available on most computer terminals.
  489. Since we are dealing with more characters than were present in the first
  490. \PASCAL\ compilers, we have to decide what to call the associated data
  491. type. Some \PASCAL s use the original name |char| for the
  492. characters in text files, even though there now are more than 64 such
  493. characters, while other \PASCAL s consider |char| to be a 64-element
  494. subrange of a larger data type that has some other name.
  495. In order to accommodate this difference, we shall use the name |text_char|
  496. to stand for the data type of the characters that are converted to and
  497. from |ASCII_code| when they are input and output. We shall also assume
  498. that |text_char| consists of the elements |chr(first_text_char)| through
  499. |chr(last_text_char)|, inclusive. The following definitions should be
  500. adjusted if necessary.
  501. @^system dependencies@>
  502. @d text_char == char {the data type of characters in text files}
  503. @d first_text_char=0 {ordinal number of the smallest element of |text_char|}
  504. @d last_text_char=255 {ordinal number of the largest element of |text_char|}
  505. @<Local variables for init...@>=
  506. @!i:integer;
  507. @ The \TeX\ processor converts between ASCII code and
  508. the user's external character set by means of arrays |xord| and |xchr|
  509. that are analogous to \PASCAL's |ord| and |chr| functions.
  510. @<Glob...@>=
  511. @!xord: array [text_char] of ASCII_code;
  512.   {specifies conversion of input characters}
  513. @!xchr: array [ASCII_code] of text_char;
  514.   {specifies conversion of output characters}
  515. @ Since we are assuming that our \PASCAL\ system is able to read and
  516. write the visible characters of standard ASCII (although not
  517. necessarily using the ASCII codes to represent them), the following
  518. assignment statements initialize the standard part of the |xchr| array
  519. properly, without needing any system-dependent changes. On the other
  520. hand, it is possible to implement \TeX\ with less complete character
  521. sets, and in such cases it will be necessary to change something here.
  522. @^system dependencies@>
  523. @<Set init...@>=
  524. xchr[@'40]:=' ';
  525. xchr[@'41]:='!';
  526. xchr[@'42]:='"';
  527. xchr[@'43]:='#';
  528. xchr[@'44]:='$';
  529. xchr[@'45]:='%';
  530. xchr[@'46]:='&';
  531. xchr[@'47]:='''';@/
  532. xchr[@'50]:='(';
  533. xchr[@'51]:=')';
  534. xchr[@'52]:='*';
  535. xchr[@'53]:='+';
  536. xchr[@'54]:=',';
  537. xchr[@'55]:='-';
  538. xchr[@'56]:='.';
  539. xchr[@'57]:='/';@/
  540. xchr[@'60]:='0';
  541. xchr[@'61]:='1';
  542. xchr[@'62]:='2';
  543. xchr[@'63]:='3';
  544. xchr[@'64]:='4';
  545. xchr[@'65]:='5';
  546. xchr[@'66]:='6';
  547. xchr[@'67]:='7';@/
  548. xchr[@'70]:='8';
  549. xchr[@'71]:='9';
  550. xchr[@'72]:=':';
  551. xchr[@'73]:=';';
  552. xchr[@'74]:='<';
  553. xchr[@'75]:='=';
  554. xchr[@'76]:='>';
  555. xchr[@'77]:='?';@/
  556. xchr[@'100]:='@@';
  557. xchr[@'101]:='A';
  558. xchr[@'102]:='B';
  559. xchr[@'103]:='C';
  560. xchr[@'104]:='D';
  561. xchr[@'105]:='E';
  562. xchr[@'106]:='F';
  563. xchr[@'107]:='G';@/
  564. xchr[@'110]:='H';
  565. xchr[@'111]:='I';
  566. xchr[@'112]:='J';
  567. xchr[@'113]:='K';
  568. xchr[@'114]:='L';
  569. xchr[@'115]:='M';
  570. xchr[@'116]:='N';
  571. xchr[@'117]:='O';@/
  572. xchr[@'120]:='P';
  573. xchr[@'121]:='Q';
  574. xchr[@'122]:='R';
  575. xchr[@'123]:='S';
  576. xchr[@'124]:='T';
  577. xchr[@'125]:='U';
  578. xchr[@'126]:='V';
  579. xchr[@'127]:='W';@/
  580. xchr[@'130]:='X';
  581. xchr[@'131]:='Y';
  582. xchr[@'132]:='Z';
  583. xchr[@'133]:='[';
  584. xchr[@'134]:='\';
  585. xchr[@'135]:=']';
  586. xchr[@'136]:='^';
  587. xchr[@'137]:='_';@/
  588. xchr[@'140]:='`';
  589. xchr[@'141]:='a';
  590. xchr[@'142]:='b';
  591. xchr[@'143]:='c';
  592. xchr[@'144]:='d';
  593. xchr[@'145]:='e';
  594. xchr[@'146]:='f';
  595. xchr[@'147]:='g';@/
  596. xchr[@'150]:='h';
  597. xchr[@'151]:='i';
  598. xchr[@'152]:='j';
  599. xchr[@'153]:='k';
  600. xchr[@'154]:='l';
  601. xchr[@'155]:='m';
  602. xchr[@'156]:='n';
  603. xchr[@'157]:='o';@/
  604. xchr[@'160]:='p';
  605. xchr[@'161]:='q';
  606. xchr[@'162]:='r';
  607. xchr[@'163]:='s';
  608. xchr[@'164]:='t';
  609. xchr[@'165]:='u';
  610. xchr[@'166]:='v';
  611. xchr[@'167]:='w';@/
  612. xchr[@'170]:='x';
  613. xchr[@'171]:='y';
  614. xchr[@'172]:='z';
  615. xchr[@'173]:='{';
  616. xchr[@'174]:='|';
  617. xchr[@'175]:='}';
  618. xchr[@'176]:='~';@/
  619. @ Some of the ASCII codes without visible characters have been given symbolic
  620. names in this program because they are used with a special meaning.
  621. @d null_code=@'0 {ASCII code that might disappear}
  622. @d carriage_return=@'15 {ASCII code used at end of line}
  623. @d invalid_code=@'177 {ASCII code that many systems prohibit in text files}
  624. @ The ASCII code is ``standard'' only to a certain extent, since many
  625. computer installations have found it advantageous to have ready access
  626. to more than 94 printing characters. Appendix~C of {\sl The \TeX book\/}
  627. gives a complete specification of the intended correspondence between
  628. characters and \TeX's internal representation.
  629. @:TeXbook}{\sl The \TeX book@>
  630. If \TeX\ is being used
  631. on a garden-variety \PASCAL\ for which only standard ASCII
  632. codes will appear in the input and output files, it doesn't really matter
  633. what codes are specified in |xchr[0..@'37]|, but the safest policy is to
  634. blank everything out by using the code shown below.
  635. However, other settings of |xchr| will make \TeX\ more friendly on
  636. computers that have an extended character set, so that users can type things
  637. like `\.^^Z' instead of `\.{\\ne}'. People with extended character sets can
  638. assign codes arbitrarily, giving an |xchr| equivalent to whatever
  639. characters the users of \TeX\ are allowed to have in their input files.
  640. It is best to make the codes correspond to the intended interpretations as
  641. shown in Appendix~C whenever possible; but this is not necessary. For
  642. example, in countries with an alphabet of more than 26 letters, it is
  643. usually best to map the additional letters into codes less than~@'40.
  644. To get the most ``permissive'' character set, change |' '| on the
  645. right of these assignment statements to |chr(i)|.
  646. @^character set dependencies@>
  647. @^system dependencies@>
  648. @<Set init...@>=
  649. for i:=0 to @'37 do xchr[i]:=' ';
  650. for i:=@'177 to @'377 do xchr[i]:=' ';
  651. @ The following system-independent code makes the |xord| array contain a
  652. suitable inverse to the information in |xchr|. Note that if |xchr[i]=xchr[j]|
  653. where |i<j<@'177|, the value of |xord[xchr[i]]| will turn out to be
  654. |j| or more; hence, standard ASCII code numbers will be used instead of
  655. codes below @'40 in case there is a coincidence.
  656. @<Set init...@>=
  657. for i:=first_text_char to last_text_char do xord[chr(i)]:=invalid_code;
  658. for i:=@'200 to @'377 do xord[xchr[i]]:=i;
  659. for i:=0 to @'176 do xord[xchr[i]]:=i;
  660. @* \[3] Input and output.
  661. The bane of portability is the fact that different operating systems treat
  662. input and output quite differently, perhaps because computer scientists
  663. have not given sufficient attention to this problem. People have felt somehow
  664. that input and output are not part of ``real'' programming. Well, it is true
  665. that some kinds of programming are more fun than others. With existing
  666. input/output conventions being so diverse and so messy, the only sources of
  667. joy in such parts of the code are the rare occasions when one can find a
  668. way to make the program a little less bad than it might have been. We have
  669. two choices, either to attack I/O now and get it over with, or to postpone
  670. I/O until near the end. Neither prospect is very attractive, so let's
  671. get it over with.
  672. The basic operations we need to do are (1)~inputting and outputting of
  673. text, to or from a file or the user's terminal; (2)~inputting and
  674. outputting of eight-bit bytes, to or from a file; (3)~instructing the
  675. operating system to initiate (``open'') or to terminate (``close'') input or
  676. output from a specified file; (4)~testing whether the end of an input
  677. file has been reached.
  678. \TeX\ needs to deal with two kinds of files.
  679. We shall use the term |alpha_file| for a file that contains textual data,
  680. and the term |byte_file| for a file that contains eight-bit binary information.
  681. These two types turn out to be the same on many computers, but
  682. sometimes there is a significant distinction, so we shall be careful to
  683. distinguish between them. Standard protocols for transferring
  684. such files from computer to computer, via high-speed networks, are
  685. now becoming available to more and more communities of users.
  686. The program actually makes use also of a third kind of file, called a
  687. |word_file|, when dumping and reloading base information for its own
  688. initialization.  We shall define a word file later; but it will be possible
  689. for us to specify simple operations on word files before they are defined.
  690. @<Types...@>=
  691. @!eight_bits=0..255; {unsigned one-byte quantity}
  692. @!alpha_file=packed file of text_char; {files that contain textual data}
  693. @!byte_file=packed file of eight_bits; {files that contain binary data}
  694. @ Most of what we need to do with respect to input and output can be handled
  695. by the I/O facilities that are standard in \PASCAL, i.e., the routines
  696. called |get|, |put|, |eof|, and so on. But
  697. standard \PASCAL\ does not allow file variables to be associated with file
  698. names that are determined at run time, so it cannot be used to implement
  699. \TeX; some sort of extension to \PASCAL's ordinary |reset| and |rewrite|
  700. is crucial for our purposes. We shall assume that |name_of_file| is a variable
  701. of an appropriate type such that the \PASCAL\ run-time system being used to
  702. implement \TeX\ can open a file whose external name is specified by
  703. |name_of_file|.
  704. @^system dependencies@>
  705. @<Glob...@>=
  706. @!name_of_file:packed array[1..file_name_size] of char;@;@/
  707.   {on some systems this may be a \&{record} variable}
  708. @!name_length:0..file_name_size;@/{this many characters are actually
  709.   relevant in |name_of_file| (the rest are blank)}
  710. @ The \ph\ compiler with which the present version of \TeX\ was prepared has
  711. extended the rules of \PASCAL\ in a very convenient way. To open file~|f|,
  712. we can write
  713. $$\vbox{\halign{#\hfil\qquad&#\hfil\cr
  714. |reset(f,@t\\{name}@>,'/O')|&for input;\cr
  715. |rewrite(f,@t\\{name}@>,'/O')|&for output.\cr}}$$
  716. The `\\{name}' parameter, which is of type `{\bf packed array
  717. $[\langle\\{any}\rangle]$ of \\{char}}', stands for the name of
  718. the external file that is being opened for input or output.
  719. Blank spaces that might appear in \\{name} are ignored.
  720. The `\.{/O}' parameter tells the operating system not to issue its own
  721. error messages if something goes wrong. If a file of the specified name
  722. cannot be found, or if such a file cannot be opened for some other reason
  723. (e.g., someone may already be trying to write the same file), we will have
  724. |@!erstat(f)<>0| after an unsuccessful |reset| or |rewrite|.  This allows
  725. \TeX\ to undertake appropriate corrective action.
  726. @:PASCAL H}{\ph@>
  727. @^system dependencies@>
  728. \TeX's file-opening procedures return |false| if no file identified by
  729. |name_of_file| could be opened.
  730. @d reset_OK(#)==erstat(#)=0
  731. @d rewrite_OK(#)==erstat(#)=0
  732. @p function a_open_in(var f:alpha_file):boolean;
  733.   {open a text file for input}
  734. begin reset(f,name_of_file,'/O'); a_open_in:=reset_OK(f);
  735. function a_open_out(var f:alpha_file):boolean;
  736.   {open a text file for output}
  737. begin rewrite(f,name_of_file,'/O'); a_open_out:=rewrite_OK(f);
  738. function b_open_in(var f:byte_file):boolean;
  739.   {open a binary file for input}
  740. begin reset(f,name_of_file,'/O'); b_open_in:=reset_OK(f);
  741. function b_open_out(var f:byte_file):boolean;
  742.   {open a binary file for output}
  743. begin rewrite(f,name_of_file,'/O'); b_open_out:=rewrite_OK(f);
  744. function w_open_in(var f:word_file):boolean;
  745.   {open a word file for input}
  746. begin reset(f,name_of_file,'/O'); w_open_in:=reset_OK(f);
  747. function w_open_out(var f:word_file):boolean;
  748.   {open a word file for output}
  749. begin rewrite(f,name_of_file,'/O'); w_open_out:=rewrite_OK(f);
  750. @ Files can be closed with the \ph\ routine `|close(f)|', which
  751. @^system dependencies@>
  752. should be used when all input or output with respect to |f| has been completed.
  753. This makes |f| available to be opened again, if desired; and if |f| was used for
  754. output, the |close| operation makes the corresponding external file appear
  755. on the user's area, ready to be read.
  756. These procedures should not generate error messages if a file is
  757. being closed before it has been successfully opened.
  758. @p procedure a_close(var f:alpha_file); {close a text file}
  759. begin close(f);
  760. procedure b_close(var f:byte_file); {close a binary file}
  761. begin close(f);
  762. procedure w_close(var f:word_file); {close a word file}
  763. begin close(f);
  764. @ Binary input and output are done with \PASCAL's ordinary |get| and |put|
  765. procedures, so we don't have to make any other special arrangements for
  766. binary~I/O. Text output is also easy to do with standard \PASCAL\ routines.
  767. The treatment of text input is more difficult, however, because
  768. of the necessary translation to |ASCII_code| values.
  769. \TeX's conventions should be efficient, and they should
  770. blend nicely with the user's operating environment.
  771. @ Input from text files is read one line at a time, using a routine called
  772. |input_ln|. This function is defined in terms of global variables called
  773. |buffer|, |first|, and |last| that will be described in detail later; for
  774. now, it suffices for us to know that |buffer| is an array of |ASCII_code|
  775. values, and that |first| and |last| are indices into this array
  776. representing the beginning and ending of a line of text.
  777. @<Glob...@>=
  778. @!buffer:array[0..buf_size] of ASCII_code; {lines of characters being read}
  779. @!first:0..buf_size; {the first unused position in |buffer|}
  780. @!last:0..buf_size; {end of the line just input to |buffer|}
  781. @!max_buf_stack:0..buf_size; {largest index used in |buffer|}
  782. @ The |input_ln| function brings the next line of input from the specified
  783. file into available positions of the buffer array and returns the value
  784. |true|, unless the file has already been entirely read, in which case it
  785. returns |false| and sets |last:=first|.  In general, the |ASCII_code|
  786. numbers that represent the next line of the file are input into
  787. |buffer[first]|, |buffer[first+1]|, \dots, |buffer[last-1]|; and the
  788. global variable |last| is set equal to |first| plus the length of the
  789. line. Trailing blanks are removed from the line; thus, either |last=first|
  790. (in which case the line was entirely blank) or |buffer[last-1]<>" "|.
  791. An overflow error is given, however, if the normal actions of |input_ln|
  792. would make |last>=buf_size|; this is done so that other parts of \TeX\
  793. can safely look at the contents of |buffer[last+1]| without overstepping
  794. the bounds of the |buffer| array. Upon entry to |input_ln|, the condition
  795. |first<buf_size| will always hold, so that there is always room for an
  796. ``empty'' line.
  797. The variable |max_buf_stack|, which is used to keep track of how large
  798. the |buf_size| parameter must be to accommodate the present job, is
  799. also kept up to date by |input_ln|.
  800. If the |bypass_eoln| parameter is |true|, |input_ln| will do a |get|
  801. before looking at the first character of the line; this skips over
  802. an |eoln| that was in |f^|. The procedure does not do a |get| when it
  803. reaches the end of the line; therefore it can be used to acquire input
  804. from the user's terminal as well as from ordinary text files.
  805. Standard \PASCAL\ says that a file should have |eoln| immediately
  806. before |eof|, but \TeX\ needs only a weaker restriction: If |eof|
  807. occurs in the middle of a line, the system function |eoln| should return
  808. a |true| result (even though |f^| will be undefined).
  809. Since the inner loop of |input_ln| is part of \TeX's ``inner loop''---each
  810. character of input comes in at this place---it is wise to reduce system
  811. overhead by making use of special routines that read in an entire array
  812. of characters at once, if such routines are available. The following
  813. code uses standard \PASCAL\ to illustrate what needs to be done, but
  814. finer tuning is often possible at well-developed \PASCAL\ sites.
  815. @^inner loop@>
  816. @p function input_ln(var f:alpha_file;@!bypass_eoln:boolean):boolean;
  817.   {inputs the next line or returns |false|}
  818. var last_nonblank:0..buf_size; {|last| with trailing blanks removed}
  819. begin if bypass_eoln then if not eof(f) then get(f);
  820.   {input the first character of the line into |f^|}
  821. last:=first; {cf.\ Matthew 19\thinspace:\thinspace30}
  822. if eof(f) then input_ln:=false
  823. else  begin last_nonblank:=first;
  824.   while not eoln(f) do
  825.     begin if last>=max_buf_stack then
  826.       begin max_buf_stack:=last+1;
  827.       if max_buf_stack=buf_size then
  828.         @<Report overflow of the input buffer, and abort@>;
  829.       end;
  830.     buffer[last]:=xord[f^]; get(f); incr(last);
  831.     if buffer[last-1]<>" " then last_nonblank:=last;
  832.     end;
  833.   last:=last_nonblank; input_ln:=true;
  834.   end;
  835. @ The user's terminal acts essentially like other files of text, except
  836. that it is used both for input and for output. When the terminal is
  837. considered an input file, the file variable is called |term_in|, and when it
  838. is considered an output file the file variable is |term_out|.
  839. @^system dependencies@>
  840. @<Glob...@>=
  841. @!term_in:alpha_file; {the terminal as an input file}
  842. @!term_out:alpha_file; {the terminal as an output file}
  843. @ Here is how to open the terminal files
  844. in \ph. The `\.{/I}' switch suppresses the first |get|.
  845. @^system dependencies@>
  846. @d t_open_in==reset(term_in,'TTY:','/O/I') {open the terminal for text input}
  847. @d t_open_out==rewrite(term_out,'TTY:','/O') {open the terminal for text output}
  848. @ Sometimes it is necessary to synchronize the input/output mixture that
  849. happens on the user's terminal, and three system-dependent
  850. procedures are used for this
  851. purpose. The first of these, |update_terminal|, is called when we want
  852. to make sure that everything we have output to the terminal so far has
  853. actually left the computer's internal buffers and been sent.
  854. The second, |clear_terminal|, is called when we wish to cancel any
  855. input that the user may have typed ahead (since we are about to
  856. issue an unexpected error message). The third, |wake_up_terminal|,
  857. is supposed to revive the terminal if the user has disabled it by
  858. some instruction to the operating system.  The following macros show how
  859. these operations can be specified in \ph:
  860. @^system dependencies@>
  861. @d update_terminal == break(term_out) {empty the terminal output buffer}
  862. @d clear_terminal == break_in(term_in,true) {clear the terminal input buffer}
  863. @d wake_up_terminal == do_nothing {cancel the user's cancellation of output}
  864. @ We need a special routine to read the first line of \TeX\ input from
  865. the user's terminal. This line is different because it is read before we
  866. have opened the transcript file; there is sort of a ``chicken and
  867. egg'' problem here. If the user types `\.{\\input paper}' on the first
  868. line, or if some macro invoked by that line does such an \.{\\input},
  869. the transcript file will be named `\.{paper.log}'; but if no \.{\\input}
  870. commands are performed during the first line of terminal input, the transcript
  871. file will acquire its default name `\.{texput.log}'. (The transcript file
  872. will not contain error messages generated by the first line before the
  873. first \.{\\input} command.)
  874. @.texput@>
  875. The first line is even more special if we are lucky enough to have an operating
  876. system that treats \TeX\ differently from a run-of-the-mill \PASCAL\ object
  877. program. It's nice to let the user start running a \TeX\ job by typing
  878. a command line like `\.{tex paper}'; in such a case, \TeX\ will operate
  879. as if the first line of input were `\.{paper}', i.e., the first line will
  880. consist of the remainder of the command line, after the part that invoked
  881. \TeX.
  882. The first line is special also because it may be read before \TeX\ has
  883. input a format file. In such cases, normal error messages cannot yet
  884. be given. The following code uses concepts that will be explained later.
  885. (If the \PASCAL\ compiler does not support non-local |@!goto|\unskip, the
  886. @^system dependencies@>
  887. statement `|goto final_end|' should be replaced by something that
  888. quietly terminates the program.)
  889. @<Report overflow of the input buffer, and abort@>=
  890. if format_ident=0 then
  891.   begin write_ln(term_out,'Buffer size exceeded!'); goto final_end;
  892. @.Buffer size exceeded@>
  893.   end
  894. else begin cur_input.loc_field:=first; cur_input.limit_field:=last-1;
  895.   overflow("buffer size",buf_size);
  896. @:TeX capacity exceeded buffer size}{\quad buffer size@>
  897.   end
  898. @ Different systems have different ways to get started. But regardless of
  899. what conventions are adopted, the routine that initializes the terminal
  900. should satisfy the following specifications:
  901. \yskip\textindent{1)}It should open file |term_in| for input from the
  902.   terminal. (The file |term_out| will already be open for output to the
  903.   terminal.)
  904. \textindent{2)}If the user has given a command line, this line should be
  905.   considered the first line of terminal input. Otherwise the
  906.   user should be prompted with `\.{**}', and the first line of input
  907.   should be whatever is typed in response.
  908. \textindent{3)}The first line of input, which might or might not be a
  909.   command line, should appear in locations |first| to |last-1| of the
  910.   |buffer| array.
  911. \textindent{4)}The global variable |loc| should be set so that the
  912.   character to be read next by \TeX\ is in |buffer[loc]|. This
  913.   character should not be blank, and we should have |loc<last|.
  914. \yskip\noindent(It may be necessary to prompt the user several times
  915. before a non-blank line comes in. The prompt is `\.{**}' instead of the
  916. later `\.*' because the meaning is slightly different: `\.{\\input}' need
  917. not be typed immediately after~`\.{**}'.)
  918. @d loc==cur_input.loc_field {location of first unread character in |buffer|}
  919. @ The following program does the required initialization
  920. without retrieving a possible command line.
  921. It should be clear how to modify this routine to deal with command lines,
  922. if the system permits them.
  923. @^system dependencies@>
  924. @p function init_terminal:boolean; {gets the terminal input started}
  925. label exit;
  926. begin t_open_in;
  927. loop@+begin wake_up_terminal; write(term_out,'**'); update_terminal;
  928. @.**@>
  929.   if not input_ln(term_in,true) then {this shouldn't happen}
  930.     begin write_ln(term_out);
  931.     write(term_out,'! End of file on the terminal... why?');
  932. @.End of file on the terminal@>
  933.     init_terminal:=false; return;
  934.     end;
  935.   loc:=first;
  936.   while (loc<last)and(buffer[loc]=" ") do incr(loc);
  937.   if loc<last then
  938.     begin init_terminal:=true;
  939.     return; {return unless the line was all blank}
  940.     end;
  941.   write_ln(term_out,'Please type the name of your input file.');
  942.   end;
  943. exit:end;
  944. @* \[4] String handling.
  945. Control sequence names and diagnostic messages are variable-length strings
  946. of eight-bit characters. Since \PASCAL\ does not have a well-developed string
  947. mechanism, \TeX\ does all of its string processing by homegrown methods.
  948. Elaborate facilities for dynamic strings are not needed, so all of the
  949. necessary operations can be handled with a simple data structure.
  950. The array |str_pool| contains all of the (eight-bit) ASCII codes in all
  951. of the strings, and the array |str_start| contains indices of the starting
  952. points of each string. Strings are referred to by integer numbers, so that
  953. string number |s| comprises the characters |str_pool[j]| for
  954. |str_start[s]<=j<str_start[s+1]|. Additional integer variables
  955. |pool_ptr| and |str_ptr| indicate the number of entries used so far
  956. in |str_pool| and |str_start|, respectively; locations
  957. |str_pool[pool_ptr]| and |str_start[str_ptr]| are
  958. ready for the next string to be allocated.
  959. String numbers 0 to 255 are reserved for strings that correspond to single
  960. ASCII characters. This is in accordance with the conventions of \.{WEB},
  961. @.WEB@>
  962. which converts single-character strings into the ASCII code number of the
  963. single character involved, while it converts other strings into integers
  964. and builds a string pool file. Thus, when the string constant \.{"."} appears
  965. in the program below, \.{WEB} converts it into the integer 46, which is the
  966. ASCII code for a period, while \.{WEB} will convert a string like \.{"hello"}
  967. into some integer greater than~255. String number 46 will presumably be the
  968. single character `\..'; but some ASCII codes have no standard visible
  969. representation, and \TeX\ sometimes needs to be able to print an arbitrary
  970. ASCII character, so the first 256 strings are used to specify exactly what
  971. should be printed for each of the 256 possibilities.
  972. Elements of the |str_pool| array must be ASCII codes that can actually
  973. be printed; i.e., they must have an |xchr| equivalent in the local
  974. character set. (This restriction applies only to preloaded strings,
  975. not to those generated dynamically by the user.)
  976. Some \PASCAL\ compilers won't pack integers into a single byte unless the
  977. integers lie in the range |-128..127|. To accommodate such systems
  978. we access the string pool only via macros that can easily be redefined.
  979. @d si(#) == # {convert from |ASCII_code| to |packed_ASCII_code|}
  980. @d so(#) == # {convert from |packed_ASCII_code| to |ASCII_code|}
  981. @<Types...@>=
  982. @!pool_pointer = 0..pool_size; {for variables that point into |str_pool|}
  983. @!str_number = 0..max_strings; {for variables that point into |str_start|}
  984. @!packed_ASCII_code = 0..255; {elements of |str_pool| array}
  985. @ @<Glob...@>=
  986. @!str_pool:packed array[pool_pointer] of packed_ASCII_code; {the characters}
  987. @!str_start : array[str_number] of pool_pointer; {the starting pointers}
  988. @!pool_ptr : pool_pointer; {first unused position in |str_pool|}
  989. @!str_ptr : str_number; {number of the current string being created}
  990. @!init_pool_ptr : pool_pointer; {the starting value of |pool_ptr|}
  991. @!init_str_ptr : str_number; {the starting value of |str_ptr|}
  992. @ Several of the elementary string operations are performed using \.{WEB}
  993. macros instead of \PASCAL\ procedures, because many of the
  994. operations are done quite frequently and we want to avoid the
  995. overhead of procedure calls. For example, here is
  996. a simple macro that computes the length of a string.
  997. @.WEB@>
  998. @d length(#)==(str_start[#+1]-str_start[#]) {the number of characters
  999.   in string number \#}
  1000. @ The length of the current string is called |cur_length|:
  1001. @d cur_length == (pool_ptr - str_start[str_ptr])
  1002. @ Strings are created by appending character codes to |str_pool|.
  1003. The |append_char| macro, defined here, does not check to see if the
  1004. value of |pool_ptr| has gotten too high; this test is supposed to be
  1005. made before |append_char| is used. There is also a |flush_char|
  1006. macro, which erases the last character appended.
  1007. To test if there is room to append |l| more characters to |str_pool|,
  1008. we shall write |str_room(l)|, which aborts \TeX\ and gives an
  1009. apologetic error message if there isn't enough room.
  1010. @d append_char(#) == {put |ASCII_code| \# at the end of |str_pool|}
  1011. begin str_pool[pool_ptr]:=si(#); incr(pool_ptr);
  1012. @d flush_char == decr(pool_ptr) {forget the last character in the pool}
  1013. @d str_room(#) == {make sure that the pool hasn't overflowed}
  1014.   begin if pool_ptr+# > pool_size then
  1015.   overflow("pool size",pool_size-init_pool_ptr);
  1016. @:TeX capacity exceeded pool size}{\quad pool size@>
  1017.   end
  1018. @ Once a sequence of characters has been appended to |str_pool|, it
  1019. officially becomes a string when the function |make_string| is called.
  1020. This function returns the identification number of the new string as its
  1021. value.
  1022. @p function make_string : str_number; {current string enters the pool}
  1023. begin if str_ptr=max_strings then
  1024.   overflow("number of strings",max_strings-init_str_ptr);
  1025. @:TeX capacity exceeded number of strings}{\quad number of strings@>
  1026. incr(str_ptr); str_start[str_ptr]:=pool_ptr;
  1027. make_string:=str_ptr-1;
  1028. @ To destroy the most recently made string, we say |flush_string|.
  1029. @d flush_string==begin decr(str_ptr); pool_ptr:=str_start[str_ptr];
  1030.   end
  1031. @ The following subroutine compares string |s| with another string of the
  1032. same length that appears in |buffer| starting at position |k|;
  1033. the result is |true| if and only if the strings are equal.
  1034. Empirical tests indicate that |str_eq_buf| is used in such a way that
  1035. it tends to return |true| about 80 percent of the time.
  1036. @p function str_eq_buf(@!s:str_number;@!k:integer):boolean;
  1037.   {test equality of strings}
  1038. label not_found; {loop exit}
  1039. var j: pool_pointer; {running index}
  1040. @!result: boolean; {result of comparison}
  1041. begin j:=str_start[s];
  1042. while j<str_start[s+1] do
  1043.   begin if so(str_pool[j])<>buffer[k] then
  1044.     begin result:=false; goto not_found;
  1045.     end;
  1046.   incr(j); incr(k);
  1047.   end;
  1048. result:=true;
  1049. not_found: str_eq_buf:=result;
  1050. @ Here is a similar routine, but it compares two strings in the string pool,
  1051. and it does not assume that they have the same length.
  1052. @p function str_eq_str(@!s,@!t:str_number):boolean;
  1053.   {test equality of strings}
  1054. label not_found; {loop exit}
  1055. var j,@!k: pool_pointer; {running indices}
  1056. @!result: boolean; {result of comparison}
  1057. begin result:=false;
  1058. if length(s)<>length(t) then goto not_found;
  1059. j:=str_start[s]; k:=str_start[t];
  1060. while j<str_start[s+1] do
  1061.   begin if str_pool[j]<>str_pool[k] then goto not_found;
  1062.   incr(j); incr(k);
  1063.   end;
  1064. result:=true;
  1065. not_found: str_eq_str:=result;
  1066. @ The initial values of |str_pool|, |str_start|, |pool_ptr|,
  1067. and |str_ptr| are computed by the \.{INITEX} program, based in part
  1068. on the information that \.{WEB} has output while processing \TeX.
  1069. @.INITEX@>
  1070. @^string pool@>
  1071. @p @!init function get_strings_started:boolean; {initializes the string pool,
  1072.   but returns |false| if something goes wrong}
  1073. label done,exit;
  1074. var k,@!l:0..255; {small indices or counters}
  1075. @!m,@!n:text_char; {characters input from |pool_file|}
  1076. @!g:str_number; {garbage}
  1077. @!a:integer; {accumulator for check sum}
  1078. @!c:boolean; {check sum has been checked}
  1079. begin pool_ptr:=0; str_ptr:=0; str_start[0]:=0;
  1080. @<Make the first 256 strings@>;
  1081. @<Read the other strings from the \.{TEX.POOL} file and return |true|,
  1082.   or give an error message and return |false|@>;
  1083. exit:end;
  1084. @ @d app_lc_hex(#)==l:=#;
  1085.   if l<10 then append_char(l+"0")@+else append_char(l-10+"a")
  1086. @<Make the first 256...@>=
  1087. for k:=0 to 255 do
  1088.   begin if (@<Character |k| cannot be printed@>) then
  1089.     begin append_char("^"); append_char("^");
  1090.     if k<@'100 then append_char(k+@'100)
  1091.     else if k<@'200 then append_char(k-@'100)
  1092.     else begin app_lc_hex(k div 16); app_lc_hex(k mod 16);
  1093.       end;
  1094.     end
  1095.   else append_char(k);
  1096.   g:=make_string;
  1097.   end
  1098. @ The first 128 strings will contain 95 standard ASCII characters, and the
  1099. other 33 characters will be printed in three-symbol form like `\.{\^\^A}'
  1100. unless a system-dependent change is made here. Installations that have
  1101. an extended character set, where for example |xchr[@'32]=@t\.{\'^^Z\'}@>|,
  1102. would like string @'32 to be the single character @'32 instead of the
  1103. three characters @'136, @'136, @'132 (\.{\^\^Z}). On the other hand,
  1104. even people with an extended character set will want to represent string
  1105. @'15 by \.{\^\^M}, since @'15 is |carriage_return|; the idea is to
  1106. produce visible strings instead of tabs or line-feeds or carriage-returns
  1107. or bell-rings or characters that are treated anomalously in text files.
  1108. Unprintable characters of codes 128--255 are, similarly, rendered
  1109. \.{\^\^80}--\.{\^\^ff}.
  1110. The boolean expression defined here should be |true| unless \TeX\
  1111. internal code number~|k| corresponds to a non-troublesome visible
  1112. symbol in the local character set.  An appropriate formula for the
  1113. extended character set recommended in {\sl The \TeX book\/} would, for
  1114. example, be `|k in [0,@'10..@'12,@'14,@'15,@'33,@'177..@'377]|'.
  1115. If character |k| cannot be printed, and |k<@'200|, then character |k+@'100| or
  1116. |k-@'100| must be printable; moreover, ASCII codes |[@'41..@'46,
  1117. @'60..@'71, @'141..@'146, @'160..@'171]| must be printable.
  1118. Thus, at least 80 printable characters are needed.
  1119. @:TeXbook}{\sl The \TeX book@>
  1120. @^character set dependencies@>
  1121. @^system dependencies@>
  1122. @<Character |k| cannot be printed@>=
  1123.   (k<" ")or(k>"~")
  1124. @ When the \.{WEB} system program called \.{TANGLE} processes the \.{TEX.WEB}
  1125. description that you are now reading, it outputs the \PASCAL\ program
  1126. \.{TEX.PAS} and also a string pool file called \.{TEX.POOL}. The \.{INITEX}
  1127. @.WEB@>@.INITEX@>
  1128. program reads the latter file, where each string appears as a two-digit decimal
  1129. length followed by the string itself, and the information is recorded in
  1130. \TeX's string memory.
  1131. @<Glob...@>=
  1132. @!init @!pool_file:alpha_file; {the string-pool file output by \.{TANGLE}}
  1133. @ @d bad_pool(#)==begin wake_up_terminal; write_ln(term_out,#);
  1134.   a_close(pool_file); get_strings_started:=false; return;
  1135.   end
  1136. @<Read the other strings...@>=
  1137. name_of_file:=pool_name; {we needn't set |name_length|}
  1138. if a_open_in(pool_file) then
  1139.   begin c:=false;
  1140.   repeat @<Read one string, but return |false| if the
  1141.     string memory space is getting too tight for comfort@>;
  1142.   until c;
  1143.   a_close(pool_file); get_strings_started:=true;
  1144.   end
  1145. else  bad_pool('! I can''t read TEX.POOL.')
  1146. @.I can't read TEX.POOL@>
  1147. @ @<Read one string...@>=
  1148. begin if eof(pool_file) then bad_pool('! TEX.POOL has no check sum.');
  1149. @.TEX.POOL has no check sum@>
  1150. read(pool_file,m,n); {read two digits of string length}
  1151. if m='*' then @<Check the pool check sum@>
  1152. else  begin if (xord[m]<"0")or(xord[m]>"9")or@|
  1153.       (xord[n]<"0")or(xord[n]>"9") then
  1154.     bad_pool('! TEX.POOL line doesn''t begin with two digits.');
  1155. @.TEX.POOL line doesn't...@>
  1156.   l:=xord[m]*10+xord[n]-"0"*11; {compute the length}
  1157.   if pool_ptr+l+string_vacancies>pool_size then
  1158.     bad_pool('! You have to increase POOLSIZE.');
  1159. @.You have to increase POOLSIZE@>
  1160.   for k:=1 to l do
  1161.     begin if eoln(pool_file) then m:=' '@+else read(pool_file,m);
  1162.     append_char(xord[m]);
  1163.     end;
  1164.   read_ln(pool_file); g:=make_string;
  1165.   end;
  1166. @ The \.{WEB} operation \.{@@\$} denotes the value that should be at the
  1167. end of this \.{TEX.POOL} file; any other value means that the wrong pool
  1168. file has been loaded.
  1169. @^check sum@>
  1170. @<Check the pool check sum@>=
  1171. begin a:=0; k:=1;
  1172. loop@+  begin if (xord[n]<"0")or(xord[n]>"9") then
  1173.   bad_pool('! TEX.POOL check sum doesn''t have nine digits.');
  1174. @.TEX.POOL check sum...@>
  1175.   a:=10*a+xord[n]-"0";
  1176.   if k=9 then goto done;
  1177.   incr(k); read(pool_file,n);
  1178.   end;
  1179. done: if a<>@$ then bad_pool('! TEX.POOL doesn''t match; TANGLE me again.');
  1180. @.TEX.POOL doesn't match@>
  1181. c:=true;
  1182. @* \[5] On-line and off-line printing.
  1183. Messages that are sent to a user's terminal and to the transcript-log file
  1184. are produced by several `|print|' procedures. These procedures will
  1185. direct their output to a variety of places, based on the setting of
  1186. the global variable |selector|, which has the following possible
  1187. values:
  1188. \yskip
  1189. \hang |term_and_log|, the normal setting, prints on the terminal and on the
  1190.   transcript file.
  1191. \hang |log_only|, prints only on the transcript file.
  1192. \hang |term_only|, prints only on the terminal.
  1193. \hang |no_print|, doesn't print at all. This is used only in rare cases
  1194.   before the transcript file is open.
  1195. \hang |pseudo|, puts output into a cyclic buffer that is used
  1196.   by the |show_context| routine; when we get to that routine we shall discuss
  1197.   the reasoning behind this curious mode.
  1198. \hang |new_string|, appends the output to the current string in the
  1199.   string pool.
  1200. \hang 0 to 15, prints on one of the sixteen files for \.{\\write} output.
  1201. \yskip
  1202. \noindent The symbolic names `|term_and_log|', etc., have been assigned
  1203. numeric codes that satisfy the convenient relations |no_print+1=term_only|,
  1204. |no_print+2=log_only|, |term_only+2=log_only+1=term_and_log|.
  1205. Three additional global variables, |tally| and |term_offset| and
  1206. |file_offset|, record the number of characters that have been printed
  1207. since they were most recently cleared to zero. We use |tally| to record
  1208. the length of (possibly very long) stretches of printing; |term_offset|
  1209. and |file_offset|, on the other hand, keep track of how many characters
  1210. have appeared so far on the current line that has been output to the
  1211. terminal or to the transcript file, respectively.
  1212. @d no_print=16 {|selector| setting that makes data disappear}
  1213. @d term_only=17 {printing is destined for the terminal only}
  1214. @d log_only=18 {printing is destined for the transcript file only}
  1215. @d term_and_log=19 {normal |selector| setting}
  1216. @d pseudo=20 {special |selector| setting for |show_context|}
  1217. @d new_string=21 {printing is deflected to the string pool}
  1218. @d max_selector=21 {highest selector setting}
  1219. @<Glob...@>=
  1220. @!log_file : alpha_file; {transcript of \TeX\ session}
  1221. @!selector : 0..max_selector; {where to print a message}
  1222. @!dig : array[0..22] of 0..15; {digits in a number being output}
  1223. @!tally : integer; {the number of characters recently printed}
  1224. @!term_offset : 0..max_print_line;
  1225.   {the number of characters on the current terminal line}
  1226. @!file_offset : 0..max_print_line;
  1227.   {the number of characters on the current file line}
  1228. @!trick_buf:array[0..error_line] of ASCII_code; {circular buffer for
  1229.   pseudoprinting}
  1230. @!trick_count: integer; {threshold for pseudoprinting, explained later}
  1231. @!first_count: integer; {another variable for pseudoprinting}
  1232. @ @<Initialize the output routines@>=
  1233. selector:=term_only; tally:=0; term_offset:=0; file_offset:=0;
  1234. @ Macro abbreviations for output to the terminal and to the log file are
  1235. defined here for convenience. Some systems need special conventions
  1236. for terminal output, and it is possible to adhere to those conventions
  1237. by changing |wterm|, |wterm_ln|, and |wterm_cr| in this section.
  1238. @^system dependencies@>
  1239. @d wterm(#)==write(term_out,#)
  1240. @d wterm_ln(#)==write_ln(term_out,#)
  1241. @d wterm_cr==write_ln(term_out)
  1242. @d wlog(#)==write(log_file,#)
  1243. @d wlog_ln(#)==write_ln(log_file,#)
  1244. @d wlog_cr==write_ln(log_file)
  1245. @ To end a line of text output, we call |print_ln|.
  1246. @<Basic print...@>=
  1247. procedure print_ln; {prints an end-of-line}
  1248. begin case selector of
  1249. term_and_log: begin wterm_cr; wlog_cr;
  1250.   term_offset:=0; file_offset:=0;
  1251.   end;
  1252. log_only: begin wlog_cr; file_offset:=0;
  1253.   end;
  1254. term_only: begin wterm_cr; term_offset:=0;
  1255.   end;
  1256. no_print,pseudo,new_string: do_nothing;
  1257. othercases write_ln(write_file[selector])
  1258. endcases;@/
  1259. end; {|tally| is not affected}
  1260. @ The |print_char| procedure sends one character to the desired destination,
  1261. using the |xchr| array to map it into an external character compatible with
  1262. |input_ln|. All printing comes through |print_ln| or |print_char|.
  1263. @<Basic printing...@>=
  1264. procedure print_char(@!s:ASCII_code); {prints a single character}
  1265. label exit;
  1266. begin if @<Character |s| is the current new-line character@> then
  1267.  if selector<pseudo then
  1268.   begin print_ln; return;
  1269.   end;
  1270. case selector of
  1271. term_and_log: begin wterm(xchr[s]); wlog(xchr[s]);
  1272.   incr(term_offset); incr(file_offset);
  1273.   if term_offset=max_print_line then
  1274.     begin wterm_cr; term_offset:=0;
  1275.     end;
  1276.   if file_offset=max_print_line then
  1277.     begin wlog_cr; file_offset:=0;
  1278.     end;
  1279.   end;
  1280. log_only: begin wlog(xchr[s]); incr(file_offset);
  1281.   if file_offset=max_print_line then print_ln;
  1282.   end;
  1283. term_only: begin wterm(xchr[s]); incr(term_offset);
  1284.   if term_offset=max_print_line then print_ln;
  1285.   end;
  1286. no_print: do_nothing;
  1287. pseudo: if tally<trick_count then trick_buf[tally mod error_line]:=s;
  1288. new_string: begin if pool_ptr<pool_size then append_char(s);
  1289.   end; {we drop characters if the string space is full}
  1290. othercases write(write_file[selector],xchr[s])
  1291. endcases;@/
  1292. incr(tally);
  1293. exit:end;
  1294. @ An entire string is output by calling |print|. Note that if we are outputting
  1295. the single standard ASCII character \.c, we could call |print("c")|, since
  1296. |"c"=99| is the number of a single-character string, as explained above. But
  1297. |print_char("c")| is quicker, so \TeX\ goes directly to the |print_char|
  1298. routine when it knows that this is safe. (The present implementation
  1299. assumes that it is always safe to print a visible ASCII character.)
  1300. @^system dependencies@>
  1301. @<Basic print...@>=
  1302. procedure print(@!s:integer); {prints string |s|}
  1303. label exit;
  1304. var j:pool_pointer; {current character code position}
  1305. @!nl:integer; {new-line character to restore}
  1306. begin if s>=str_ptr then s:="???" {this can't happen}
  1307. @.???@>
  1308. else if s<256 then
  1309.   if s<0 then s:="???" {can't happen}
  1310.   else begin if selector>pseudo then
  1311.       begin print_char(s); return; {internal strings are not expanded}
  1312.       end;
  1313.     if (@<Character |s| is the current new-line character@>) then
  1314.       if selector<pseudo then
  1315.         begin print_ln; return;
  1316.         end;
  1317.     nl:=new_line_char; new_line_char:=-1;
  1318.       {temporarily disable new-line character}
  1319.     j:=str_start[s];
  1320.     while j<str_start[s+1] do
  1321.       begin print_char(so(str_pool[j])); incr(j);
  1322.       end;
  1323.     new_line_char:=nl; return;
  1324.     end;
  1325. j:=str_start[s];
  1326. while j<str_start[s+1] do
  1327.   begin print_char(so(str_pool[j])); incr(j);
  1328.   end;
  1329. exit:end;
  1330. @ Control sequence names, file names, and strings constructed with
  1331. \.{\\string} might contain |ASCII_code| values that can't
  1332. be printed using |print_char|. Therefore we use |slow_print| for them:
  1333. @<Basic print...@>=
  1334. procedure slow_print(@!s:integer); {prints string |s|}
  1335. var j:pool_pointer; {current character code position}
  1336. begin if (s>=str_ptr) or (s<256) then print(s)
  1337. else begin j:=str_start[s];
  1338.   while j<str_start[s+1] do
  1339.     begin print(so(str_pool[j])); incr(j);
  1340.     end;
  1341.   end;
  1342. @ Here is the very first thing that \TeX\ prints: a headline that identifies
  1343. the version number and format package. The |term_offset| variable is temporarily
  1344. incorrect, but the discrepancy is not serious since we assume that the banner
  1345. and format identifier together will occupy at most |max_print_line|
  1346. character positions.
  1347. @<Initialize the output...@>=
  1348. wterm(banner);
  1349. if format_ident=0 then wterm_ln(' (no format preloaded)')
  1350. else  begin slow_print(format_ident); print_ln;
  1351.   end;
  1352. update_terminal;
  1353. @ The procedure |print_nl| is like |print|, but it makes sure that the
  1354. string appears at the beginning of a new line.
  1355. @<Basic print...@>=
  1356. procedure print_nl(@!s:str_number); {prints string |s| at beginning of line}
  1357. begin if ((term_offset>0)and(odd(selector)))or@|
  1358.   ((file_offset>0)and(selector>=log_only)) then print_ln;
  1359. print(s);
  1360. @ The procedure |print_esc| prints a string that is preceded by
  1361. the user's escape character (which is usually a backslash).
  1362. @<Basic print...@>=
  1363. procedure print_esc(@!s:str_number); {prints escape character, then |s|}
  1364. var c:integer; {the escape character code}
  1365. begin  @<Set variable |c| to the current escape character@>;
  1366. if c>=0 then if c<256 then print(c);
  1367. slow_print(s);
  1368. @ An array of digits in the range |0..15| is printed by |print_the_digs|.
  1369. @<Basic print...@>=
  1370. procedure print_the_digs(@!k:eight_bits);
  1371.   {prints |dig[k-1]|$\,\ldots\,$|dig[0]|}
  1372. begin while k>0 do
  1373.   begin decr(k);
  1374.   if dig[k]<10 then print_char("0"+dig[k])
  1375.   else print_char("A"-10+dig[k]);
  1376.   end;
  1377. @ The following procedure, which prints out the decimal representation of a
  1378. given integer |n|, has been written carefully so that it works properly
  1379. if |n=0| or if |(-n)| would cause overflow. It does not apply |mod| or |div|
  1380. to negative arguments, since such operations are not implemented consistently
  1381. by all \PASCAL\ compilers.
  1382. @<Basic print...@>=
  1383. procedure print_int(@!n:integer); {prints an integer in decimal form}
  1384. var k:0..23; {index to current digit; we assume that $|n|<10^{23}$}
  1385. @!m:integer; {used to negate |n| in possibly dangerous cases}
  1386. begin k:=0;
  1387. if n<0 then
  1388.   begin print_char("-");
  1389.   if n>-100000000 then negate(n)
  1390.   else  begin m:=-1-n; n:=m div 10; m:=(m mod 10)+1; k:=1;
  1391.     if m<10 then dig[0]:=m
  1392.     else  begin dig[0]:=0; incr(n);
  1393.       end;
  1394.     end;
  1395.   end;
  1396. repeat dig[k]:=n mod 10; n:=n div 10; incr(k);
  1397. until n=0;
  1398. print_the_digs(k);
  1399. @ Here is a trivial procedure to print two digits; it is usually called with
  1400. a parameter in the range |0<=n<=99|.
  1401. @p procedure print_two(@!n:integer); {prints two least significant digits}
  1402. begin n:=abs(n) mod 100; print_char("0"+(n div 10));
  1403. print_char("0"+(n mod 10));
  1404. @ Hexadecimal printing of nonnegative integers is accomplished by |print_hex|.
  1405. @p procedure print_hex(@!n:integer);
  1406.   {prints a positive integer in hexadecimal form}
  1407. var k:0..22; {index to current digit; we assume that $0\L n<16^{22}$}
  1408. begin k:=0; print_char("""");
  1409. repeat dig[k]:=n mod 16; n:=n div 16; incr(k);
  1410. until n=0;
  1411. print_the_digs(k);
  1412. @ Old versions of \TeX\ needed a procedure called |print_ASCII| whose function
  1413. is now subsumed by |print|. We retain the old name here as a possible aid to
  1414. future software arch\ae ologists.
  1415. @d print_ASCII == print
  1416. @ Roman numerals are produced by the |print_roman_int| routine.  Readers
  1417. who like puzzles might enjoy trying to figure out how this tricky code
  1418. works; therefore no explanation will be given. Notice that 1990 yields
  1419. \.{mcmxc}, not \.{mxm}.
  1420. @p procedure print_roman_int(@!n:integer);
  1421. label exit;
  1422. var j,@!k: pool_pointer; {mysterious indices into |str_pool|}
  1423. @!u,@!v: nonnegative_integer; {mysterious numbers}
  1424. begin j:=str_start["m2d5c2l5x2v5i"]; v:=1000;
  1425. loop@+  begin while n>=v do
  1426.     begin print_char(so(str_pool[j])); n:=n-v;
  1427.     end;
  1428.   if n<=0 then return; {nonpositive input produces no output}
  1429.   k:=j+2; u:=v div (so(str_pool[k-1])-"0");
  1430.   if str_pool[k-1]=si("2") then
  1431.     begin k:=k+2; u:=u div (so(str_pool[k-1])-"0");
  1432.     end;
  1433.   if n+u>=v then
  1434.     begin print_char(so(str_pool[k])); n:=n+u;
  1435.     end
  1436.   else  begin j:=j+2; v:=v div (so(str_pool[j-1])-"0");
  1437.     end;
  1438.   end;
  1439. exit:end;
  1440. @ The |print| subroutine will not print a string that is still being
  1441. created. The following procedure will.
  1442. @p procedure print_current_string; {prints a yet-unmade string}
  1443. var j:pool_pointer; {points to current character code}
  1444. begin j:=str_start[str_ptr];
  1445. while j<pool_ptr do
  1446.   begin print_char(so(str_pool[j])); incr(j);
  1447.   end;
  1448. @ Here is a procedure that asks the user to type a line of input,
  1449. assuming that the |selector| setting is either |term_only| or |term_and_log|.
  1450. The input is placed into locations |first| through |last-1| of the
  1451. |buffer| array, and echoed on the transcript file if appropriate.
  1452. This procedure is never called when |interaction<scroll_mode|.
  1453. @d prompt_input(#)==begin wake_up_terminal; print(#); term_input;
  1454.     end {prints a string and gets a line of input}
  1455. @p procedure term_input; {gets a line from the terminal}
  1456. var k:0..buf_size; {index into |buffer|}
  1457. begin update_terminal; {Now the user sees the prompt for sure}
  1458. if not input_ln(term_in,true) then fatal_error("End of file on the terminal!");
  1459. @.End of file on the terminal@>
  1460. term_offset:=0; {the user's line ended with \<\rm return>}
  1461. decr(selector); {prepare to echo the input}
  1462. if last<>first then for k:=first to last-1 do print(buffer[k]);
  1463. print_ln; incr(selector); {restore previous status}
  1464. @* \[6] Reporting errors.
  1465. When something anomalous is detected, \TeX\ typically does something like this:
  1466. $$\vbox{\halign{#\hfil\cr
  1467. |print_err("Something anomalous has been detected");|\cr
  1468. |help3("This is the first line of my offer to help.")|\cr
  1469. |("This is the second line. I'm trying to")|\cr
  1470. |("explain the best way for you to proceed.");|\cr
  1471. |error;|\cr}}$$
  1472. A two-line help message would be given using |help2|, etc.; these informal
  1473. helps should use simple vocabulary that complements the words used in the
  1474. official error message that was printed. (Outside the U.S.A., the help
  1475. messages should preferably be translated into the local vernacular. Each
  1476. line of help is at most 60 characters long, in the present implementation,
  1477. so that |max_print_line| will not be exceeded.)
  1478. The |print_err| procedure supplies a `\.!' before the official message,
  1479. and makes sure that the terminal is awake if a stop is going to occur.
  1480. The |error| procedure supplies a `\..' after the official message, then it
  1481. shows the location of the error; and if |interaction=error_stop_mode|,
  1482. it also enters into a dialog with the user, during which time the help
  1483. message may be printed.
  1484. @^system dependencies@>
  1485. @ The global variable |interaction| has four settings, representing increasing
  1486. amounts of user interaction:
  1487. @d batch_mode=0 {omits all stops and omits terminal output}
  1488. @d nonstop_mode=1 {omits all stops}
  1489. @d scroll_mode=2 {omits error stops}
  1490. @d error_stop_mode=3 {stops at every opportunity to interact}
  1491. @d print_err(#)==begin if interaction=error_stop_mode then wake_up_terminal;
  1492.   print_nl("! "); print(#);
  1493.   end
  1494. @<Glob...@>=
  1495. @!interaction:batch_mode..error_stop_mode; {current level of interaction}
  1496. @ @<Set init...@>=interaction:=error_stop_mode;
  1497. @ \TeX\ is careful not to call |error| when the print |selector| setting
  1498. might be unusual. The only possible values of |selector| at the time of
  1499. error messages are
  1500. \yskip\hang|no_print| (when |interaction=batch_mode|
  1501.   and |log_file| not yet open);
  1502. \hang|term_only| (when |interaction>batch_mode| and |log_file| not yet open);
  1503. \hang|log_only| (when |interaction=batch_mode| and |log_file| is open);
  1504. \hang|term_and_log| (when |interaction>batch_mode| and |log_file| is open).
  1505. @<Initialize the print |selector| based on |interaction|@>=
  1506. if interaction=batch_mode then selector:=no_print@+else selector:=term_only
  1507. @ A global variable |deletions_allowed| is set |false| if the |get_next|
  1508. routine is active when |error| is called; this ensures that |get_next|
  1509. and related routines like |get_token| will never be called recursively.
  1510. A similar interlock is provided by |set_box_allowed|.
  1511. @^recursion@>
  1512. The global variable |history| records the worst level of error that
  1513. has been detected. It has four possible values: |spotless|, |warning_issued|,
  1514. |error_message_issued|, and |fatal_error_stop|.
  1515. Another global variable, |error_count|, is increased by one when an
  1516. |error| occurs without an interactive dialog, and it is reset to zero at
  1517. the end of every paragraph.  If |error_count| reaches 100, \TeX\ decides
  1518. that there is no point in continuing further.
  1519. @d spotless=0 {|history| value when nothing has been amiss yet}
  1520. @d warning_issued=1 {|history| value when |begin_diagnostic| has been called}
  1521. @d error_message_issued=2 {|history| value when |error| has been called}
  1522. @d fatal_error_stop=3 {|history| value when termination was premature}
  1523. @<Glob...@>=
  1524. @!deletions_allowed:boolean; {is it safe for |error| to call |get_token|?}
  1525. @!set_box_allowed:boolean; {is it safe to do a \.{\\setbox} assignment?}
  1526. @!history:spotless..fatal_error_stop; {has the source input been clean so far?}
  1527. @!error_count:-1..100; {the number of scrolled errors since the
  1528.   last paragraph ended}
  1529. @ The value of |history| is initially |fatal_error_stop|, but it will
  1530. be changed to |spotless| if \TeX\ survives the initialization process.
  1531. @<Set init...@>=
  1532. deletions_allowed:=true; set_box_allowed:=true;
  1533. error_count:=0; {|history| is initialized elsewhere}
  1534. @ Since errors can be detected almost anywhere in \TeX, we want to declare the
  1535. error procedures near the beginning of the program. But the error procedures
  1536. in turn use some other procedures, which need to be declared |forward|
  1537. before we get to |error| itself.
  1538. It is possible for |error| to be called recursively if some error arises
  1539. when |get_token| is being used to delete a token, and/or if some fatal error
  1540. occurs while \TeX\ is trying to fix a non-fatal one. But such recursion
  1541. @^recursion@>
  1542. is never more than two levels deep.
  1543. @<Error handling...@>=
  1544. procedure@?normalize_selector; forward;@t\2@>@/
  1545. procedure@?get_token; forward;@t\2@>@/
  1546. procedure@?term_input; forward;@t\2@>@/
  1547. procedure@?show_context; forward;@t\2@>@/
  1548. procedure@?begin_file_reading; forward;@t\2@>@/
  1549. procedure@?open_log_file; forward;@t\2@>@/
  1550. procedure@?close_files_and_terminate; forward;@t\2@>@/
  1551. procedure@?clear_for_error_prompt; forward;@t\2@>@/
  1552. procedure@?give_err_help; forward;@t\2@>@/
  1553. @t\4\hskip-\fontdimen2\font@>@;@+@!debug@+procedure@?debug_help;
  1554.   forward;@;@+gubed
  1555. @ Individual lines of help are recorded in the array |help_line|, which
  1556. contains entries in positions |0..(help_ptr-1)|. They should be printed
  1557. in reverse order, i.e., with |help_line[0]| appearing last.
  1558. @d hlp1(#)==help_line[0]:=#;@+end
  1559. @d hlp2(#)==help_line[1]:=#; hlp1
  1560. @d hlp3(#)==help_line[2]:=#; hlp2
  1561. @d hlp4(#)==help_line[3]:=#; hlp3
  1562. @d hlp5(#)==help_line[4]:=#; hlp4
  1563. @d hlp6(#)==help_line[5]:=#; hlp5
  1564. @d help0==help_ptr:=0 {sometimes there might be no help}
  1565. @d help1==@+begin help_ptr:=1; hlp1 {use this with one help line}
  1566. @d help2==@+begin help_ptr:=2; hlp2 {use this with two help lines}
  1567. @d help3==@+begin help_ptr:=3; hlp3 {use this with three help lines}
  1568. @d help4==@+begin help_ptr:=4; hlp4 {use this with four help lines}
  1569. @d help5==@+begin help_ptr:=5; hlp5 {use this with five help lines}
  1570. @d help6==@+begin help_ptr:=6; hlp6 {use this with six help lines}
  1571. @<Glob...@>=
  1572. @!help_line:array[0..5] of str_number; {helps for the next |error|}
  1573. @!help_ptr:0..6; {the number of help lines present}
  1574. @!use_err_help:boolean; {should the |err_help| list be shown?}
  1575. @ @<Set init...@>=
  1576. help_ptr:=0; use_err_help:=false;
  1577. @ The |jump_out| procedure just cuts across all active procedure levels and
  1578. goes to |end_of_TEX|. This is the only nontrivial |@!goto| statement in the
  1579. whole program. It is used when there is no recovery from a particular error.
  1580. Some \PASCAL\ compilers do not implement non-local |goto| statements.
  1581. @^system dependencies@>
  1582. In such cases the body of |jump_out| should simply be
  1583. `|close_files_and_terminate|;\thinspace' followed by a call on some system
  1584. procedure that quietly terminates the program.
  1585. @<Error hand...@>=
  1586. procedure jump_out;
  1587. begin goto end_of_TEX;
  1588. @ Here now is the general |error| routine.
  1589. @<Error hand...@>=
  1590. procedure error; {completes the job of error reporting}
  1591. label continue,exit;
  1592. var c:ASCII_code; {what the user types}
  1593. @!s1,@!s2,@!s3,@!s4:integer;
  1594.   {used to save global variables when deleting tokens}
  1595. begin if history<error_message_issued then history:=error_message_issued;
  1596. print_char("."); show_context;
  1597. if interaction=error_stop_mode then @<Get user's advice and |return|@>;
  1598. incr(error_count);
  1599. if error_count=100 then
  1600.   begin print_nl("(That makes 100 errors; please try again.)");
  1601. @.That makes 100 errors...@>
  1602.   history:=fatal_error_stop; jump_out;
  1603.   end;
  1604. @<Put help message on the transcript file@>;
  1605. exit:end;
  1606. @ @<Get user's advice...@>=
  1607. loop@+begin continue: clear_for_error_prompt; prompt_input("? ");
  1608. @.?\relax@>
  1609.   if last=first then return;
  1610.   c:=buffer[first];
  1611.   if c>="a" then c:=c+"A"-"a"; {convert to uppercase}
  1612.   @<Interpret code |c| and |return| if done@>;
  1613.   end
  1614. @ It is desirable to provide an `\.E' option here that gives the user
  1615. an easy way to return from \TeX\ to the system editor, with the offending
  1616. line ready to be edited. But such an extension requires some system
  1617. wizardry, so the present implementation simply types out the name of the
  1618. file that should be
  1619. edited and the relevant line number.
  1620. @^system dependencies@>
  1621. There is a secret `\.D' option available when the debugging routines haven't
  1622. been commented~out.
  1623. @^debugging@>
  1624. @<Interpret code |c| and |return| if done@>=
  1625. case c of
  1626. "0","1","2","3","4","5","6","7","8","9": if deletions_allowed then
  1627.   @<Delete \(c)|c-"0"| tokens and |goto continue|@>;
  1628. @t\4\4@>@;@+@!debug "D": begin debug_help; goto continue;@+end;@+gubed@/
  1629. "E": if base_ptr>0 then
  1630.   begin print_nl("You want to edit file ");
  1631. @.You want to edit file x@>
  1632.   slow_print(input_stack[base_ptr].name_field);
  1633.   print(" at line "); print_int(line);
  1634.   interaction:=scroll_mode; jump_out;
  1635.   end;
  1636. "H": @<Print the help information and |goto continue|@>;
  1637. "I":@<Introduce new material from the terminal and |return|@>;
  1638. "Q","R","S":@<Change the interaction level and |return|@>;
  1639. "X":begin interaction:=scroll_mode; jump_out;
  1640.   end;
  1641. othercases do_nothing
  1642. endcases;@/
  1643. @<Print the menu of available options@>
  1644. @ @<Print the menu...@>=
  1645. begin print("Type <return> to proceed, S to scroll future error messages,");@/
  1646. @.Type <return> to proceed...@>
  1647. print_nl("R to run without stopping, Q to run quietly,");@/
  1648. print_nl("I to insert something, ");
  1649. if base_ptr>0 then print("E to edit your file,");
  1650. if deletions_allowed then
  1651.   print_nl("1 or ... or 9 to ignore the next 1 to 9 tokens of input,");
  1652. print_nl("H for help, X to quit.");
  1653. @ Here the author of \TeX\ apologizes for making use of the numerical
  1654. relation between |"Q"|, |"R"|, |"S"|, and the desired interaction settings
  1655. |batch_mode|, |nonstop_mode|, |scroll_mode|.
  1656. @^Knuth, Donald Ervin@>
  1657. @<Change the interaction...@>=
  1658. begin error_count:=0; interaction:=batch_mode+c-"Q";
  1659. print("OK, entering ");
  1660. case c of
  1661. "Q":begin print_esc("batchmode"); decr(selector);
  1662.   end;
  1663. "R":print_esc("nonstopmode");
  1664. "S":print_esc("scrollmode");
  1665. end; {there are no other cases}
  1666. print("..."); print_ln; update_terminal; return;
  1667. @ When the following code is executed, |buffer[(first+1)..(last-1)]| may
  1668. contain the material inserted by the user; otherwise another prompt will
  1669. be given. In order to understand this part of the program fully, you need
  1670. to be familiar with \TeX's input stacks.
  1671. @<Introduce new material...@>=
  1672. begin begin_file_reading; {enter a new syntactic level for terminal input}
  1673. {now |state=mid_line|, so an initial blank space will count as a blank}
  1674. if last>first+1 then
  1675.   begin loc:=first+1; buffer[first]:=" ";
  1676.   end
  1677. else  begin prompt_input("insert>"); loc:=first;
  1678. @.insert>@>
  1679.   end;
  1680. first:=last;
  1681. cur_input.limit_field:=last-1; {no |end_line_char| ends this line}
  1682. return;
  1683. @ We allow deletion of up to 99 tokens at a time.
  1684. @<Delete \(c)|c-"0"| tokens...@>=
  1685. begin s1:=cur_tok; s2:=cur_cmd; s3:=cur_chr; s4:=align_state;
  1686. align_state:=1000000; OK_to_interrupt:=false;
  1687. if (last>first+1) and (buffer[first+1]>="0")and(buffer[first+1]<="9") then
  1688.   c:=c*10+buffer[first+1]-"0"*11
  1689. else c:=c-"0";
  1690. while c>0 do
  1691.   begin get_token; {one-level recursive call of |error| is possible}
  1692.   decr(c);
  1693.   end;
  1694. cur_tok:=s1; cur_cmd:=s2; cur_chr:=s3; align_state:=s4; OK_to_interrupt:=true;
  1695. help2("I have just deleted some text, as you asked.")@/
  1696. ("You can now delete more, or insert, or whatever.");
  1697. show_context; goto continue;
  1698. @ @<Print the help info...@>=
  1699. begin if use_err_help then
  1700.   begin give_err_help; use_err_help:=false;
  1701.   end
  1702. else  begin if help_ptr=0 then
  1703.     help2("Sorry, I don't know how to help in this situation.")@/
  1704.     @t\kern1em@>("Maybe you should try asking a human?");
  1705.   repeat decr(help_ptr); print(help_line[help_ptr]); print_ln;
  1706.   until help_ptr=0;
  1707.   end;
  1708. help4("Sorry, I already gave what help I could...")@/
  1709.   ("Maybe you should try asking a human?")@/
  1710.   ("An error might have occurred before I noticed any problems.")@/
  1711.   ("``If all else fails, read the instructions.''");@/
  1712. goto continue;
  1713. @ @<Put help message on the transcript file@>=
  1714. if interaction>batch_mode then decr(selector); {avoid terminal output}
  1715. if use_err_help then
  1716.   begin print_ln; give_err_help;
  1717.   end
  1718. else while help_ptr>0 do
  1719.   begin decr(help_ptr); print_nl(help_line[help_ptr]);
  1720.   end;
  1721. print_ln;
  1722. if interaction>batch_mode then incr(selector); {re-enable terminal output}
  1723. print_ln
  1724. @ A dozen or so error messages end with a parenthesized integer, so we
  1725. save a teeny bit of program space by declaring the following procedure:
  1726. @p procedure int_error(@!n:integer);
  1727. begin print(" ("); print_int(n); print_char(")"); error;
  1728. @ In anomalous cases, the print selector might be in an unknown state;
  1729. the following subroutine is called to fix things just enough to keep
  1730. running a bit longer.
  1731. @p procedure normalize_selector;
  1732. begin if log_opened then selector:=term_and_log
  1733. else selector:=term_only;
  1734. if job_name=0 then open_log_file;
  1735. if interaction=batch_mode then decr(selector);
  1736. @ The following procedure prints \TeX's last words before dying.
  1737. @d succumb==begin if interaction=error_stop_mode then
  1738.     interaction:=scroll_mode; {no more interaction}
  1739.   if log_opened then error;
  1740.   @!debug if interaction>batch_mode then debug_help;@+gubed@;@/
  1741.   history:=fatal_error_stop; jump_out; {irrecoverable error}
  1742.   end
  1743. @<Error hand...@>=
  1744. procedure fatal_error(@!s:str_number); {prints |s|, and that's it}
  1745. begin normalize_selector;@/
  1746. print_err("Emergency stop"); help1(s); succumb;
  1747. @.Emergency stop@>
  1748. @ Here is the most dreaded error message.
  1749. @<Error hand...@>=
  1750. procedure overflow(@!s:str_number;@!n:integer); {stop due to finiteness}
  1751. begin normalize_selector;
  1752. print_err("TeX capacity exceeded, sorry [");
  1753. @.TeX capacity exceeded ...@>
  1754. print(s); print_char("="); print_int(n); print_char("]");
  1755. help2("If you really absolutely need more capacity,")@/
  1756.   ("you can ask a wizard to enlarge me.");
  1757. succumb;
  1758. @ The program might sometime run completely amok, at which point there is
  1759. no choice but to stop. If no previous error has been detected, that's bad
  1760. news; a message is printed that is really intended for the \TeX\
  1761. maintenance person instead of the user (unless the user has been
  1762. particularly diabolical).  The index entries for `this can't happen' may
  1763. help to pinpoint the problem.
  1764. @^dry rot@>
  1765. @<Error hand...@>=
  1766. procedure confusion(@!s:str_number);
  1767.   {consistency check violated; |s| tells where}
  1768. begin normalize_selector;
  1769. if history<error_message_issued then
  1770.   begin print_err("This can't happen ("); print(s); print_char(")");
  1771. @.This can't happen@>
  1772.   help1("I'm broken. Please show this to someone who can fix can fix");
  1773.   end
  1774. else  begin print_err("I can't go on meeting you like this");
  1775. @.I can't go on...@>
  1776.   help2("One of your faux pas seems to have wounded me deeply...")@/
  1777.     ("in fact, I'm barely conscious. Please fix it and try again.");
  1778.   end;
  1779. succumb;
  1780. @ Users occasionally want to interrupt \TeX\ while it's running.
  1781. If the \PASCAL\ runtime system allows this, one can implement
  1782. a routine that sets the global variable |interrupt| to some nonzero value
  1783. when such an interrupt is signalled. Otherwise there is probably at least
  1784. a way to make |interrupt| nonzero using the \PASCAL\ debugger.
  1785. @^system dependencies@>
  1786. @^debugging@>
  1787. @d check_interrupt==begin if interrupt<>0 then pause_for_instructions;
  1788.   end
  1789. @<Global...@>=
  1790. @!interrupt:integer; {should \TeX\ pause for instructions?}
  1791. @!OK_to_interrupt:boolean; {should interrupts be observed?}
  1792. @ @<Set init...@>=
  1793. interrupt:=0; OK_to_interrupt:=true;
  1794. @ When an interrupt has been detected, the program goes into its
  1795. highest interaction level and lets the user have nearly the full flexibility of
  1796. the |error| routine.  \TeX\ checks for interrupts only at times when it is
  1797. safe to do this.
  1798. @p procedure pause_for_instructions;
  1799. begin if OK_to_interrupt then
  1800.   begin interaction:=error_stop_mode;
  1801.   if (selector=log_only)or(selector=no_print) then
  1802.     incr(selector);
  1803.   print_err("Interruption");
  1804. @.Interruption@>
  1805.   help3("You rang?")@/
  1806.   ("Try to insert some instructions for me (e.g.,`I\showlists'),")@/
  1807.   ("unless you just want to quit by typing `X'.");
  1808.   deletions_allowed:=false; error; deletions_allowed:=true;
  1809.   interrupt:=0;
  1810.   end;
  1811. @* \[7] Arithmetic with scaled dimensions.
  1812. The principal computations performed by \TeX\ are done entirely in terms of
  1813. integers less than $2^{31}$ in magnitude; and divisions are done only when both
  1814. dividend and divisor are nonnegative. Thus, the arithmetic specified in this
  1815. program can be carried out in exactly the same way on a wide variety of
  1816. computers, including some small ones. Why? Because the arithmetic
  1817. calculations need to be spelled out precisely in order to guarantee that
  1818. \TeX\ will produce identical output on different machines. If some
  1819. quantities were rounded differently in different implementations, we would
  1820. find that line breaks and even page breaks might occur in different places.
  1821. Hence the arithmetic of \TeX\ has been designed with care, and systems that
  1822. claim to be implementations of \TeX82 should follow precisely the
  1823. @:TeX82}{\TeX82@>
  1824. calculations as they appear in the present program.
  1825. (Actually there are three places where \TeX\ uses |div| with a possibly negative
  1826. numerator. These are harmless; see |div| in the index. Also if the user
  1827. sets the \.{\\time} or the \.{\\year} to a negative value, some diagnostic
  1828. information will involve negative-numerator division. The same remarks
  1829. apply for |mod| as well as for |div|.)
  1830. @ Here is a routine that calculates half of an integer, using an
  1831. unambiguous convention with respect to signed odd numbers.
  1832. @p function half(@!x:integer):integer;
  1833. begin if odd(x) then half:=(x+1) div 2
  1834. else half:=x @!div 2;
  1835. @ Fixed-point arithmetic is done on {\sl scaled integers\/} that are multiples
  1836. of $2^{-16}$. In other words, a binary point is assumed to be sixteen bit
  1837. positions from the right end of a binary computer word.
  1838. @d unity == @'200000 {$2^{16}$, represents 1.00000}
  1839. @d two == @'400000 {$2^{17}$, represents 2.00000}
  1840. @<Types...@>=
  1841. @!scaled = integer; {this type is used for scaled integers}
  1842. @!nonnegative_integer=0..@'17777777777; {$0\L x<2^{31}$}
  1843. @!small_number=0..63; {this type is self-explanatory}
  1844. @ The following function is used to create a scaled integer from a given decimal
  1845. fraction $(.d_0d_1\ldots d_{k-1})$, where |0<=k<=17|. The digit $d_i$ is
  1846. given in |dig[i]|, and the calculation produces a correctly rounded result.
  1847. @p function round_decimals(@!k:small_number) : scaled;
  1848.   {converts a decimal fraction}
  1849. var a:integer; {the accumulator}
  1850. begin a:=0;
  1851. while k>0 do
  1852.   begin decr(k); a:=(a+dig[k]*two) div 10;
  1853.   end;
  1854. round_decimals:=(a+1) div 2;
  1855. @ Conversely, here is a procedure analogous to |print_int|. If the output
  1856. of this procedure is subsequently read by \TeX\ and converted by the
  1857. |round_decimals| routine above, it turns out that the original value will
  1858. be reproduced exactly; the ``simplest'' such decimal number is output,
  1859. but there is always at least one digit following the decimal point.
  1860. The invariant relation in the \&{repeat} loop is that a sequence of
  1861. decimal digits yet to be printed will yield the original number if and only if
  1862. they form a fraction~$f$ in the range $s-\delta\L10\cdot2^{16}f<s$.
  1863. We can stop if and only if $f=0$ satisfies this condition; the loop will
  1864. terminate before $s$ can possibly become zero.
  1865. @p procedure print_scaled(@!s:scaled); {prints scaled real, rounded to five
  1866.   digits}
  1867. var delta:scaled; {amount of allowable inaccuracy}
  1868. begin if s<0 then
  1869.   begin print_char("-"); negate(s); {print the sign, if negative}
  1870.   end;
  1871. print_int(s div unity); {print the integer part}
  1872. print_char(".");
  1873. s:=10*(s mod unity)+5; delta:=10;
  1874. repeat if delta>unity then s:=s+@'100000-50000; {round the last digit}
  1875. print_char("0"+(s div unity)); s:=10*(s mod unity); delta:=delta*10;
  1876. until s<=delta;
  1877. @ Physical sizes that a \TeX\ user specifies for portions of documents are
  1878. represented internally as scaled points. Thus, if we define an `sp' (scaled
  1879. @^sp@>
  1880. point) as a unit equal to $2^{-16}$ printer's points, every dimension
  1881. inside of \TeX\ is an integer number of sp. There are exactly
  1882. 4,736,286.72 sp per inch.  Users are not allowed to specify dimensions
  1883. larger than $2^{30}-1$ sp, which is a distance of about 18.892 feet (5.7583
  1884. meters); two such quantities can be added without overflow on a 32-bit
  1885. computer.
  1886. The present implementation of \TeX\ does not check for overflow when
  1887. @^Overflow in arithmetic@>
  1888. dimensions are added or subtracted. This could be done by inserting a
  1889. few dozen tests of the form `\ignorespaces|if x>=@'10000000000 then
  1890. @t\\{report\_overflow}@>|', but the chance of overflow is so remote that
  1891. such tests do not seem worthwhile.
  1892. \TeX\ needs to do only a few arithmetic operations on scaled quantities,
  1893. other than addition and subtraction, and the following subroutines do most of
  1894. the work. A single computation might use several subroutine calls, and it is
  1895. desirable to avoid producing multiple error messages in case of arithmetic
  1896. overflow; so the routines set the global variable |arith_error| to |true|
  1897. instead of reporting errors directly to the user. Another global variable,
  1898. |remainder|, holds the remainder after a division.
  1899. @<Glob...@>=
  1900. @!arith_error:boolean; {has arithmetic overflow occurred recently?}
  1901. @!remainder:scaled; {amount subtracted to get an exact division}
  1902. @ The first arithmetical subroutine we need computes $nx+y$, where |x|
  1903. and~|y| are |scaled| and |n| is an integer. We will also use it to
  1904. multiply integers.
  1905. @d nx_plus_y(#)==mult_and_add(#,@'7777777777)
  1906. @d mult_integers(#)==mult_and_add(#,0,@'17777777777)
  1907. @p function mult_and_add(@!n:integer;@!x,@!y,@!max_answer:scaled):scaled;
  1908. begin if n<0 then
  1909.   begin negate(x); negate(n);
  1910.   end;
  1911. if n=0 then mult_and_add:=y
  1912. else if ((x<=(max_answer-y) div n)and(-x<=(max_answer+y) div n)) then
  1913.   mult_and_add:=n*x+y
  1914. else  begin arith_error:=true; mult_and_add:=0;
  1915.   end;
  1916. @ We also need to divide scaled dimensions by integers.
  1917. @p function x_over_n(@!x:scaled;@!n:integer):scaled;
  1918. var negative:boolean; {should |remainder| be negated?}
  1919. begin negative:=false;
  1920. if n=0 then
  1921.   begin arith_error:=true; x_over_n:=0; remainder:=x;
  1922.   end
  1923. else  begin if n<0 then
  1924.     begin negate(x); negate(n); negative:=true;
  1925.     end;
  1926.   if x>=0 then
  1927.     begin x_over_n:=x div n; remainder:=x mod n;
  1928.     end
  1929.   else  begin x_over_n:=-((-x) div n); remainder:=-((-x) mod n);
  1930.     end;
  1931.   end;
  1932. if negative then negate(remainder);
  1933. @ Then comes the multiplication of a scaled number by a fraction |n/d|,
  1934. where |n| and |d| are nonnegative integers |<=@t$2^{16}$@>| and |d| is
  1935. positive. It would be too dangerous to multiply by~|n| and then divide
  1936. by~|d|, in separate operations, since overflow might well occur; and it
  1937. would be too inaccurate to divide by |d| and then multiply by |n|. Hence
  1938. this subroutine simulates 1.5-precision arithmetic.
  1939. @p function xn_over_d(@!x:scaled; @!n,@!d:integer):scaled;
  1940. var positive:boolean; {was |x>=0|?}
  1941. @!t,@!u,@!v:nonnegative_integer; {intermediate quantities}
  1942. begin if x>=0 then positive:=true
  1943. else  begin negate(x); positive:=false;
  1944.   end;
  1945. t:=(x mod @'100000)*n;
  1946. u:=(x div @'100000)*n+(t div @'100000);
  1947. v:=(u mod d)*@'100000 + (t mod @'100000);
  1948. if u div d>=@'100000 then arith_error:=true
  1949. else u:=@'100000*(u div d) + (v div d);
  1950. if positive then
  1951.   begin xn_over_d:=u; remainder:=v mod d;
  1952.   end
  1953. else  begin xn_over_d:=-u; remainder:=-(v mod d);
  1954.   end;
  1955. @ The next subroutine is used to compute the ``badness'' of glue, when a
  1956. total~|t| is supposed to be made from amounts that sum to~|s|.  According
  1957. to {\sl The \TeX book}, the badness of this situation is $100(t/s)^3$;
  1958. however, badness is simply a heuristic, so we need not squeeze out the
  1959. last drop of accuracy when computing it. All we really want is an
  1960. approximation that has similar properties.
  1961. @:TeXbook}{\sl The \TeX book@>
  1962. The actual method used to compute the badness is easier to read from the
  1963. program than to describe in words. It produces an integer value that is a
  1964. reasonably close approximation to $100(t/s)^3$, and all implementations
  1965. of \TeX\ should use precisely this method. Any badness of $2^{13}$ or more is
  1966. treated as infinitely bad, and represented by 10000.
  1967. It is not difficult to prove that $$\hbox{|badness(t+1,s)>=badness(t,s)
  1968. >=badness(t,s+1)|}.$$ The badness function defined here is capable of
  1969. computing at most 1095 distinct values, but that is plenty.
  1970. @d inf_bad = 10000 {infinitely bad value}
  1971. @p function badness(@!t,@!s:scaled):halfword; {compute badness, given |t>=0|}
  1972. var r:integer; {approximation to $\alpha t/s$, where $\alpha^3\approx
  1973.   100\cdot2^{18}$}
  1974. begin if t=0 then badness:=0
  1975. else if s<=0 then badness:=inf_bad
  1976. else  begin if t<=7230584 then  r:=(t*297) div s {$297^3=99.94\times2^{18}$}
  1977.   else if s>=1663497 then r:=t div (s div 297)
  1978.   else r:=t;
  1979.   if r>1290 then badness:=inf_bad {$1290^3<2^{31}<1291^3$}
  1980.   else badness:=(r*r*r+@'400000) div @'1000000;
  1981.   end; {that was $r^3/2^{18}$, rounded to the nearest integer}
  1982. @ When \TeX\ ``packages'' a list into a box, it needs to calculate the
  1983. proportionality ratio by which the glue inside the box should stretch
  1984. or shrink. This calculation does not affect \TeX's decision making,
  1985. so the precise details of rounding, etc., in the glue calculation are not
  1986. of critical importance for the consistency of results on different computers.
  1987. We shall use the type |glue_ratio| for such proportionality ratios.
  1988. A glue ratio should take the same amount of memory as an
  1989. |integer| (usually 32 bits) if it is to blend smoothly with \TeX's
  1990. other data structures. Thus |glue_ratio| should be equivalent to
  1991. |short_real| in some implementations of \PASCAL. Alternatively,
  1992. it is possible to deal with glue ratios using nothing but fixed-point
  1993. arithmetic; see {\sl TUGboat \bf3},1 (March 1982), 10--27. (But the
  1994. routines cited there must be modified to allow negative glue ratios.)
  1995. @^system dependencies@>
  1996. @d set_glue_ratio_zero(#) == #:=0.0 {store the representation of zero ratio}
  1997. @d set_glue_ratio_one(#) == #:=1.0 {store the representation of unit ratio}
  1998. @d float(#) == # {convert from |glue_ratio| to type |real|}
  1999. @d unfloat(#) == # {convert from |real| to type |glue_ratio|}
  2000. @d float_constant(#) == #.0 {convert |integer| constant to |real|}
  2001. @<Types...@>=
  2002. @!glue_ratio=real; {one-word representation of a glue expansion factor}
  2003. @* \[8] Packed data.
  2004. In order to make efficient use of storage space, \TeX\ bases its major data
  2005. structures on a |memory_word|, which contains either a (signed) integer,
  2006. possibly scaled, or a (signed) |glue_ratio|, or a small number of
  2007. fields that are one half or one quarter of the size used for storing
  2008. integers.
  2009. If |x| is a variable of type |memory_word|, it contains up to four
  2010. fields that can be referred to as follows:
  2011. $$\vbox{\halign{\hfil#&#\hfil&#\hfil\cr
  2012. |x|&.|int|&(an |integer|)\cr
  2013. |x|&.|sc|\qquad&(a |scaled| integer)\cr
  2014. |x|&.|gr|&(a |glue_ratio|)\cr
  2015. |x.hh.lh|, |x.hh|&.|rh|&(two halfword fields)\cr
  2016. |x.hh.b0|, |x.hh.b1|, |x.hh|&.|rh|&(two quarterword fields, one halfword
  2017.   field)\cr
  2018. |x.qqqq.b0|, |x.qqqq.b1|, |x.qqqq|&.|b2|, |x.qqqq.b3|\hskip-100pt
  2019.   &\qquad\qquad\qquad(four quarterword fields)\cr}}$$
  2020. This is somewhat cumbersome to write, and not very readable either, but
  2021. macros will be used to make the notation shorter and more transparent.
  2022. The \PASCAL\ code below gives a formal definition of |memory_word| and
  2023. its subsidiary types, using packed variant records. \TeX\ makes no
  2024. assumptions about the relative positions of the fields within a word.
  2025. Since we are assuming 32-bit integers, a halfword must contain at least
  2026. 16 bits, and a quarterword must contain at least 8 bits.
  2027. @^system dependencies@>
  2028. But it doesn't hurt to have more bits; for example, with enough 36-bit
  2029. words you might be able to have |mem_max| as large as 262142, which is
  2030. eight times as much memory as anybody had during the first four years of
  2031. \TeX's existence.
  2032. N.B.: Valuable memory space will be dreadfully wasted unless \TeX\ is compiled
  2033. by a \PASCAL\ that packs all of the |memory_word| variants into
  2034. the space of a single integer. This means, for example, that |glue_ratio|
  2035. words should be |short_real| instead of |real| on some computers. Some
  2036. \PASCAL\ compilers will pack an integer whose subrange is `|0..255|' into
  2037. an eight-bit field, but others insist on allocating space for an additional
  2038. sign bit; on such systems you can get 256 values into a quarterword only
  2039. if the subrange is `|-128..127|'.
  2040. The present implementation tries to accommodate as many variations as possible,
  2041. so it makes few assumptions. If integers having the subrange
  2042. `|min_quarterword..max_quarterword|' can be packed into a quarterword,
  2043. and if integers having the subrange `|min_halfword..max_halfword|'
  2044. can be packed into a halfword, everything should work satisfactorily.
  2045. It is usually most efficient to have |min_quarterword=min_halfword=0|,
  2046. so one should try to achieve this unless it causes a severe problem.
  2047. The values defined here are recommended for most 32-bit computers.
  2048. @d min_quarterword=0 {smallest allowable value in a |quarterword|}
  2049. @d max_quarterword=255 {largest allowable value in a |quarterword|}
  2050. @d min_halfword==0 {smallest allowable value in a |halfword|}
  2051. @d max_halfword==65535 {largest allowable value in a |halfword|}
  2052. @ Here are the inequalities that the quarterword and halfword values
  2053. must satisfy (or rather, the inequalities that they mustn't satisfy):
  2054. @<Check the ``constant''...@>=
  2055. init if (mem_min<>mem_bot)or(mem_max<>mem_top) then bad:=10;@+tini@;@/
  2056. if (mem_min>mem_bot)or(mem_max<mem_top) then bad:=10;
  2057. if (min_quarterword>0)or(max_quarterword<127) then bad:=11;
  2058. if (min_halfword>0)or(max_halfword<32767) then bad:=12;
  2059. if (min_quarterword<min_halfword)or@|
  2060.   (max_quarterword>max_halfword) then bad:=13;
  2061. if (mem_min<min_halfword)or(mem_max>=max_halfword)or@|
  2062.   (mem_bot-mem_min>max_halfword+1) then bad:=14;
  2063. if (font_base<min_quarterword)or(font_max>max_quarterword) then bad:=15;
  2064. if font_max>font_base+256 then bad:=16;
  2065. if (save_size>max_halfword)or(max_strings>max_halfword) then bad:=17;
  2066. if buf_size>max_halfword then bad:=18;
  2067. if max_quarterword-min_quarterword<255 then bad:=19;
  2068. @ The operation of adding or subtracting |min_quarterword| occurs quite
  2069. frequently in \TeX, so it is convenient to abbreviate this operation
  2070. by using the macros |qi| and |qo| for input and output to and from
  2071. quarterword format.
  2072. The inner loop of \TeX\ will run faster with respect to compilers
  2073. that don't optimize expressions like `|x+0|' and `|x-0|', if these
  2074. macros are simplified in the obvious way when |min_quarterword=0|.
  2075. @^inner loop@>@^system dependencies@>
  2076. @d qi(#)==#+min_quarterword
  2077.   {to put an |eight_bits| item into a quarterword}
  2078. @d qo(#)==#-min_quarterword
  2079.   {to take an |eight_bits| item out of a quarterword}
  2080. @d hi(#)==#+min_halfword
  2081.   {to put a sixteen-bit item into a halfword}
  2082. @d ho(#)==#-min_halfword
  2083.   {to take a sixteen-bit item from a halfword}
  2084. @ The reader should study the following definitions closely:
  2085. @^system dependencies@>
  2086. @d sc==int {|scaled| data is equivalent to |integer|}
  2087. @<Types...@>=
  2088. @!quarterword = min_quarterword..max_quarterword; {1/4 of a word}
  2089. @!halfword=min_halfword..max_halfword; {1/2 of a word}
  2090. @!two_choices = 1..2; {used when there are two variants in a record}
  2091. @!four_choices = 1..4; {used when there are four variants in a record}
  2092. @!two_halves = packed record@;@/
  2093.   @!rh:halfword;
  2094.   case two_choices of
  2095.   1: (@!lh:halfword);
  2096.   2: (@!b0:quarterword; @!b1:quarterword);
  2097.   end;
  2098. @!four_quarters = packed record@;@/
  2099.   @!b0:quarterword;
  2100.   @!b1:quarterword;
  2101.   @!b2:quarterword;
  2102.   @!b3:quarterword;
  2103.   end;
  2104. @!memory_word = record@;@/
  2105.   case four_choices of
  2106.   1: (@!int:integer);
  2107.   2: (@!gr:glue_ratio);
  2108.   3: (@!hh:two_halves);
  2109.   4: (@!qqqq:four_quarters);
  2110.   end;
  2111. @!word_file = file of memory_word;
  2112. @ When debugging, we may want to print a |memory_word| without knowing
  2113. what type it is; so we print it in all modes.
  2114. @^dirty \PASCAL@>@^debugging@>
  2115. @p @!debug procedure print_word(@!w:memory_word);
  2116.   {prints |w| in all ways}
  2117. begin print_int(w.int); print_char(" ");@/
  2118. print_scaled(w.sc); print_char(" ");@/
  2119. print_scaled(round(unity*float(w.gr))); print_ln;@/
  2120. @^real multiplication@>
  2121. print_int(w.hh.lh); print_char("="); print_int(w.hh.b0); print_char(":");
  2122. print_int(w.hh.b1); print_char(";"); print_int(w.hh.rh); print_char(" ");@/
  2123. print_int(w.qqqq.b0); print_char(":"); print_int(w.qqqq.b1); print_char(":");
  2124. print_int(w.qqqq.b2); print_char(":"); print_int(w.qqqq.b3);
  2125. gubed
  2126. @* \[9] Dynamic memory allocation.
  2127. The \TeX\ system does nearly all of its own memory allocation, so that it
  2128. can readily be transported into environments that do not have automatic
  2129. facilities for strings, garbage collection, etc., and so that it can be in
  2130. control of what error messages the user receives. The dynamic storage
  2131. requirements of \TeX\ are handled by providing a large array |mem| in
  2132. which consecutive blocks of words are used as nodes by the \TeX\ routines.
  2133. Pointer variables are indices into this array, or into another array
  2134. called |eqtb| that will be explained later. A pointer variable might
  2135. also be a special flag that lies outside the bounds of |mem|, so we
  2136. allow pointers to assume any |halfword| value. The minimum halfword
  2137. value represents a null pointer. \TeX\ does not assume that |mem[null]| exists.
  2138. @d pointer==halfword {a flag or a location in |mem| or |eqtb|}
  2139. @d null==min_halfword {the null pointer}
  2140. @<Glob...@>=
  2141. @!temp_ptr:pointer; {a pointer variable for occasional emergency use}
  2142. @ The |mem| array is divided into two regions that are allocated separately,
  2143. but the dividing line between these two regions is not fixed; they grow
  2144. together until finding their ``natural'' size in a particular job.
  2145. Locations less than or equal to |lo_mem_max| are used for storing
  2146. variable-length records consisting of two or more words each. This region
  2147. is maintained using an algorithm similar to the one described in exercise
  2148. 2.5--19 of {\sl The Art of Computer Programming}. However, no size field
  2149. appears in the allocated nodes; the program is responsible for knowing the
  2150. relevant size when a node is freed. Locations greater than or equal to
  2151. |hi_mem_min| are used for storing one-word records; a conventional
  2152. \.{AVAIL} stack is used for allocation in this region.
  2153. Locations of |mem| between |mem_bot| and |mem_top| may be dumped as part
  2154. of preloaded format files, by the \.{INITEX} preprocessor.
  2155. @.INITEX@>
  2156. Production versions of \TeX\ may extend the memory at both ends in order to
  2157. provide more space; locations between |mem_min| and |mem_bot| are always
  2158. used for variable-size nodes, and locations between |mem_top| and |mem_max|
  2159. are always used for single-word nodes.
  2160. The key pointers that govern |mem| allocation have a prescribed order:
  2161. $$\advance\thickmuskip-2mu
  2162. \hbox{|null<=mem_min<=mem_bot<lo_mem_max<
  2163.   hi_mem_min<mem_top<=mem_end<=mem_max|.}$$
  2164. Empirical tests show that the present implementation of \TeX\ tends to
  2165. spend about 9\pct! of its running time allocating nodes, and about 6\pct!
  2166. deallocating them after their use.
  2167. @<Glob...@>=
  2168. @!mem : array[mem_min..mem_max] of memory_word; {the big dynamic storage area}
  2169. @!lo_mem_max : pointer; {the largest location of variable-size memory in use}
  2170. @!hi_mem_min : pointer; {the smallest location of one-word memory in use}
  2171. @ In order to study the memory requirements of particular applications, it
  2172. is possible to prepare a version of \TeX\ that keeps track of current and
  2173. maximum memory usage. When code between the delimiters |@!stat| $\ldots$
  2174. |tats| is not ``commented out,'' \TeX\ will run a bit slower but it will
  2175. report these statistics when |tracing_stats| is sufficiently large.
  2176. @<Glob...@>=
  2177. @!var_used, @!dyn_used : integer; {how much memory is in use}
  2178. @ Let's consider the one-word memory region first, since it's the
  2179. simplest. The pointer variable |mem_end| holds the highest-numbered location
  2180. of |mem| that has ever been used. The free locations of |mem| that
  2181. occur between |hi_mem_min| and |mem_end|, inclusive, are of type
  2182. |two_halves|, and we write |info(p)| and |link(p)| for the |lh|
  2183. and |rh| fields of |mem[p]| when it is of this type. The single-word
  2184. free locations form a linked list
  2185. $$|avail|,\;\hbox{|link(avail)|},\;\hbox{|link(link(avail))|},\;\ldots$$
  2186. terminated by |null|.
  2187. @d link(#) == mem[#].hh.rh {the |link| field of a memory word}
  2188. @d info(#) == mem[#].hh.lh {the |info| field of a memory word}
  2189. @<Glob...@>=
  2190. @!avail : pointer; {head of the list of available one-word nodes}
  2191. @!mem_end : pointer; {the last one-word node used in |mem|}
  2192. @ If memory is exhausted, it might mean that the user has forgotten
  2193. a right brace. We will define some procedures later that try to help
  2194. pinpoint the trouble.
  2195. @p @<Declare the procedure called |show_token_list|@>@/
  2196. @<Declare the procedure called |runaway|@>
  2197. @ The function |get_avail| returns a pointer to a new one-word node whose
  2198. |link| field is null. However, \TeX\ will halt if there is no more room left.
  2199. @^inner loop@>
  2200. If the available-space list is empty, i.e., if |avail=null|,
  2201. we try first to increase |mem_end|. If that cannot be done, i.e., if
  2202. |mem_end=mem_max|, we try to decrease |hi_mem_min|. If that cannot be
  2203. done, i.e., if |hi_mem_min=lo_mem_max+1|, we have to quit.
  2204. @p function get_avail : pointer; {single-word node allocation}
  2205. var p:pointer; {the new node being got}
  2206. begin p:=avail; {get top location in the |avail| stack}
  2207. if p<>null then avail:=link(avail) {and pop it off}
  2208. else if mem_end<mem_max then {or go into virgin territory}
  2209.   begin incr(mem_end); p:=mem_end;
  2210.   end
  2211. else   begin decr(hi_mem_min); p:=hi_mem_min;
  2212.   if hi_mem_min<=lo_mem_max then
  2213.     begin runaway; {if memory is exhausted, display possible runaway text}
  2214.     overflow("main memory size",mem_max+1-mem_min);
  2215.       {quit; all one-word nodes are busy}
  2216. @:TeX capacity exceeded main memory size}{\quad main memory size@>
  2217.     end;
  2218.   end;
  2219. link(p):=null; {provide an oft-desired initialization of the new node}
  2220. @!stat incr(dyn_used);@+tats@;{maintain statistics}
  2221. get_avail:=p;
  2222. @ Conversely, a one-word node is recycled by calling |free_avail|.
  2223. This routine is part of \TeX's ``inner loop,'' so we want it to be fast.
  2224. @^inner loop@>
  2225. @d free_avail(#)== {single-word node liberation}
  2226.   begin link(#):=avail; avail:=#;
  2227.   @!stat decr(dyn_used);@+tats@/
  2228.   end
  2229. @ There's also a |fast_get_avail| routine, which saves the procedure-call
  2230. overhead at the expense of extra programming. This routine is used in
  2231. the places that would otherwise account for the most calls of |get_avail|.
  2232. @^inner loop@>
  2233. @d fast_get_avail(#)==@t@>@;@/
  2234.   begin #:=avail; {avoid |get_avail| if possible, to save time}
  2235.   if #=null then #:=get_avail
  2236.   else  begin avail:=link(#); link(#):=null;
  2237.     @!stat incr(dyn_used);@+tats@/
  2238.     end;
  2239.   end
  2240. @ The procedure |flush_list(p)| frees an entire linked list of
  2241. one-word nodes that starts at position |p|.
  2242. @^inner loop@>
  2243. @p procedure flush_list(@!p:pointer); {makes list of single-word nodes
  2244.   available}
  2245. var @!q,@!r:pointer; {list traversers}
  2246. begin if p<>null then
  2247.   begin r:=p;
  2248.   repeat q:=r; r:=link(r); @!stat decr(dyn_used);@+tats@/
  2249.   until r=null; {now |q| is the last node on the list}
  2250.   link(q):=avail; avail:=p;
  2251.   end;
  2252. @ The available-space list that keeps track of the variable-size portion
  2253. of |mem| is a nonempty, doubly-linked circular list of empty nodes,
  2254. pointed to by the roving pointer |rover|.
  2255. Each empty node has size 2 or more; the first word contains the special
  2256. value |max_halfword| in its |link| field and the size in its |info| field;
  2257. the second word contains the two pointers for double linking.
  2258. Each nonempty node also has size 2 or more. Its first word is of type
  2259. |two_halves|\kern-1pt, and its |link| field is never equal to |max_halfword|.
  2260. Otherwise there is complete flexibility with respect to the contents
  2261. of its other fields and its other words.
  2262. (We require |mem_max<max_halfword| because terrible things can happen
  2263. when |max_halfword| appears in the |link| field of a nonempty node.)
  2264. @d empty_flag == max_halfword {the |link| of an empty variable-size node}
  2265. @d is_empty(#) == (link(#)=empty_flag) {tests for empty node}
  2266. @d node_size == info {the size field in empty variable-size nodes}
  2267. @d llink(#) == info(#+1) {left link in doubly-linked list of empty nodes}
  2268. @d rlink(#) == link(#+1) {right link in doubly-linked list of empty nodes}
  2269. @<Glob...@>=
  2270. @!rover : pointer; {points to some node in the list of empties}
  2271. @ A call to |get_node| with argument |s| returns a pointer to a new node
  2272. of size~|s|, which must be 2~or more. The |link| field of the first word
  2273. of this new node is set to null. An overflow stop occurs if no suitable
  2274. space exists.
  2275. If |get_node| is called with $s=2^{30}$, it simply merges adjacent free
  2276. areas and returns the value |max_halfword|.
  2277. @p function get_node(@!s:integer):pointer; {variable-size node allocation}
  2278. label found,exit,restart;
  2279. var p:pointer; {the node currently under inspection}
  2280. @!q:pointer; {the node physically after node |p|}
  2281. @!r:integer; {the newly allocated node, or a candidate for this honor}
  2282. @!t:integer; {temporary register}
  2283. begin restart: p:=rover; {start at some free node in the ring}
  2284. repeat @<Try to allocate within node |p| and its physical successors,
  2285.   and |goto found| if allocation was possible@>;
  2286. @^inner loop@>
  2287. p:=rlink(p); {move to the next node in the ring}
  2288. until p=rover; {repeat until the whole list has been traversed}
  2289. if s=@'10000000000 then
  2290.   begin get_node:=max_halfword; return;
  2291.   end;
  2292. if lo_mem_max+2<hi_mem_min then if lo_mem_max+2<=mem_bot+max_halfword then
  2293.   @<Grow more variable-size memory and |goto restart|@>;
  2294. overflow("main memory size",mem_max+1-mem_min);
  2295.   {sorry, nothing satisfactory is left}
  2296. @:TeX capacity exceeded main memory size}{\quad main memory size@>
  2297. found: link(r):=null; {this node is now nonempty}
  2298. @!stat var_used:=var_used+s; {maintain usage statistics}
  2299. tats@;@/
  2300. get_node:=r;
  2301. exit:end;
  2302. @ The lower part of |mem| grows by 1000 words at a time, unless
  2303. we are very close to going under. When it grows, we simply link
  2304. a new node into the available-space list. This method of controlled
  2305. growth helps to keep the |mem| usage consecutive when \TeX\ is
  2306. implemented on ``virtual memory'' systems.
  2307. @^virtual memory@>
  2308. @<Grow more variable-size memory and |goto restart|@>=
  2309. begin if hi_mem_min-lo_mem_max>=1998 then t:=lo_mem_max+1000
  2310. else t:=lo_mem_max+1+(hi_mem_min-lo_mem_max) div 2;
  2311.   {|lo_mem_max+2<=t<hi_mem_min|}
  2312. p:=llink(rover); q:=lo_mem_max; rlink(p):=q; llink(rover):=q;@/
  2313. if t>mem_bot+max_halfword then t:=mem_bot+max_halfword;
  2314. rlink(q):=rover; llink(q):=p; link(q):=empty_flag; node_size(q):=t-lo_mem_max;@/
  2315. lo_mem_max:=t; link(lo_mem_max):=null; info(lo_mem_max):=null;
  2316. rover:=q; goto restart;
  2317. @ Empirical tests show that the routine in this section performs a
  2318. node-merging operation about 0.75 times per allocation, on the average,
  2319. after which it finds that |r>p+1| about 95\pct! of the time.
  2320. @<Try to allocate...@>=
  2321. q:=p+node_size(p); {find the physical successor}
  2322. @^inner loop@>
  2323. while is_empty(q) do {merge node |p| with node |q|}
  2324.   begin t:=rlink(q);
  2325.   if q=rover then rover:=t;
  2326.   llink(t):=llink(q); rlink(llink(q)):=t;@/
  2327.   q:=q+node_size(q);
  2328.   end;
  2329. r:=q-s;
  2330. if r>p+1 then @<Allocate from the top of node |p| and |goto found|@>;
  2331. if r=p then if rlink(p)<>p then
  2332.   @<Allocate entire node |p| and |goto found|@>;
  2333. node_size(p):=q-p {reset the size in case it grew}
  2334. @ @<Allocate from the top...@>=
  2335. begin node_size(p):=r-p; {store the remaining size}
  2336. @^inner loop@>
  2337. rover:=p; {start searching here next time}
  2338. goto found;
  2339. @ Here we delete node |p| from the ring, and let |rover| rove around.
  2340. @<Allocate entire...@>=
  2341. begin rover:=rlink(p); t:=llink(p);
  2342. llink(rover):=t; rlink(t):=rover;
  2343. goto found;
  2344. @ Conversely, when some variable-size node |p| of size |s| is no longer needed,
  2345. the operation |free_node(p,s)| will make its words available, by inserting
  2346. |p| as a new empty node just before where |rover| now points.
  2347. @^inner loop@>
  2348. @p procedure free_node(@!p:pointer; @!s:halfword); {variable-size node
  2349.   liberation}
  2350. var q:pointer; {|llink(rover)|}
  2351. begin node_size(p):=s; link(p):=empty_flag;
  2352. q:=llink(rover); llink(p):=q; rlink(p):=rover; {set both links}
  2353. llink(rover):=p; rlink(q):=p; {insert |p| into the ring}
  2354. @!stat var_used:=var_used-s;@+tats@;{maintain statistics}
  2355. @ Just before \.{INITEX} writes out the memory, it sorts the doubly linked
  2356. available space list. The list is probably very short at such times, so a
  2357. simple insertion sort is used. The smallest available location will be
  2358. pointed to by |rover|, the next-smallest by |rlink(rover)|, etc.
  2359. @p @!init procedure sort_avail; {sorts the available variable-size nodes
  2360.   by location}
  2361. var p,@!q,@!r: pointer; {indices into |mem|}
  2362. @!old_rover:pointer; {initial |rover| setting}
  2363. begin p:=get_node(@'10000000000); {merge adjacent free areas}
  2364. p:=rlink(rover); rlink(rover):=max_halfword; old_rover:=rover;
  2365. while p<>old_rover do @<Sort \(p)|p| into the list starting at |rover|
  2366.   and advance |p| to |rlink(p)|@>;
  2367. p:=rover;
  2368. while rlink(p)<>max_halfword do
  2369.   begin llink(rlink(p)):=p; p:=rlink(p);
  2370.   end;
  2371. rlink(p):=rover; llink(rover):=p;
  2372. @ The following |while| loop is guaranteed to
  2373. terminate, since the list that starts at
  2374. |rover| ends with |max_halfword| during the sorting procedure.
  2375. @<Sort \(p)|p|...@>=
  2376. if p<rover then
  2377.   begin q:=p; p:=rlink(q); rlink(q):=rover; rover:=q;
  2378.   end
  2379. else  begin q:=rover;
  2380.   while rlink(q)<p do q:=rlink(q);
  2381.   r:=rlink(p); rlink(p):=rlink(q); rlink(q):=p; p:=r;
  2382.   end
  2383. @* \[10] Data structures for boxes and their friends.
  2384. From the computer's standpoint, \TeX's chief mission is to create
  2385. horizontal and vertical lists. We shall now investigate how the elements
  2386. of these lists are represented internally as nodes in the dynamic memory.
  2387. A horizontal or vertical list is linked together by |link| fields in
  2388. the first word of each node. Individual nodes represent boxes, glue,
  2389. penalties, or special things like discretionary hyphens; because of this
  2390. variety, some nodes are longer than others, and we must distinguish different
  2391. kinds of nodes. We do this by putting a `|type|' field in the first word,
  2392. together with the link and an optional `|subtype|'.
  2393. @d type(#) == mem[#].hh.b0 {identifies what kind of node this is}
  2394. @d subtype(#) == mem[#].hh.b1 {secondary identification in some cases}
  2395. @ A |@!char_node|, which represents a single character, is the most important
  2396. kind of node because it accounts for the vast majority of all boxes.
  2397. Special precautions are therefore taken to ensure that a |char_node| does
  2398. not take up much memory space. Every such node is one word long, and in fact
  2399. it is identifiable by this property, since other kinds of nodes have at least
  2400. two words, and they appear in |mem| locations less than |hi_mem_min|.
  2401. This makes it possible to omit the |type| field in a |char_node|, leaving
  2402. us room for two bytes that identify a |font| and a |character| within
  2403. that font.
  2404. Note that the format of a |char_node| allows for up to 256 different
  2405. fonts and up to 256 characters per font; but most implementations will
  2406. probably limit the total number of fonts to fewer than 75 per job,
  2407. and most fonts will stick to characters whose codes are
  2408. less than 128 (since higher codes
  2409. are more difficult to access on most keyboards).
  2410. Extensions of \TeX\ intended for oriental languages will need even more
  2411. than $256\times256$ possible characters, when we consider different sizes
  2412. @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
  2413. and styles of type.  It is suggested that Chinese and Japanese fonts be
  2414. handled by representing such characters in two consecutive |char_node|
  2415. entries: The first of these has |font=font_base|, and its |link| points
  2416. to the second;
  2417. the second identifies the font and the character dimensions.
  2418. The saving feature about oriental characters is that most of them have
  2419. the same box dimensions. The |character| field of the first |char_node|
  2420. is a ``\\{charext}'' that distinguishes between graphic symbols whose
  2421. dimensions are identical for typesetting purposes. (See the \MF\ manual.)
  2422. Such an extension of \TeX\ would not be difficult; further details are
  2423. left to the reader.
  2424. In order to make sure that the |character| code fits in a quarterword,
  2425. \TeX\ adds the quantity |min_quarterword| to the actual code.
  2426. Character nodes appear only in horizontal lists, never in vertical lists.
  2427. @d is_char_node(#) == (#>=hi_mem_min)
  2428.   {does the argument point to a |char_node|?}
  2429. @d font == type {the font code in a |char_node|}
  2430. @d character == subtype {the character code in a |char_node|}
  2431. @ An |hlist_node| stands for a box that was made from a horizontal list.
  2432. Each |hlist_node| is seven words long, and contains the following fields
  2433. (in addition to the mandatory |type| and |link|, which we shall not
  2434. mention explicitly when discussing the other node types): The |height| and
  2435. |width| and |depth| are scaled integers denoting the dimensions of the
  2436. box.  There is also a |shift_amount| field, a scaled integer indicating
  2437. how much this box should be lowered (if it appears in a horizontal list),
  2438. or how much it should be moved to the right (if it appears in a vertical
  2439. list). There is a |list_ptr| field, which points to the beginning of the
  2440. list from which this box was fabricated; if |list_ptr| is |null|, the box
  2441. is empty. Finally, there are three fields that represent the setting of
  2442. the glue:  |glue_set(p)| is a word of type |glue_ratio| that represents
  2443. the proportionality constant for glue setting; |glue_sign(p)| is
  2444. |stretching| or |shrinking| or |normal| depending on whether or not the
  2445. glue should stretch or shrink or remain rigid; and |glue_order(p)|
  2446. specifies the order of infinity to which glue setting applies (|normal|,
  2447. |fil|, |fill|, or |filll|). The |subtype| field is not used.
  2448. @d hlist_node=0 {|type| of hlist nodes}
  2449. @d box_node_size=7 {number of words to allocate for a box node}
  2450. @d width_offset=1 {position of |width| field in a box node}
  2451. @d depth_offset=2 {position of |depth| field in a box node}
  2452. @d height_offset=3 {position of |height| field in a box node}
  2453. @d width(#) == mem[#+width_offset].sc {width of the box, in sp}
  2454. @d depth(#) == mem[#+depth_offset].sc {depth of the box, in sp}
  2455. @d height(#) == mem[#+height_offset].sc {height of the box, in sp}
  2456. @d shift_amount(#) == mem[#+4].sc {repositioning distance, in sp}
  2457. @d list_offset=5 {position of |list_ptr| field in a box node}
  2458. @d list_ptr(#) == link(#+list_offset) {beginning of the list inside the box}
  2459. @d glue_order(#) == subtype(#+list_offset) {applicable order of infinity}
  2460. @d glue_sign(#) == type(#+list_offset) {stretching or shrinking}
  2461. @d normal=0 {the most common case when several cases are named}
  2462. @d stretching = 1 {glue setting applies to the stretch components}
  2463. @d shrinking = 2 {glue setting applies to the shrink components}
  2464. @d glue_offset = 6 {position of |glue_set| in a box node}
  2465. @d glue_set(#) == mem[#+glue_offset].gr
  2466.   {a word of type |glue_ratio| for glue setting}
  2467. @ The |new_null_box| function returns a pointer to an |hlist_node| in
  2468. which all subfields have the values corresponding to `\.{\\hbox\{\}}'.
  2469. The |subtype| field is set to |min_quarterword|, since that's the desired
  2470. |span_count| value if this |hlist_node| is changed to an |unset_node|.
  2471. @p function new_null_box:pointer; {creates a new box node}
  2472. var p:pointer; {the new node}
  2473. begin p:=get_node(box_node_size); type(p):=hlist_node;
  2474. subtype(p):=min_quarterword;
  2475. width(p):=0; depth(p):=0; height(p):=0; shift_amount(p):=0; list_ptr(p):=null;
  2476. glue_sign(p):=normal; glue_order(p):=normal; set_glue_ratio_zero(glue_set(p));
  2477. new_null_box:=p;
  2478. @ A |vlist_node| is like an |hlist_node| in all respects except that it
  2479. contains a vertical list.
  2480. @d vlist_node=1 {|type| of vlist nodes}
  2481. @ A |rule_node| stands for a solid black rectangle; it has |width|,
  2482. |depth|, and |height| fields just as in an |hlist_node|. However, if
  2483. any of these dimensions is $-2^{30}$, the actual value will be determined
  2484. by running the rule up to the boundary of the innermost enclosing box.
  2485. This is called a ``running dimension.'' The |width| is never running in
  2486. an hlist; the |height| and |depth| are never running in a~vlist.
  2487. @d rule_node=2 {|type| of rule nodes}
  2488. @d rule_node_size=4 {number of words to allocate for a rule node}
  2489. @d null_flag==-@'10000000000 {$-2^{30}$, signifies a missing item}
  2490. @d is_running(#) == (#=null_flag) {tests for a running dimension}
  2491. @ A new rule node is delivered by the |new_rule| function. It
  2492. makes all the dimensions ``running,'' so you have to change the
  2493. ones that are not allowed to run.
  2494. @p function new_rule:pointer;
  2495. var p:pointer; {the new node}
  2496. begin p:=get_node(rule_node_size); type(p):=rule_node;
  2497. subtype(p):=0; {the |subtype| is not used}
  2498. width(p):=null_flag; depth(p):=null_flag; height(p):=null_flag;
  2499. new_rule:=p;
  2500. @ Insertions are represented by |ins_node| records, where the |subtype|
  2501. indicates the corresponding box number. For example, `\.{\\insert 250}'
  2502. leads to an |ins_node| whose |subtype| is |250+min_quarterword|.
  2503. The |height| field of an |ins_node| is slightly misnamed; it actually holds
  2504. the natural height plus depth of the vertical list being inserted.
  2505. The |depth| field holds the |split_max_depth| to be used in case this
  2506. insertion is split, and the |split_top_ptr| points to the corresponding
  2507. |split_top_skip|. The |float_cost| field holds the |floating_penalty| that
  2508. will be used if this insertion floats to a subsequent page after a
  2509. split insertion of the same class.  There is one more field, the
  2510. |ins_ptr|, which points to the beginning of the vlist for the insertion.
  2511. @d ins_node=3 {|type| of insertion nodes}
  2512. @d ins_node_size=5 {number of words to allocate for an insertion}
  2513. @d float_cost(#)==mem[#+1].int {the |floating_penalty| to be used}
  2514. @d ins_ptr(#)==info(#+4) {the vertical list to be inserted}
  2515. @d split_top_ptr(#)==link(#+4) {the |split_top_skip| to be used}
  2516. @ A |mark_node| has a |mark_ptr| field that points to the reference count
  2517. of a token list that contains the user's \.{\\mark} text.
  2518. This field occupies a full word instead of a halfword, because
  2519. there's nothing to put in the other halfword; it is easier in \PASCAL\ to
  2520. use the full word than to risk leaving garbage in the unused half.
  2521. @d mark_node=4 {|type| of a mark node}
  2522. @d small_node_size=2 {number of words to allocate for most node types}
  2523. @d mark_ptr(#)==mem[#+1].int {head of the token list for a mark}
  2524. @ An |adjust_node|, which occurs only in horizontal lists,
  2525. specifies material that will be moved out into the surrounding
  2526. vertical list; i.e., it is used to implement \TeX's `\.{\\vadjust}'
  2527. operation.  The |adjust_ptr| field points to the vlist containing this
  2528. material.
  2529. @d adjust_node=5 {|type| of an adjust node}
  2530. @d adjust_ptr==mark_ptr {vertical list to be moved out of horizontal list}
  2531. @ A |ligature_node|, which occurs only in horizontal lists, specifies
  2532. a character that was fabricated from the interaction of two or more
  2533. actual characters.  The second word of the node, which is called the
  2534. |lig_char| word, contains |font| and |character| fields just as in a
  2535. |char_node|. The characters that generated the ligature have not been
  2536. forgotten, since they are needed for diagnostic messages and for
  2537. hyphenation; the |lig_ptr| field points to a linked list of character
  2538. nodes for all original characters that have been deleted. (This list
  2539. might be empty if the characters that generated the ligature were
  2540. retained in other nodes.)
  2541. The |subtype| field is 0, plus 2 and/or 1 if the original source of the
  2542. ligature included implicit left and/or right boundaries.
  2543. @d ligature_node=6 {|type| of a ligature node}
  2544. @d lig_char(#)==#+1 {the word where the ligature is to be found}
  2545. @d lig_ptr(#)==link(lig_char(#)) {the list of characters}
  2546. @ The |new_ligature| function creates a ligature node having given
  2547. contents of the |font|, |character|, and |lig_ptr| fields. We also have
  2548. a |new_lig_item| function, which returns a two-word node having a given
  2549. |character| field. Such nodes are used for temporary processing as ligatures
  2550. are being created.
  2551. @p function new_ligature(@!f,@!c:quarterword; @!q:pointer):pointer;
  2552. var p:pointer; {the new node}
  2553. begin p:=get_node(small_node_size); type(p):=ligature_node;
  2554. font(lig_char(p)):=f; character(lig_char(p)):=c; lig_ptr(p):=q;
  2555. subtype(p):=0; new_ligature:=p;
  2556. function new_lig_item(@!c:quarterword):pointer;
  2557. var p:pointer; {the new node}
  2558. begin p:=get_node(small_node_size); character(p):=c; lig_ptr(p):=null;
  2559. new_lig_item:=p;
  2560. @ A |disc_node|, which occurs only in horizontal lists, specifies a
  2561. ``dis\-cretion\-ary'' line break. If such a break occurs at node |p|, the text
  2562. that starts at |pre_break(p)| will precede the break, the text that starts at
  2563. |post_break(p)| will follow the break, and text that appears in the next
  2564. |replace_count(p)| nodes will be ignored. For example, an ordinary
  2565. discretionary hyphen, indicated by `\.{\\-}', yields a |disc_node| with
  2566. |pre_break| pointing to a |char_node| containing a hyphen, |post_break=null|,
  2567. and |replace_count=0|. All three of the discretionary texts must be
  2568. lists that consist entirely of character, kern, box, rule, and ligature nodes.
  2569. If |pre_break(p)=null|, the |ex_hyphen_penalty| will be charged for this
  2570. break.  Otherwise the |hyphen_penalty| will be charged.  The texts will
  2571. actually be substituted into the list by the line-breaking algorithm if it
  2572. decides to make the break, and the discretionary node will disappear at
  2573. that time; thus, the output routine sees only discretionaries that were
  2574. not chosen.
  2575. @d disc_node=7 {|type| of a discretionary node}
  2576. @d replace_count==subtype {how many subsequent nodes to replace}
  2577. @d pre_break==llink {text that precedes a discretionary break}
  2578. @d post_break==rlink {text that follows a discretionary break}
  2579. @p function new_disc:pointer; {creates an empty |disc_node|}
  2580. var p:pointer; {the new node}
  2581. begin p:=get_node(small_node_size); type(p):=disc_node;
  2582. replace_count(p):=0; pre_break(p):=null; post_break(p):=null;
  2583. new_disc:=p;
  2584. @ A |whatsit_node| is a wild card reserved for extensions to \TeX. The
  2585. |subtype| field in its first word says what `\\{whatsit}' it is, and
  2586. implicitly determines the node size (which must be 2 or more) and the
  2587. format of the remaining words. When a |whatsit_node| is encountered
  2588. in a list, special actions are invoked; knowledgeable people who are
  2589. careful not to mess up the rest of \TeX\ are able to make \TeX\ do new
  2590. things by adding code at the end of the program. For example, there
  2591. might be a `\TeX nicolor' extension to specify different colors of ink,
  2592. @^extensions to \TeX@>
  2593. and the whatsit node might contain the desired parameters.
  2594. The present implementation of \TeX\ treats the features associated with
  2595. `\.{\\write}' and `\.{\\special}' as if they were extensions, in order to
  2596. illustrate how such routines might be coded. We shall defer further
  2597. discussion of extensions until the end of this program.
  2598. @d whatsit_node=8 {|type| of special extension nodes}
  2599. @ A |math_node|, which occurs only in horizontal lists, appears before and
  2600. after mathematical formulas. The |subtype| field is |before| before the
  2601. formula and |after| after it. There is a |width| field, which represents
  2602. the amount of surrounding space inserted by \.{\\mathsurround}.
  2603. @d math_node=9 {|type| of a math node}
  2604. @d before=0 {|subtype| for math node that introduces a formula}
  2605. @d after=1 {|subtype| for math node that winds up a formula}
  2606. @p function new_math(@!w:scaled;@!s:small_number):pointer;
  2607. var p:pointer; {the new node}
  2608. begin p:=get_node(small_node_size); type(p):=math_node;
  2609. subtype(p):=s; width(p):=w; new_math:=p;
  2610. @ \TeX\ makes use of the fact that |hlist_node|, |vlist_node|,
  2611. |rule_node|, |ins_node|, |mark_node|, |adjust_node|, |ligature_node|,
  2612. |disc_node|, |whatsit_node|, and |math_node| are at the low end of the
  2613. type codes, by permitting a break at glue in a list if and only if the
  2614. |type| of the previous node is less than |math_node|. Furthermore, a
  2615. node is discarded after a break if its type is |math_node| or~more.
  2616. @d precedes_break(#)==(type(#)<math_node)
  2617. @d non_discardable(#)==(type(#)<math_node)
  2618. @ A |glue_node| represents glue in a list. However, it is really only
  2619. a pointer to a separate glue specification, since \TeX\ makes use of the
  2620. fact that many essentially identical nodes of glue are usually present.
  2621. If |p| points to a |glue_node|, |glue_ptr(p)| points to
  2622. another packet of words that specify the stretch and shrink components, etc.
  2623. Glue nodes also serve to represent leaders; the |subtype| is used to
  2624. distinguish between ordinary glue (which is called |normal|) and the three
  2625. kinds of leaders (which are called |a_leaders|, |c_leaders|, and |x_leaders|).
  2626. The |leader_ptr| field points to a rule node or to a box node containing the
  2627. leaders; it is set to |null| in ordinary glue nodes.
  2628. Many kinds of glue are computed from \TeX's ``skip'' parameters, and
  2629. it is helpful to know which parameter has led to a particular glue node.
  2630. Therefore the |subtype| is set to indicate the source of glue, whenever
  2631. it originated as a parameter. We will be defining symbolic names for the
  2632. parameter numbers later (e.g., |line_skip_code=0|, |baseline_skip_code=1|,
  2633. etc.); it suffices for now to say that the |subtype| of parametric glue
  2634. will be the same as the parameter number, plus~one.
  2635. In math formulas there are two more possibilities for the |subtype| in a
  2636. glue node: |mu_glue| denotes an \.{\\mskip} (where the units are scaled \.{mu}
  2637. instead of scaled \.{pt}); and |cond_math_glue| denotes the `\.{\\nonscript}'
  2638. feature that cancels the glue node immediately following if it appears
  2639. in a subscript.
  2640. @d glue_node=10 {|type| of node that points to a glue specification}
  2641. @d cond_math_glue=98 {special |subtype| to suppress glue in the next node}
  2642. @d mu_glue=99 {|subtype| for math glue}
  2643. @d a_leaders=100 {|subtype| for aligned leaders}
  2644. @d c_leaders=101 {|subtype| for centered leaders}
  2645. @d x_leaders=102 {|subtype| for expanded leaders}
  2646. @d glue_ptr==llink {pointer to a glue specification}
  2647. @d leader_ptr==rlink {pointer to box or rule node for leaders}
  2648. @ A glue specification has a halfword reference count in its first word,
  2649. @^reference counts@>
  2650. representing |null| plus the number of glue nodes that point to it (less one).
  2651. Note that the reference count appears in the same position as
  2652. the |link| field in list nodes; this is the field that is initialized
  2653. to |null| when a node is allocated, and it is also the field that is flagged
  2654. by |empty_flag| in empty nodes.
  2655. Glue specifications also contain three |scaled| fields, for the |width|,
  2656. |stretch|, and |shrink| dimensions. Finally, there are two one-byte
  2657. fields called |stretch_order| and |shrink_order|; these contain the
  2658. orders of infinity (|normal|, |fil|, |fill|, or |filll|)
  2659. corresponding to the stretch and shrink values.
  2660. @d glue_spec_size=4 {number of words to allocate for a glue specification}
  2661. @d glue_ref_count(#) == link(#) {reference count of a glue specification}
  2662. @d stretch(#) == mem[#+2].sc {the stretchability of this glob of glue}
  2663. @d shrink(#) == mem[#+3].sc {the shrinkability of this glob of glue}
  2664. @d stretch_order == type {order of infinity for stretching}
  2665. @d shrink_order == subtype {order of infinity for shrinking}
  2666. @d fil=1 {first-order infinity}
  2667. @d fill=2 {second-order infinity}
  2668. @d filll=3 {third-order infinity}
  2669. @<Types...@>=
  2670. @!glue_ord=normal..filll; {infinity to the 0, 1, 2, or 3 power}
  2671. @ Here is a function that returns a pointer to a copy of a glue spec.
  2672. The reference count in the copy is |null|, because there is assumed
  2673. to be exactly one reference to the new specification.
  2674. @p function new_spec(@!p:pointer):pointer; {duplicates a glue specification}
  2675. var q:pointer; {the new spec}
  2676. begin q:=get_node(glue_spec_size);@/
  2677. mem[q]:=mem[p]; glue_ref_count(q):=null;@/
  2678. width(q):=width(p); stretch(q):=stretch(p); shrink(q):=shrink(p);
  2679. new_spec:=q;
  2680. @ And here's a function that creates a glue node for a given parameter
  2681. identified by its code number; for example,
  2682. |new_param_glue(line_skip_code)| returns a pointer to a glue node for the
  2683. current \.{\\lineskip}.
  2684. @p function new_param_glue(@!n:small_number):pointer;
  2685. var p:pointer; {the new node}
  2686. @!q:pointer; {the glue specification}
  2687. begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=n+1;
  2688. leader_ptr(p):=null;@/
  2689. q:=@<Current |mem| equivalent of glue parameter number |n|@>@t@>;
  2690. glue_ptr(p):=q; incr(glue_ref_count(q));
  2691. new_param_glue:=p;
  2692. @ Glue nodes that are more or less anonymous are created by |new_glue|,
  2693. whose argument points to a glue specification.
  2694. @p function new_glue(@!q:pointer):pointer;
  2695. var p:pointer; {the new node}
  2696. begin p:=get_node(small_node_size); type(p):=glue_node; subtype(p):=normal;
  2697. leader_ptr(p):=null; glue_ptr(p):=q; incr(glue_ref_count(q));
  2698. new_glue:=p;
  2699. @ Still another subroutine is needed: this one is sort of a combination
  2700. of |new_param_glue| and |new_glue|. It creates a glue node for one of
  2701. the current glue parameters, but it makes a fresh copy of the glue
  2702. specification, since that specification will probably be subject to change,
  2703. while the parameter will stay put. The global variable |temp_ptr| is
  2704. set to the address of the new spec.
  2705. @p function new_skip_param(@!n:small_number):pointer;
  2706. var p:pointer; {the new node}
  2707. begin temp_ptr:=new_spec(@<Current |mem| equivalent of glue parameter...@>);
  2708. p:=new_glue(temp_ptr); glue_ref_count(temp_ptr):=null; subtype(p):=n+1;
  2709. new_skip_param:=p;
  2710. @ A |kern_node| has a |width| field to specify a (normally negative)
  2711. amount of spacing. This spacing correction appears in horizontal lists
  2712. between letters like A and V when the font designer said that it looks
  2713. better to move them closer together or further apart. A kern node can
  2714. also appear in a vertical list, when its `|width|' denotes additional
  2715. spacing in the vertical direction. The |subtype| is either |normal| (for
  2716. kerns inserted from font information or math mode calculations) or |explicit|
  2717. (for kerns inserted from \.{\\kern} and \.{\\/} commands) or |acc_kern|
  2718. (for kerns inserted from non-math accents) or |mu_glue| (for kerns
  2719. inserted from \.{\\mkern} specifications in math formulas).
  2720. @d kern_node=11 {|type| of a kern node}
  2721. @d explicit=1 {|subtype| of kern nodes from \.{\\kern} and \.{\\/}}
  2722. @d acc_kern=2 {|subtype| of kern nodes from accents}
  2723. @ The |new_kern| function creates a kern node having a given width.
  2724. @p function new_kern(@!w:scaled):pointer;
  2725. var p:pointer; {the new node}
  2726. begin p:=get_node(small_node_size); type(p):=kern_node;
  2727. subtype(p):=normal;
  2728. width(p):=w;
  2729. new_kern:=p;
  2730. @ A |penalty_node| specifies the penalty associated with line or page
  2731. breaking, in its |penalty| field. This field is a fullword integer, but
  2732. the full range of integer values is not used: Any penalty |>=10000| is
  2733. treated as infinity, and no break will be allowed for such high values.
  2734. Similarly, any penalty |<=-10000| is treated as negative infinity, and a
  2735. break will be forced.
  2736. @d penalty_node=12 {|type| of a penalty node}
  2737. @d inf_penalty=inf_bad {``infinite'' penalty value}
  2738. @d eject_penalty=-inf_penalty {``negatively infinite'' penalty value}
  2739. @d penalty(#) == mem[#+1].int {the added cost of breaking a list here}
  2740. @ Anyone who has been reading the last few sections of the program will
  2741. be able to guess what comes next.
  2742. @p function new_penalty(@!m:integer):pointer;
  2743. var p:pointer; {the new node}
  2744. begin p:=get_node(small_node_size); type(p):=penalty_node;
  2745. subtype(p):=0; {the |subtype| is not used}
  2746. penalty(p):=m; new_penalty:=p;
  2747. @ You might think that we have introduced enough node types by now. Well,
  2748. almost, but there is one more: An |unset_node| has nearly the same format
  2749. as an |hlist_node| or |vlist_node|; it is used for entries in \.{\\halign}
  2750. or \.{\\valign} that are not yet in their final form, since the box
  2751. dimensions are their ``natural'' sizes before any glue adjustment has been
  2752. made. The |glue_set| word is not present; instead, we have a |glue_stretch|
  2753. field, which contains the total stretch of order |glue_order| that is
  2754. present in the hlist or vlist being boxed.
  2755. Similarly, the |shift_amount| field is replaced by a |glue_shrink| field,
  2756. containing the total shrink of order |glue_sign| that is present.
  2757. The |subtype| field is called |span_count|; an unset box typically
  2758. contains the data for |qo(span_count)+1| columns.
  2759. Unset nodes will be changed to box nodes when alignment is completed.
  2760. @d unset_node=13 {|type| for an unset node}
  2761. @d glue_stretch(#)==mem[#+glue_offset].sc {total stretch in an unset node}
  2762. @d glue_shrink==shift_amount {total shrink in an unset node}
  2763. @d span_count==subtype {indicates the number of spanned columns}
  2764. @ In fact, there are still more types coming. When we get to math formula
  2765. processing we will see that a |style_node| has |type=14|; and a number
  2766. of larger type codes will also be defined, for use in math mode only.
  2767. @ Warning: If any changes are made to these data structure layouts, such as
  2768. changing any of the node sizes or even reordering the words of nodes,
  2769. the |copy_node_list| procedure and the memory initialization code
  2770. below may have to be changed. Such potentially dangerous parts of the
  2771. program are listed in the index under `data structure assumptions'.
  2772. @!@^data structure assumptions@>
  2773. However, other references to the nodes are made symbolically in terms of
  2774. the \.{WEB} macro definitions above, so that format changes will leave
  2775. \TeX's other algorithms intact.
  2776. @^system dependencies@>
  2777. @* \[11] Memory layout.
  2778. Some areas of |mem| are dedicated to fixed usage, since static allocation is
  2779. more efficient than dynamic allocation when we can get away with it. For
  2780. example, locations |mem_bot| to |mem_bot+3| are always used to store the
  2781. specification for glue that is `\.{0pt plus 0pt minus 0pt}'. The
  2782. following macro definitions accomplish the static allocation by giving
  2783. symbolic names to the fixed positions. Static variable-size nodes appear
  2784. in locations |mem_bot| through |lo_mem_stat_max|, and static single-word nodes
  2785. appear in locations |hi_mem_stat_min| through |mem_top|, inclusive. It is
  2786. harmless to let |lig_trick| and |garbage| share the same location of |mem|.
  2787. @d zero_glue==mem_bot {specification for \.{0pt plus 0pt minus 0pt}}
  2788. @d fil_glue==zero_glue+glue_spec_size {\.{0pt plus 1fil minus 0pt}}
  2789. @d fill_glue==fil_glue+glue_spec_size {\.{0pt plus 1fill minus 0pt}}
  2790. @d ss_glue==fill_glue+glue_spec_size {\.{0pt plus 1fil minus 1fil}}
  2791. @d fil_neg_glue==ss_glue+glue_spec_size {\.{0pt plus -1fil minus 0pt}}
  2792. @d lo_mem_stat_max==fil_neg_glue+glue_spec_size-1 {largest statically
  2793.   allocated word in the variable-size |mem|}
  2794. @d page_ins_head==mem_top {list of insertion data for current page}
  2795. @d contrib_head==mem_top-1 {vlist of items not yet on current page}
  2796. @d page_head==mem_top-2 {vlist for current page}
  2797. @d temp_head==mem_top-3 {head of a temporary list of some kind}
  2798. @d hold_head==mem_top-4 {head of a temporary list of another kind}
  2799. @d adjust_head==mem_top-5 {head of adjustment list returned by |hpack|}
  2800. @d active==mem_top-7 {head of active list in |line_break|, needs two words}
  2801. @d align_head==mem_top-8 {head of preamble list for alignments}
  2802. @d end_span==mem_top-9 {tail of spanned-width lists}
  2803. @d omit_template==mem_top-10 {a constant token list}
  2804. @d null_list==mem_top-11 {permanently empty list}
  2805. @d lig_trick==mem_top-12 {a ligature masquerading as a |char_node|}
  2806. @d garbage==mem_top-12 {used for scrap information}
  2807. @d backup_head==mem_top-13 {head of token list built by |scan_keyword|}
  2808. @d hi_mem_stat_min==mem_top-13 {smallest statically allocated word in
  2809.   the one-word |mem|}
  2810. @d hi_mem_stat_usage=14 {the number of one-word nodes always present}
  2811. @ The following code gets |mem| off to a good start, when \TeX\ is
  2812. initializing itself the slow~way.
  2813. @<Local variables for init...@>=
  2814. @!k:integer; {index into |mem|, |eqtb|, etc.}
  2815. @ @<Initialize table entries...@>=
  2816. for k:=mem_bot+1 to lo_mem_stat_max do mem[k].sc:=0;
  2817.   {all glue dimensions are zeroed}
  2818. @^data structure assumptions@>
  2819. k:=mem_bot;@+while k<=lo_mem_stat_max do
  2820.     {set first words of glue specifications}
  2821.   begin glue_ref_count(k):=null+1;
  2822.   stretch_order(k):=normal; shrink_order(k):=normal;
  2823.   k:=k+glue_spec_size;
  2824.   end;
  2825. stretch(fil_glue):=unity; stretch_order(fil_glue):=fil;@/
  2826. stretch(fill_glue):=unity; stretch_order(fill_glue):=fill;@/
  2827. stretch(ss_glue):=unity; stretch_order(ss_glue):=fil;@/
  2828. shrink(ss_glue):=unity; shrink_order(ss_glue):=fil;@/
  2829. stretch(fil_neg_glue):=-unity; stretch_order(fil_neg_glue):=fil;@/
  2830. rover:=lo_mem_stat_max+1;
  2831. link(rover):=empty_flag; {now initialize the dynamic memory}
  2832. node_size(rover):=1000; {which is a 1000-word available node}
  2833. llink(rover):=rover; rlink(rover):=rover;@/
  2834. lo_mem_max:=rover+1000; link(lo_mem_max):=null; info(lo_mem_max):=null;@/
  2835. for k:=hi_mem_stat_min to mem_top do
  2836.   mem[k]:=mem[lo_mem_max]; {clear list heads}
  2837. @<Initialize the special list heads and constant nodes@>;
  2838. avail:=null; mem_end:=mem_top;
  2839. hi_mem_min:=hi_mem_stat_min; {initialize the one-word memory}
  2840. var_used:=lo_mem_stat_max+1-mem_bot; dyn_used:=hi_mem_stat_usage;
  2841.   {initialize statistics}
  2842. @ If \TeX\ is extended improperly, the |mem| array might get screwed up.
  2843. For example, some pointers might be wrong, or some ``dead'' nodes might not
  2844. have been freed when the last reference to them disappeared. Procedures
  2845. |check_mem| and |search_mem| are available to help diagnose such
  2846. problems. These procedures make use of two arrays called |free| and
  2847. |was_free| that are present only if \TeX's debugging routines have
  2848. been included. (You may want to decrease the size of |mem| while you
  2849. @^debugging@>
  2850. are debugging.)
  2851. @<Glob...@>=
  2852. @!debug @!free: packed array [mem_min..mem_max] of boolean; {free cells}
  2853. @t\hskip10pt@>@!was_free: packed array [mem_min..mem_max] of boolean;
  2854.   {previously free cells}
  2855. @t\hskip10pt@>@!was_mem_end,@!was_lo_max,@!was_hi_min: pointer;
  2856.   {previous |mem_end|, |lo_mem_max|, and |hi_mem_min|}
  2857. @t\hskip10pt@>@!panicking:boolean; {do we want to check memory constantly?}
  2858. gubed
  2859. @ @<Set initial...@>=
  2860. @!debug was_mem_end:=mem_min; {indicate that everything was previously free}
  2861. was_lo_max:=mem_min; was_hi_min:=mem_max;
  2862. panicking:=false;
  2863. gubed
  2864. @ Procedure |check_mem| makes sure that the available space lists of
  2865. |mem| are well formed, and it optionally prints out all locations
  2866. that are reserved now but were free the last time this procedure was called.
  2867. @p @!debug procedure check_mem(@!print_locs : boolean);
  2868. label done1,done2; {loop exits}
  2869. var p,@!q:pointer; {current locations of interest in |mem|}
  2870. @!clobbered:boolean; {is something amiss?}
  2871. begin for p:=mem_min to lo_mem_max do free[p]:=false; {you can probably
  2872.   do this faster}
  2873. for p:=hi_mem_min to mem_end do free[p]:=false; {ditto}
  2874. @<Check single-word |avail| list@>;
  2875. @<Check variable-size |avail| list@>;
  2876. @<Check flags of unavailable nodes@>;
  2877. if print_locs then @<Print newly busy locations@>;
  2878. for p:=mem_min to lo_mem_max do was_free[p]:=free[p];
  2879. for p:=hi_mem_min to mem_end do was_free[p]:=free[p];
  2880.   {|was_free:=free| might be faster}
  2881. was_mem_end:=mem_end; was_lo_max:=lo_mem_max; was_hi_min:=hi_mem_min;
  2882. gubed
  2883. @ @<Check single-word...@>=
  2884. p:=avail; q:=null; clobbered:=false;
  2885. while p<>null do
  2886.   begin if (p>mem_end)or(p<hi_mem_min) then clobbered:=true
  2887.   else if free[p] then clobbered:=true;
  2888.   if clobbered then
  2889.     begin print_nl("AVAIL list clobbered at ");
  2890. @.AVAIL list clobbered...@>
  2891.     print_int(q); goto done1;
  2892.     end;
  2893.   free[p]:=true; q:=p; p:=link(q);
  2894.   end;
  2895. done1:
  2896. @ @<Check variable-size...@>=
  2897. p:=rover; q:=null; clobbered:=false;
  2898. repeat if (p>=lo_mem_max)or(p<mem_min) then clobbered:=true
  2899.   else if (rlink(p)>=lo_mem_max)or(rlink(p)<mem_min) then clobbered:=true
  2900.   else if  not(is_empty(p))or(node_size(p)<2)or@|
  2901.    (p+node_size(p)>lo_mem_max)or@| (llink(rlink(p))<>p) then clobbered:=true;
  2902.   if clobbered then
  2903.   begin print_nl("Double-AVAIL list clobbered at ");
  2904.   print_int(q); goto done2;
  2905.   end;
  2906. for q:=p to p+node_size(p)-1 do {mark all locations free}
  2907.   begin if free[q] then
  2908.     begin print_nl("Doubly free location at ");
  2909. @.Doubly free location...@>
  2910.     print_int(q); goto done2;
  2911.     end;
  2912.   free[q]:=true;
  2913.   end;
  2914. q:=p; p:=rlink(p);
  2915. until p=rover;
  2916. done2:
  2917. @ @<Check flags...@>=
  2918. p:=mem_min;
  2919. while p<=lo_mem_max do {node |p| should not be empty}
  2920.   begin if is_empty(p) then
  2921.     begin print_nl("Bad flag at "); print_int(p);
  2922. @.Bad flag...@>
  2923.     end;
  2924.   while (p<=lo_mem_max) and not free[p] do incr(p);
  2925.   while (p<=lo_mem_max) and free[p] do incr(p);
  2926.   end
  2927. @ @<Print newly busy...@>=
  2928. begin print_nl("New busy locs:");
  2929. for p:=mem_min to lo_mem_max do
  2930.   if not free[p] and ((p>was_lo_max) or was_free[p]) then
  2931.     begin print_char(" "); print_int(p);
  2932.     end;
  2933. for p:=hi_mem_min to mem_end do
  2934.   if not free[p] and
  2935.    ((p<was_hi_min) or (p>was_mem_end) or was_free[p]) then
  2936.     begin print_char(" "); print_int(p);
  2937.     end;
  2938. @ The |search_mem| procedure attempts to answer the question ``Who points
  2939. to node~|p|?'' In doing so, it fetches |link| and |info| fields of |mem|
  2940. that might not be of type |two_halves|. Strictly speaking, this is
  2941. @^dirty \PASCAL@>
  2942. undefined in \PASCAL, and it can lead to ``false drops'' (words that seem to
  2943. point to |p| purely by coincidence). But for debugging purposes, we want
  2944. to rule out the places that do {\sl not\/} point to |p|, so a few false
  2945. drops are tolerable.
  2946. @p @!debug procedure search_mem(@!p:pointer); {look for pointers to |p|}
  2947. var q:integer; {current position being searched}
  2948. begin for q:=mem_min to lo_mem_max do
  2949.   begin if link(q)=p then
  2950.     begin print_nl("LINK("); print_int(q); print_char(")");
  2951.     end;
  2952.   if info(q)=p then
  2953.     begin print_nl("INFO("); print_int(q); print_char(")");
  2954.     end;
  2955.   end;
  2956. for q:=hi_mem_min to mem_end do
  2957.   begin if link(q)=p then
  2958.     begin print_nl("LINK("); print_int(q); print_char(")");
  2959.     end;
  2960.   if info(q)=p then
  2961.     begin print_nl("INFO("); print_int(q); print_char(")");
  2962.     end;
  2963.   end;
  2964. @<Search |eqtb| for equivalents equal to |p|@>;
  2965. @<Search |save_stack| for equivalents that point to |p|@>;
  2966. @<Search |hyph_list| for pointers to |p|@>;
  2967. gubed
  2968. @* \[12] Displaying boxes.
  2969. We can reinforce our knowledge of the data structures just introduced
  2970. by considering two procedures that display a list in symbolic form.
  2971. The first of these, called |short_display|, is used in ``overfull box''
  2972. messages to give the top-level description of a list. The other one,
  2973. called |show_node_list|, prints a detailed description of exactly what
  2974. is in the data structure.
  2975. The philosophy of |short_display| is to ignore the fine points about exactly
  2976. what is inside boxes, except that ligatures and discretionary breaks are
  2977. expanded. As a result, |short_display| is a recursive procedure, but the
  2978. recursion is never more than one level deep.
  2979. @^recursion@>
  2980. A global variable |font_in_short_display| keeps track of the font code that
  2981. is assumed to be present when |short_display| begins; deviations from this
  2982. font will be printed.
  2983. @<Glob...@>=
  2984. @!font_in_short_display:integer; {an internal font number}
  2985. @ Boxes, rules, inserts, whatsits, marks, and things in general that are
  2986. sort of ``complicated'' are indicated only by printing `\.{[]}'.
  2987. @p procedure short_display(@!p:integer); {prints highlights of list |p|}
  2988. var n:integer; {for replacement counts}
  2989. begin while p>mem_min do
  2990.   begin if is_char_node(p) then
  2991.     begin if p<=mem_end then
  2992.       begin if font(p)<>font_in_short_display then
  2993.         begin if (font(p)<font_base)or(font(p)>font_max) then
  2994.           print_char("*")
  2995. @.*\relax@>
  2996.         else @<Print the font identifier for |font(p)|@>;
  2997.         print_char(" "); font_in_short_display:=font(p);
  2998.         end;
  2999.       print_ASCII(qo(character(p)));
  3000.       end;
  3001.     end
  3002.   else @<Print a short indication of the contents of node |p|@>;
  3003.   p:=link(p);
  3004.   end;
  3005. @ @<Print a short indication of the contents of node |p|@>=
  3006. case type(p) of
  3007. hlist_node,vlist_node,ins_node,whatsit_node,mark_node,adjust_node,
  3008.   unset_node: print("[]");
  3009. rule_node: print_char("|");
  3010. glue_node: if glue_ptr(p)<>zero_glue then print_char(" ");
  3011. math_node: print_char("$");
  3012. ligature_node: short_display(lig_ptr(p));
  3013. disc_node: begin short_display(pre_break(p));
  3014.   short_display(post_break(p));@/
  3015.   n:=replace_count(p);
  3016.   while n>0 do
  3017.     begin if link(p)<>null then p:=link(p);
  3018.     decr(n);
  3019.     end;
  3020.   end;
  3021. othercases do_nothing
  3022. endcases
  3023. @ The |show_node_list| routine requires some auxiliary subroutines: one to
  3024. print a font-and-character combination, one to print a token list without
  3025. its reference count, and one to print a rule dimension.
  3026. @p procedure print_font_and_char(@!p:integer); {prints |char_node| data}
  3027. begin if p>mem_end then print_esc("CLOBBERED.")
  3028. else  begin if (font(p)<font_base)or(font(p)>font_max) then print_char("*")
  3029. @.*\relax@>
  3030.   else @<Print the font identifier for |font(p)|@>;
  3031.   print_char(" "); print_ASCII(qo(character(p)));
  3032.   end;
  3033. procedure print_mark(@!p:integer); {prints token list data in braces}
  3034. begin print_char("{");
  3035. if (p<hi_mem_min)or(p>mem_end) then print_esc("CLOBBERED.")
  3036. else show_token_list(link(p),null,max_print_line-10);
  3037. print_char("}");
  3038. procedure print_rule_dimen(@!d:scaled); {prints dimension in rule node}
  3039. begin if is_running(d) then print_char("*") else print_scaled(d);
  3040. @.*\relax@>
  3041. @ Then there is a subroutine that prints glue stretch and shrink, possibly
  3042. followed by the name of finite units:
  3043. @p procedure print_glue(@!d:scaled;@!order:integer;@!s:str_number);
  3044.   {prints a glue component}
  3045. begin print_scaled(d);
  3046. if (order<normal)or(order>filll) then print("foul")
  3047. else if order>normal then
  3048.   begin print("fil");
  3049.   while order>fil do
  3050.     begin print_char("l"); decr(order);
  3051.     end;
  3052.   end
  3053. else if s<>0 then print(s);
  3054. @ The next subroutine prints a whole glue specification.
  3055. @p procedure print_spec(@!p:integer;@!s:str_number);
  3056.   {prints a glue specification}
  3057. begin if (p<mem_min)or(p>=lo_mem_max) then print_char("*")
  3058. @.*\relax@>
  3059. else  begin print_scaled(width(p));
  3060.   if s<>0 then print(s);
  3061.   if stretch(p)<>0 then
  3062.     begin print(" plus "); print_glue(stretch(p),stretch_order(p),s);
  3063.     end;
  3064.   if shrink(p)<>0 then
  3065.     begin print(" minus "); print_glue(shrink(p),shrink_order(p),s);
  3066.     end;
  3067.   end;
  3068. @ We also need to declare some procedures that appear later in this
  3069. documentation.
  3070. @p @<Declare procedures needed for displaying the elements of mlists@>@;
  3071. @<Declare the procedure called |print_skip_param|@>
  3072. @ Since boxes can be inside of boxes, |show_node_list| is inherently recursive,
  3073. @^recursion@>
  3074. up to a given maximum number of levels.  The history of nesting is indicated
  3075. by the current string, which will be printed at the beginning of each line;
  3076. the length of this string, namely |cur_length|, is the depth of nesting.
  3077. Recursive calls on |show_node_list| therefore use the following pattern:
  3078. @d node_list_display(#)==
  3079.   begin append_char("."); show_node_list(#); flush_char;
  3080.   end {|str_room| need not be checked; see |show_box| below}
  3081. @ A global variable called |depth_threshold| is used to record the maximum
  3082. depth of nesting for which |show_node_list| will show information.  If we
  3083. have |depth_threshold=0|, for example, only the top level information will
  3084. be given and no sublists will be traversed. Another global variable, called
  3085. |breadth_max|, tells the maximum number of items to show at each level;
  3086. |breadth_max| had better be positive, or you won't see anything.
  3087. @<Glob...@>=
  3088. @!depth_threshold : integer; {maximum nesting depth in box displays}
  3089. @!breadth_max : integer; {maximum number of items shown at the same list level}
  3090. @ Now we are ready for |show_node_list| itself. This procedure has been
  3091. written to be ``extra robust'' in the sense that it should not crash or get
  3092. into a loop even if the data structures have been messed up by bugs in
  3093. the rest of the program. You can safely call its parent routine
  3094. |show_box(p)| for arbitrary values of |p| when you are debugging \TeX.
  3095. However, in the presence of bad data, the procedure may
  3096. @^dirty \PASCAL@>@^debugging@>
  3097. fetch a |memory_word| whose variant is different from the way it was stored;
  3098. for example, it might try to read |mem[p].hh| when |mem[p]|
  3099. contains a scaled integer, if |p| is a pointer that has been
  3100. clobbered or chosen at random.
  3101. @p procedure show_node_list(@!p:integer); {prints a node list symbolically}
  3102. label exit;
  3103. var n:integer; {the number of items already printed at this level}
  3104. @!g:real; {a glue ratio, as a floating point number}
  3105. begin if cur_length>depth_threshold then
  3106.   begin if p>null then print(" []");
  3107.     {indicate that there's been some truncation}
  3108.   return;
  3109.   end;
  3110. n:=0;
  3111. while p>mem_min do
  3112.   begin print_ln; print_current_string; {display the nesting history}
  3113.   if p>mem_end then {pointer out of range}
  3114.     begin print("Bad link, display aborted."); return;
  3115. @.Bad link...@>
  3116.     end;
  3117.   incr(n); if n>breadth_max then {time to stop}
  3118.     begin print("etc."); return;
  3119. @.etc@>
  3120.     end;
  3121.   @<Display node |p|@>;
  3122.   p:=link(p);
  3123.   end;
  3124. exit:
  3125. @ @<Display node |p|@>=
  3126. if is_char_node(p) then print_font_and_char(p)
  3127. else  case type(p) of
  3128.   hlist_node,vlist_node,unset_node: @<Display box |p|@>;
  3129.   rule_node: @<Display rule |p|@>;
  3130.   ins_node: @<Display insertion |p|@>;
  3131.   whatsit_node: @<Display the whatsit node |p|@>;
  3132.   glue_node: @<Display glue |p|@>;
  3133.   kern_node: @<Display kern |p|@>;
  3134.   math_node: @<Display math node |p|@>;
  3135.   ligature_node: @<Display ligature |p|@>;
  3136.   penalty_node: @<Display penalty |p|@>;
  3137.   disc_node: @<Display discretionary |p|@>;
  3138.   mark_node: @<Display mark |p|@>;
  3139.   adjust_node: @<Display adjustment |p|@>;
  3140.   @t\4@>@<Cases of |show_node_list| that arise in mlists only@>@;
  3141.   othercases print("Unknown node type!")
  3142.   endcases
  3143. @ @<Display box |p|@>=
  3144. begin if type(p)=hlist_node then print_esc("h")
  3145. else if type(p)=vlist_node then print_esc("v")
  3146. else print_esc("unset");
  3147. print("box("); print_scaled(height(p)); print_char("+");
  3148. print_scaled(depth(p)); print(")x"); print_scaled(width(p));
  3149. if type(p)=unset_node then
  3150.   @<Display special fields of the unset node |p|@>
  3151. else  begin @<Display the value of |glue_set(p)|@>;
  3152.   if shift_amount(p)<>0 then
  3153.     begin print(", shifted "); print_scaled(shift_amount(p));
  3154.     end;
  3155.   end;
  3156. node_list_display(list_ptr(p)); {recursive call}
  3157. @ @<Display special fields of the unset node |p|@>=
  3158. begin if span_count(p)<>min_quarterword then
  3159.   begin print(" ("); print_int(qo(span_count(p))+1);
  3160.   print(" columns)");
  3161.   end;
  3162. if glue_stretch(p)<>0 then
  3163.   begin print(", stretch "); print_glue(glue_stretch(p),glue_order(p),0);
  3164.   end;
  3165. if glue_shrink(p)<>0 then
  3166.   begin print(", shrink "); print_glue(glue_shrink(p),glue_sign(p),0);
  3167.   end;
  3168. @ The code will have to change in this place if |glue_ratio| is
  3169. a structured type instead of an ordinary |real|. Note that this routine
  3170. should avoid arithmetic errors even if the |glue_set| field holds an
  3171. arbitrary random value. The following code assumes that a properly
  3172. formed nonzero |real| number has absolute value $2^{20}$ or more when
  3173. it is regarded as an integer; this precaution was adequate to prevent
  3174. floating point underflow on the author's computer.
  3175. @^system dependencies@>
  3176. @^dirty \PASCAL@>
  3177. @<Display the value of |glue_set(p)|@>=
  3178. g:=float(glue_set(p));
  3179. if (g<>float_constant(0))and(glue_sign(p)<>normal) then
  3180.   begin print(", glue set ");
  3181.   if glue_sign(p)=shrinking then print("- ");
  3182.   if abs(mem[p+glue_offset].int)<@'4000000 then print("?.?")
  3183.   else if abs(g)>float_constant(20000) then
  3184.     begin if g>float_constant(0) then print_char(">")
  3185.     else print("< -");
  3186.     print_glue(20000*unity,glue_order(p),0);
  3187.     end
  3188.   else print_glue(round(unity*g),glue_order(p),0);
  3189. @^real multiplication@>
  3190.   end
  3191. @ @<Display rule |p|@>=
  3192. begin print_esc("rule("); print_rule_dimen(height(p)); print_char("+");
  3193. print_rule_dimen(depth(p)); print(")x"); print_rule_dimen(width(p));
  3194. @ @<Display insertion |p|@>=
  3195. begin print_esc("insert"); print_int(qo(subtype(p)));
  3196. print(", natural size "); print_scaled(height(p));
  3197. print("; split("); print_spec(split_top_ptr(p),0);
  3198. print_char(","); print_scaled(depth(p));
  3199. print("); float cost "); print_int(float_cost(p));
  3200. node_list_display(ins_ptr(p)); {recursive call}
  3201. @ @<Display glue |p|@>=
  3202. if subtype(p)>=a_leaders then @<Display leaders |p|@>
  3203. else  begin print_esc("glue");
  3204.   if subtype(p)<>normal then
  3205.     begin print_char("(");
  3206.     if subtype(p)<cond_math_glue then
  3207.       print_skip_param(subtype(p)-1)
  3208.     else if subtype(p)=cond_math_glue then print_esc("nonscript")
  3209.     else print_esc("mskip");
  3210.     print_char(")");
  3211.     end;
  3212.   if subtype(p)<>cond_math_glue then
  3213.     begin print_char(" ");
  3214.     if subtype(p)<cond_math_glue then print_spec(glue_ptr(p),0)
  3215.     else print_spec(glue_ptr(p),"mu");
  3216.     end;
  3217.   end
  3218. @ @<Display leaders |p|@>=
  3219. begin print_esc("");
  3220. if subtype(p)=c_leaders then print_char("c")
  3221. else if subtype(p)=x_leaders then print_char("x");
  3222. print("leaders "); print_spec(glue_ptr(p),0);
  3223. node_list_display(leader_ptr(p)); {recursive call}
  3224. @ An ``explicit'' kern value is indicated implicitly by an explicit space.
  3225. @<Display kern |p|@>=
  3226. if subtype(p)<>mu_glue then
  3227.   begin print_esc("kern");
  3228.   if subtype(p)<>normal then print_char(" ");
  3229.   print_scaled(width(p));
  3230.   if subtype(p)=acc_kern then print(" (for accent)");
  3231. @.for accent@>
  3232.   end
  3233. else  begin print_esc("mkern"); print_scaled(width(p)); print("mu");
  3234.   end
  3235. @ @<Display math node |p|@>=
  3236. begin print_esc("math");
  3237. if subtype(p)=before then print("on")
  3238. else print("off");
  3239. if width(p)<>0 then
  3240.   begin print(", surrounded "); print_scaled(width(p));
  3241.   end;
  3242. @ @<Display ligature |p|@>=
  3243. begin print_font_and_char(lig_char(p)); print(" (ligature ");
  3244. if subtype(p)>1 then print_char("|");
  3245. font_in_short_display:=font(lig_char(p)); short_display(lig_ptr(p));
  3246. if odd(subtype(p)) then print_char("|");
  3247. print_char(")");
  3248. @ @<Display penalty |p|@>=
  3249. begin print_esc("penalty "); print_int(penalty(p));
  3250. @ The |post_break| list of a discretionary node is indicated by a prefixed
  3251. `\.{\char'174}' instead of the `\..' before the |pre_break| list.
  3252. @<Display discretionary |p|@>=
  3253. begin print_esc("discretionary");
  3254. if replace_count(p)>0 then
  3255.   begin print(" replacing "); print_int(replace_count(p));
  3256.   end;
  3257. node_list_display(pre_break(p)); {recursive call}
  3258. append_char("|"); show_node_list(post_break(p)); flush_char; {recursive call}
  3259. @ @<Display mark |p|@>=
  3260. begin print_esc("mark"); print_mark(mark_ptr(p));
  3261. @ @<Display adjustment |p|@>=
  3262. begin print_esc("vadjust"); node_list_display(adjust_ptr(p)); {recursive call}
  3263. @ The recursive machinery is started by calling |show_box|.
  3264. @^recursion@>
  3265. @p procedure show_box(@!p:pointer);
  3266. begin @<Assign the values |depth_threshold:=show_box_depth| and
  3267.   |breadth_max:=show_box_breadth|@>;
  3268. if breadth_max<=0 then breadth_max:=5;
  3269. if pool_ptr+depth_threshold>=pool_size then
  3270.   depth_threshold:=pool_size-pool_ptr-1;
  3271.   {now there's enough room for prefix string}
  3272. show_node_list(p); {the show starts at |p|}
  3273. print_ln;
  3274. @* \[13] Destroying boxes.
  3275. When we are done with a node list, we are obliged to return it to free
  3276. storage, including all of its sublists. The recursive procedure
  3277. |flush_node_list| does this for us.
  3278. @ First, however, we shall consider two non-recursive procedures that do
  3279. simpler tasks. The first of these, |delete_token_ref|, is called when
  3280. a pointer to a token list's reference count is being removed. This means
  3281. that the token list should disappear if the reference count was |null|,
  3282. otherwise the count should be decreased by one.
  3283. @^reference counts@>
  3284. @d token_ref_count(#) == info(#) {reference count preceding a token list}
  3285. @p procedure delete_token_ref(@!p:pointer); {|p| points to the reference count
  3286.   of a token list that is losing one reference}
  3287. begin if token_ref_count(p)=null then flush_list(p)
  3288. else decr(token_ref_count(p));
  3289. @ Similarly, |delete_glue_ref| is called when a pointer to a glue
  3290. specification is being withdrawn.
  3291. @^reference counts@>
  3292. @d fast_delete_glue_ref(#)==@t@>@;@/
  3293.   begin if glue_ref_count(#)=null then free_node(#,glue_spec_size)
  3294.   else decr(glue_ref_count(#));
  3295.   end
  3296. @p procedure delete_glue_ref(@!p:pointer); {|p| points to a glue specification}
  3297. fast_delete_glue_ref(p);
  3298. @ Now we are ready to delete any node list, recursively.
  3299. In practice, the nodes deleted are usually charnodes (about 2/3 of the time),
  3300. and they are glue nodes in about half of the remaining cases.
  3301. @^recursion@>
  3302. @p procedure flush_node_list(@!p:pointer); {erase list of nodes starting at |p|}
  3303. label done; {go here when node |p| has been freed}
  3304. var q:pointer; {successor to node |p|}
  3305. begin while p<>null do
  3306. @^inner loop@>
  3307.   begin q:=link(p);
  3308.   if is_char_node(p) then free_avail(p)
  3309.   else  begin case type(p) of
  3310.     hlist_node,vlist_node,unset_node: begin flush_node_list(list_ptr(p));
  3311.       free_node(p,box_node_size); goto done;
  3312.       end;
  3313.     rule_node: begin free_node(p,rule_node_size); goto done;
  3314.       end;
  3315.     ins_node: begin flush_node_list(ins_ptr(p));
  3316.       delete_glue_ref(split_top_ptr(p));
  3317.       free_node(p,ins_node_size); goto done;
  3318.       end;
  3319.     whatsit_node: @<Wipe out the whatsit node |p| and |goto done|@>;
  3320.     glue_node: begin fast_delete_glue_ref(glue_ptr(p));
  3321.       if leader_ptr(p)<>null then flush_node_list(leader_ptr(p));
  3322.       end;
  3323.     kern_node,math_node,penalty_node: do_nothing;
  3324.     ligature_node: flush_node_list(lig_ptr(p));
  3325.     mark_node: delete_token_ref(mark_ptr(p));
  3326.     disc_node: begin flush_node_list(pre_break(p));
  3327.       flush_node_list(post_break(p));
  3328.       end;
  3329.     adjust_node: flush_node_list(adjust_ptr(p));
  3330.     @t\4@>@<Cases of |flush_node_list| that arise in mlists only@>@;
  3331.     othercases confusion("flushing")
  3332. @:this can't happen flushing}{\quad flushing@>
  3333.     endcases;@/
  3334.     free_node(p,small_node_size);
  3335.     done:end;
  3336.   p:=q;
  3337.   end;
  3338. @* \[14] Copying boxes.
  3339. Another recursive operation that acts on boxes is sometimes needed: The
  3340. procedure |copy_node_list| returns a pointer to another node list that has
  3341. the same structure and meaning as the original. Note that since glue
  3342. specifications and token lists have reference counts, we need not make
  3343. copies of them. Reference counts can never get too large to fit in a
  3344. halfword, since each pointer to a node is in a different memory address,
  3345. and the total number of memory addresses fits in a halfword.
  3346. @^recursion@>
  3347. @^reference counts@>
  3348. (Well, there actually are also references from outside |mem|; if the
  3349. |save_stack| is made arbitrarily large, it would theoretically be possible
  3350. to break \TeX\ by overflowing a reference count. But who would want to do that?)
  3351. @d add_token_ref(#)==incr(token_ref_count(#)) {new reference to a token list}
  3352. @d add_glue_ref(#)==incr(glue_ref_count(#)) {new reference to a glue spec}
  3353. @ The copying procedure copies words en masse without bothering
  3354. to look at their individual fields. If the node format changes---for
  3355. example, if the size is altered, or if some link field is moved to another
  3356. relative position---then this code may need to be changed too.
  3357. @^data structure assumptions@>
  3358. @p function copy_node_list(@!p:pointer):pointer; {makes a duplicate of the
  3359.   node list that starts at |p| and returns a pointer to the new list}
  3360. var h:pointer; {temporary head of copied list}
  3361. @!q:pointer; {previous position in new list}
  3362. @!r:pointer; {current node being fabricated for new list}
  3363. @!words:0..5; {number of words remaining to be copied}
  3364. begin h:=get_avail; q:=h;
  3365. while p<>null do
  3366.   begin @<Make a copy of node |p| in node |r|@>;
  3367.   link(q):=r; q:=r; p:=link(p);
  3368.   end;
  3369. link(q):=null; q:=link(h); free_avail(h);
  3370. copy_node_list:=q;
  3371. @ @<Make a copy of node |p|...@>=
  3372. words:=1; {this setting occurs in more branches than any other}
  3373. if is_char_node(p) then r:=get_avail
  3374. else @<Case statement to copy different types and set |words| to the number
  3375.   of initial words not yet copied@>;
  3376. while words>0 do
  3377.   begin decr(words); mem[r+words]:=mem[p+words];
  3378.   end
  3379. @ @<Case statement to copy...@>=
  3380. case type(p) of
  3381. hlist_node,vlist_node,unset_node: begin r:=get_node(box_node_size);
  3382.   mem[r+6]:=mem[p+6]; mem[r+5]:=mem[p+5]; {copy the last two words}
  3383.   list_ptr(r):=copy_node_list(list_ptr(p)); {this affects |mem[r+5]|}
  3384.   words:=5;
  3385.   end;
  3386. rule_node: begin r:=get_node(rule_node_size); words:=rule_node_size;
  3387.   end;
  3388. ins_node: begin r:=get_node(ins_node_size); mem[r+4]:=mem[p+4];
  3389.   add_glue_ref(split_top_ptr(p));
  3390.   ins_ptr(r):=copy_node_list(ins_ptr(p)); {this affects |mem[r+4]|}
  3391.   words:=ins_node_size-1;
  3392.   end;
  3393. whatsit_node:@<Make a partial copy of the whatsit node |p| and make |r|
  3394.   point to it; set |words| to the number of initial words not yet copied@>;
  3395. glue_node: begin r:=get_node(small_node_size); add_glue_ref(glue_ptr(p));
  3396.   glue_ptr(r):=glue_ptr(p); leader_ptr(r):=copy_node_list(leader_ptr(p));
  3397.   end;
  3398. kern_node,math_node,penalty_node: begin r:=get_node(small_node_size);
  3399.   words:=small_node_size;
  3400.   end;
  3401. ligature_node: begin r:=get_node(small_node_size);
  3402.   mem[lig_char(r)]:=mem[lig_char(p)]; {copy |font| and |character|}
  3403.   lig_ptr(r):=copy_node_list(lig_ptr(p));
  3404.   end;
  3405. disc_node: begin r:=get_node(small_node_size);
  3406.   pre_break(r):=copy_node_list(pre_break(p));
  3407.   post_break(r):=copy_node_list(post_break(p));
  3408.   end;
  3409. mark_node: begin r:=get_node(small_node_size); add_token_ref(mark_ptr(p));
  3410.   words:=small_node_size;
  3411.   end;
  3412. adjust_node: begin r:=get_node(small_node_size);
  3413.   adjust_ptr(r):=copy_node_list(adjust_ptr(p));
  3414.   end; {|words=1=small_node_size-1|}
  3415. othercases confusion("copying")
  3416. @:this can't happen copying}{\quad copying@>
  3417. endcases
  3418. @* \[15] The command codes.
  3419. Before we can go any further, we need to define symbolic names for the internal
  3420. code numbers that represent the various commands obeyed by \TeX. These codes
  3421. are somewhat arbitrary, but not completely so. For example, the command
  3422. codes for character types are fixed by the language, since a user says,
  3423. e.g., `\.{\\catcode \`\\\${} = 3}' to make \.{\char'44} a math delimiter,
  3424. and the command code |math_shift| is equal to~3. Some other codes have
  3425. been made adjacent so that |case| statements in the program need not consider
  3426. cases that are widely spaced, or so that |case| statements can be replaced
  3427. by |if| statements.
  3428. At any rate, here is the list, for future reference. First come the
  3429. ``catcode'' commands, several of which share their numeric codes with
  3430. ordinary commands when the catcode cannot emerge from \TeX's scanning routine.
  3431. @d escape=0 {escape delimiter (called \.\\ in {\sl The \TeX book\/})}
  3432. @:TeXbook}{\sl The \TeX book@>
  3433. @d relax=0 {do nothing ( \.{\\relax} )}
  3434. @d left_brace=1 {beginning of a group ( \.\{ )}
  3435. @d right_brace=2 {ending of a group ( \.\} )}
  3436. @d math_shift=3 {mathematics shift character ( \.\$ )}
  3437. @d tab_mark=4 {alignment delimiter ( \.\&, \.{\\span} )}
  3438. @d car_ret=5 {end of line ( |carriage_return|, \.{\\cr}, \.{\\crcr} )}
  3439. @d out_param=5 {output a macro parameter}
  3440. @d mac_param=6 {macro parameter symbol ( \.\# )}
  3441. @d sup_mark=7 {superscript ( \.{\char'136} )}
  3442. @d sub_mark=8 {subscript ( \.{\char'137} )}
  3443. @d ignore=9 {characters to ignore ( \.{\^\^J} )}
  3444. @d endv=9 {end of \<v_j> list in alignment template}
  3445. @d spacer=10 {characters equivalent to blank space ( \.{\ } )}
  3446. @d letter=11 {characters regarded as letters ( \.{A..Z}, \.{a..z} )}
  3447. @d other_char=12 {none of the special character types}
  3448. @d active_char=13 {characters that invoke macros ( \.{\^\^[} )}
  3449. @d par_end=13 {end of paragraph ( \.{\\par} )}
  3450. @d match=13 {match a macro parameter}
  3451. @d comment=14 {characters that introduce comments ( \.\% )}
  3452. @d end_match=14 {end of parameters to macro}
  3453. @d stop=14 {end of job ( \.{\\end}, \.{\\dump} )}
  3454. @d invalid_char=15 {characters that shouldn't appear ( \.{\^\^?} )}
  3455. @d delim_num=15 {specify delimiter numerically ( \.{\\delimiter} )}
  3456. @d max_char_code=15 {largest catcode for individual characters}
  3457. @ Next are the ordinary run-of-the-mill command codes.  Codes that are
  3458. |min_internal| or more represent internal quantities that might be
  3459. expanded by `\.{\\the}'.
  3460. @d char_num=16 {character specified numerically ( \.{\\char} )}
  3461. @d math_char_num=17 {explicit math code ( \.{\\mathchar} )}
  3462. @d mark=18 {mark definition ( \.{\\mark} )}
  3463. @d xray=19 {peek inside of \TeX\ ( \.{\\show}, \.{\\showbox}, etc.~)}
  3464. @d make_box=20 {make a box ( \.{\\box}, \.{\\copy}, \.{\\hbox}, etc.~)}
  3465. @d hmove=21 {horizontal motion ( \.{\\moveleft}, \.{\\moveright} )}
  3466. @d vmove=22 {vertical motion ( \.{\\raise}, \.{\\lower} )}
  3467. @d un_hbox=23 {unglue a box ( \.{\\unhbox}, \.{\\unhcopy} )}
  3468. @d un_vbox=24 {unglue a box ( \.{\\unvbox}, \.{\\unvcopy} )}
  3469. @d remove_item=25 {nullify last item ( \.{\\unpenalty},
  3470.   \.{\\unkern}, \.{\\unskip} )}
  3471. @d hskip=26 {horizontal glue ( \.{\\hskip}, \.{\\hfil}, etc.~)}
  3472. @d vskip=27 {vertical glue ( \.{\\vskip}, \.{\\vfil}, etc.~)}
  3473. @d mskip=28 {math glue ( \.{\\mskip} )}
  3474. @d kern=29 {fixed space ( \.{\\kern})}
  3475. @d mkern=30 {math kern ( \.{\\mkern} )}
  3476. @d leader_ship=31 {use a box ( \.{\\shipout}, \.{\\leaders}, etc.~)}
  3477. @d halign=32 {horizontal table alignment ( \.{\\halign} )}
  3478. @d valign=33 {vertical table alignment ( \.{\\valign} )}
  3479. @d no_align=34 {temporary escape from alignment ( \.{\\noalign} )}
  3480. @d vrule=35 {vertical rule ( \.{\\vrule} )}
  3481. @d hrule=36 {horizontal rule ( \.{\\hrule} )}
  3482. @d insert=37 {vlist inserted in box ( \.{\\insert} )}
  3483. @d vadjust=38 {vlist inserted in enclosing paragraph ( \.{\\vadjust} )}
  3484. @d ignore_spaces=39 {gobble |spacer| tokens ( \.{\\ignorespaces} )}
  3485. @d after_assignment=40 {save till assignment is done ( \.{\\afterassignment} )}
  3486. @d after_group=41 {save till group is done ( \.{\\aftergroup} )}
  3487. @d break_penalty=42 {additional badness ( \.{\\penalty} )}
  3488. @d start_par=43 {begin paragraph ( \.{\\indent}, \.{\\noindent} )}
  3489. @d ital_corr=44 {italic correction ( \.{\\/} )}
  3490. @d accent=45 {attach accent in text ( \.{\\accent} )}
  3491. @d math_accent=46 {attach accent in math ( \.{\\mathaccent} )}
  3492. @d discretionary=47 {discretionary texts ( \.{\\-}, \.{\\discretionary} )}
  3493. @d eq_no=48 {equation number ( \.{\\eqno}, \.{\\leqno} )}
  3494. @d left_right=49 {variable delimiter ( \.{\\left}, \.{\\right} )}
  3495. @d math_comp=50 {component of formula ( \.{\\mathbin}, etc.~)}
  3496. @d limit_switch=51 {diddle limit conventions ( \.{\\displaylimits}, etc.~)}
  3497. @d above=52 {generalized fraction ( \.{\\above}, \.{\\atop}, etc.~)}
  3498. @d math_style=53 {style specification ( \.{\\displaystyle}, etc.~)}
  3499. @d math_choice=54 {choice specification ( \.{\\mathchoice} )}
  3500. @d non_script=55 {conditional math glue ( \.{\\nonscript} )}
  3501. @d vcenter=56 {vertically center a vbox ( \.{\\vcenter} )}
  3502. @d case_shift=57 {force specific case ( \.{\\lowercase}, \.{\\uppercase}~)}
  3503. @d message=58 {send to user ( \.{\\message}, \.{\\errmessage} )}
  3504. @d extension=59 {extensions to \TeX\ ( \.{\\write}, \.{\\special}, etc.~)}
  3505. @d in_stream=60 {files for reading ( \.{\\openin}, \.{\\closein} )}
  3506. @d begin_group=61 {begin local grouping ( \.{\\begingroup} )}
  3507. @d end_group=62 {end local grouping ( \.{\\endgroup} )}
  3508. @d omit=63 {omit alignment template ( \.{\\omit} )}
  3509. @d ex_space=64 {explicit space ( \.{\\\ } )}
  3510. @d no_boundary=65 {suppress boundary ligatures ( \.{\\noboundary} )}
  3511. @d radical=66 {square root and similar signs ( \.{\\radical} )}
  3512. @d end_cs_name=67 {end control sequence ( \.{\\endcsname} )}
  3513. @d min_internal=68 {the smallest code that can follow \.{\\the}}
  3514. @d char_given=68 {character code defined by \.{\\chardef}}
  3515. @d math_given=69 {math code defined by \.{\\mathchardef}}
  3516. @d last_item=70 {most recent item ( \.{\\lastpenalty},
  3517.   \.{\\lastkern}, \.{\\lastskip} )}
  3518. @d max_non_prefixed_command=70 {largest command code that can't be \.{\\global}}
  3519. @ The next codes are special; they all relate to mode-independent
  3520. assignment of values to \TeX's internal registers or tables.
  3521. Codes that are |max_internal| or less represent internal quantities
  3522. that might be expanded by `\.{\\the}'.
  3523. @d toks_register=71 {token list register ( \.{\\toks} )}
  3524. @d assign_toks=72 {special token list ( \.{\\output}, \.{\\everypar}, etc.~)}
  3525. @d assign_int=73 {user-defined integer ( \.{\\tolerance}, \.{\\day}, etc.~)}
  3526. @d assign_dimen=74 {user-defined length ( \.{\\hsize}, etc.~)}
  3527. @d assign_glue=75 {user-defined glue ( \.{\\baselineskip}, etc.~)}
  3528. @d assign_mu_glue=76 {user-defined muglue ( \.{\\thinmuskip}, etc.~)}
  3529. @d assign_font_dimen=77 {user-defined font dimension ( \.{\\fontdimen} )}
  3530. @d assign_font_int=78 {user-defined font integer ( \.{\\hyphenchar},
  3531.   \.{\\skewchar} )}
  3532. @d set_aux=79 {specify state info ( \.{\\spacefactor}, \.{\\prevdepth} )}
  3533. @d set_prev_graf=80 {specify state info ( \.{\\prevgraf} )}
  3534. @d set_page_dimen=81 {specify state info ( \.{\\pagegoal}, etc.~)}
  3535. @d set_page_int=82 {specify state info ( \.{\\deadcycles},
  3536.   \.{\\insertpenalties} )}
  3537. @d set_box_dimen=83 {change dimension of box ( \.{\\wd}, \.{\\ht}, \.{\\dp} )}
  3538. @d set_shape=84 {specify fancy paragraph shape ( \.{\\parshape} )}
  3539. @d def_code=85 {define a character code ( \.{\\catcode}, etc.~)}
  3540. @d def_family=86 {declare math fonts ( \.{\\textfont}, etc.~)}
  3541. @d set_font=87 {set current font ( font identifiers )}
  3542. @d def_font=88 {define a font file ( \.{\\font} )}
  3543. @d register=89 {internal register ( \.{\\count}, \.{\\dimen}, etc.~)}
  3544. @d max_internal=89 {the largest code that can follow \.{\\the}}
  3545. @d advance=90 {advance a register or parameter ( \.{\\advance} )}
  3546. @d multiply=91 {multiply a register or parameter ( \.{\\multiply} )}
  3547. @d divide=92 {divide a register or parameter ( \.{\\divide} )}
  3548. @d prefix=93 {qualify a definition ( \.{\\global}, \.{\\long}, \.{\\outer} )}
  3549. @d let=94 {assign a command code ( \.{\\let}, \.{\\futurelet} )}
  3550. @d shorthand_def=95 {code definition ( \.{\\chardef}, \.{\\countdef}, etc.~)}
  3551. @d read_to_cs=96 {read into a control sequence ( \.{\\read} )}
  3552. @d def=97 {macro definition ( \.{\\def}, \.{\\gdef}, \.{\\xdef}, \.{\\edef} )}
  3553. @d set_box=98 {set a box ( \.{\\setbox} )}
  3554. @d hyph_data=99 {hyphenation data ( \.{\\hyphenation}, \.{\\patterns} )}
  3555. @d set_interaction=100 {define level of interaction ( \.{\\batchmode}, etc.~)}
  3556. @d max_command=100 {the largest command code seen at |big_switch|}
  3557. @ The remaining command codes are extra special, since they cannot get through
  3558. \TeX's scanner to the main control routine. They have been given values higher
  3559. than |max_command| so that their special nature is easily discernible.
  3560. The ``expandable'' commands come first.
  3561. @d undefined_cs=max_command+1 {initial state of most |eq_type| fields}
  3562. @d expand_after=max_command+2 {special expansion ( \.{\\expandafter} )}
  3563. @d no_expand=max_command+3 {special nonexpansion ( \.{\\noexpand} )}
  3564. @d input=max_command+4 {input a source file ( \.{\\input}, \.{\\endinput} )}
  3565. @d if_test=max_command+5 {conditional text ( \.{\\if}, \.{\\ifcase}, etc.~)}
  3566. @d fi_or_else=max_command+6 {delimiters for conditionals ( \.{\\else}, etc.~)}
  3567. @d cs_name=max_command+7 {make a control sequence from tokens ( \.{\\csname} )}
  3568. @d convert=max_command+8 {convert to text ( \.{\\number}, \.{\\string}, etc.~)}
  3569. @d the=max_command+9 {expand an internal quantity ( \.{\\the} )}
  3570. @d top_bot_mark=max_command+10 {inserted mark ( \.{\\topmark}, etc.~)}
  3571. @d call=max_command+11 {non-long, non-outer control sequence}
  3572. @d long_call=max_command+12 {long, non-outer control sequence}
  3573. @d outer_call=max_command+13 {non-long, outer control sequence}
  3574. @d long_outer_call=max_command+14 {long, outer control sequence}
  3575. @d end_template=max_command+15 {end of an alignment template}
  3576. @d dont_expand=max_command+16 {the following token was marked by \.{\\noexpand}}
  3577. @d glue_ref=max_command+17 {the equivalent points to a glue specification}
  3578. @d shape_ref=max_command+18 {the equivalent points to a parshape specification}
  3579. @d box_ref=max_command+19 {the equivalent points to a box node, or is |null|}
  3580. @d data=max_command+20 {the equivalent is simply a halfword number}
  3581. @* \[16] The semantic nest.
  3582. \TeX\ is typically in the midst of building many lists at once. For example,
  3583. when a math formula is being processed, \TeX\ is in math mode and
  3584. working on an mlist; this formula has temporarily interrupted \TeX\ from
  3585. being in horizontal mode and building the hlist of a paragraph; and this
  3586. paragraph has temporarily interrupted \TeX\ from being in vertical mode
  3587. and building the vlist for the next page of a document. Similarly, when a
  3588. \.{\\vbox} occurs inside of an \.{\\hbox}, \TeX\ is temporarily
  3589. interrupted from working in restricted horizontal mode, and it enters
  3590. internal vertical mode.  The ``semantic nest'' is a stack that
  3591. keeps track of what lists and modes are currently suspended.
  3592. At each level of processing we are in one of six modes:
  3593. \yskip\hang|vmode| stands for vertical mode (the page builder);
  3594. \hang|hmode| stands for horizontal mode (the paragraph builder);
  3595. \hang|mmode| stands for displayed formula mode;
  3596. \hang|-vmode| stands for internal vertical mode (e.g., in a \.{\\vbox});
  3597. \hang|-hmode| stands for restricted horizontal mode (e.g., in an \.{\\hbox});
  3598. \hang|-mmode| stands for math formula mode (not displayed).
  3599. \yskip\noindent The mode is temporarily set to zero while processing \.{\\write}
  3600. texts in the |ship_out| routine.
  3601. Numeric values are assigned to |vmode|, |hmode|, and |mmode| so that
  3602. \TeX's ``big semantic switch'' can select the appropriate thing to
  3603. do by computing the value |abs(mode)+cur_cmd|, where |mode| is the current
  3604. mode and |cur_cmd| is the current command code.
  3605. @d vmode=1 {vertical mode}
  3606. @d hmode=vmode+max_command+1 {horizontal mode}
  3607. @d mmode=hmode+max_command+1 {math mode}
  3608. @p procedure print_mode(@!m:integer); {prints the mode represented by |m|}
  3609. begin if m>0 then
  3610.   case m div (max_command+1) of
  3611.   0:print("vertical");
  3612.   1:print("horizontal");
  3613.   2:print("display math");
  3614.   end
  3615. else if m=0 then print("no")
  3616. else  case (-m) div (max_command+1) of
  3617.   0:print("internal vertical");
  3618.   1:print("restricted horizontal");
  3619.   2:print("math");
  3620.   end;
  3621. print(" mode");
  3622. @ The state of affairs at any semantic level can be represented by
  3623. five values:
  3624. \yskip\hang|mode| is the number representing the semantic mode, as
  3625. just explained.
  3626. \yskip\hang|head| is a |pointer| to a list head for the list being built;
  3627. |link(head)| therefore points to the first element of the list, or
  3628. to |null| if the list is empty.
  3629. \yskip\hang|tail| is a |pointer| to the final node of the list being
  3630. built; thus, |tail=head| if and only if the list is empty.
  3631. \yskip\hang|prev_graf| is the number of lines of the current paragraph that
  3632. have already been put into the present vertical list.
  3633. \yskip\hang|aux| is an auxiliary |memory_word| that gives further information
  3634. that is needed to characterize the situation.
  3635. \yskip\noindent
  3636. In vertical mode, |aux| is also known as |prev_depth|; it is the scaled
  3637. value representing the depth of the previous box, for use in baseline
  3638. calculations, or it is |<=-1000|pt if the next box on the vertical list is to
  3639. be exempt from baseline calculations.  In horizontal mode, |aux| is also
  3640. known as |space_factor| and |clang|; it holds the current space factor used in
  3641. spacing calculations, and the current language used for hyphenation.
  3642. (The value of |clang| is undefined in restricted horizontal mode.)
  3643. In math mode, |aux| is also known as |incompleat_noad|; if
  3644. not |null|, it points to a record that represents the numerator of a
  3645. generalized fraction for which the denominator is currently being formed
  3646. in the current list.
  3647. There is also a sixth quantity, |mode_line|, which correlates
  3648. the semantic nest with the user's input; |mode_line| contains the source
  3649. line number at which the current level of nesting was entered. The negative
  3650. of this line number is the |mode_line| at the level of the
  3651. user's output routine.
  3652. In horizontal mode, the |prev_graf| field is used for initial language data.
  3653. The semantic nest is an array called |nest| that holds the |mode|, |head|,
  3654. |tail|, |prev_graf|, |aux|, and |mode_line| values for all semantic levels
  3655. below the currently active one. Information about the currently active
  3656. level is kept in the global quantities |mode|, |head|, |tail|, |prev_graf|,
  3657. |aux|, and |mode_line|, which live in a \PASCAL\ record that is ready to
  3658. be pushed onto |nest| if necessary.
  3659. @d ignore_depth==-65536000 {|prev_depth| value that is ignored}
  3660. @<Types...@>=
  3661. @!list_state_record=record@!mode_field:-mmode..mmode;@+
  3662.   @!head_field,@!tail_field: pointer;
  3663.   @!pg_field,@!ml_field: integer;@+
  3664.   @!aux_field: memory_word;
  3665.   end;
  3666. @ @d mode==cur_list.mode_field {current mode}
  3667. @d head==cur_list.head_field {header node of current list}
  3668. @d tail==cur_list.tail_field {final node on current list}
  3669. @d prev_graf==cur_list.pg_field {number of paragraph lines accumulated}
  3670. @d aux==cur_list.aux_field {auxiliary data about the current list}
  3671. @d prev_depth==aux.sc {the name of |aux| in vertical mode}
  3672. @d space_factor==aux.hh.lh {part of |aux| in horizontal mode}
  3673. @d clang==aux.hh.rh {the other part of |aux| in horizontal mode}
  3674. @d incompleat_noad==aux.int {the name of |aux| in math mode}
  3675. @d mode_line==cur_list.ml_field {source file line number at beginning of list}
  3676. @<Glob...@>=
  3677. @!nest:array[0..nest_size] of list_state_record;
  3678. @!nest_ptr:0..nest_size; {first unused location of |nest|}
  3679. @!max_nest_stack:0..nest_size; {maximum of |nest_ptr| when pushing}
  3680. @!cur_list:list_state_record; {the ``top'' semantic state}
  3681. @!shown_mode:-mmode..mmode; {most recent mode shown by \.{\\tracingcommands}}
  3682. @ Here is a common way to make the current list grow:
  3683. @d tail_append(#)==begin link(tail):=#; tail:=link(tail);
  3684.   end
  3685. @ We will see later that the vertical list at the bottom semantic level is split
  3686. into two parts; the ``current page'' runs from |page_head| to |page_tail|,
  3687. and the ``contribution list'' runs from |contrib_head| to |tail| of
  3688. semantic level zero. The idea is that contributions are first formed in
  3689. vertical mode, then ``contributed'' to the current page (during which time
  3690. the page-breaking decisions are made). For now, we don't need to know
  3691. any more details about the page-building process.
  3692. @<Set init...@>=
  3693. nest_ptr:=0; max_nest_stack:=0;
  3694. mode:=vmode; head:=contrib_head; tail:=contrib_head;
  3695. prev_depth:=ignore_depth; mode_line:=0;
  3696. prev_graf:=0; shown_mode:=0;
  3697. @<Start a new current page@>;
  3698. @ When \TeX's work on one level is interrupted, the state is saved by
  3699. calling |push_nest|. This routine changes |head| and |tail| so that
  3700. a new (empty) list is begun; it does not change |mode| or |aux|.
  3701. @p procedure push_nest; {enter a new semantic level, save the old}
  3702. begin if nest_ptr>max_nest_stack then
  3703.   begin max_nest_stack:=nest_ptr;
  3704.   if nest_ptr=nest_size then overflow("semantic nest size",nest_size);
  3705. @:TeX capacity exceeded semantic nest size}{\quad semantic nest size@>
  3706.   end;
  3707. nest[nest_ptr]:=cur_list; {stack the record}
  3708. incr(nest_ptr); head:=get_avail; tail:=head; prev_graf:=0; mode_line:=line;
  3709. @ Conversely, when \TeX\ is finished on the current level, the former
  3710. state is restored by calling |pop_nest|. This routine will never be
  3711. called at the lowest semantic level, nor will it be called unless |head|
  3712. is a node that should be returned to free memory.
  3713. @p procedure pop_nest; {leave a semantic level, re-enter the old}
  3714. begin free_avail(head); decr(nest_ptr); cur_list:=nest[nest_ptr];
  3715. @ Here is a procedure that displays what \TeX\ is working on, at all levels.
  3716. @p procedure@?print_totals; forward;@t\2@>
  3717. procedure show_activities;
  3718. var p:0..nest_size; {index into |nest|}
  3719. @!m:-mmode..mmode; {mode}
  3720. @!a:memory_word; {auxiliary}
  3721. @!q,@!r:pointer; {for showing the current page}
  3722. @!t:integer; {ditto}
  3723. begin nest[nest_ptr]:=cur_list; {put the top level into the array}
  3724. print_nl(""); print_ln;
  3725. for p:=nest_ptr downto 0 do
  3726.   begin m:=nest[p].mode_field; a:=nest[p].aux_field;
  3727.   print_nl("### "); print_mode(m);
  3728.   print(" entered at line "); print_int(abs(nest[p].ml_field));
  3729.   if m=hmode then if nest[p].pg_field <> @'40600000 then
  3730.     begin print(" (language"); print_int(nest[p].pg_field mod @'200000);
  3731.     print(":hyphenmin"); print_int(nest[p].pg_field div @'20000000);
  3732.     print_char(","); print_int((nest[p].pg_field div @'200000) mod @'100);
  3733.     print_char(")");
  3734.     end;
  3735.   if nest[p].ml_field<0 then print(" (\output routine)");
  3736.   if p=0 then
  3737.     begin @<Show the status of the current page@>;
  3738.     if link(contrib_head)<>null then
  3739.       print_nl("### recent contributions:");
  3740.     end;
  3741.   show_box(link(nest[p].head_field));
  3742.   @<Show the auxiliary field, |a|@>;
  3743.   end;
  3744. @ @<Show the auxiliary...@>=
  3745. case abs(m) div (max_command+1) of
  3746. 0: begin print_nl("prevdepth ");
  3747.   if a.sc<=ignore_depth then print("ignored")
  3748.   else print_scaled(a.sc);
  3749.   if nest[p].pg_field<>0 then
  3750.     begin print(", prevgraf ");
  3751.     print_int(nest[p].pg_field); print(" line");
  3752.     if nest[p].pg_field<>1 then print_char("s");
  3753.     end;
  3754.   end;
  3755. 1: begin print_nl("spacefactor "); print_int(a.hh.lh);
  3756.   if m>0 then@+ if a.hh.rh>0 then
  3757.     begin print(", current language "); print_int(a.hh.rh);@+
  3758.     end;
  3759.   end;
  3760. 2: if a.int<>null then
  3761.   begin print("this will be denominator of:"); show_box(a.int);@+
  3762.   end;
  3763. end {there are no other cases}
  3764. @* \[17] The table of equivalents.
  3765. Now that we have studied the data structures for \TeX's semantic routines,
  3766. we ought to consider the data structures used by its syntactic routines. In
  3767. other words, our next concern will be
  3768. the tables that \TeX\ looks at when it is scanning
  3769. what the user has written.
  3770. The biggest and most important such table is called |eqtb|. It holds the
  3771. current ``equivalents'' of things; i.e., it explains what things mean
  3772. or what their current values are, for all quantities that are subject to
  3773. the nesting structure provided by \TeX's grouping mechanism. There are six
  3774. parts to |eqtb|:
  3775. \yskip\hang 1) |eqtb[active_base..(hash_base-1)]| holds the current
  3776. equivalents of single-character control sequences.
  3777. \yskip\hang 2) |eqtb[hash_base..(glue_base-1)]| holds the current
  3778. equivalents of multiletter control sequences.
  3779. \yskip\hang 3) |eqtb[glue_base..(local_base-1)]| holds the current
  3780. equivalents of glue parameters like the current baselineskip.
  3781. \yskip\hang 4) |eqtb[local_base..(int_base-1)]| holds the current
  3782. equivalents of local halfword quantities like the current box registers,
  3783. the current ``catcodes,'' the current font, and a pointer to the current
  3784. paragraph shape.
  3785. \yskip\hang 5) |eqtb[int_base..(dimen_base-1)]| holds the current
  3786. equivalents of fullword integer parameters like the current hyphenation
  3787. penalty.
  3788. \yskip\hang 6) |eqtb[dimen_base..eqtb_size]| holds the current equivalents
  3789. of fullword dimension parameters like the current hsize or amount of
  3790. hanging indentation.
  3791. \yskip\noindent Note that, for example, the current amount of
  3792. baselineskip glue is determined by the setting of a particular location
  3793. in region~3 of |eqtb|, while the current meaning of the control sequence
  3794. `\.{\\baselineskip}' (which might have been changed by \.{\\def} or
  3795. \.{\\let}) appears in region~2.
  3796. @ Each entry in |eqtb| is a |memory_word|. Most of these words are of type
  3797. |two_halves|, and subdivided into three fields:
  3798. \yskip\hang 1) The |eq_level| (a quarterword) is the level of grouping at
  3799. which this equivalent was defined. If the level is |level_zero|, the
  3800. equivalent has never been defined; |level_one| refers to the outer level
  3801. (outside of all groups), and this level is also used for global
  3802. definitions that never go away. Higher levels are for equivalents that
  3803. will disappear at the end of their group.  @^global definitions@>
  3804. \yskip\hang 2) The |eq_type| (another quarterword) specifies what kind of
  3805. entry this is. There are many types, since each \TeX\ primitive like
  3806. \.{\\hbox}, \.{\\def}, etc., has its own special code. The list of
  3807. command codes above includes all possible settings of the |eq_type| field.
  3808. \yskip\hang 3) The |equiv| (a halfword) is the current equivalent value.
  3809. This may be a font number, a pointer into |mem|, or a variety of other
  3810. things.
  3811. @d eq_level_field(#)==#.hh.b1
  3812. @d eq_type_field(#)==#.hh.b0
  3813. @d equiv_field(#)==#.hh.rh
  3814. @d eq_level(#)==eq_level_field(eqtb[#]) {level of definition}
  3815. @d eq_type(#)==eq_type_field(eqtb[#]) {command code for equivalent}
  3816. @d equiv(#)==equiv_field(eqtb[#]) {equivalent value}
  3817. @d level_zero=min_quarterword {level for undefined quantities}
  3818. @d level_one=level_zero+1 {outermost level for defined quantities}
  3819. @ Many locations in |eqtb| have symbolic names. The purpose of the next
  3820. paragraphs is to define these names, and to set up the initial values of the
  3821. equivalents.
  3822. In the first region we have 256 equivalents for ``active characters'' that
  3823. act as control sequences, followed by 256 equivalents for single-character
  3824. control sequences.
  3825. Then comes region~2, which corresponds to the hash table that we will
  3826. define later.  The maximum address in this region is used for a dummy
  3827. control sequence that is perpetually undefined. There also are several
  3828. locations for control sequences that are perpetually defined
  3829. (since they are used in error recovery).
  3830. @d active_base=1 {beginning of region 1, for active character equivalents}
  3831. @d single_base=active_base+256 {equivalents of one-character control sequences}
  3832. @d null_cs=single_base+256 {equivalent of \.{\\csname\\endcsname}}
  3833. @d hash_base=null_cs+1 {beginning of region 2, for the hash table}
  3834. @d frozen_control_sequence=hash_base+hash_size {for error recovery}
  3835. @d frozen_protection=frozen_control_sequence {inaccessible but definable}
  3836. @d frozen_cr=frozen_control_sequence+1 {permanent `\.{\\cr}'}
  3837. @d frozen_end_group=frozen_control_sequence+2 {permanent `\.{\\endgroup}'}
  3838. @d frozen_right=frozen_control_sequence+3 {permanent `\.{\\right}'}
  3839. @d frozen_fi=frozen_control_sequence+4 {permanent `\.{\\fi}'}
  3840. @d frozen_end_template=frozen_control_sequence+5 {permanent `\.{\\endtemplate}'}
  3841. @d frozen_endv=frozen_control_sequence+6 {second permanent `\.{\\endtemplate}'}
  3842. @d frozen_relax=frozen_control_sequence+7 {permanent `\.{\\relax}'}
  3843. @d end_write=frozen_control_sequence+8 {permanent `\.{\\endwrite}'}
  3844. @d frozen_dont_expand=frozen_control_sequence+9
  3845.   {permanent `\.{\\notexpanded:}'}
  3846. @d frozen_null_font=frozen_control_sequence+10
  3847.   {permanent `\.{\\nullfont}'}
  3848. @d font_id_base=frozen_null_font-font_base
  3849.   {begins table of 257 permanent font identifiers}
  3850. @d undefined_control_sequence=frozen_null_font+257 {dummy location}
  3851. @d glue_base=undefined_control_sequence+1 {beginning of region 3}
  3852. @<Initialize table entries...@>=
  3853. eq_type(undefined_control_sequence):=undefined_cs;
  3854. equiv(undefined_control_sequence):=null;
  3855. eq_level(undefined_control_sequence):=level_zero;
  3856. for k:=active_base to undefined_control_sequence-1 do
  3857.   eqtb[k]:=eqtb[undefined_control_sequence];
  3858. @ Here is a routine that displays the current meaning of an |eqtb| entry
  3859. in region 1 or~2. (Similar routines for the other regions will appear
  3860. below.)
  3861. @<Show equivalent |n|, in region 1 or 2@>=
  3862. begin sprint_cs(n); print_char("="); print_cmd_chr(eq_type(n),equiv(n));
  3863. if eq_type(n)>=call then
  3864.   begin print_char(":"); show_token_list(link(equiv(n)),null,32);
  3865.   end;
  3866. @ Region 3 of |eqtb| contains the 256 \.{\\skip} registers, as well as the
  3867. glue parameters defined here. It is important that the ``muskip''
  3868. parameters have larger numbers than the others.
  3869. @d line_skip_code=0 {interline glue if |baseline_skip| is infeasible}
  3870. @d baseline_skip_code=1 {desired glue between baselines}
  3871. @d par_skip_code=2 {extra glue just above a paragraph}
  3872. @d above_display_skip_code=3 {extra glue just above displayed math}
  3873. @d below_display_skip_code=4 {extra glue just below displayed math}
  3874. @d above_display_short_skip_code=5
  3875.   {glue above displayed math following short lines}
  3876. @d below_display_short_skip_code=6
  3877.   {glue below displayed math following short lines}
  3878. @d left_skip_code=7 {glue at left of justified lines}
  3879. @d right_skip_code=8 {glue at right of justified lines}
  3880. @d top_skip_code=9 {glue at top of main pages}
  3881. @d split_top_skip_code=10 {glue at top of split pages}
  3882. @d tab_skip_code=11 {glue between aligned entries}
  3883. @d space_skip_code=12 {glue between words (if not |zero_glue|)}
  3884. @d xspace_skip_code=13 {glue after sentences (if not |zero_glue|)}
  3885. @d par_fill_skip_code=14 {glue on last line of paragraph}
  3886. @d thin_mu_skip_code=15 {thin space in math formula}
  3887. @d med_mu_skip_code=16 {medium space in math formula}
  3888. @d thick_mu_skip_code=17 {thick space in math formula}
  3889. @d glue_pars=18 {total number of glue parameters}
  3890. @d skip_base=glue_base+glue_pars {table of 256 ``skip'' registers}
  3891. @d mu_skip_base=skip_base+256 {table of 256 ``muskip'' registers}
  3892. @d local_base=mu_skip_base+256 {beginning of region 4}
  3893. @d skip(#)==equiv(skip_base+#) {|mem| location of glue specification}
  3894. @d mu_skip(#)==equiv(mu_skip_base+#) {|mem| location of math glue spec}
  3895. @d glue_par(#)==equiv(glue_base+#) {|mem| location of glue specification}
  3896. @d line_skip==glue_par(line_skip_code)
  3897. @d baseline_skip==glue_par(baseline_skip_code)
  3898. @d par_skip==glue_par(par_skip_code)
  3899. @d above_display_skip==glue_par(above_display_skip_code)
  3900. @d below_display_skip==glue_par(below_display_skip_code)
  3901. @d above_display_short_skip==glue_par(above_display_short_skip_code)
  3902. @d below_display_short_skip==glue_par(below_display_short_skip_code)
  3903. @d left_skip==glue_par(left_skip_code)
  3904. @d right_skip==glue_par(right_skip_code)
  3905. @d top_skip==glue_par(top_skip_code)
  3906. @d split_top_skip==glue_par(split_top_skip_code)
  3907. @d tab_skip==glue_par(tab_skip_code)
  3908. @d space_skip==glue_par(space_skip_code)
  3909. @d xspace_skip==glue_par(xspace_skip_code)
  3910. @d par_fill_skip==glue_par(par_fill_skip_code)
  3911. @d thin_mu_skip==glue_par(thin_mu_skip_code)
  3912. @d med_mu_skip==glue_par(med_mu_skip_code)
  3913. @d thick_mu_skip==glue_par(thick_mu_skip_code)
  3914. @<Current |mem| equivalent of glue parameter number |n|@>=glue_par(n)
  3915. @ Sometimes we need to convert \TeX's internal code numbers into symbolic
  3916. form. The |print_skip_param| routine gives the symbolic name of a glue
  3917. parameter.
  3918. @<Declare the procedure called |print_skip_param|@>=
  3919. procedure print_skip_param(@!n:integer);
  3920. begin case n of
  3921. line_skip_code: print_esc("lineskip");
  3922. baseline_skip_code: print_esc("baselineskip");
  3923. par_skip_code: print_esc("parskip");
  3924. above_display_skip_code: print_esc("abovedisplayskip");
  3925. below_display_skip_code: print_esc("belowdisplayskip");
  3926. above_display_short_skip_code: print_esc("abovedisplayshortskip");
  3927. below_display_short_skip_code: print_esc("belowdisplayshortskip");
  3928. left_skip_code: print_esc("leftskip");
  3929. right_skip_code: print_esc("rightskip");
  3930. top_skip_code: print_esc("topskip");
  3931. split_top_skip_code: print_esc("splittopskip");
  3932. tab_skip_code: print_esc("tabskip");
  3933. space_skip_code: print_esc("spaceskip");
  3934. xspace_skip_code: print_esc("xspaceskip");
  3935. par_fill_skip_code: print_esc("parfillskip");
  3936. thin_mu_skip_code: print_esc("thinmuskip");
  3937. med_mu_skip_code: print_esc("medmuskip");
  3938. thick_mu_skip_code: print_esc("thickmuskip");
  3939. othercases print("[unknown glue parameter!]")
  3940. endcases;
  3941. @ The symbolic names for glue parameters are put into \TeX's hash table
  3942. by using the routine called |primitive|, defined below. Let us enter them
  3943. now, so that we don't have to list all those parameter names anywhere else.
  3944. @<Put each of \TeX's primitives into the hash table@>=
  3945. primitive("lineskip",assign_glue,glue_base+line_skip_code);@/
  3946. @!@:line_skip_}{\.{\\lineskip} primitive@>
  3947. primitive("baselineskip",assign_glue,glue_base+baseline_skip_code);@/
  3948. @!@:baseline_skip_}{\.{\\baselineskip} primitive@>
  3949. primitive("parskip",assign_glue,glue_base+par_skip_code);@/
  3950. @!@:par_skip_}{\.{\\parskip} primitive@>
  3951. primitive("abovedisplayskip",assign_glue,glue_base+above_display_skip_code);@/
  3952. @!@:above_display_skip_}{\.{\\abovedisplayskip} primitive@>
  3953. primitive("belowdisplayskip",assign_glue,glue_base+below_display_skip_code);@/
  3954. @!@:below_display_skip_}{\.{\\belowdisplayskip} primitive@>
  3955. primitive("abovedisplayshortskip",
  3956.   assign_glue,glue_base+above_display_short_skip_code);@/
  3957. @!@:above_display_short_skip_}{\.{\\abovedisplayshortskip} primitive@>
  3958. primitive("belowdisplayshortskip",
  3959.   assign_glue,glue_base+below_display_short_skip_code);@/
  3960. @!@:below_display_short_skip_}{\.{\\belowdisplayshortskip} primitive@>
  3961. primitive("leftskip",assign_glue,glue_base+left_skip_code);@/
  3962. @!@:left_skip_}{\.{\\leftskip} primitive@>
  3963. primitive("rightskip",assign_glue,glue_base+right_skip_code);@/
  3964. @!@:right_skip_}{\.{\\rightskip} primitive@>
  3965. primitive("topskip",assign_glue,glue_base+top_skip_code);@/
  3966. @!@:top_skip_}{\.{\\topskip} primitive@>
  3967. primitive("splittopskip",assign_glue,glue_base+split_top_skip_code);@/
  3968. @!@:split_top_skip_}{\.{\\splittopskip} primitive@>
  3969. primitive("tabskip",assign_glue,glue_base+tab_skip_code);@/
  3970. @!@:tab_skip_}{\.{\\tabskip} primitive@>
  3971. primitive("spaceskip",assign_glue,glue_base+space_skip_code);@/
  3972. @!@:space_skip_}{\.{\\spaceskip} primitive@>
  3973. primitive("xspaceskip",assign_glue,glue_base+xspace_skip_code);@/
  3974. @!@:xspace_skip_}{\.{\\xspaceskip} primitive@>
  3975. primitive("parfillskip",assign_glue,glue_base+par_fill_skip_code);@/
  3976. @!@:par_fill_skip_}{\.{\\parfillskip} primitive@>
  3977. primitive("thinmuskip",assign_mu_glue,glue_base+thin_mu_skip_code);@/
  3978. @!@:thin_mu_skip_}{\.{\\thinmuskip} primitive@>
  3979. primitive("medmuskip",assign_mu_glue,glue_base+med_mu_skip_code);@/
  3980. @!@:med_mu_skip_}{\.{\\medmuskip} primitive@>
  3981. primitive("thickmuskip",assign_mu_glue,glue_base+thick_mu_skip_code);@/
  3982. @!@:thick_mu_skip_}{\.{\\thickmuskip} primitive@>
  3983. @ @<Cases of |print_cmd_chr| for symbolic printing of primitives@>=
  3984. assign_glue,assign_mu_glue: if chr_code<skip_base then
  3985.     print_skip_param(chr_code-glue_base)
  3986.   else if chr_code<mu_skip_base then
  3987.     begin print_esc("skip"); print_int(chr_code-skip_base);
  3988.     end
  3989.   else  begin print_esc("muskip"); print_int(chr_code-mu_skip_base);
  3990.     end;
  3991. @ All glue parameters and registers are initially `\.{0pt plus0pt minus0pt}'.
  3992. @<Initialize table entries...@>=
  3993. equiv(glue_base):=zero_glue; eq_level(glue_base):=level_one;
  3994. eq_type(glue_base):=glue_ref;
  3995. for k:=glue_base+1 to local_base-1 do eqtb[k]:=eqtb[glue_base];
  3996. glue_ref_count(zero_glue):=glue_ref_count(zero_glue)+local_base-glue_base;
  3997. @ @<Show equivalent |n|, in region 3@>=
  3998. if n<skip_base then
  3999.   begin print_skip_param(n-glue_base); print_char("=");
  4000.   if n<glue_base+thin_mu_skip_code then print_spec(equiv(n),"pt")
  4001.   else print_spec(equiv(n),"mu");
  4002.   end
  4003. else if n<mu_skip_base then
  4004.   begin print_esc("skip"); print_int(n-skip_base); print_char("=");
  4005.   print_spec(equiv(n),"pt");
  4006.   end
  4007. else  begin print_esc("muskip"); print_int(n-mu_skip_base); print_char("=");
  4008.   print_spec(equiv(n),"mu");
  4009.   end
  4010. @ Region 4 of |eqtb| contains the local quantities defined here. The
  4011. bulk of this region is taken up by five tables that are indexed by eight-bit
  4012. characters; these tables are important to both the syntactic and semantic
  4013. portions of \TeX. There are also a bunch of special things like font and
  4014. token parameters, as well as the tables of \.{\\toks} and \.{\\box}
  4015. registers.
  4016. @d par_shape_loc=local_base {specifies paragraph shape}
  4017. @d output_routine_loc=local_base+1 {points to token list for \.{\\output}}
  4018. @d every_par_loc=local_base+2 {points to token list for \.{\\everypar}}
  4019. @d every_math_loc=local_base+3 {points to token list for \.{\\everymath}}
  4020. @d every_display_loc=local_base+4 {points to token list for \.{\\everydisplay}}
  4021. @d every_hbox_loc=local_base+5 {points to token list for \.{\\everyhbox}}
  4022. @d every_vbox_loc=local_base+6 {points to token list for \.{\\everyvbox}}
  4023. @d every_job_loc=local_base+7 {points to token list for \.{\\everyjob}}
  4024. @d every_cr_loc=local_base+8 {points to token list for \.{\\everycr}}
  4025. @d err_help_loc=local_base+9 {points to token list for \.{\\errhelp}}
  4026. @d toks_base=local_base+10 {table of 256 token list registers}
  4027. @d box_base=toks_base+256 {table of 256 box registers}
  4028. @d cur_font_loc=box_base+256 {internal font number outside math mode}
  4029. @d math_font_base=cur_font_loc+1 {table of 48 math font numbers}
  4030. @d cat_code_base=math_font_base+48
  4031.   {table of 256 command codes (the ``catcodes'')}
  4032. @d lc_code_base=cat_code_base+256 {table of 256 lowercase mappings}
  4033. @d uc_code_base=lc_code_base+256 {table of 256 uppercase mappings}
  4034. @d sf_code_base=uc_code_base+256 {table of 256 spacefactor mappings}
  4035. @d math_code_base=sf_code_base+256 {table of 256 math mode mappings}
  4036. @d int_base=math_code_base+256 {beginning of region 5}
  4037. @d par_shape_ptr==equiv(par_shape_loc)
  4038. @d output_routine==equiv(output_routine_loc)
  4039. @d every_par==equiv(every_par_loc)
  4040. @d every_math==equiv(every_math_loc)
  4041. @d every_display==equiv(every_display_loc)
  4042. @d every_hbox==equiv(every_hbox_loc)
  4043. @d every_vbox==equiv(every_vbox_loc)
  4044. @d every_job==equiv(every_job_loc)
  4045. @d every_cr==equiv(every_cr_loc)
  4046. @d err_help==equiv(err_help_loc)
  4047. @d toks(#)==equiv(toks_base+#)
  4048. @d box(#)==equiv(box_base+#)
  4049. @d cur_font==equiv(cur_font_loc)
  4050. @d fam_fnt(#)==equiv(math_font_base+#)
  4051. @d cat_code(#)==equiv(cat_code_base+#)
  4052. @d lc_code(#)==equiv(lc_code_base+#)
  4053. @d uc_code(#)==equiv(uc_code_base+#)
  4054. @d sf_code(#)==equiv(sf_code_base+#)
  4055. @d math_code(#)==equiv(math_code_base+#)
  4056.   {Note: |math_code(c)| is the true math code plus |min_halfword|}
  4057. @<Put each...@>=
  4058. primitive("output",assign_toks,output_routine_loc);
  4059. @!@:output_}{\.{\\output} primitive@>
  4060. primitive("everypar",assign_toks,every_par_loc);
  4061. @!@:every_par_}{\.{\\everypar} primitive@>
  4062. primitive("everymath",assign_toks,every_math_loc);
  4063. @!@:every_math_}{\.{\\everymath} primitive@>
  4064. primitive("everydisplay",assign_toks,every_display_loc);
  4065. @!@:every_display_}{\.{\\everydisplay} primitive@>
  4066. primitive("everyhbox",assign_toks,every_hbox_loc);
  4067. @!@:every_hbox_}{\.{\\everyhbox} primitive@>
  4068. primitive("everyvbox",assign_toks,every_vbox_loc);
  4069. @!@:every_vbox_}{\.{\\everyvbox} primitive@>
  4070. primitive("everyjob",assign_toks,every_job_loc);
  4071. @!@:every_job_}{\.{\\everyjob} primitive@>
  4072. primitive("everycr",assign_toks,every_cr_loc);
  4073. @!@:every_cr_}{\.{\\everycr} primitive@>
  4074. primitive("errhelp",assign_toks,err_help_loc);
  4075. @!@:err_help_}{\.{\\errhelp} primitive@>
  4076. @ @<Cases of |print_cmd_chr|...@>=
  4077. assign_toks: if chr_code>=toks_base then
  4078.   begin print_esc("toks"); print_int(chr_code-toks_base);
  4079.   end
  4080. else  case chr_code of
  4081.   output_routine_loc: print_esc("output");
  4082.   every_par_loc: print_esc("everypar");
  4083.   every_math_loc: print_esc("everymath");
  4084.   every_display_loc: print_esc("everydisplay");
  4085.   every_hbox_loc: print_esc("everyhbox");
  4086.   every_vbox_loc: print_esc("everyvbox");
  4087.   every_job_loc: print_esc("everyjob");
  4088.   every_cr_loc: print_esc("everycr");
  4089.   othercases print_esc("errhelp")
  4090.   endcases;
  4091. @ We initialize most things to null or undefined values. An undefined font
  4092. is represented by the internal code |font_base|.
  4093. However, the character code tables are given initial values based on the
  4094. conventional interpretation of ASCII code. These initial values should
  4095. not be changed when \TeX\ is adapted for use with non-English languages;
  4096. all changes to the initialization conventions should be made in format
  4097. packages, not in \TeX\ itself, so that global interchange of formats is
  4098. possible.
  4099. @d null_font==font_base
  4100. @d var_code==@'70000 {math code meaning ``use the current family''}
  4101. @<Initialize table entries...@>=
  4102. par_shape_ptr:=null; eq_type(par_shape_loc):=shape_ref;
  4103. eq_level(par_shape_loc):=level_one;@/
  4104. for k:=output_routine_loc to toks_base+255 do
  4105.   eqtb[k]:=eqtb[undefined_control_sequence];
  4106. box(0):=null; eq_type(box_base):=box_ref; eq_level(box_base):=level_one;
  4107. for k:=box_base+1 to box_base+255 do eqtb[k]:=eqtb[box_base];
  4108. cur_font:=null_font; eq_type(cur_font_loc):=data;
  4109. eq_level(cur_font_loc):=level_one;@/
  4110. for k:=math_font_base to math_font_base+47 do eqtb[k]:=eqtb[cur_font_loc];
  4111. equiv(cat_code_base):=0; eq_type(cat_code_base):=data;
  4112. eq_level(cat_code_base):=level_one;@/
  4113. for k:=cat_code_base+1 to int_base-1 do eqtb[k]:=eqtb[cat_code_base];
  4114. for k:=0 to 255 do
  4115.   begin cat_code(k):=other_char; math_code(k):=hi(k); sf_code(k):=1000;
  4116.   end;
  4117. cat_code(carriage_return):=car_ret; cat_code(" "):=spacer;
  4118. cat_code("\"):=escape; cat_code("%"):=comment;
  4119. cat_code(invalid_code):=invalid_char; cat_code(null_code):=ignore;
  4120. for k:="0" to "9" do math_code(k):=hi(k+var_code);
  4121. for k:="A" to "Z" do
  4122.   begin cat_code(k):=letter; cat_code(k+"a"-"A"):=letter;@/
  4123.   math_code(k):=hi(k+var_code+@"100);
  4124.   math_code(k+"a"-"A"):=hi(k+"a"-"A"+var_code+@"100);@/
  4125.   lc_code(k):=k+"a"-"A"; lc_code(k+"a"-"A"):=k+"a"-"A";@/
  4126.   uc_code(k):=k; uc_code(k+"a"-"A"):=k;@/
  4127.   sf_code(k):=999;
  4128.   end;
  4129. @ @<Show equivalent |n|, in region 4@>=
  4130. if n=par_shape_loc then
  4131.   begin print_esc("parshape"); print_char("=");
  4132.   if par_shape_ptr=null then print_char("0")
  4133.   else print_int(info(par_shape_ptr));
  4134.   end
  4135. else if n<toks_base then
  4136.   begin print_cmd_chr(assign_toks,n); print_char("=");
  4137.   if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
  4138.   end
  4139. else if n<box_base then
  4140.   begin print_esc("toks"); print_int(n-toks_base); print_char("=");
  4141.   if equiv(n)<>null then show_token_list(link(equiv(n)),null,32);
  4142.   end
  4143. else if n<cur_font_loc then
  4144.   begin print_esc("box"); print_int(n-box_base); print_char("=");
  4145.   if equiv(n)=null then print("void")
  4146.   else  begin depth_threshold:=0; breadth_max:=1; show_node_list(equiv(n));
  4147.     end;
  4148.   end
  4149. else if n<cat_code_base then @<Show the font identifier in |eqtb[n]|@>
  4150. else @<Show the halfword code in |eqtb[n]|@>
  4151. @ @<Show the font identifier in |eqtb[n]|@>=
  4152. begin if n=cur_font_loc then print("current font")
  4153. else if n<math_font_base+16 then
  4154.   begin print_esc("textfont"); print_int(n-math_font_base);
  4155.   end
  4156. else if n<math_font_base+32 then
  4157.   begin print_esc("scriptfont"); print_int(n-math_font_base-16);
  4158.   end
  4159. else  begin print_esc("scriptscriptfont"); print_int(n-math_font_base-32);
  4160.   end;
  4161. print_char("=");@/
  4162. print_esc(hash[font_id_base+equiv(n)].rh);
  4163.   {that's |font_id_text(equiv(n))|}
  4164. @ @<Show the halfword code in |eqtb[n]|@>=
  4165. if n<math_code_base then
  4166.   begin if n<lc_code_base then
  4167.     begin print_esc("catcode"); print_int(n-cat_code_base);
  4168.     end
  4169.   else if n<uc_code_base then
  4170.     begin print_esc("lccode"); print_int(n-lc_code_base);
  4171.     end
  4172.   else if n<sf_code_base then
  4173.     begin print_esc("uccode"); print_int(n-uc_code_base);
  4174.     end
  4175.   else  begin print_esc("sfcode"); print_int(n-sf_code_base);
  4176.     end;
  4177.   print_char("="); print_int(equiv(n));
  4178.   end
  4179. else  begin print_esc("mathcode"); print_int(n-math_code_base);
  4180.   print_char("="); print_int(ho(equiv(n)));
  4181.   end
  4182. @ Region 5 of |eqtb| contains the integer parameters and registers defined
  4183. here, as well as the |del_code| table. The latter table differs from the
  4184. |cat_code..math_code| tables that precede it, since delimiter codes are
  4185. fullword integers while the other kinds of codes occupy at most a
  4186. halfword. This is what makes region~5 different from region~4. We will
  4187. store the |eq_level| information in an auxiliary array of quarterwords
  4188. that will be defined later.
  4189. @d pretolerance_code=0 {badness tolerance before hyphenation}
  4190. @d tolerance_code=1 {badness tolerance after hyphenation}
  4191. @d line_penalty_code=2 {added to the badness of every line}
  4192. @d hyphen_penalty_code=3 {penalty for break after discretionary hyphen}
  4193. @d ex_hyphen_penalty_code=4 {penalty for break after explicit hyphen}
  4194. @d club_penalty_code=5 {penalty for creating a club line}
  4195. @d widow_penalty_code=6 {penalty for creating a widow line}
  4196. @d display_widow_penalty_code=7 {ditto, just before a display}
  4197. @d broken_penalty_code=8 {penalty for breaking a page at a broken line}
  4198. @d bin_op_penalty_code=9 {penalty for breaking after a binary operation}
  4199. @d rel_penalty_code=10 {penalty for breaking after a relation}
  4200. @d pre_display_penalty_code=11
  4201.   {penalty for breaking just before a displayed formula}
  4202. @d post_display_penalty_code=12
  4203.   {penalty for breaking just after a displayed formula}
  4204. @d inter_line_penalty_code=13 {additional penalty between lines}
  4205. @d double_hyphen_demerits_code=14 {demerits for double hyphen break}
  4206. @d final_hyphen_demerits_code=15 {demerits for final hyphen break}
  4207. @d adj_demerits_code=16 {demerits for adjacent incompatible lines}
  4208. @d mag_code=17 {magnification ratio}
  4209. @d delimiter_factor_code=18 {ratio for variable-size delimiters}
  4210. @d looseness_code=19 {change in number of lines for a paragraph}
  4211. @d time_code=20 {current time of day}
  4212. @d day_code=21 {current day of the month}
  4213. @d month_code=22 {current month of the year}
  4214. @d year_code=23 {current year of our Lord}
  4215. @d show_box_breadth_code=24 {nodes per level in |show_box|}
  4216. @d show_box_depth_code=25 {maximum level in |show_box|}
  4217. @d hbadness_code=26 {hboxes exceeding this badness will be shown by |hpack|}
  4218. @d vbadness_code=27 {vboxes exceeding this badness will be shown by |vpack|}
  4219. @d pausing_code=28 {pause after each line is read from a file}
  4220. @d tracing_online_code=29 {show diagnostic output on terminal}
  4221. @d tracing_macros_code=30 {show macros as they are being expanded}
  4222. @d tracing_stats_code=31 {show memory usage if \TeX\ knows it}
  4223. @d tracing_paragraphs_code=32 {show line-break calculations}
  4224. @d tracing_pages_code=33 {show page-break calculations}
  4225. @d tracing_output_code=34 {show boxes when they are shipped out}
  4226. @d tracing_lost_chars_code=35 {show characters that aren't in the font}
  4227. @d tracing_commands_code=36 {show command codes at |big_switch|}
  4228. @d tracing_restores_code=37 {show equivalents when they are restored}
  4229. @d uc_hyph_code=38 {hyphenate words beginning with a capital letter}
  4230. @d output_penalty_code=39 {penalty found at current page break}
  4231. @d max_dead_cycles_code=40 {bound on consecutive dead cycles of output}
  4232. @d hang_after_code=41 {hanging indentation changes after this many lines}
  4233. @d floating_penalty_code=42 {penalty for insertions heldover after a split}
  4234. @d global_defs_code=43 {override \.{\\global} specifications}
  4235. @d cur_fam_code=44 {current family}
  4236. @d escape_char_code=45 {escape character for token output}
  4237. @d default_hyphen_char_code=46 {value of \.{\\hyphenchar} when a font is loaded}
  4238. @d default_skew_char_code=47 {value of \.{\\skewchar} when a font is loaded}
  4239. @d end_line_char_code=48 {character placed at the right end of the buffer}
  4240. @d new_line_char_code=49 {character that prints as |print_ln|}
  4241. @d language_code=50 {current hyphenation table}
  4242. @d left_hyphen_min_code=51 {minimum left hyphenation fragment size}
  4243. @d right_hyphen_min_code=52 {minimum right hyphenation fragment size}
  4244. @d holding_inserts_code=53 {do not remove insertion nodes from \.{\\box255}}
  4245. @d error_context_lines_code=54 {maximum intermediate line pairs shown}
  4246. @d int_pars=55 {total number of integer parameters}
  4247. @d count_base=int_base+int_pars {256 user \.{\\count} registers}
  4248. @d del_code_base=count_base+256 {256 delimiter code mappings}
  4249. @d dimen_base=del_code_base+256 {beginning of region 6}
  4250. @d del_code(#)==eqtb[del_code_base+#].int
  4251. @d count(#)==eqtb[count_base+#].int
  4252. @d int_par(#)==eqtb[int_base+#].int {an integer parameter}
  4253. @d pretolerance==int_par(pretolerance_code)
  4254. @d tolerance==int_par(tolerance_code)
  4255. @d line_penalty==int_par(line_penalty_code)
  4256. @d hyphen_penalty==int_par(hyphen_penalty_code)
  4257. @d ex_hyphen_penalty==int_par(ex_hyphen_penalty_code)
  4258. @d club_penalty==int_par(club_penalty_code)
  4259. @d widow_penalty==int_par(widow_penalty_code)
  4260. @d display_widow_penalty==int_par(display_widow_penalty_code)
  4261. @d broken_penalty==int_par(broken_penalty_code)
  4262. @d bin_op_penalty==int_par(bin_op_penalty_code)
  4263. @d rel_penalty==int_par(rel_penalty_code)
  4264. @d pre_display_penalty==int_par(pre_display_penalty_code)
  4265. @d post_display_penalty==int_par(post_display_penalty_code)
  4266. @d inter_line_penalty==int_par(inter_line_penalty_code)
  4267. @d double_hyphen_demerits==int_par(double_hyphen_demerits_code)
  4268. @d final_hyphen_demerits==int_par(final_hyphen_demerits_code)
  4269. @d adj_demerits==int_par(adj_demerits_code)
  4270. @d mag==int_par(mag_code)
  4271. @d delimiter_factor==int_par(delimiter_factor_code)
  4272. @d looseness==int_par(looseness_code)
  4273. @d time==int_par(time_code)
  4274. @d day==int_par(day_code)
  4275. @d month==int_par(month_code)
  4276. @d year==int_par(year_code)
  4277. @d show_box_breadth==int_par(show_box_breadth_code)
  4278. @d show_box_depth==int_par(show_box_depth_code)
  4279. @d hbadness==int_par(hbadness_code)
  4280. @d vbadness==int_par(vbadness_code)
  4281. @d pausing==int_par(pausing_code)
  4282. @d tracing_online==int_par(tracing_online_code)
  4283. @d tracing_macros==int_par(tracing_macros_code)
  4284. @d tracing_stats==int_par(tracing_stats_code)
  4285. @d tracing_paragraphs==int_par(tracing_paragraphs_code)
  4286. @d tracing_pages==int_par(tracing_pages_code)
  4287. @d tracing_output==int_par(tracing_output_code)
  4288. @d tracing_lost_chars==int_par(tracing_lost_chars_code)
  4289. @d tracing_commands==int_par(tracing_commands_code)
  4290. @d tracing_restores==int_par(tracing_restores_code)
  4291. @d uc_hyph==int_par(uc_hyph_code)
  4292. @d output_penalty==int_par(output_penalty_code)
  4293. @d max_dead_cycles==int_par(max_dead_cycles_code)
  4294. @d hang_after==int_par(hang_after_code)
  4295. @d floating_penalty==int_par(floating_penalty_code)
  4296. @d global_defs==int_par(global_defs_code)
  4297. @d cur_fam==int_par(cur_fam_code)
  4298. @d escape_char==int_par(escape_char_code)
  4299. @d default_hyphen_char==int_par(default_hyphen_char_code)
  4300. @d default_skew_char==int_par(default_skew_char_code)
  4301. @d end_line_char==int_par(end_line_char_code)
  4302. @d new_line_char==int_par(new_line_char_code)
  4303. @d language==int_par(language_code)
  4304. @d left_hyphen_min==int_par(left_hyphen_min_code)
  4305. @d right_hyphen_min==int_par(right_hyphen_min_code)
  4306. @d holding_inserts==int_par(holding_inserts_code)
  4307. @d error_context_lines==int_par(error_context_lines_code)
  4308. @<Assign the values |depth_threshold:=show_box_depth|...@>=
  4309. depth_threshold:=show_box_depth;
  4310. breadth_max:=show_box_breadth
  4311. @ We can print the symbolic name of an integer parameter as follows.
  4312. @p procedure print_param(@!n:integer);
  4313. begin case n of
  4314. pretolerance_code:print_esc("pretolerance");
  4315. tolerance_code:print_esc("tolerance");
  4316. line_penalty_code:print_esc("linepenalty");
  4317. hyphen_penalty_code:print_esc("hyphenpenalty");
  4318. ex_hyphen_penalty_code:print_esc("exhyphenpenalty");
  4319. club_penalty_code:print_esc("clubpenalty");
  4320. widow_penalty_code:print_esc("widowpenalty");
  4321. display_widow_penalty_code:print_esc("displaywidowpenalty");
  4322. broken_penalty_code:print_esc("brokenpenalty");
  4323. bin_op_penalty_code:print_esc("binoppenalty");
  4324. rel_penalty_code:print_esc("relpenalty");
  4325. pre_display_penalty_code:print_esc("predisplaypenalty");
  4326. post_display_penalty_code:print_esc("postdisplaypenalty");
  4327. inter_line_penalty_code:print_esc("interlinepenalty");
  4328. double_hyphen_demerits_code:print_esc("doublehyphendemerits");
  4329. final_hyphen_demerits_code:print_esc("finalhyphendemerits");
  4330. adj_demerits_code:print_esc("adjdemerits");
  4331. mag_code:print_esc("mag");
  4332. delimiter_factor_code:print_esc("delimiterfactor");
  4333. looseness_code:print_esc("looseness");
  4334. time_code:print_esc("time");
  4335. day_code:print_esc("day");
  4336. month_code:print_esc("month");
  4337. year_code:print_esc("year");
  4338. show_box_breadth_code:print_esc("showboxbreadth");
  4339. show_box_depth_code:print_esc("showboxdepth");
  4340. hbadness_code:print_esc("hbadness");
  4341. vbadness_code:print_esc("vbadness");
  4342. pausing_code:print_esc("pausing");
  4343. tracing_online_code:print_esc("tracingonline");
  4344. tracing_macros_code:print_esc("tracingmacros");
  4345. tracing_stats_code:print_esc("tracingstats");
  4346. tracing_paragraphs_code:print_esc("tracingparagraphs");
  4347. tracing_pages_code:print_esc("tracingpages");
  4348. tracing_output_code:print_esc("tracingoutput");
  4349. tracing_lost_chars_code:print_esc("tracinglostchars");
  4350. tracing_commands_code:print_esc("tracingcommands");
  4351. tracing_restores_code:print_esc("tracingrestores");
  4352. uc_hyph_code:print_esc("uchyph");
  4353. output_penalty_code:print_esc("outputpenalty");
  4354. max_dead_cycles_code:print_esc("maxdeadcycles");
  4355. hang_after_code:print_esc("hangafter");
  4356. floating_penalty_code:print_esc("floatingpenalty");
  4357. global_defs_code:print_esc("globaldefs");
  4358. cur_fam_code:print_esc("fam");
  4359. escape_char_code:print_esc("escapechar");
  4360. default_hyphen_char_code:print_esc("defaulthyphenchar");
  4361. default_skew_char_code:print_esc("defaultskewchar");
  4362. end_line_char_code:print_esc("endlinechar");
  4363. new_line_char_code:print_esc("newlinechar");
  4364. language_code:print_esc("language");
  4365. left_hyphen_min_code:print_esc("lefthyphenmin");
  4366. right_hyphen_min_code:print_esc("righthyphenmin");
  4367. holding_inserts_code:print_esc("holdinginserts");
  4368. error_context_lines_code:print_esc("errorcontextlines");
  4369. othercases print("[unknown integer parameter!]")
  4370. endcases;
  4371. @ The integer parameter names must be entered into the hash table.
  4372. @<Put each...@>=
  4373. primitive("pretolerance",assign_int,int_base+pretolerance_code);@/
  4374. @!@:pretolerance_}{\.{\\pretolerance} primitive@>
  4375. primitive("tolerance",assign_int,int_base+tolerance_code);@/
  4376. @!@:tolerance_}{\.{\\tolerance} primitive@>
  4377. primitive("linepenalty",assign_int,int_base+line_penalty_code);@/
  4378. @!@:line_penalty_}{\.{\\linepenalty} primitive@>
  4379. primitive("hyphenpenalty",assign_int,int_base+hyphen_penalty_code);@/
  4380. @!@:hyphen_penalty_}{\.{\\hyphenpenalty} primitive@>
  4381. primitive("exhyphenpenalty",assign_int,int_base+ex_hyphen_penalty_code);@/
  4382. @!@:ex_hyphen_penalty_}{\.{\\exhyphenpenalty} primitive@>
  4383. primitive("clubpenalty",assign_int,int_base+club_penalty_code);@/
  4384. @!@:club_penalty_}{\.{\\clubpenalty} primitive@>
  4385. primitive("widowpenalty",assign_int,int_base+widow_penalty_code);@/
  4386. @!@:widow_penalty_}{\.{\\widowpenalty} primitive@>
  4387. primitive("displaywidowpenalty",
  4388.   assign_int,int_base+display_widow_penalty_code);@/
  4389. @!@:display_widow_penalty_}{\.{\\displaywidowpenalty} primitive@>
  4390. primitive("brokenpenalty",assign_int,int_base+broken_penalty_code);@/
  4391. @!@:broken_penalty_}{\.{\\brokenpenalty} primitive@>
  4392. primitive("binoppenalty",assign_int,int_base+bin_op_penalty_code);@/
  4393. @!@:bin_op_penalty_}{\.{\\binoppenalty} primitive@>
  4394. primitive("relpenalty",assign_int,int_base+rel_penalty_code);@/
  4395. @!@:rel_penalty_}{\.{\\relpenalty} primitive@>
  4396. primitive("predisplaypenalty",assign_int,int_base+pre_display_penalty_code);@/
  4397. @!@:pre_display_penalty_}{\.{\\predisplaypenalty} primitive@>
  4398. primitive("postdisplaypenalty",assign_int,int_base+post_display_penalty_code);@/
  4399. @!@:post_display_penalty_}{\.{\\postdisplaypenalty} primitive@>
  4400. primitive("interlinepenalty",assign_int,int_base+inter_line_penalty_code);@/
  4401. @!@:inter_line_penalty_}{\.{\\interlinepenalty} primitive@>
  4402. primitive("doublehyphendemerits",
  4403.   assign_int,int_base+double_hyphen_demerits_code);@/
  4404. @!@:double_hyphen_demerits_}{\.{\\doublehyphendemerits} primitive@>
  4405. primitive("finalhyphendemerits",
  4406.   assign_int,int_base+final_hyphen_demerits_code);@/
  4407. @!@:final_hyphen_demerits_}{\.{\\finalhyphendemerits} primitive@>
  4408. primitive("adjdemerits",assign_int,int_base+adj_demerits_code);@/
  4409. @!@:adj_demerits_}{\.{\\adjdemerits} primitive@>
  4410. primitive("mag",assign_int,int_base+mag_code);@/
  4411. @!@:mag_}{\.{\\mag} primitive@>
  4412. primitive("delimiterfactor",assign_int,int_base+delimiter_factor_code);@/
  4413. @!@:delimiter_factor_}{\.{\\delimiterfactor} primitive@>
  4414. primitive("looseness",assign_int,int_base+looseness_code);@/
  4415. @!@:looseness_}{\.{\\looseness} primitive@>
  4416. primitive("time",assign_int,int_base+time_code);@/
  4417. @!@:time_}{\.{\\time} primitive@>
  4418. primitive("day",assign_int,int_base+day_code);@/
  4419. @!@:day_}{\.{\\day} primitive@>
  4420. primitive("month",assign_int,int_base+month_code);@/
  4421. @!@:month_}{\.{\\month} primitive@>
  4422. primitive("year",assign_int,int_base+year_code);@/
  4423. @!@:year_}{\.{\\year} primitive@>
  4424. primitive("showboxbreadth",assign_int,int_base+show_box_breadth_code);@/
  4425. @!@:show_box_breadth_}{\.{\\showboxbreadth} primitive@>
  4426. primitive("showboxdepth",assign_int,int_base+show_box_depth_code);@/
  4427. @!@:show_box_depth_}{\.{\\showboxdepth} primitive@>
  4428. primitive("hbadness",assign_int,int_base+hbadness_code);@/
  4429. @!@:hbadness_}{\.{\\hbadness} primitive@>
  4430. primitive("vbadness",assign_int,int_base+vbadness_code);@/
  4431. @!@:vbadness_}{\.{\\vbadness} primitive@>
  4432. primitive("pausing",assign_int,int_base+pausing_code);@/
  4433. @!@:pausing_}{\.{\\pausing} primitive@>
  4434. primitive("tracingonline",assign_int,int_base+tracing_online_code);@/
  4435. @!@:tracing_online_}{\.{\\tracingonline} primitive@>
  4436. primitive("tracingmacros",assign_int,int_base+tracing_macros_code);@/
  4437. @!@:tracing_macros_}{\.{\\tracingmacros} primitive@>
  4438. primitive("tracingstats",assign_int,int_base+tracing_stats_code);@/
  4439. @!@:tracing_stats_}{\.{\\tracingstats} primitive@>
  4440. primitive("tracingparagraphs",assign_int,int_base+tracing_paragraphs_code);@/
  4441. @!@:tracing_paragraphs_}{\.{\\tracingparagraphs} primitive@>
  4442. primitive("tracingpages",assign_int,int_base+tracing_pages_code);@/
  4443. @!@:tracing_pages_}{\.{\\tracingpages} primitive@>
  4444. primitive("tracingoutput",assign_int,int_base+tracing_output_code);@/
  4445. @!@:tracing_output_}{\.{\\tracingoutput} primitive@>
  4446. primitive("tracinglostchars",assign_int,int_base+tracing_lost_chars_code);@/
  4447. @!@:tracing_lost_chars_}{\.{\\tracinglostchars} primitive@>
  4448. primitive("tracingcommands",assign_int,int_base+tracing_commands_code);@/
  4449. @!@:tracing_commands_}{\.{\\tracingcommands} primitive@>
  4450. primitive("tracingrestores",assign_int,int_base+tracing_restores_code);@/
  4451. @!@:tracing_restores_}{\.{\\tracingrestores} primitive@>
  4452. primitive("uchyph",assign_int,int_base+uc_hyph_code);@/
  4453. @!@:uc_hyph_}{\.{\\uchyph} primitive@>
  4454. primitive("outputpenalty",assign_int,int_base+output_penalty_code);@/
  4455. @!@:output_penalty_}{\.{\\outputpenalty} primitive@>
  4456. primitive("maxdeadcycles",assign_int,int_base+max_dead_cycles_code);@/
  4457. @!@:max_dead_cycles_}{\.{\\maxdeadcycles} primitive@>
  4458. primitive("hangafter",assign_int,int_base+hang_after_code);@/
  4459. @!@:hang_after_}{\.{\\hangafter} primitive@>
  4460. primitive("floatingpenalty",assign_int,int_base+floating_penalty_code);@/
  4461. @!@:floating_penalty_}{\.{\\floatingpenalty} primitive@>
  4462. primitive("globaldefs",assign_int,int_base+global_defs_code);@/
  4463. @!@:global_defs_}{\.{\\globaldefs} primitive@>
  4464. primitive("fam",assign_int,int_base+cur_fam_code);@/
  4465. @!@:fam_}{\.{\\fam} primitive@>
  4466. primitive("escapechar",assign_int,int_base+escape_char_code);@/
  4467. @!@:escape_char_}{\.{\\escapechar} primitive@>
  4468. primitive("defaulthyphenchar",assign_int,int_base+default_hyphen_char_code);@/
  4469. @!@:default_hyphen_char_}{\.{\\defaulthyphenchar} primitive@>
  4470. primitive("defaultskewchar",assign_int,int_base+default_skew_char_code);@/
  4471. @!@:default_skew_char_}{\.{\\defaultskewchar} primitive@>
  4472. primitive("endlinechar",assign_int,int_base+end_line_char_code);@/
  4473. @!@:end_line_char_}{\.{\\endlinechar} primitive@>
  4474. primitive("newlinechar",assign_int,int_base+new_line_char_code);@/
  4475. @!@:new_line_char_}{\.{\\newlinechar} primitive@>
  4476. primitive("language",assign_int,int_base+language_code);@/
  4477. @!@:language_}{\.{\\language} primitive@>
  4478. primitive("lefthyphenmin",assign_int,int_base+left_hyphen_min_code);@/
  4479. @!@:left_hyphen_min_}{\.{\\lefthyphenmin} primitive@>
  4480. primitive("righthyphenmin",assign_int,int_base+right_hyphen_min_code);@/
  4481. @!@:right_hyphen_min_}{\.{\\righthyphenmin} primitive@>
  4482. primitive("holdinginserts",assign_int,int_base+holding_inserts_code);@/
  4483. @!@:holding_inserts_}{\.{\\holdinginserts} primitive@>
  4484. primitive("errorcontextlines",assign_int,int_base+error_context_lines_code);@/
  4485. @!@:error_context_lines_}{\.{\\errorcontextlines} primitive@>
  4486. @ @<Cases of |print_cmd_chr|...@>=
  4487. assign_int: if chr_code<count_base then print_param(chr_code-int_base)
  4488.   else  begin print_esc("count"); print_int(chr_code-count_base);
  4489.     end;
  4490. @ The integer parameters should really be initialized by a macro package;
  4491. the following initialization does the minimum to keep \TeX\ from
  4492. complete failure.
  4493. @^null delimiter@>
  4494. @<Initialize table entries...@>=
  4495. for k:=int_base to del_code_base-1 do eqtb[k].int:=0;
  4496. mag:=1000; tolerance:=10000; hang_after:=1; max_dead_cycles:=25;
  4497. escape_char:="\"; end_line_char:=carriage_return;
  4498. for k:=0 to 255 do del_code(k):=-1;
  4499. del_code("."):=0; {this null delimiter is used in error recovery}
  4500. @ The following procedure, which is called just before \TeX\ initializes its
  4501. input and output, establishes the initial values of the date and time.
  4502. @^system dependencies@>
  4503. Since standard \PASCAL\ cannot provide such information, something special
  4504. is needed. The program here simply specifies July 4, 1776, at noon; but
  4505. users probably want a better approximation to the truth.
  4506. @p procedure fix_date_and_time;
  4507. begin time:=12*60; {minutes since midnight}
  4508. day:=4; {fourth day of the month}
  4509. month:=7; {seventh month of the year}
  4510. year:=1776; {Anno Domini}
  4511. @ @<Show equivalent |n|, in region 5@>=
  4512. begin if n<count_base then print_param(n-int_base)
  4513. else if  n<del_code_base then
  4514.   begin print_esc("count"); print_int(n-count_base);
  4515.   end
  4516. else  begin print_esc("delcode"); print_int(n-del_code_base);
  4517.   end;
  4518. print_char("="); print_int(eqtb[n].int);
  4519. @ @<Set variable |c| to the current escape character@>=c:=escape_char
  4520. @ @<Character |s| is the current new-line character@>=s=new_line_char
  4521. @ \TeX\ is occasionally supposed to print diagnostic information that
  4522. goes only into the transcript file, unless |tracing_online| is positive.
  4523. Here are two routines that adjust the destination of print commands:
  4524. @p procedure begin_diagnostic; {prepare to do some tracing}
  4525. begin old_setting:=selector;
  4526. if (tracing_online<=0)and(selector=term_and_log) then
  4527.   begin decr(selector);
  4528.   if history=spotless then history:=warning_issued;
  4529.   end;
  4530. procedure end_diagnostic(@!blank_line:boolean);
  4531.   {restore proper conditions after tracing}
  4532. begin print_nl("");
  4533. if blank_line then print_ln;
  4534. selector:=old_setting;
  4535. @ Of course we had better declare another global variable, if the previous
  4536. routines are going to work.
  4537. @<Glob...@>=
  4538. @!old_setting:0..max_selector;
  4539. @ The final region of |eqtb| contains the dimension parameters defined
  4540. here, and the 256 \.{\\dimen} registers.
  4541. @d par_indent_code=0 {indentation of paragraphs}
  4542. @d math_surround_code=1 {space around math in text}
  4543. @d line_skip_limit_code=2 {threshold for |line_skip| instead of |baseline_skip|}
  4544. @d hsize_code=3 {line width in horizontal mode}
  4545. @d vsize_code=4 {page height in vertical mode}
  4546. @d max_depth_code=5 {maximum depth of boxes on main pages}
  4547. @d split_max_depth_code=6 {maximum depth of boxes on split pages}
  4548. @d box_max_depth_code=7 {maximum depth of explicit vboxes}
  4549. @d hfuzz_code=8 {tolerance for overfull hbox messages}
  4550. @d vfuzz_code=9 {tolerance for overfull vbox messages}
  4551. @d delimiter_shortfall_code=10 {maximum amount uncovered by variable delimiters}
  4552. @d null_delimiter_space_code=11 {blank space in null delimiters}
  4553. @d script_space_code=12 {extra space after subscript or superscript}
  4554. @d pre_display_size_code=13 {length of text preceding a display}
  4555. @d display_width_code=14 {length of line for displayed equation}
  4556. @d display_indent_code=15 {indentation of line for displayed equation}
  4557. @d overfull_rule_code=16 {width of rule that identifies overfull hboxes}
  4558. @d hang_indent_code=17 {amount of hanging indentation}
  4559. @d h_offset_code=18 {amount of horizontal offset when shipping pages out}
  4560. @d v_offset_code=19 {amount of vertical offset when shipping pages out}
  4561. @d emergency_stretch_code=20 {reduces badnesses on final pass of line-breaking}
  4562. @d dimen_pars=21 {total number of dimension parameters}
  4563. @d scaled_base=dimen_base+dimen_pars
  4564.   {table of 256 user-defined \.{\\dimen} registers}
  4565. @d eqtb_size=scaled_base+255 {largest subscript of |eqtb|}
  4566. @d dimen(#)==eqtb[scaled_base+#].sc
  4567. @d dimen_par(#)==eqtb[dimen_base+#].sc {a scaled quantity}
  4568. @d par_indent==dimen_par(par_indent_code)
  4569. @d math_surround==dimen_par(math_surround_code)
  4570. @d line_skip_limit==dimen_par(line_skip_limit_code)
  4571. @d hsize==dimen_par(hsize_code)
  4572. @d vsize==dimen_par(vsize_code)
  4573. @d max_depth==dimen_par(max_depth_code)
  4574. @d split_max_depth==dimen_par(split_max_depth_code)
  4575. @d box_max_depth==dimen_par(box_max_depth_code)
  4576. @d hfuzz==dimen_par(hfuzz_code)
  4577. @d vfuzz==dimen_par(vfuzz_code)
  4578. @d delimiter_shortfall==dimen_par(delimiter_shortfall_code)
  4579. @d null_delimiter_space==dimen_par(null_delimiter_space_code)
  4580. @d script_space==dimen_par(script_space_code)
  4581. @d pre_display_size==dimen_par(pre_display_size_code)
  4582. @d display_width==dimen_par(display_width_code)
  4583. @d display_indent==dimen_par(display_indent_code)
  4584. @d overfull_rule==dimen_par(overfull_rule_code)
  4585. @d hang_indent==dimen_par(hang_indent_code)
  4586. @d h_offset==dimen_par(h_offset_code)
  4587. @d v_offset==dimen_par(v_offset_code)
  4588. @d emergency_stretch==dimen_par(emergency_stretch_code)
  4589. @p procedure print_length_param(@!n:integer);
  4590. begin case n of
  4591. par_indent_code:print_esc("parindent");
  4592. math_surround_code:print_esc("mathsurround");
  4593. line_skip_limit_code:print_esc("lineskiplimit");
  4594. hsize_code:print_esc("hsize");
  4595. vsize_code:print_esc("vsize");
  4596. max_depth_code:print_esc("maxdepth");
  4597. split_max_depth_code:print_esc("splitmaxdepth");
  4598. box_max_depth_code:print_esc("boxmaxdepth");
  4599. hfuzz_code:print_esc("hfuzz");
  4600. vfuzz_code:print_esc("vfuzz");
  4601. delimiter_shortfall_code:print_esc("delimitershortfall");
  4602. null_delimiter_space_code:print_esc("nulldelimiterspace");
  4603. script_space_code:print_esc("scriptspace");
  4604. pre_display_size_code:print_esc("predisplaysize");
  4605. display_width_code:print_esc("displaywidth");
  4606. display_indent_code:print_esc("displayindent");
  4607. overfull_rule_code:print_esc("overfullrule");
  4608. hang_indent_code:print_esc("hangindent");
  4609. h_offset_code:print_esc("hoffset");
  4610. v_offset_code:print_esc("voffset");
  4611. emergency_stretch_code:print_esc("emergencystretch");
  4612. othercases print("[unknown dimen parameter!]")
  4613. endcases;
  4614. @ @<Put each...@>=
  4615. primitive("parindent",assign_dimen,dimen_base+par_indent_code);@/
  4616. @!@:par_indent_}{\.{\\parindent} primitive@>
  4617. primitive("mathsurround",assign_dimen,dimen_base+math_surround_code);@/
  4618. @!@:math_surround_}{\.{\\mathsurround} primitive@>
  4619. primitive("lineskiplimit",assign_dimen,dimen_base+line_skip_limit_code);@/
  4620. @!@:line_skip_limit_}{\.{\\lineskiplimit} primitive@>
  4621. primitive("hsize",assign_dimen,dimen_base+hsize_code);@/
  4622. @!@:hsize_}{\.{\\hsize} primitive@>
  4623. primitive("vsize",assign_dimen,dimen_base+vsize_code);@/
  4624. @!@:vsize_}{\.{\\vsize} primitive@>
  4625. primitive("maxdepth",assign_dimen,dimen_base+max_depth_code);@/
  4626. @!@:max_depth_}{\.{\\maxdepth} primitive@>
  4627. primitive("splitmaxdepth",assign_dimen,dimen_base+split_max_depth_code);@/
  4628. @!@:split_max_depth_}{\.{\\splitmaxdepth} primitive@>
  4629. primitive("boxmaxdepth",assign_dimen,dimen_base+box_max_depth_code);@/
  4630. @!@:box_max_depth_}{\.{\\boxmaxdepth} primitive@>
  4631. primitive("hfuzz",assign_dimen,dimen_base+hfuzz_code);@/
  4632. @!@:hfuzz_}{\.{\\hfuzz} primitive@>
  4633. primitive("vfuzz",assign_dimen,dimen_base+vfuzz_code);@/
  4634. @!@:vfuzz_}{\.{\\vfuzz} primitive@>
  4635. primitive("delimitershortfall",
  4636.   assign_dimen,dimen_base+delimiter_shortfall_code);@/
  4637. @!@:delimiter_shortfall_}{\.{\\delimitershortfall} primitive@>
  4638. primitive("nulldelimiterspace",
  4639.   assign_dimen,dimen_base+null_delimiter_space_code);@/
  4640. @!@:null_delimiter_space_}{\.{\\nulldelimiterspace} primitive@>
  4641. primitive("scriptspace",assign_dimen,dimen_base+script_space_code);@/
  4642. @!@:script_space_}{\.{\\scriptspace} primitive@>
  4643. primitive("predisplaysize",assign_dimen,dimen_base+pre_display_size_code);@/
  4644. @!@:pre_display_size_}{\.{\\predisplaysize} primitive@>
  4645. primitive("displaywidth",assign_dimen,dimen_base+display_width_code);@/
  4646. @!@:display_width_}{\.{\\displaywidth} primitive@>
  4647. primitive("displayindent",assign_dimen,dimen_base+display_indent_code);@/
  4648. @!@:display_indent_}{\.{\\displayindent} primitive@>
  4649. primitive("overfullrule",assign_dimen,dimen_base+overfull_rule_code);@/
  4650. @!@:overfull_rule_}{\.{\\overfullrule} primitive@>
  4651. primitive("hangindent",assign_dimen,dimen_base+hang_indent_code);@/
  4652. @!@:hang_indent_}{\.{\\hangindent} primitive@>
  4653. primitive("hoffset",assign_dimen,dimen_base+h_offset_code);@/
  4654. @!@:h_offset_}{\.{\\hoffset} primitive@>
  4655. primitive("voffset",assign_dimen,dimen_base+v_offset_code);@/
  4656. @!@:v_offset_}{\.{\\voffset} primitive@>
  4657. primitive("emergencystretch",assign_dimen,dimen_base+emergency_stretch_code);@/
  4658. @!@:emergency_stretch_}{\.{\\emergencystretch} primitive@>
  4659. @ @<Cases of |print_cmd_chr|...@>=
  4660. assign_dimen: if chr_code<scaled_base then
  4661.     print_length_param(chr_code-dimen_base)
  4662.   else  begin print_esc("dimen"); print_int(chr_code-scaled_base);
  4663.     end;
  4664. @ @<Initialize table entries...@>=
  4665. for k:=dimen_base to eqtb_size do eqtb[k].sc:=0;
  4666. @ @<Show equivalent |n|, in region 6@>=
  4667. begin if n<scaled_base then print_length_param(n-dimen_base)
  4668. else  begin print_esc("dimen"); print_int(n-scaled_base);
  4669.   end;
  4670. print_char("="); print_scaled(eqtb[n].sc); print("pt");
  4671. @ Here is a procedure that displays the contents of |eqtb[n]|
  4672. symbolically.
  4673. @p@t\4@>@<Declare the procedure called |print_cmd_chr|@>@;@/
  4674. @!stat procedure show_eqtb(@!n:pointer);
  4675. begin if n<active_base then print_char("?") {this can't happen}
  4676. else if n<glue_base then @<Show equivalent |n|, in region 1 or 2@>
  4677. else if n<local_base then @<Show equivalent |n|, in region 3@>
  4678. else if n<int_base then @<Show equivalent |n|, in region 4@>
  4679. else if n<dimen_base then @<Show equivalent |n|, in region 5@>
  4680. else if n<=eqtb_size then @<Show equivalent |n|, in region 6@>
  4681. else print_char("?"); {this can't happen either}
  4682. @ The last two regions of |eqtb| have fullword values instead of the
  4683. three fields |eq_level|, |eq_type|, and |equiv|. An |eq_type| is unnecessary,
  4684. but \TeX\ needs to store the |eq_level| information in another array
  4685. called |xeq_level|.
  4686. @<Glob...@>=
  4687. @!eqtb:array[active_base..eqtb_size] of memory_word;
  4688. @!xeq_level:array[int_base..eqtb_size] of quarterword;
  4689. @ @<Set init...@>=
  4690. for k:=int_base to eqtb_size do xeq_level[k]:=level_one;
  4691. @ When the debugging routine |search_mem| is looking for pointers having a
  4692. given value, it is interested only in regions 1 to~3 of~|eqtb|, and in the
  4693. first part of region~4.
  4694. @<Search |eqtb| for equivalents equal to |p|@>=
  4695. for q:=active_base to box_base+255 do
  4696.   begin if equiv(q)=p then
  4697.     begin print_nl("EQUIV("); print_int(q); print_char(")");
  4698.     end;
  4699.   end
  4700. @* \[18] The hash table.
  4701. Control sequences are stored and retrieved by means of a fairly standard hash
  4702. table algorithm called the method of ``coalescing lists'' (cf.\ Algorithm 6.4C
  4703. in {\sl The Art of Computer Programming\/}). Once a control sequence enters the
  4704. table, it is never removed, because there are complicated situations
  4705. involving \.{\\gdef} where the removal of a control sequence at the end of
  4706. a group would be a mistake preventable only by the introduction of a
  4707. complicated reference-count mechanism.
  4708. The actual sequence of letters forming a control sequence identifier is
  4709. stored in the |str_pool| array together with all the other strings. An
  4710. auxiliary array |hash| consists of items with two halfword fields per
  4711. word. The first of these, called |next(p)|, points to the next identifier
  4712. belonging to the same coalesced list as the identifier corresponding to~|p|;
  4713. and the other, called |text(p)|, points to the |str_start| entry for
  4714. |p|'s identifier. If position~|p| of the hash table is empty, we have
  4715. |text(p)=0|; if position |p| is either empty or the end of a coalesced
  4716. hash list, we have |next(p)=0|. An auxiliary pointer variable called
  4717. |hash_used| is maintained in such a way that all locations |p>=hash_used|
  4718. are nonempty. The global variable |cs_count| tells how many multiletter
  4719. control sequences have been defined, if statistics are being kept.
  4720. A global boolean variable called |no_new_control_sequence| is set to
  4721. |true| during the time that new hash table entries are forbidden.
  4722. @d next(#) == hash[#].lh {link for coalesced lists}
  4723. @d text(#) == hash[#].rh {string number for control sequence name}
  4724. @d hash_is_full == (hash_used=hash_base) {test if all positions are occupied}
  4725. @d font_id_text(#) == text(font_id_base+#) {a frozen font identifier's name}
  4726. @<Glob...@>=
  4727. @!hash: array[hash_base..undefined_control_sequence-1] of two_halves;
  4728.   {the hash table}
  4729. @!hash_used:pointer; {allocation pointer for |hash|}
  4730. @!no_new_control_sequence:boolean; {are new identifiers legal?}
  4731. @!cs_count:integer; {total number of known identifiers}
  4732. @ @<Set init...@>=
  4733. no_new_control_sequence:=true; {new identifiers are usually forbidden}
  4734. next(hash_base):=0; text(hash_base):=0;
  4735. for k:=hash_base+1 to undefined_control_sequence-1 do hash[k]:=hash[hash_base];
  4736. @ @<Initialize table entries...@>=
  4737. hash_used:=frozen_control_sequence; {nothing is used}
  4738. cs_count:=0;
  4739. eq_type(frozen_dont_expand):=dont_expand;
  4740. text(frozen_dont_expand):="notexpanded:";
  4741. @.notexpanded:@>
  4742. @ Here is the subroutine that searches the hash table for an identifier
  4743. that matches a given string of length |l>1| appearing in |buffer[j..
  4744. (j+l-1)]|. If the identifier is found, the corresponding hash table address
  4745. is returned. Otherwise, if the global variable |no_new_control_sequence|
  4746. is |true|, the dummy address |undefined_control_sequence| is returned.
  4747. Otherwise the identifier is inserted into the hash table and its location
  4748. is returned.
  4749. @p function id_lookup(@!j,@!l:integer):pointer; {search the hash table}
  4750. label found; {go here if you found it}
  4751. var h:integer; {hash code}
  4752. @!d:integer; {number of characters in incomplete current string}
  4753. @!p:pointer; {index in |hash| array}
  4754. @!k:pointer; {index in |buffer| array}
  4755. begin @<Compute the hash code |h|@>;
  4756. p:=h+hash_base; {we start searching here; note that |0<=h<hash_prime|}
  4757. loop@+begin if text(p)>0 then if length(text(p))=l then
  4758.     if str_eq_buf(text(p),j) then goto found;
  4759.   if next(p)=0 then
  4760.     begin if no_new_control_sequence then
  4761.       p:=undefined_control_sequence
  4762.     else @<Insert a new control sequence after |p|, then make
  4763.       |p| point to it@>;
  4764.     goto found;
  4765.     end;
  4766.   p:=next(p);
  4767.   end;
  4768. found: id_lookup:=p;
  4769. @ @<Insert a new control...@>=
  4770. begin if text(p)>0 then
  4771.   begin repeat if hash_is_full then overflow("hash size",hash_size);
  4772. @:TeX capacity exceeded hash size}{\quad hash size@>
  4773.   decr(hash_used);
  4774.   until text(hash_used)=0; {search for an empty location in |hash|}
  4775.   next(p):=hash_used; p:=hash_used;
  4776.   end;
  4777. str_room(l); d:=cur_length;
  4778. while pool_ptr>str_start[str_ptr] do
  4779.   begin decr(pool_ptr); str_pool[pool_ptr+l]:=str_pool[pool_ptr];
  4780.   end; {move current string up to make room for another}
  4781. for k:=j to j+l-1 do append_char(buffer[k]);
  4782. text(p):=make_string; pool_ptr:=pool_ptr+d;
  4783. @!stat incr(cs_count);@+tats@;@/
  4784. @ The value of |hash_prime| should be roughly 85\pct! of |hash_size|, and it
  4785. should be a prime number.  The theory of hashing tells us to expect fewer
  4786. than two table probes, on the average, when the search is successful.
  4787. [See J.~S. Vitter, {\sl Journal of the ACM\/ \bf30} (1983), 231--258.]
  4788. @^Vitter, Jeffrey Scott@>
  4789. @<Compute the hash code |h|@>=
  4790. h:=buffer[j];
  4791. for k:=j+1 to j+l-1 do
  4792.   begin h:=h+h+buffer[k];
  4793.   while h>=hash_prime do h:=h-hash_prime;
  4794.   end
  4795. @ Single-character control sequences do not need to be looked up in a hash
  4796. table, since we can use the character code itself as a direct address.
  4797. The procedure |print_cs| prints the name of a control sequence, given
  4798. a pointer to its address in |eqtb|. A space is printed after the name
  4799. unless it is a single nonletter or an active character. This procedure
  4800. might be invoked with invalid data, so it is ``extra robust.'' The
  4801. individual characters must be printed one at a time using |print|, since
  4802. they may be unprintable.
  4803. @<Basic printing...@>=
  4804. procedure print_cs(@!p:integer); {prints a purported control sequence}
  4805. begin if p<hash_base then {single character}
  4806.   if p>=single_base then
  4807.     if p=null_cs then
  4808.       begin print_esc("csname"); print_esc("endcsname");
  4809.       end
  4810.     else  begin print_esc(p-single_base);
  4811.       if cat_code(p-single_base)=letter then print_char(" ");
  4812.       end
  4813.   else if p<active_base then print_esc("IMPOSSIBLE.")
  4814. @.IMPOSSIBLE@>
  4815.   else print(p-active_base)
  4816. else if p>=undefined_control_sequence then print_esc("IMPOSSIBLE.")
  4817. else if (text(p)<0)or(text(p)>=str_ptr) then print_esc("NONEXISTENT.")
  4818. @.NONEXISTENT@>
  4819. else  begin print_esc(text(p));
  4820.   print_char(" ");
  4821.   end;
  4822. @ Here is a similar procedure; it avoids the error checks, and it never
  4823. prints a space after the control sequence.
  4824. @<Basic printing procedures@>=
  4825. procedure sprint_cs(@!p:pointer); {prints a control sequence}
  4826. begin if p<hash_base then
  4827.   if p<single_base then print(p-active_base)
  4828.   else  if p<null_cs then print_esc(p-single_base)
  4829.     else  begin print_esc("csname"); print_esc("endcsname");
  4830.       end
  4831. else print_esc(text(p));
  4832. @ We need to put \TeX's ``primitive'' control sequences into the hash
  4833. table, together with their command code (which will be the |eq_type|)
  4834. and an operand (which will be the |equiv|). The |primitive| procedure
  4835. does this, in a way that no \TeX\ user can. The global value |cur_val|
  4836. contains the new |eqtb| pointer after |primitive| has acted.
  4837. @p @!init procedure primitive(@!s:str_number;@!c:quarterword;@!o:halfword);
  4838. var k:pool_pointer; {index into |str_pool|}
  4839. @!j:small_number; {index into |buffer|}
  4840. @!l:small_number; {length of the string}
  4841. begin if s<256 then cur_val:=s+single_base
  4842. else  begin k:=str_start[s]; l:=str_start[s+1]-k;
  4843.     {we will move |s| into the (empty) |buffer|}
  4844.   for j:=0 to l-1 do buffer[j]:=so(str_pool[k+j]);
  4845.   cur_val:=id_lookup(0,l); {|no_new_control_sequence| is |false|}
  4846.   flush_string; text(cur_val):=s; {we don't want to have the string twice}
  4847.   end;
  4848. eq_level(cur_val):=level_one; eq_type(cur_val):=c; equiv(cur_val):=o;
  4849. @ Many of \TeX's primitives need no |equiv|, since they are identifiable
  4850. by their |eq_type| alone. These primitives are loaded into the hash table
  4851. as follows:
  4852. @<Put each of \TeX's primitives into the hash table@>=
  4853. primitive(" ",ex_space,0);@/
  4854. @!@:Single-character primitives /}{\quad\.{\\\ }@>
  4855. primitive("/",ital_corr,0);@/
  4856. @!@:Single-character primitives /}{\quad\.{\\/}@>
  4857. primitive("accent",accent,0);@/
  4858. @!@:accent_}{\.{\\accent} primitive@>
  4859. primitive("advance",advance,0);@/
  4860. @!@:advance_}{\.{\\advance} primitive@>
  4861. primitive("afterassignment",after_assignment,0);@/
  4862. @!@:after_assignment_}{\.{\\afterassignment} primitive@>
  4863. primitive("aftergroup",after_group,0);@/
  4864. @!@:after_group_}{\.{\\aftergroup} primitive@>
  4865. primitive("begingroup",begin_group,0);@/
  4866. @!@:begin_group_}{\.{\\begingroup} primitive@>
  4867. primitive("char",char_num,0);@/
  4868. @!@:char_}{\.{\\char} primitive@>
  4869. primitive("csname",cs_name,0);@/
  4870. @!@:cs_name_}{\.{\\csname} primitive@>
  4871. primitive("delimiter",delim_num,0);@/
  4872. @!@:delimiter_}{\.{\\delimiter} primitive@>
  4873. primitive("divide",divide,0);@/
  4874. @!@:divide_}{\.{\\divide} primitive@>
  4875. primitive("endcsname",end_cs_name,0);@/
  4876. @!@:end_cs_name_}{\.{\\endcsname} primitive@>
  4877. primitive("endgroup",end_group,0);
  4878. @!@:end_group_}{\.{\\endgroup} primitive@>
  4879. text(frozen_end_group):="endgroup"; eqtb[frozen_end_group]:=eqtb[cur_val];@/
  4880. primitive("expandafter",expand_after,0);@/
  4881. @!@:expand_after_}{\.{\\expandafter} primitive@>
  4882. primitive("font",def_font,0);@/
  4883. @!@:font_}{\.{\\font} primitive@>
  4884. primitive("fontdimen",assign_font_dimen,0);@/
  4885. @!@:font_dimen_}{\.{\\fontdimen} primitive@>
  4886. primitive("halign",halign,0);@/
  4887. @!@:halign_}{\.{\\halign} primitive@>
  4888. primitive("hrule",hrule,0);@/
  4889. @!@:hrule_}{\.{\\hrule} primitive@>
  4890. primitive("ignorespaces",ignore_spaces,0);@/
  4891. @!@:ignore_spaces_}{\.{\\ignorespaces} primitive@>
  4892. primitive("insert",insert,0);@/
  4893. @!@:insert_}{\.{\\insert} primitive@>
  4894. primitive("mark",mark,0);@/
  4895. @!@:mark_}{\.{\\mark} primitive@>
  4896. primitive("mathaccent",math_accent,0);@/
  4897. @!@:math_accent_}{\.{\\mathaccent} primitive@>
  4898. primitive("mathchar",math_char_num,0);@/
  4899. @!@:math_char_}{\.{\\mathchar} primitive@>
  4900. primitive("mathchoice",math_choice,0);@/
  4901. @!@:math_choice_}{\.{\\mathchoice} primitive@>
  4902. primitive("multiply",multiply,0);@/
  4903. @!@:multiply_}{\.{\\multiply} primitive@>
  4904. primitive("noalign",no_align,0);@/
  4905. @!@:no_align_}{\.{\\noalign} primitive@>
  4906. primitive("noboundary",no_boundary,0);@/
  4907. @!@:no_boundary_}{\.{\\noboundary} primitive@>
  4908. primitive("noexpand",no_expand,0);@/
  4909. @!@:no_expand_}{\.{\\noexpand} primitive@>
  4910. primitive("nonscript",non_script,0);@/
  4911. @!@:non_script_}{\.{\\nonscript} primitive@>
  4912. primitive("omit",omit,0);@/
  4913. @!@:omit_}{\.{\\omit} primitive@>
  4914. primitive("parshape",set_shape,0);@/
  4915. @!@:par_shape_}{\.{\\parshape} primitive@>
  4916. primitive("penalty",break_penalty,0);@/
  4917. @!@:penalty_}{\.{\\penalty} primitive@>
  4918. primitive("prevgraf",set_prev_graf,0);@/
  4919. @!@:prev_graf_}{\.{\\prevgraf} primitive@>
  4920. primitive("radical",radical,0);@/
  4921. @!@:radical_}{\.{\\radical} primitive@>
  4922. primitive("read",read_to_cs,0);@/
  4923. @!@:read_}{\.{\\read} primitive@>
  4924. primitive("relax",relax,256); {cf.\ |scan_file_name|}
  4925. @!@:relax_}{\.{\\relax} primitive@>
  4926. text(frozen_relax):="relax"; eqtb[frozen_relax]:=eqtb[cur_val];@/
  4927. primitive("setbox",set_box,0);@/
  4928. @!@:set_box_}{\.{\\setbox} primitive@>
  4929. primitive("the",the,0);@/
  4930. @!@:the_}{\.{\\the} primitive@>
  4931. primitive("toks",toks_register,0);@/
  4932. @!@:toks_}{\.{\\toks} primitive@>
  4933. primitive("vadjust",vadjust,0);@/
  4934. @!@:vadjust_}{\.{\\vadjust} primitive@>
  4935. primitive("valign",valign,0);@/
  4936. @!@:valign_}{\.{\\valign} primitive@>
  4937. primitive("vcenter",vcenter,0);@/
  4938. @!@:vcenter_}{\.{\\vcenter} primitive@>
  4939. primitive("vrule",vrule,0);@/
  4940. @!@:vrule_}{\.{\\vrule} primitive@>
  4941. @ Each primitive has a corresponding inverse, so that it is possible to
  4942. display the cryptic numeric contents of |eqtb| in symbolic form.
  4943. Every call of |primitive| in this program is therefore accompanied by some
  4944. straightforward code that forms part of the |print_cmd_chr| routine
  4945. below.
  4946. @<Cases of |print_cmd_chr|...@>=
  4947. accent: print_esc("accent");
  4948. advance: print_esc("advance");
  4949. after_assignment: print_esc("afterassignment");
  4950. after_group: print_esc("aftergroup");
  4951. assign_font_dimen: print_esc("fontdimen");
  4952. begin_group: print_esc("begingroup");
  4953. break_penalty: print_esc("penalty");
  4954. char_num: print_esc("char");
  4955. cs_name: print_esc("csname");
  4956. def_font: print_esc("font");
  4957. delim_num: print_esc("delimiter");
  4958. divide: print_esc("divide");
  4959. end_cs_name: print_esc("endcsname");
  4960. end_group: print_esc("endgroup");
  4961. ex_space: print_esc(" ");
  4962. expand_after: print_esc("expandafter");
  4963. halign: print_esc("halign");
  4964. hrule: print_esc("hrule");
  4965. ignore_spaces: print_esc("ignorespaces");
  4966. insert: print_esc("insert");
  4967. ital_corr: print_esc("/");
  4968. mark: print_esc("mark");
  4969. math_accent: print_esc("mathaccent");
  4970. math_char_num: print_esc("mathchar");
  4971. math_choice: print_esc("mathchoice");
  4972. multiply: print_esc("multiply");
  4973. no_align: print_esc("noalign");
  4974. no_boundary:print_esc("noboundary");
  4975. no_expand: print_esc("noexpand");
  4976. non_script: print_esc("nonscript");
  4977. omit: print_esc("omit");
  4978. radical: print_esc("radical");
  4979. read_to_cs: print_esc("read");
  4980. relax: print_esc("relax");
  4981. set_box: print_esc("setbox");
  4982. set_prev_graf: print_esc("prevgraf");
  4983. set_shape: print_esc("parshape");
  4984. the: print_esc("the");
  4985. toks_register: print_esc("toks");
  4986. vadjust: print_esc("vadjust");
  4987. valign: print_esc("valign");
  4988. vcenter: print_esc("vcenter");
  4989. vrule: print_esc("vrule");
  4990. @ We will deal with the other primitives later, at some point in the program
  4991. where their |eq_type| and |equiv| values are more meaningful.  For example,
  4992. the primitives for math mode will be loaded when we consider the routines
  4993. that deal with formulas. It is easy to find where each particular
  4994. primitive was treated by looking in the index at the end; for example, the
  4995. section where |"radical"| entered |eqtb| is listed under `\.{\\radical}
  4996. primitive'. (Primitives consisting of a single nonalphabetic character,
  4997. @!like `\.{\\/}', are listed under `Single-character primitives'.)
  4998. @!@^Single-character primitives@>
  4999. Meanwhile, this is a convenient place to catch up on something we were unable
  5000. to do before the hash table was defined:
  5001. @<Print the font identifier for |font(p)|@>=
  5002. print_esc(font_id_text(font(p)))
  5003. @* \[19] Saving and restoring equivalents.
  5004. The nested structure provided by `$\.{\char'173}\ldots\.{\char'175}$' groups
  5005. in \TeX\ means that |eqtb| entries valid in outer groups should be saved
  5006. and restored later if they are overridden inside the braces. When a new |eqtb|
  5007. value is being assigned, the program therefore checks to see if the previous
  5008. entry belongs to an outer level. In such a case, the old value is placed
  5009. on the |save_stack| just before the new value enters |eqtb|. At the
  5010. end of a grouping level, i.e., when the right brace is sensed, the
  5011. |save_stack| is used to restore the outer values, and the inner ones are
  5012. destroyed.
  5013. Entries on the |save_stack| are of type |memory_word|. The top item on
  5014. this stack is |save_stack[p]|, where |p=save_ptr-1|; it contains three
  5015. fields called |save_type|, |save_level|, and |save_index|, and it is
  5016. interpreted in one of four ways:
  5017. \yskip\hang 1) If |save_type(p)=restore_old_value|, then
  5018. |save_index(p)| is a location in |eqtb| whose current value should
  5019. be destroyed at the end of the current group and replaced by |save_stack[p-1]|.
  5020. Furthermore if |save_index(p)>=int_base|, then |save_level(p)|
  5021. should replace the corresponding entry in |xeq_level|.
  5022. \yskip\hang 2) If |save_type(p)=restore_zero|, then |save_index(p)|
  5023. is a location in |eqtb| whose current value should be destroyed at the end
  5024. of the current group, when it should be
  5025. replaced by the current value of |eqtb[undefined_control_sequence]|.
  5026. \yskip\hang 3) If |save_type(p)=insert_token|, then |save_index(p)|
  5027. is a token that should be inserted into \TeX's input when the current
  5028. group ends.
  5029. \yskip\hang 4) If |save_type(p)=level_boundary|, then |save_level(p)|
  5030. is a code explaining what kind of group we were previously in, and
  5031. |save_index(p)| points to the level boundary word at the bottom of
  5032. the entries for that group.
  5033. @d save_type(#)==save_stack[#].hh.b0 {classifies a |save_stack| entry}
  5034. @d save_level(#)==save_stack[#].hh.b1
  5035.   {saved level for regions 5 and 6, or group code}
  5036. @d save_index(#)==save_stack[#].hh.rh
  5037.   {|eqtb| location or |save_stack| location}
  5038. @d restore_old_value=0 {|save_type| when a value should be restored later}
  5039. @d restore_zero=1 {|save_type| when an undefined entry should be restored}
  5040. @d insert_token=2 {|save_type| when a token is being saved for later use}
  5041. @d level_boundary=3 {|save_type| corresponding to beginning of group}
  5042. @ Here are the group codes that are used to discriminate between different
  5043. kinds of groups. They allow \TeX\ to decide what special actions, if any,
  5044. should be performed when a group ends.
  5045. \def\grp{\.{\char'173...\char'175}}
  5046. Some groups are not supposed to be ended by right braces. For example,
  5047. the `\.\$' that begins a math formula causes a |math_shift_group| to
  5048. be started, and this should be terminated by a matching `\.\$'. Similarly,
  5049. a group that starts with \.{\\left} should end with \.{\\right}, and
  5050. one that starts with \.{\\begingroup} should end with \.{\\endgroup}.
  5051. @d bottom_level=0 {group code for the outside world}
  5052. @d simple_group=1 {group code for local structure only}
  5053. @d hbox_group=2 {code for `\.{\\hbox}\grp'}
  5054. @d adjusted_hbox_group=3 {code for `\.{\\hbox}\grp' in vertical mode}
  5055. @d vbox_group=4 {code for `\.{\\vbox}\grp'}
  5056. @d vtop_group=5 {code for `\.{\\vtop}\grp'}
  5057. @d align_group=6 {code for `\.{\\halign}\grp', `\.{\\valign}\grp'}
  5058. @d no_align_group=7 {code for `\.{\\noalign}\grp'}
  5059. @d output_group=8 {code for output routine}
  5060. @d math_group=9 {code for, e.g, `\.{\char'136}\grp'}
  5061. @d disc_group=10 {code for `\.{\\discretionary}\grp\grp\grp'}
  5062. @d insert_group=11 {code for `\.{\\insert}\grp', `\.{\\vadjust}\grp'}
  5063. @d vcenter_group=12 {code for `\.{\\vcenter}\grp'}
  5064. @d math_choice_group=13 {code for `\.{\\mathchoice}\grp\grp\grp\grp'}
  5065. @d semi_simple_group=14 {code for `\.{\\begingroup...\\endgroup}'}
  5066. @d math_shift_group=15 {code for `\.{\$...\$}'}
  5067. @d math_left_group=16 {code for `\.{\\left...\\right}'}
  5068. @d max_group_code=16
  5069. @<Types...@>=
  5070. @!group_code=0..max_group_code; {|save_level| for a level boundary}
  5071. @ The global variable |cur_group| keeps track of what sort of group we are
  5072. currently in. Another global variable, |cur_boundary|, points to the
  5073. topmost |level_boundary| word.  And |cur_level| is the current depth of
  5074. nesting. The routines are designed to preserve the condition that no entry
  5075. in the |save_stack| or in |eqtb| ever has a level greater than |cur_level|.
  5076. @ @<Glob...@>=
  5077. @!save_stack : array[0..save_size] of memory_word;
  5078. @!save_ptr : 0..save_size; {first unused entry on |save_stack|}
  5079. @!max_save_stack:0..save_size; {maximum usage of save stack}
  5080. @!cur_level: quarterword; {current nesting level for groups}
  5081. @!cur_group: group_code; {current group type}
  5082. @!cur_boundary: 0..save_size; {where the current level begins}
  5083. @ At this time it might be a good idea for the reader to review the introduction
  5084. to |eqtb| that was given above just before the long lists of parameter names.
  5085. Recall that the ``outer level'' of the program is |level_one|, since
  5086. undefined control sequences are assumed to be ``defined'' at |level_zero|.
  5087. @<Set init...@>=
  5088. save_ptr:=0; cur_level:=level_one; cur_group:=bottom_level; cur_boundary:=0;
  5089. max_save_stack:=0;
  5090. @ The following macro is used to test if there is room for up to six more
  5091. entries on |save_stack|. By making a conservative test like this, we can
  5092. get by with testing for overflow in only a few places.
  5093. @d check_full_save_stack==if save_ptr>max_save_stack then
  5094.   begin max_save_stack:=save_ptr;
  5095.   if max_save_stack>save_size-6 then overflow("save size",save_size);
  5096. @:TeX capacity exceeded save size}{\quad save size@>
  5097.   end
  5098. @ Procedure |new_save_level| is called when a group begins. The
  5099. argument is a group identification code like `|hbox_group|'. After
  5100. calling this routine, it is safe to put five more entries on |save_stack|.
  5101. In some cases integer-valued items are placed onto the
  5102. |save_stack| just below a |level_boundary| word, because this is a
  5103. convenient place to keep information that is supposed to ``pop up'' just
  5104. when the group has finished.
  5105. For example, when `\.{\\hbox to 100pt}\grp' is being treated, the 100pt
  5106. dimension is stored on |save_stack| just before |new_save_level| is
  5107. called.
  5108. We use the notation |saved(k)| to stand for an integer item that
  5109. appears in location |save_ptr+k| of the save stack.
  5110. @d saved(#)==save_stack[save_ptr+#].int
  5111. @p procedure new_save_level(@!c:group_code); {begin a new level of grouping}
  5112. begin check_full_save_stack;
  5113. save_type(save_ptr):=level_boundary; save_level(save_ptr):=cur_group;
  5114. save_index(save_ptr):=cur_boundary;
  5115. if cur_level=max_quarterword then overflow("grouping levels",
  5116. @:TeX capacity exceeded grouping levels}{\quad grouping levels@>
  5117.   max_quarterword-min_quarterword);
  5118.   {quit if |(cur_level+1)| is too big to be stored in |eqtb|}
  5119. cur_boundary:=save_ptr; incr(cur_level); incr(save_ptr); cur_group:=c;
  5120. @ Just before an entry of |eqtb| is changed, the following procedure should
  5121. be called to update the other data structures properly. It is important
  5122. to keep in mind that reference counts in |mem| include references from
  5123. within |save_stack|, so these counts must be handled carefully.
  5124. @^reference counts@>
  5125. @p procedure eq_destroy(@!w:memory_word); {gets ready to forget |w|}
  5126. var q:pointer; {|equiv| field of |w|}
  5127. begin case eq_type_field(w) of
  5128. call,long_call,outer_call,long_outer_call: delete_token_ref(equiv_field(w));
  5129. glue_ref: delete_glue_ref(equiv_field(w));
  5130. shape_ref: begin q:=equiv_field(w); {we need to free a \.{\\parshape} block}
  5131.   if q<>null then free_node(q,info(q)+info(q)+1);
  5132.   end; {such a block is |2n+1| words long, where |n=info(q)|}
  5133. box_ref: flush_node_list(equiv_field(w));
  5134. othercases do_nothing
  5135. endcases;
  5136. @ To save a value of |eqtb[p]| that was established at level |l|, we
  5137. can use the following subroutine.
  5138. @p procedure eq_save(@!p:pointer;@!l:quarterword); {saves |eqtb[p]|}
  5139. begin check_full_save_stack;
  5140. if l=level_zero then save_type(save_ptr):=restore_zero
  5141. else  begin save_stack[save_ptr]:=eqtb[p]; incr(save_ptr);
  5142.   save_type(save_ptr):=restore_old_value;
  5143.   end;
  5144. save_level(save_ptr):=l; save_index(save_ptr):=p; incr(save_ptr);
  5145. @ The procedure |eq_define| defines an |eqtb| entry having specified
  5146. |eq_type| and |equiv| fields, and saves the former value if appropriate.
  5147. This procedure is used only for entries in the first four regions of |eqtb|,
  5148. i.e., only for entries that have |eq_type| and |equiv| fields.
  5149. After calling this routine, it is safe to put four more entries on
  5150. |save_stack|, provided that there was room for four more entries before
  5151. the call, since |eq_save| makes the necessary test.
  5152. @p procedure eq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
  5153.   {new data for |eqtb|}
  5154. begin if eq_level(p)=cur_level then eq_destroy(eqtb[p])
  5155. else if cur_level>level_one then eq_save(p,eq_level(p));
  5156. eq_level(p):=cur_level; eq_type(p):=t; equiv(p):=e;
  5157. @ The counterpart of |eq_define| for the remaining (fullword) positions in
  5158. |eqtb| is called |eq_word_define|. Since |xeq_level[p]>=level_one| for all
  5159. |p|, a `|restore_zero|' will never be used in this case.
  5160. @p procedure eq_word_define(@!p:pointer;@!w:integer);
  5161. begin if xeq_level[p]<>cur_level then
  5162.   begin eq_save(p,xeq_level[p]); xeq_level[p]:=cur_level;
  5163.   end;
  5164. eqtb[p].int:=w;
  5165. @ The |eq_define| and |eq_word_define| routines take care of local definitions.
  5166. @^global definitions@>
  5167. Global definitions are done in almost the same way, but there is no need
  5168. to save old values, and the new value is associated with |level_one|.
  5169. @p procedure geq_define(@!p:pointer;@!t:quarterword;@!e:halfword);
  5170.   {global |eq_define|}
  5171. begin eq_destroy(eqtb[p]);
  5172. eq_level(p):=level_one; eq_type(p):=t; equiv(p):=e;
  5173. procedure geq_word_define(@!p:pointer;@!w:integer); {global |eq_word_define|}
  5174. begin eqtb[p].int:=w; xeq_level[p]:=level_one;
  5175. @ Subroutine |save_for_after| puts a token on the stack for save-keeping.
  5176. @p procedure save_for_after(@!t:halfword);
  5177. begin if cur_level>level_one then
  5178.   begin check_full_save_stack;
  5179.   save_type(save_ptr):=insert_token; save_level(save_ptr):=level_zero;
  5180.   save_index(save_ptr):=t; incr(save_ptr);
  5181.   end;
  5182. @ The |unsave| routine goes the other way, taking items off of |save_stack|.
  5183. This routine takes care of restoration when a level ends; everything
  5184. belonging to the topmost group is cleared off of the save stack.
  5185. @p@t\4@>@<Declare the procedure called |restore_trace|@>@;@/
  5186. procedure@?back_input; forward; @t\2@>
  5187. procedure unsave; {pops the top level off the save stack}
  5188. label done;
  5189. var p:pointer; {position to be restored}
  5190. @!l:quarterword; {saved level, if in fullword regions of |eqtb|}
  5191. @!t:halfword; {saved value of |cur_tok|}
  5192. begin if cur_level>level_one then
  5193.   begin decr(cur_level);
  5194.   @<Clear off top level from |save_stack|@>;
  5195.   end
  5196. else confusion("curlevel"); {|unsave| is not used when |cur_group=bottom_level|}
  5197. @:this can't happen curlevel}{\quad curlevel@>
  5198. @ @<Clear off...@>=
  5199. loop@+begin decr(save_ptr);
  5200.   if save_type(save_ptr)=level_boundary then goto done;
  5201.   p:=save_index(save_ptr);
  5202.   if save_type(save_ptr)=insert_token then
  5203.     @<Insert token |p| into \TeX's input@>
  5204.   else  begin if save_type(save_ptr)=restore_old_value then
  5205.       begin l:=save_level(save_ptr); decr(save_ptr);
  5206.       end
  5207.     else save_stack[save_ptr]:=eqtb[undefined_control_sequence];
  5208.     @<Store \(s)|save_stack[save_ptr]| in |eqtb[p]|, unless
  5209.       |eqtb[p]| holds a global value@>;
  5210.     end;
  5211.   end;
  5212. done: cur_group:=save_level(save_ptr); cur_boundary:=save_index(save_ptr)
  5213. @ A global definition, which sets the level to |level_one|,
  5214. @^global definitions@>
  5215. will not be undone by |unsave|. If at least one global definition of
  5216. |eqtb[p]| has been carried out within the group that just ended, the
  5217. last such definition will therefore survive.
  5218. @<Store \(s)|save...@>=
  5219. if p<int_base then
  5220.   if eq_level(p)=level_one then
  5221.     begin eq_destroy(save_stack[save_ptr]); {destroy the saved value}
  5222.     @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
  5223.     end
  5224.   else  begin eq_destroy(eqtb[p]); {destroy the current value}
  5225.     eqtb[p]:=save_stack[save_ptr]; {restore the saved value}
  5226.     @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
  5227.     end
  5228. else if xeq_level[p]<>level_one then
  5229.   begin eqtb[p]:=save_stack[save_ptr]; xeq_level[p]:=l;
  5230.   @!stat if tracing_restores>0 then restore_trace(p,"restoring");@+tats@;@/
  5231.   end
  5232. else  begin
  5233.   @!stat if tracing_restores>0 then restore_trace(p,"retaining");@+tats@;@/
  5234.   end
  5235. @ @<Declare the procedure called |restore_trace|@>=
  5236. @!stat procedure restore_trace(@!p:pointer;@!s:str_number);
  5237.   {|eqtb[p]| has just been restored or retained}
  5238. begin begin_diagnostic; print_char("{"); print(s); print_char(" ");
  5239. show_eqtb(p); print_char("}");
  5240. end_diagnostic(false);
  5241. @ When looking for possible pointers to a memory location, it is helpful
  5242. to look for references from |eqtb| that might be waiting on the
  5243. save stack. Of course, we might find spurious pointers too; but this
  5244. routine is merely an aid when debugging, and at such times we are
  5245. grateful for any scraps of information, even if they prove to be irrelevant.
  5246. @^dirty \PASCAL@>
  5247. @<Search |save_stack| for equivalents that point to |p|@>=
  5248. if save_ptr>0 then for q:=0 to save_ptr-1 do
  5249.   begin if equiv_field(save_stack[q])=p then
  5250.     begin print_nl("SAVE("); print_int(q); print_char(")");
  5251.     end;
  5252.   end
  5253. @ Most of the parameters kept in |eqtb| can be changed freely, but there's
  5254. an exception:  The magnification should not be used with two different
  5255. values during any \TeX\ job, since a single magnification is applied to an
  5256. entire run. The global variable |mag_set| is set to the current magnification
  5257. whenever it becomes necessary to ``freeze'' it at a particular value.
  5258. @<Glob...@>=
  5259. @!mag_set:integer; {if nonzero, this magnification should be used henceforth}
  5260. @ @<Set init...@>=
  5261. mag_set:=0;
  5262. @ The |prepare_mag| subroutine is called whenever \TeX\ wants to use |mag|
  5263. for magnification.
  5264. @p procedure prepare_mag;
  5265. begin if (mag_set>0)and(mag<>mag_set) then
  5266.   begin print_err("Incompatible magnification ("); print_int(mag);
  5267. @.Incompatible magnification@>
  5268.   print(");"); print_nl(" the previous value will be retained");
  5269.   help2("I can handle only one magnification ratio per job. So I've")@/
  5270.   ("reverted to the magnification you used earlier on this run.");@/
  5271.   int_error(mag_set);
  5272.   geq_word_define(int_base+mag_code,mag_set); {|mag:=mag_set|}
  5273.   end;
  5274. if (mag<=0)or(mag>32768) then
  5275.   begin print_err("Illegal magnification has been changed to 1000");@/
  5276. @.Illegal magnification...@>
  5277.   help1("The magnification ratio must be between 1 and 32768.");
  5278.   int_error(mag); geq_word_define(int_base+mag_code,1000);
  5279.   end;
  5280. mag_set:=mag;
  5281. @* \[20] Token lists.
  5282. A \TeX\ token is either a character or a control sequence, and it is
  5283. @^token@>
  5284. represented internally in one of two ways: (1)~A character whose ASCII
  5285. code number is |c| and whose command code is |m| is represented as the
  5286. number $2^8m+c$; the command code is in the range |1<=m<=14|. (2)~A control
  5287. sequence whose |eqtb| address is |p| is represented as the number
  5288. |cs_token_flag+p|. Here |cs_token_flag=@t$2^{12}-1$@>| is larger than
  5289. $2^8m+c$, yet it is small enough that |cs_token_flag+p< max_halfword|;
  5290. thus, a token fits comfortably in a halfword.
  5291. A token |t| represents a |left_brace| command if and only if
  5292. |t<left_brace_limit|; it represents a |right_brace| command if and only if
  5293. we have |left_brace_limit<=t<right_brace_limit|; and it represents a |match| or
  5294. |end_match| command if and only if |match_token<=t<=end_match_token|.
  5295. The following definitions take care of these token-oriented constants
  5296. and a few others.
  5297. @d cs_token_flag==@'7777 {amount added to the |eqtb| location in a
  5298.   token that stands for a control sequence; is a multiple of~256, less~1}
  5299. @d left_brace_token=@'0400 {$2^8\cdot|left_brace|$}
  5300. @d left_brace_limit=@'1000 {$2^8\cdot(|left_brace|+1)$}
  5301. @d right_brace_token=@'1000 {$2^8\cdot|right_brace|$}
  5302. @d right_brace_limit=@'1400 {$2^8\cdot(|right_brace|+1)$}
  5303. @d math_shift_token=@'1400 {$2^8\cdot|math_shift|$}
  5304. @d tab_token=@'2000 {$2^8\cdot|tab_mark|$}
  5305. @d out_param_token=@'2400 {$2^8\cdot|out_param|$}
  5306. @d space_token=@'5040 {$2^8\cdot|spacer|+|" "|$}
  5307. @d letter_token=@'5400 {$2^8\cdot|letter|$}
  5308. @d other_token=@'6000 {$2^8\cdot|other_char|$}
  5309. @d match_token=@'6400 {$2^8\cdot|match|$}
  5310. @d end_match_token=@'7000 {$2^8\cdot|end_match|$}
  5311. @ @<Check the ``constant''...@>=
  5312. if cs_token_flag+undefined_control_sequence>max_halfword then bad:=21;
  5313. @ A token list is a singly linked list of one-word nodes in |mem|, where
  5314. each word contains a token and a link. Macro definitions, output-routine
  5315. definitions, marks, \.{\\write} texts, and a few other things
  5316. are remembered by \TeX\ in the form
  5317. of token lists, usually preceded by a node with a reference count in its
  5318. |token_ref_count| field. The token stored in location |p| is called
  5319. |info(p)|.
  5320. Three special commands appear in the token lists of macro definitions.
  5321. When |m=match|, it means that \TeX\ should scan a parameter
  5322. for the current macro; when |m=end_match|, it means that parameter
  5323. matching should end and \TeX\ should start reading the macro text; and
  5324. when |m=out_param|, it means that \TeX\ should insert parameter
  5325. number |c| into the text at this point.
  5326. The enclosing \.{\char'173} and \.{\char'175} characters of a macro
  5327. definition are omitted, but the final right brace of an output routine
  5328. is included at the end of its token list.
  5329. Here is an example macro definition that illustrates these conventions.
  5330. After \TeX\ processes the text
  5331. $$\.{\\def\\mac a\#1\#2 \\b \{\#1\\-a \#\#1\#2 \#2\}}$$
  5332. the definition of \.{\\mac} is represented as a token list containing
  5333. $$\def\,{\hskip2pt}
  5334. \vbox{\halign{\hfil#\hfil\cr
  5335. (reference count), |letter|\,\.a, |match|\,\#, |match|\,\#, |spacer|\,\.\ ,
  5336. \.{\\b}, |end_match|,\cr
  5337. |out_param|\,1, \.{\\-}, |letter|\,\.a, |spacer|\,\.\ , |mac_param|\,\#,
  5338. |other_char|\,\.1,\cr
  5339. |out_param|\,2, |spacer|\,\.\ , |out_param|\,2.\cr}}$$
  5340. The procedure |scan_toks| builds such token lists, and |macro_call|
  5341. does the parameter matching.
  5342. @^reference counts@>
  5343. Examples such as
  5344. $$\.{\\def\\m\{\\def\\m\{a\}\ b\}}$$
  5345. explain why reference counts would be needed even if \TeX\ had no \.{\\let}
  5346. operation: When the token list for \.{\\m} is being read, the redefinition of
  5347. \.{\\m} changes the |eqtb| entry before the token list has been fully
  5348. consumed, so we dare not simply destroy a token list when its
  5349. control sequence is being redefined.
  5350. If the parameter-matching part of a definition ends with `\.{\#\{}',
  5351. the corresponding token list will have `\.\{' just before the `|end_match|'
  5352. and also at the very end. The first `\.\{' is used to delimit the parameter; the
  5353. second one keeps the first from disappearing.
  5354. @ The procedure |show_token_list|, which prints a symbolic form of
  5355. the token list that starts at a given node |p|, illustrates these
  5356. conventions. The token list being displayed should not begin with a reference
  5357. count. However, the procedure is intended to be robust, so that if the
  5358. memory links are awry or if |p| is not really a pointer to a token list,
  5359. nothing catastrophic will happen.
  5360. An additional parameter |q| is also given; this parameter is either null
  5361. or it points to a node in the token list where a certain magic computation
  5362. takes place that will be explained later. (Basically, |q| is non-null when
  5363. we are printing the two-line context information at the time of an error
  5364. message; |q| marks the place corresponding to where the second line
  5365. should begin.)
  5366. For example, if |p| points to the node containing the first \.a in the
  5367. token list above, then |show_token_list| will print the string
  5368. $$\hbox{`\.{a\#1\#2\ \\b\ ->\#1\\-a\ \#\#1\#2\ \#2}';}$$
  5369. and if |q| points to the node containing the second \.a,
  5370. the magic computation will be performed just before the second \.a is printed.
  5371. The generation will stop, and `\.{\\ETC.}' will be printed, if the length
  5372. of printing exceeds a given limit~|l|. Anomalous entries are printed in the
  5373. form of control sequences that are not followed by a blank space, e.g.,
  5374. `\.{\\BAD.}'; this cannot be confused with actual control sequences because
  5375. a real control sequence named \.{BAD} would come out `\.{\\BAD\ }'.
  5376. @<Declare the procedure called |show_token_list|@>=
  5377. procedure show_token_list(@!p,@!q:integer;@!l:integer);
  5378. label exit;
  5379. var m,@!c:integer; {pieces of a token}
  5380. @!match_chr:ASCII_code; {character used in a `|match|'}
  5381. @!n:ASCII_code; {the highest parameter number, as an ASCII digit}
  5382. begin match_chr:="#"; n:="0"; tally:=0;
  5383. while (p<>null) and (tally<l) do
  5384.   begin if p=q then @<Do magic computation@>;
  5385.   @<Display token |p|, and |return| if there are problems@>;
  5386.   p:=link(p);
  5387.   end;
  5388. if p<>null then print_esc("ETC.");
  5389. @.ETC@>
  5390. exit:
  5391. @ @<Display token |p|...@>=
  5392. if (p<hi_mem_min) or (p>mem_end) then
  5393.   begin print_esc("CLOBBERED."); return;
  5394. @.CLOBBERED@>
  5395.   end;
  5396. if info(p)>=cs_token_flag then print_cs(info(p)-cs_token_flag)
  5397. else  begin m:=info(p) div @'400; c:=info(p) mod @'400;
  5398.   if info(p)<0 then print_esc("BAD.")
  5399. @.BAD@>
  5400.   else @<Display the token $(|m|,|c|)$@>;
  5401.   end
  5402. @ The procedure usually ``learns'' the character code used for macro
  5403. parameters by seeing one in a |match| command before it runs into any
  5404. |out_param| commands.
  5405. @<Display the token ...@>=
  5406. case m of
  5407. left_brace,right_brace,math_shift,tab_mark,sup_mark,sub_mark,spacer,
  5408.   letter,other_char: print(c);
  5409. mac_param: begin print(c); print(c);
  5410.   end;
  5411. out_param: begin print(match_chr);
  5412.   if c<=9 then print_char(c+"0")
  5413.   else  begin print_char("!"); return;
  5414.     end;
  5415.   end;
  5416. match: begin match_chr:=c; print(c); incr(n); print_char(n);
  5417.   if n>"9" then return;
  5418.   end;
  5419. end_match: print("->");
  5420. @.->@>
  5421. othercases print_esc("BAD.")
  5422. @.BAD@>
  5423. endcases
  5424. @ Here's the way we sometimes want to display a token list, given a pointer
  5425. to its reference count; the pointer may be null.
  5426. @p procedure token_show(@!p:pointer);
  5427. begin if p<>null then show_token_list(link(p),null,10000000);
  5428. @ The |print_meaning| subroutine displays |cur_cmd| and |cur_chr| in
  5429. symbolic form, including the expansion of a macro or mark.
  5430. @p procedure print_meaning;
  5431. begin print_cmd_chr(cur_cmd,cur_chr);
  5432. if cur_cmd>=call then
  5433.   begin print_char(":"); print_ln; token_show(cur_chr);
  5434.   end
  5435. else if cur_cmd=top_bot_mark then
  5436.   begin print_char(":"); print_ln;
  5437.   token_show(cur_mark[cur_chr]);
  5438.   end;
  5439. @* \[21] Introduction to the syntactic routines.
  5440. Let's pause a moment now and try to look at the Big Picture.
  5441. The \TeX\ program consists of three main parts: syntactic routines,
  5442. semantic routines, and output routines. The chief purpose of the
  5443. syntactic routines is to deliver the user's input to the semantic routines,
  5444. one token at a time. The semantic routines act as an interpreter
  5445. responding to these tokens, which may be regarded as commands. And the
  5446. output routines are periodically called on to convert box-and-glue
  5447. lists into a compact set of instructions that will be sent
  5448. to a typesetter. We have discussed the basic data structures and utility
  5449. routines of \TeX, so we are good and ready to plunge into the real activity by
  5450. considering the syntactic routines.
  5451. Our current goal is to come to grips with the |get_next| procedure,
  5452. which is the keystone of \TeX's input mechanism. Each call of |get_next|
  5453. sets the value of three variables |cur_cmd|, |cur_chr|, and |cur_cs|,
  5454. representing the next input token.
  5455. $$\vbox{\halign{#\hfil\cr
  5456.   \hbox{|cur_cmd| denotes a command code from the long list of codes
  5457.    given above;}\cr
  5458.   \hbox{|cur_chr| denotes a character code or other modifier of the command
  5459.    code;}\cr
  5460.   \hbox{|cur_cs| is the |eqtb| location of the current control sequence,}\cr
  5461.   \hbox{\qquad if the current token was a control sequence,
  5462.    otherwise it's zero.}\cr}}$$
  5463. Underlying this external behavior of |get_next| is all the machinery
  5464. necessary to convert from character files to tokens. At a given time we
  5465. may be only partially finished with the reading of several files (for
  5466. which \.{\\input} was specified), and partially finished with the expansion
  5467. of some user-defined macros and/or some macro parameters, and partially
  5468. finished with the generation of some text in a template for \.{\\halign},
  5469. and so on. When reading a character file, special characters must be
  5470. classified as math delimiters, etc.; comments and extra blank spaces must
  5471. be removed, paragraphs must be recognized, and control sequences must be
  5472. found in the hash table. Furthermore there are occasions in which the
  5473. scanning routines have looked ahead for a word like `\.{plus}' but only
  5474. part of that word was found, hence a few characters must be put back
  5475. into the input and scanned again.
  5476. To handle these situations, which might all be present simultaneously,
  5477. \TeX\ uses various stacks that hold information about the incomplete
  5478. activities, and there is a finite state control for each level of the
  5479. input mechanism. These stacks record the current state of an implicitly
  5480. recursive process, but the |get_next| procedure is not recursive.
  5481. Therefore it will not be difficult to translate these algorithms into
  5482. low-level languages that do not support recursion.
  5483. @<Glob...@>=
  5484. @!cur_cmd: eight_bits; {current command set by |get_next|}
  5485. @!cur_chr: halfword; {operand of current command}
  5486. @!cur_cs: pointer; {control sequence found here, zero if none found}
  5487. @!cur_tok: halfword; {packed representative of |cur_cmd| and |cur_chr|}
  5488. @ The |print_cmd_chr| routine prints a symbolic interpretation of a
  5489. command code and its modifier. This is used in certain `\.{You can\'t}'
  5490. error messages, and in the implementation of diagnostic routines like
  5491. \.{\\show}.
  5492. The body of |print_cmd_chr| is a rather tedious listing of print
  5493. commands, and most of it is essentially an inverse to the |primitive|
  5494. routine that enters a \TeX\ primitive into |eqtb|. Therefore much of
  5495. this procedure appears elsewhere in the program,
  5496. together with the corresponding |primitive| calls.
  5497. @d chr_cmd(#)==begin print(#); print_ASCII(chr_code);
  5498.   end
  5499. @<Declare the procedure called |print_cmd_chr|@>=
  5500. procedure print_cmd_chr(@!cmd:quarterword;@!chr_code:halfword);
  5501. begin case cmd of
  5502. left_brace: chr_cmd("begin-group character ");
  5503. right_brace: chr_cmd("end-group character ");
  5504. math_shift: chr_cmd("math shift character ");
  5505. mac_param: chr_cmd("macro parameter character ");
  5506. sup_mark: chr_cmd("superscript character ");
  5507. sub_mark: chr_cmd("subscript character ");
  5508. endv: print("end of alignment template");
  5509. spacer: chr_cmd("blank space ");
  5510. letter: chr_cmd("the letter ");
  5511. other_char: chr_cmd("the character ");
  5512. @t\4@>@<Cases of |print_cmd_chr| for symbolic printing of primitives@>@/
  5513. othercases print("[unknown command code!]")
  5514. endcases;
  5515. @ Here is a procedure that displays the current command.
  5516. @p procedure show_cur_cmd_chr;
  5517. begin begin_diagnostic; print_nl("{");
  5518. if mode<>shown_mode then
  5519.   begin print_mode(mode); print(": "); shown_mode:=mode;
  5520.   end;
  5521. print_cmd_chr(cur_cmd,cur_chr); print_char("}");
  5522. end_diagnostic(false);
  5523. @* \[22] Input stacks and states.
  5524. This implementation of
  5525. \TeX\ uses two different conventions for representing sequential stacks.
  5526. @^stack conventions@>@^conventions for representing stacks@>
  5527. \yskip\hang 1) If there is frequent access to the top entry, and if the
  5528. stack is essentially never empty, then the top entry is kept in a global
  5529. variable (even better would be a machine register), and the other entries
  5530. appear in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the
  5531. semantic stack described above is handled this way, and so is the input
  5532. stack that we are about to study.
  5533. \yskip\hang 2) If there is infrequent top access, the entire stack contents
  5534. are in the array $\\{stack}[0\to(\\{ptr}-1)]$. For example, the |save_stack|
  5535. is treated this way, as we have seen.
  5536. \yskip\noindent
  5537. The state of \TeX's input mechanism appears in the input stack, whose
  5538. entries are records with six fields, called |state|, |index|, |start|, |loc|,
  5539. |limit|, and |name|. This stack is maintained with
  5540. convention~(1), so it is declared in the following way:
  5541. @<Types...@>=
  5542. @!in_state_record = record
  5543.   @!state_field, @!index_field: quarterword;
  5544.   @!start_field,@!loc_field, @!limit_field, @!name_field: halfword;
  5545.   end;
  5546. @ @<Glob...@>=
  5547. @!input_stack : array[0..stack_size] of in_state_record;
  5548. @!input_ptr : 0..stack_size; {first unused location of |input_stack|}
  5549. @!max_in_stack: 0..stack_size; {largest value of |input_ptr| when pushing}
  5550. @!cur_input : in_state_record;
  5551.   {the ``top'' input state, according to convention (1)}
  5552. @ We've already defined the special variable |loc==cur_input.loc_field|
  5553. in our discussion of basic input-output routines. The other components of
  5554. |cur_input| are defined in the same way:
  5555. @d state==cur_input.state_field {current scanner state}
  5556. @d index==cur_input.index_field {reference for buffer information}
  5557. @d start==cur_input.start_field {starting position in |buffer|}
  5558. @d limit==cur_input.limit_field {end of current line in |buffer|}
  5559. @d name==cur_input.name_field {name of the current file}
  5560. @ Let's look more closely now at the control variables
  5561. (|state|,~|index|,~|start|,~|loc|,~|limit|,~|name|),
  5562. assuming that \TeX\ is reading a line of characters that have been input
  5563. from some file or from the user's terminal. There is an array called
  5564. |buffer| that acts as a stack of all lines of characters that are
  5565. currently being read from files, including all lines on subsidiary
  5566. levels of the input stack that are not yet completed. \TeX\ will return to
  5567. the other lines when it is finished with the present input file.
  5568. (Incidentally, on a machine with byte-oriented addressing, it might be
  5569. appropriate to combine |buffer| with the |str_pool| array,
  5570. letting the buffer entries grow downward from the top of the string pool
  5571. and checking that these two tables don't bump into each other.)
  5572. The line we are currently working on begins in position |start| of the
  5573. buffer; the next character we are about to read is |buffer[loc]|; and
  5574. |limit| is the location of the last character present.  If |loc>limit|,
  5575. the line has been completely read. Usually |buffer[limit]| is the
  5576. |end_line_char|, denoting the end of a line, but this is not
  5577. true if the current line is an insertion that was entered on the user's
  5578. terminal in response to an error message.
  5579. The |name| variable is a string number that designates the name of
  5580. the current file, if we are reading a text file. It is zero if we
  5581. are reading from the terminal; it is |n+1| if we are reading from
  5582. input stream |n|, where |0<=n<=16|. (Input stream 16 stands for
  5583. an invalid stream number; in such cases the input is actually from
  5584. the terminal, under control of the procedure |read_toks|.)
  5585. The |state| variable has one of three values, when we are scanning such
  5586. files:
  5587. $$\baselineskip 15pt\vbox{\halign{#\hfil\cr
  5588. 1) |state=mid_line| is the normal state.\cr
  5589. 2) |state=skip_blanks| is like |mid_line|, but blanks are ignored.\cr
  5590. 3) |state=new_line| is the state at the beginning of a line.\cr}}$$
  5591. These state values are assigned numeric codes so that if we add the state
  5592. code to the next character's command code, we get distinct values. For
  5593. example, `|mid_line+spacer|' stands for the case that a blank
  5594. space character occurs in the middle of a line when it is not being
  5595. ignored; after this case is processed, the next value of |state| will
  5596. be |skip_blanks|.
  5597. @d mid_line=1 {|state| code when scanning a line of characters}
  5598. @d skip_blanks=2+max_char_code {|state| code when ignoring blanks}
  5599. @d new_line=3+max_char_code+max_char_code {|state| code at start of line}
  5600. @ Additional information about the current line is available via the
  5601. |index| variable, which counts how many lines of characters are present
  5602. in the buffer below the current level. We have |index=0| when reading
  5603. from the terminal and prompting the user for each line; then if the user types,
  5604. e.g., `\.{\\input paper}', we will have |index=1| while reading
  5605. the file \.{paper.tex}. However, it does not follow that |index| is the
  5606. same as the input stack pointer, since many of the levels on the input
  5607. stack may come from token lists. For example, the instruction `\.{\\input
  5608. paper}' might occur in a token list.
  5609. The global variable |in_open| is equal to the |index|
  5610. value of the highest non-token-list level. Thus, the number of partially read
  5611. lines in the buffer is |in_open+1|, and we have |in_open=index|
  5612. when we are not reading a token list.
  5613. If we are not currently reading from the terminal, or from an input
  5614. stream, we are reading from the file variable |input_file[index]|. We use
  5615. the notation |terminal_input| as a convenient abbreviation for |name=0|,
  5616. and |cur_file| as an abbreviation for |input_file[index]|.
  5617. The global variable |line| contains the line number in the topmost
  5618. open file, for use in error messages. If we are not reading from
  5619. the terminal, |line_stack[index]| holds the line number for the
  5620. enclosing level, so that |line| can be restored when the current
  5621. file has been read. Line numbers should never be negative, since the
  5622. negative of the current line number is used to identify the user's output
  5623. routine in the |mode_line| field of the semantic nest entries.
  5624. If more information about the input state is needed, it can be
  5625. included in small arrays like those shown here. For example,
  5626. the current page or segment number in the input file might be
  5627. put into a variable |@!page|, maintained for enclosing levels in
  5628. `\ignorespaces|@!page_stack:array[1..max_in_open] of integer|\unskip'
  5629. by analogy with |line_stack|.
  5630. @^system dependencies@>
  5631. @d terminal_input==(name=0) {are we reading from the terminal?}
  5632. @d cur_file==input_file[index] {the current |alpha_file| variable}
  5633. @<Glob...@>=
  5634. @!in_open : 0..max_in_open; {the number of lines in the buffer, less one}
  5635. @!open_parens : 0..max_in_open; {the number of open text files}
  5636. @!input_file : array[1..max_in_open] of alpha_file;
  5637. @!line : integer; {current line number in the current source file}
  5638. @!line_stack : array[1..max_in_open] of integer;
  5639. @ Users of \TeX\ sometimes forget to balance left and right braces properly,
  5640. and one of the ways \TeX\ tries to spot such errors is by considering an
  5641. input file as broken into subfiles by control sequences that
  5642. are declared to be \.{\\outer}.
  5643. A variable called |scanner_status| tells \TeX\ whether or not to complain
  5644. when a subfile ends. This variable has six possible values:
  5645. \yskip\hang|normal|, means that a subfile can safely end here without incident.
  5646. \yskip\hang|skipping|, means that a subfile can safely end here, but not a file,
  5647. because we're reading past some conditional text that was not selected.
  5648. \yskip\hang|defining|, means that a subfile shouldn't end now because a
  5649. macro is being defined.
  5650. \yskip\hang|matching|, means that a subfile shouldn't end now because a
  5651. macro is being used and we are searching for the end of its arguments.
  5652. \yskip\hang|aligning|, means that a subfile shouldn't end now because we are
  5653. not finished with the preamble of an \.{\\halign} or \.{\\valign}.
  5654. \yskip\hang|absorbing|, means that a subfile shouldn't end now because we are
  5655. reading a balanced token list for \.{\\message}, \.{\\write}, etc.
  5656. \yskip\noindent
  5657. If the |scanner_status| is not |normal|, the variable |warning_index| points
  5658. to the |eqtb| location for the relevant control sequence name to print
  5659. in an error message.
  5660. @d skipping=1 {|scanner_status| when passing conditional text}
  5661. @d defining=2 {|scanner_status| when reading a macro definition}
  5662. @d matching=3 {|scanner_status| when reading macro arguments}
  5663. @d aligning=4 {|scanner_status| when reading an alignment preamble}
  5664. @d absorbing=5 {|scanner_status| when reading a balanced text}
  5665. @<Glob...@>=
  5666. @!scanner_status : normal..absorbing; {can a subfile end now?}
  5667. @!warning_index : pointer; {identifier relevant to non-|normal| scanner status}
  5668. @!def_ref : pointer; {reference count of token list being defined}
  5669. @ Here is a procedure that uses |scanner_status| to print a warning message
  5670. when a subfile has ended, and at certain other crucial times:
  5671. @<Declare the procedure called |runaway|@>=
  5672. procedure runaway;
  5673. var p:pointer; {head of runaway list}
  5674. begin if scanner_status>skipping then
  5675.   begin print_nl("Runaway ");
  5676. @.Runaway...@>
  5677.   case scanner_status of
  5678.   defining: begin print("definition"); p:=def_ref;
  5679.     end;
  5680.   matching: begin print("argument"); p:=temp_head;
  5681.     end;
  5682.   aligning: begin print("preamble"); p:=hold_head;
  5683.     end;
  5684.   absorbing: begin print("text"); p:=def_ref;
  5685.     end;
  5686.   end; {there are no other cases}
  5687.   print_char("?");print_ln; show_token_list(link(p),null,error_line-10);
  5688.   end;
  5689. @ However, all this discussion about input state really applies only to the
  5690. case that we are inputting from a file. There is another important case,
  5691. namely when we are currently getting input from a token list. In this case
  5692. |state=token_list|, and the conventions about the other state variables
  5693. are different:
  5694. \yskip\hang|loc| is a pointer to the current node in the token list, i.e.,
  5695. the node that will be read next. If |loc=null|, the token list has been
  5696. fully read.
  5697. \yskip\hang|start| points to the first node of the token list; this node
  5698. may or may not contain a reference count, depending on the type of token
  5699. list involved.
  5700. \yskip\hang|token_type|, which takes the place of |index| in the
  5701. discussion above, is a code number that explains what kind of token list
  5702. is being scanned.
  5703. \yskip\hang|name| points to the |eqtb| address of the control sequence
  5704. being expanded, if the current token list is a macro.
  5705. \yskip\hang|param_start|, which takes the place of |limit|, tells where
  5706. the parameters of the current macro begin in the |param_stack|, if the
  5707. current token list is a macro.
  5708. \yskip\noindent The |token_type| can take several values, depending on
  5709. where the current token list came from:
  5710. \yskip\hang|parameter|, if a parameter is being scanned;
  5711. \hang|u_template|, if the \<u_j> part of an alignment
  5712. template is being scanned;
  5713. \hang|v_template|, if the \<v_j> part of an alignment
  5714. template is being scanned;
  5715. \hang|backed_up|, if the token list being scanned has been inserted as
  5716. `to be read again'.
  5717. \hang|inserted|, if the token list being scanned has been inserted as
  5718. the text expansion of a \.{\\count} or similar variable;
  5719. \hang|macro|, if a user-defined control sequence is being scanned;
  5720. \hang|output_text|, if an \.{\\output} routine is being scanned;
  5721. \hang|every_par_text|, if the text of \.{\\everypar} is being scanned;
  5722. \hang|every_math_text|, if the text of \.{\\everymath} is being scanned;
  5723. \hang|every_display_text|, if the text of \.{\\everydisplay} is being scanned;
  5724. \hang|every_hbox_text|, if the text of \.{\\everyhbox} is being scanned;
  5725. \hang|every_vbox_text|, if the text of \.{\\everyvbox} is being scanned;
  5726. \hang|every_job_text|, if the text of \.{\\everyjob} is being scanned;
  5727. \hang|every_cr_text|, if the text of \.{\\everycr} is being scanned;
  5728. \hang|mark_text|, if the text of a \.{\\mark} is being scanned;
  5729. \hang|write_text|, if the text of a \.{\\write} is being scanned.
  5730. \yskip\noindent
  5731. The codes for |output_text|, |every_par_text|, etc., are equal to a constant
  5732. plus the corresponding codes for token list parameters |output_routine_loc|,
  5733. |every_par_loc|, etc.  The token list begins with a reference count if and
  5734. only if |token_type>=macro|.
  5735. @^reference counts@>
  5736. @d token_list=0 {|state| code when scanning a token list}
  5737. @d token_type==index {type of current token list}
  5738. @d param_start==limit {base of macro parameters in |param_stack|}
  5739. @d parameter=0 {|token_type| code for parameter}
  5740. @d u_template=1 {|token_type| code for \<u_j> template}
  5741. @d v_template=2 {|token_type| code for \<v_j> template}
  5742. @d backed_up=3 {|token_type| code for text to be reread}
  5743. @d inserted=4 {|token_type| code for inserted texts}
  5744. @d macro=5 {|token_type| code for defined control sequences}
  5745. @d output_text=6 {|token_type| code for output routines}
  5746. @d every_par_text=7 {|token_type| code for \.{\\everypar}}
  5747. @d every_math_text=8 {|token_type| code for \.{\\everymath}}
  5748. @d every_display_text=9 {|token_type| code for \.{\\everydisplay}}
  5749. @d every_hbox_text=10 {|token_type| code for \.{\\everyhbox}}
  5750. @d every_vbox_text=11 {|token_type| code for \.{\\everyvbox}}
  5751. @d every_job_text=12 {|token_type| code for \.{\\everyjob}}
  5752. @d every_cr_text=13 {|token_type| code for \.{\\everycr}}
  5753. @d mark_text=14 {|token_type| code for \.{\\topmark}, etc.}
  5754. @d write_text=15 {|token_type| code for \.{\\write}}
  5755. @ The |param_stack| is an auxiliary array used to hold pointers to the token
  5756. lists for parameters at the current level and subsidiary levels of input.
  5757. This stack is maintained with convention (2), and it grows at a different
  5758. rate from the others.
  5759. @<Glob...@>=
  5760. @!param_stack:array [0..param_size] of pointer;
  5761.   {token list pointers for parameters}
  5762. @!param_ptr:0..param_size; {first unused entry in |param_stack|}
  5763. @!max_param_stack:integer;
  5764.   {largest value of |param_ptr|, will be |<=param_size+9|}
  5765. @ The input routines must also interact with the processing of
  5766. \.{\\halign} and \.{\\valign}, since the appearance of tab marks and
  5767. \.{\\cr} in certain places is supposed to trigger the beginning of special
  5768. \<v_j> template text in the scanner. This magic is accomplished by an
  5769. |align_state| variable that is increased by~1 when a `\.{\char'173}' is
  5770. scanned and decreased by~1 when a `\.{\char'175}' is scanned. The |align_state|
  5771. is nonzero during the \<u_j> template, after which it is set to zero; the
  5772. \<v_j> template begins when a tab mark or \.{\\cr} occurs at a time that
  5773. |align_state=0|.
  5774. @<Glob...@>=
  5775. @!align_state:integer; {group level with respect to current alignment}
  5776. @ Thus, the ``current input state'' can be very complicated indeed; there
  5777. can be many levels and each level can arise in a variety of ways. The
  5778. |show_context| procedure, which is used by \TeX's error-reporting routine to
  5779. print out the current input state on all levels down to the most recent
  5780. line of characters from an input file, illustrates most of these conventions.
  5781. The global variable |base_ptr| contains the lowest level that was
  5782. displayed by this procedure.
  5783. @<Glob...@>=
  5784. @!base_ptr:0..stack_size; {shallowest level shown by |show_context|}
  5785. @ The status at each level is indicated by printing two lines, where the first
  5786. line indicates what was read so far and the second line shows what remains
  5787. to be read. The context is cropped, if necessary, so that the first line
  5788. contains at most |half_error_line| characters, and the second contains
  5789. at most |error_line|. Non-current input levels whose |token_type| is
  5790. `|backed_up|' are shown only if they have not been fully read.
  5791. @p procedure show_context; {prints where the scanner is}
  5792. label done;
  5793. var old_setting:0..max_selector; {saved |selector| setting}
  5794. @!nn:integer; {number of contexts shown so far, less one}
  5795. @!bottom_line:boolean; {have we reached the final context to be shown?}
  5796. @<Local variables for formatting calculations@>@/
  5797. begin base_ptr:=input_ptr; input_stack[base_ptr]:=cur_input;
  5798.   {store current state}
  5799. nn:=-1; bottom_line:=false;
  5800. loop@+begin cur_input:=input_stack[base_ptr]; {enter into the context}
  5801.   if (state<>token_list) then
  5802.     if (name>17) or (base_ptr=0) then bottom_line:=true;
  5803.   if (base_ptr=input_ptr)or bottom_line or(nn<error_context_lines) then
  5804.     @<Display the current context@>
  5805.   else if nn=error_context_lines then
  5806.     begin print_nl("..."); incr(nn); {omitted if |error_context_lines<0|}
  5807.     end;
  5808.   if bottom_line then goto done;
  5809.   decr(base_ptr);
  5810.   end;
  5811. done: cur_input:=input_stack[input_ptr]; {restore original state}
  5812. @ @<Display the current context@>=
  5813. begin if (base_ptr=input_ptr) or (state<>token_list) or
  5814.    (token_type<>backed_up) or (loc<>null) then
  5815.     {we omit backed-up token lists that have already been read}
  5816.   begin tally:=0; {get ready to count characters}
  5817.   old_setting:=selector;
  5818.   if state<>token_list then
  5819.     begin @<Print location of current line@>;
  5820.     @<Pseudoprint the line@>;
  5821.     end
  5822.   else  begin @<Print type of token list@>;
  5823.     @<Pseudoprint the token list@>;
  5824.     end;
  5825.   selector:=old_setting; {stop pseudoprinting}
  5826.   @<Print two lines using the tricky pseudoprinted information@>;
  5827.   incr(nn);
  5828.   end;
  5829. @ This routine should be changed, if necessary, to give the best possible
  5830. indication of where the current line resides in the input file.
  5831. For example, on some systems it is best to print both a page and line number.
  5832. @^system dependencies@>
  5833. @<Print location of current line@>=
  5834. if name<=17 then
  5835.   if terminal_input then
  5836.     if base_ptr=0 then print_nl("<*>") else print_nl("<insert> ")
  5837.   else  begin print_nl("<read ");
  5838.     if name=17 then print_char("*")@+else print_int(name-1);
  5839. @.*\relax@>
  5840.     print_char(">");
  5841.     end
  5842. else  begin print_nl("l."); print_int(line);
  5843.   end;
  5844. print_char(" ")
  5845. @ @<Print type of token list@>=
  5846. case token_type of
  5847. parameter: print_nl("<argument> ");
  5848. u_template,v_template: print_nl("<template> ");
  5849. backed_up: if loc=null then print_nl("<recently read> ")
  5850.   else print_nl("<to be read again> ");
  5851. inserted: print_nl("<inserted text> ");
  5852. macro: begin print_ln; print_cs(name);
  5853.   end;
  5854. output_text: print_nl("<output> ");
  5855. every_par_text: print_nl("<everypar> ");
  5856. every_math_text: print_nl("<everymath> ");
  5857. every_display_text: print_nl("<everydisplay> ");
  5858. every_hbox_text: print_nl("<everyhbox> ");
  5859. every_vbox_text: print_nl("<everyvbox> ");
  5860. every_job_text: print_nl("<everyjob> ");
  5861. every_cr_text: print_nl("<everycr> ");
  5862. mark_text: print_nl("<mark> ");
  5863. write_text: print_nl("<write> ");
  5864. othercases print_nl("?") {this should never happen}
  5865. endcases
  5866. @ Here it is necessary to explain a little trick. We don't want to store a long
  5867. string that corresponds to a token list, because that string might take up
  5868. lots of memory; and we are printing during a time when an error message is
  5869. being given, so we dare not do anything that might overflow one of \TeX's
  5870. tables. So `pseudoprinting' is the answer: We enter a mode of printing
  5871. that stores characters into a buffer of length |error_line|, where character
  5872. $k+1$ is placed into \hbox{|trick_buf[k mod error_line]|} if
  5873. |k<trick_count|, otherwise character |k| is dropped. Initially we set
  5874. |tally:=0| and |trick_count:=1000000|; then when we reach the
  5875. point where transition from line 1 to line 2 should occur, we
  5876. set |first_count:=tally| and |trick_count:=@tmax@>(error_line,
  5877. tally+1+error_line-half_error_line)|. At the end of the
  5878. pseudoprinting, the values of |first_count|, |tally|, and
  5879. |trick_count| give us all the information we need to print the two lines,
  5880. and all of the necessary text is in |trick_buf|.
  5881. Namely, let |l| be the length of the descriptive information that appears
  5882. on the first line. The length of the context information gathered for that
  5883. line is |k=first_count|, and the length of the context information
  5884. gathered for line~2 is $m=\min(|tally|, |trick_count|)-k$. If |l+k<=h|,
  5885. where |h=half_error_line|, we print |trick_buf[0..k-1]| after the
  5886. descriptive information on line~1, and set |n:=l+k|; here |n| is the
  5887. length of line~1. If $l+k>h$, some cropping is necessary, so we set |n:=h|
  5888. and print `\.{...}' followed by
  5889. $$\hbox{|trick_buf[(l+k-h+3)..k-1]|,}$$
  5890. where subscripts of |trick_buf| are circular modulo |error_line|. The
  5891. second line consists of |n|~spaces followed by |trick_buf[k..(k+m-1)]|,
  5892. unless |n+m>error_line|; in the latter case, further cropping is done.
  5893. This is easier to program than to explain.
  5894. @<Local variables for formatting...@>=
  5895. @!i:0..buf_size; {index into |buffer|}
  5896. @!j:0..buf_size; {end of current line in |buffer|}
  5897. @!l:0..half_error_line; {length of descriptive information on line 1}
  5898. @!m:integer; {context information gathered for line 2}
  5899. @!n:0..error_line; {length of line 1}
  5900. @!p: integer; {starting or ending place in |trick_buf|}
  5901. @!q: integer; {temporary index}
  5902. @ The following code sets up the print routines so that they will gather
  5903. the desired information.
  5904. @d begin_pseudoprint==
  5905.   begin l:=tally; tally:=0; selector:=pseudo;
  5906.   trick_count:=1000000;
  5907.   end
  5908. @d set_trick_count==
  5909.   begin first_count:=tally;
  5910.   trick_count:=tally+1+error_line-half_error_line;
  5911.   if trick_count<error_line then trick_count:=error_line;
  5912.   end
  5913. @ And the following code uses the information after it has been gathered.
  5914. @<Print two lines using the tricky pseudoprinted information@>=
  5915. if trick_count=1000000 then set_trick_count;
  5916.   {|set_trick_count| must be performed}
  5917. if tally<trick_count then m:=tally-first_count
  5918. else m:=trick_count-first_count; {context on line 2}
  5919. if l+first_count<=half_error_line then
  5920.   begin p:=0; n:=l+first_count;
  5921.   end
  5922. else  begin print("..."); p:=l+first_count-half_error_line+3;
  5923.   n:=half_error_line;
  5924.   end;
  5925. for q:=p to first_count-1 do print_char(trick_buf[q mod error_line]);
  5926. print_ln;
  5927. for q:=1 to n do print_char(" "); {print |n| spaces to begin line~2}
  5928. if m+n<=error_line then p:=first_count+m else p:=first_count+(error_line-n-3);
  5929. for q:=first_count to p-1 do print_char(trick_buf[q mod error_line]);
  5930. if m+n>error_line then print("...")
  5931. @ But the trick is distracting us from our current goal, which is to
  5932. understand the input state. So let's concentrate on the data structures that
  5933. are being pseudoprinted as we finish up the |show_context| procedure.
  5934. @<Pseudoprint the line@>=
  5935. begin_pseudoprint;
  5936. if buffer[limit]=end_line_char then j:=limit
  5937. else j:=limit+1; {determine the effective end of the line}
  5938. if j>0 then for i:=start to j-1 do
  5939.   begin if i=loc then set_trick_count;
  5940.   print(buffer[i]);
  5941.   end
  5942. @ @<Pseudoprint the token list@>=
  5943. begin_pseudoprint;
  5944. if token_type<macro then show_token_list(start,loc,100000)
  5945. else show_token_list(link(start),loc,100000) {avoid reference count}
  5946. @ Here is the missing piece of |show_token_list| that is activated when the
  5947. token beginning line~2 is about to be shown:
  5948. @<Do magic computation@>=set_trick_count
  5949. @* \[23] Maintaining the input stacks.
  5950. The following subroutines change the input status in commonly needed ways.
  5951. First comes |push_input|, which stores the current state and creates a
  5952. new level (having, initially, the same properties as the old).
  5953. @d push_input==@t@> {enter a new input level, save the old}
  5954.   begin if input_ptr>max_in_stack then
  5955.     begin max_in_stack:=input_ptr;
  5956.     if input_ptr=stack_size then overflow("input stack size",stack_size);
  5957. @:TeX capacity exceeded input stack size}{\quad input stack size@>
  5958.     end;
  5959.   input_stack[input_ptr]:=cur_input; {stack the record}
  5960.   incr(input_ptr);
  5961.   end
  5962. @ And of course what goes up must come down.
  5963. @d pop_input==@t@> {leave an input level, re-enter the old}
  5964.   begin decr(input_ptr); cur_input:=input_stack[input_ptr];
  5965.   end
  5966. @ Here is a procedure that starts a new level of token-list input, given
  5967. a token list |p| and its type |t|. If |t=macro|, the calling routine should
  5968. set |name| and |loc|.
  5969. @d back_list(#)==begin_token_list(#,backed_up) {backs up a simple token list}
  5970. @d ins_list(#)==begin_token_list(#,inserted) {inserts a simple token list}
  5971. @p procedure begin_token_list(@!p:pointer;@!t:quarterword);
  5972. begin push_input; state:=token_list; start:=p; token_type:=t;
  5973. if t>=macro then {the token list starts with a reference count}
  5974.   begin add_token_ref(p);
  5975.   if t=macro then param_start:=param_ptr
  5976.   else  begin loc:=link(p);
  5977.     if tracing_macros>1 then
  5978.       begin begin_diagnostic; print_nl("");
  5979.       case t of
  5980.       mark_text:print_esc("mark");
  5981.       write_text:print_esc("write");
  5982.       othercases print_cmd_chr(assign_toks,t-output_text+output_routine_loc)
  5983.       endcases;@/
  5984.       print("->"); token_show(p); end_diagnostic(false);
  5985.       end;
  5986.     end;
  5987.   end
  5988. else loc:=p;
  5989. @ When a token list has been fully scanned, the following computations
  5990. should be done as we leave that level of input. The |token_type| tends
  5991. to be equal to either |backed_up| or |inserted| about 2/3 of the time.
  5992. @^inner loop@>
  5993. @p procedure end_token_list; {leave a token-list input level}
  5994. begin if token_type>=backed_up then {token list to be deleted}
  5995.   begin if token_type<=inserted then flush_list(start)
  5996.   else  begin delete_token_ref(start); {update reference count}
  5997.     if token_type=macro then {parameters must be flushed}
  5998.       while param_ptr>param_start do
  5999.         begin decr(param_ptr);
  6000.         flush_list(param_stack[param_ptr]);
  6001.         end;
  6002.     end;
  6003.   end
  6004. else if token_type=u_template then
  6005.   if align_state>500000 then align_state:=0
  6006.   else fatal_error("(interwoven alignment preambles are not allowed)");
  6007. @.interwoven alignment preambles...@>
  6008. pop_input;
  6009. check_interrupt;
  6010. @ Sometimes \TeX\ has read too far and wants to ``unscan'' what it has
  6011. seen. The |back_input| procedure takes care of this by putting the token
  6012. just scanned back into the input stream, ready to be read again. This
  6013. procedure can be used only if |cur_tok| represents the token to be
  6014. replaced. Some applications of \TeX\ use this procedure a lot,
  6015. so it has been slightly optimized for speed.
  6016. @^inner loop@>
  6017. @p procedure back_input; {undoes one token of input}
  6018. var p:pointer; {a token list of length one}
  6019. begin while (state=token_list)and(loc=null) do
  6020.   end_token_list; {conserve stack space}
  6021. p:=get_avail; info(p):=cur_tok;
  6022. if cur_tok<right_brace_limit then
  6023.   if cur_tok<left_brace_limit then decr(align_state)
  6024.   else incr(align_state);
  6025. push_input; state:=token_list; start:=p; token_type:=backed_up;
  6026. loc:=p; {that was |back_list(p)|, without procedure overhead}
  6027. @ @<Insert token |p| into \TeX's input@>=
  6028. begin t:=cur_tok; cur_tok:=p; back_input; cur_tok:=t;
  6029. @ The |back_error| routine is used when we want to replace an offending token
  6030. just before issuing an error message. This routine, like |back_input|,
  6031. requires that |cur_tok| has been set. We disable interrupts during the
  6032. call of |back_input| so that the help message won't be lost.
  6033. @p procedure back_error; {back up one token and call |error|}
  6034. begin OK_to_interrupt:=false; back_input; OK_to_interrupt:=true; error;
  6035. procedure ins_error; {back up one inserted token and call |error|}
  6036. begin OK_to_interrupt:=false; back_input; token_type:=inserted;
  6037. OK_to_interrupt:=true; error;
  6038. @ The |begin_file_reading| procedure starts a new level of input for lines
  6039. of characters to be read from a file, or as an insertion from the
  6040. terminal. It does not take care of opening the file, nor does it set |loc|
  6041. or |limit| or |line|.
  6042. @^system dependencies@>
  6043. @p procedure begin_file_reading;
  6044. begin if in_open=max_in_open then overflow("text input levels",max_in_open);
  6045. @:TeX capacity exceeded text input levels}{\quad text input levels@>
  6046. if first=buf_size then overflow("buffer size",buf_size);
  6047. @:TeX capacity exceeded buffer size}{\quad buffer size@>
  6048. incr(in_open); push_input; index:=in_open;
  6049. line_stack[index]:=line; start:=first; state:=mid_line;
  6050. name:=0; {|terminal_input| is now |true|}
  6051. @ Conversely, the variables must be downdated when such a level of input
  6052. is finished:
  6053. @p procedure end_file_reading;
  6054. begin first:=start; line:=line_stack[index];
  6055. if name>17 then a_close(cur_file); {forget it}
  6056. pop_input; decr(in_open);
  6057. @ In order to keep the stack from overflowing during a long sequence of
  6058. inserted `\.{\\show}' commands, the following routine removes completed
  6059. error-inserted lines from memory.
  6060. @p procedure clear_for_error_prompt;
  6061. begin while (state<>token_list)and terminal_input and@|
  6062.   (input_ptr>0)and(loc>limit) do end_file_reading;
  6063. print_ln; clear_terminal;
  6064. @ To get \TeX's whole input mechanism going, we perform the following
  6065. actions.
  6066. @<Initialize the input routines@>=
  6067. begin input_ptr:=0; max_in_stack:=0;
  6068. in_open:=0; open_parens:=0; max_buf_stack:=0;
  6069. param_ptr:=0; max_param_stack:=0;
  6070. first:=buf_size; repeat buffer[first]:=0; decr(first); until first=0;
  6071. scanner_status:=normal; warning_index:=null; first:=1;
  6072. state:=new_line; start:=1; index:=0; line:=0; name:=0;
  6073. force_eof:=false;
  6074. align_state:=1000000;@/
  6075. if not init_terminal then goto final_end;
  6076. limit:=last; first:=last+1; {|init_terminal| has set |loc| and |last|}
  6077. @* \[24] Getting the next token.
  6078. The heart of \TeX's input mechanism is the |get_next| procedure, which
  6079. we shall develop in the next few sections of the program. Perhaps we
  6080. shouldn't actually call it the ``heart,'' however, because it really acts
  6081. as \TeX's eyes and mouth, reading the source files and gobbling them up.
  6082. And it also helps \TeX\ to regurgitate stored token lists that are to be
  6083. processed again.
  6084. @^eyes and mouth@>
  6085. The main duty of |get_next| is to input one token and to set |cur_cmd|
  6086. and |cur_chr| to that token's command code and modifier. Furthermore, if
  6087. the input token is a control sequence, the |eqtb| location of that control
  6088. sequence is stored in |cur_cs|; otherwise |cur_cs| is set to zero.
  6089. Underlying this simple description is a certain amount of complexity
  6090. because of all the cases that need to be handled.
  6091. However, the inner loop of |get_next| is reasonably short and fast.
  6092. When |get_next| is asked to get the next token of a \.{\\read} line,
  6093. it sets |cur_cmd=cur_chr=cur_cs=0| in the case that no more tokens
  6094. appear on that line. (There might not be any tokens at all, if the
  6095. |end_line_char| has |ignore| as its catcode.)
  6096. @ The value of |par_loc| is the |eqtb| address of `\.{\\par}'. This quantity
  6097. is needed because a blank line of input is supposed to be exactly equivalent
  6098. to the appearance of \.{\\par}; we must set |cur_cs:=par_loc|
  6099. when detecting a blank line.
  6100. @<Glob...@>=
  6101. @!par_loc:pointer; {location of `\.{\\par}' in |eqtb|}
  6102. @!par_token:halfword; {token representing `\.{\\par}'}
  6103. @ @<Put each...@>=
  6104. primitive("par",par_end,256); {cf. |scan_file_name|}
  6105. @!@:par_}{\.{\\par} primitive@>
  6106. par_loc:=cur_val; par_token:=cs_token_flag+par_loc;
  6107. @ @<Cases of |print_cmd_chr|...@>=
  6108. par_end:print_esc("par");
  6109. @ Before getting into |get_next|, let's consider the subroutine that
  6110. is called when an `\.{\\outer}' control sequence has been scanned or
  6111. when the end of a file has been reached. These two cases are distinguished
  6112. by |cur_cs|, which is zero at the end of a file.
  6113. @p procedure check_outer_validity;
  6114. var p:pointer; {points to inserted token list}
  6115. @!q:pointer; {auxiliary pointer}
  6116. begin if scanner_status<>normal then
  6117.   begin deletions_allowed:=false;
  6118.   @<Back up an outer control sequence so that it can be reread@>;
  6119.   if scanner_status>skipping then
  6120.     @<Tell the user what has run away and try to recover@>
  6121.   else  begin print_err("Incomplete "); print_cmd_chr(if_test,cur_if);
  6122. @.Incomplete \\if...@>
  6123.     print("; all text was ignored after line "); print_int(skip_line);
  6124.     help3("A forbidden control sequence occurred in skipped text.")@/
  6125.     ("This kind of error happens when you say `\if...' and forget")@/
  6126.     ("the matching `\fi'. I've inserted a `\fi'; this might work.");
  6127.     if cur_cs<>0 then cur_cs:=0
  6128.     else help_line[2]:=@|
  6129.       "The file ended while I was skipping conditional text.";
  6130.     cur_tok:=cs_token_flag+frozen_fi; ins_error;
  6131.     end;
  6132.   deletions_allowed:=true;
  6133.   end;
  6134. @ An outer control sequence that occurs in a \.{\\read} will not be reread,
  6135. since the error recovery for \.{\\read} is not very powerful.
  6136. @<Back up an outer control sequence so that it can be reread@>=
  6137. if cur_cs<>0 then
  6138.   begin if (state=token_list)or(name<1)or(name>17) then
  6139.     begin p:=get_avail; info(p):=cs_token_flag+cur_cs;
  6140.     back_list(p); {prepare to read the control sequence again}
  6141.     end;
  6142.   cur_cmd:=spacer; cur_chr:=" "; {replace it by a space}
  6143.   end
  6144. @ @<Tell the user what has run away...@>=
  6145. begin runaway; {print a definition, argument, or preamble}
  6146. if cur_cs=0 then print_err("File ended")
  6147. @.File ended while scanning...@>
  6148. else  begin cur_cs:=0; print_err("Forbidden control sequence found");
  6149. @.Forbidden control sequence...@>
  6150.   end;
  6151. print(" while scanning ");
  6152. @<Print either `\.{definition}' or `\.{use}' or `\.{preamble}' or `\.{text}',
  6153.   and insert tokens that should lead to recovery@>;
  6154. print(" of "); sprint_cs(warning_index);
  6155. help4("I suspect you have forgotten a `}', causing me")@/
  6156. ("to read past where you wanted me to stop.")@/
  6157. ("I'll try to recover; but if the error is serious,")@/
  6158. ("you'd better type `E' or `X' now and fix your file.");@/
  6159. error;
  6160. @ The recovery procedure can't be fully understood without knowing more
  6161. about the \TeX\ routines that should be aborted, but we can sketch the
  6162. ideas here:  For a runaway definition we will insert a right brace; for a
  6163. runaway preamble, we will insert a special \.{\\cr} token and a right
  6164. brace; and for a runaway argument, we will set |long_state| to
  6165. |outer_call| and insert \.{\\par}.
  6166. @<Print either `\.{definition}' or ...@>=
  6167. p:=get_avail;
  6168. case scanner_status of
  6169. defining:begin print("definition"); info(p):=right_brace_token+"}";
  6170.   end;
  6171. matching:begin print("use"); info(p):=par_token; long_state:=outer_call;
  6172.   end;
  6173. aligning:begin print("preamble"); info(p):=right_brace_token+"}"; q:=p;
  6174.   p:=get_avail; link(p):=q; info(p):=cs_token_flag+frozen_cr;
  6175.   align_state:=-1000000;
  6176.   end;
  6177. absorbing:begin print("text"); info(p):=right_brace_token+"}";
  6178.   end;
  6179. end; {there are no other cases}
  6180. ins_list(p)
  6181. @ We need to mention a procedure here that may be called by |get_next|.
  6182. @p procedure@?firm_up_the_line; forward;
  6183. @ Now we're ready to take the plunge into |get_next| itself. Parts of
  6184. this routine are executed more often than any other instructions of \TeX.
  6185. @^mastication@>@^inner loop@>
  6186. @d switch=25 {a label in |get_next|}
  6187. @d start_cs=26 {another}
  6188. @p procedure get_next; {sets |cur_cmd|, |cur_chr|, |cur_cs| to next token}
  6189. label restart, {go here to get the next input token}
  6190.   switch, {go here to eat the next character from a file}
  6191.   reswitch, {go here to digest it again}
  6192.   start_cs, {go here to start looking for a control sequence}
  6193.   found, {go here when a control sequence has been found}
  6194.   exit; {go here when the next input token has been got}
  6195. var k:0..buf_size; {an index into |buffer|}
  6196. @!t:halfword; {a token}
  6197. @!cat:0..15; {|cat_code(cur_chr)|, usually}
  6198. @!c,@!cc:ASCII_code; {constituents of a possible expanded code}
  6199. @!d:2..3; {number of excess characters in an expanded code}
  6200. begin restart: cur_cs:=0;
  6201. if state<>token_list then
  6202. @<Input from external file, |goto restart| if no input found@>
  6203. else @<Input from token list, |goto restart| if end of list or
  6204.   if a parameter needs to be expanded@>;
  6205. @<If an alignment entry has just ended, take appropriate action@>;
  6206. exit:end;
  6207. @ An alignment entry ends when a tab or \.{\\cr} occurs, provided that the
  6208. current level of braces is the same as the level that was present at the
  6209. beginning of that alignment entry; i.e., provided that |align_state| has
  6210. returned to the value it had after the \<u_j> template for that entry.
  6211. @^inner loop@>
  6212. @<If an alignment entry has just ended, take appropriate action@>=
  6213. if cur_cmd<=car_ret then if cur_cmd>=tab_mark then if align_state=0 then
  6214.   @<Insert the \(v)\<v_j> template and |goto restart|@>
  6215. @ @<Input from external file, |goto restart| if no input found@>=
  6216. @^inner loop@>
  6217. begin switch: if loc<=limit then {current line not yet finished}
  6218.   begin cur_chr:=buffer[loc]; incr(loc);
  6219.   reswitch: cur_cmd:=cat_code(cur_chr);
  6220.   @<Change state if necessary, and |goto switch| if the
  6221.     current character should be ignored,
  6222.     or |goto reswitch| if the current character
  6223.     changes to another@>;
  6224.   end
  6225. else  begin state:=new_line;@/
  6226.   @<Move to next line of file,
  6227.     or |goto restart| if there is no next line,
  6228.     or |return| if a \.{\\read} line has finished@>;
  6229.   check_interrupt;
  6230.   goto switch;
  6231.   end;
  6232. @ The following 48-way switch accomplishes the scanning quickly, assuming
  6233. that a decent \PASCAL\ compiler has translated the code. Note that the numeric
  6234. values for |mid_line|, |skip_blanks|, and |new_line| are spaced
  6235. apart from each other by |max_char_code+1|, so we can add a character's
  6236. command code to the state to get a single number that characterizes both.
  6237. @d any_state_plus(#) == mid_line+#,skip_blanks+#,new_line+#
  6238. @<Change state if necessary...@>=
  6239. case state+cur_cmd of
  6240. @<Cases where character is ignored@>: goto switch;
  6241. any_state_plus(escape): @<Scan a control sequence
  6242.   and set |state:=skip_blanks| or |mid_line|@>;
  6243. any_state_plus(active_char): @<Process an active-character control sequence
  6244.   and set |state:=mid_line|@>;
  6245. any_state_plus(sup_mark): @<If this |sup_mark| starts an expanded character
  6246.   like~\.{\^\^A} or~\.{\^\^df}, then |goto reswitch|,
  6247.   otherwise set |state:=mid_line|@>;
  6248. any_state_plus(invalid_char): @<Decry the invalid character and
  6249.   |goto restart|@>;
  6250. @t\4@>@<Handle situations involving spaces, braces, changes of state@>@;
  6251. othercases do_nothing
  6252. endcases
  6253. @ @<Cases where character is ignored@>=
  6254. any_state_plus(ignore),skip_blanks+spacer,new_line+spacer
  6255. @ We go to |restart| instead of to |switch|, because |state| might equal
  6256. |token_list| after the error has been dealt with
  6257. (cf.\ |clear_for_error_prompt|).
  6258. @<Decry the invalid...@>=
  6259. begin print_err("Text line contains an invalid character");
  6260. @.Text line contains...@>
  6261. help2("A funny symbol that I can't read has just been input.")@/
  6262. ("Continue, and I'll forget that it ever happened.");@/
  6263. deletions_allowed:=false; error; deletions_allowed:=true;
  6264. goto restart;
  6265. @ @d add_delims_to(#)==#+math_shift,#+tab_mark,#+mac_param,
  6266.   #+sub_mark,#+letter,#+other_char
  6267. @<Handle situations involving spaces, braces, changes of state@>=
  6268. mid_line+spacer:@<Enter |skip_blanks| state, emit a space@>;
  6269. mid_line+car_ret:@<Finish line, emit a space@>;
  6270. skip_blanks+car_ret,any_state_plus(comment):
  6271.   @<Finish line, |goto switch|@>;
  6272. new_line+car_ret:@<Finish line, emit a \.{\\par}@>;
  6273. mid_line+left_brace: incr(align_state);
  6274. skip_blanks+left_brace,new_line+left_brace: begin
  6275.   state:=mid_line; incr(align_state);
  6276.   end;
  6277. mid_line+right_brace: decr(align_state);
  6278. skip_blanks+right_brace,new_line+right_brace: begin
  6279.   state:=mid_line; decr(align_state);
  6280.   end;
  6281. add_delims_to(skip_blanks),add_delims_to(new_line): state:=mid_line;
  6282. @ When a character of type |spacer| gets through, its character code is
  6283. changed to $\.{"\ "}=@'40$. This means that the ASCII codes for tab and space,
  6284. and for the space inserted at the end of a line, will
  6285. be treated alike when macro parameters are being matched. We do this
  6286. since such characters are indistinguishable on most computer terminal displays.
  6287. @<Finish line, emit a space@>=
  6288. begin loc:=limit+1; cur_cmd:=spacer; cur_chr:=" ";
  6289. @ The following code is performed only when |cur_cmd=spacer|.
  6290. @<Enter |skip_blanks| state, emit a space@>=
  6291. begin state:=skip_blanks; cur_chr:=" ";
  6292. @ @<Finish line, |goto switch|@>=
  6293. begin loc:=limit+1; goto switch;
  6294. @ @<Finish line, emit a \.{\\par}@>=
  6295. begin loc:=limit+1; cur_cs:=par_loc; cur_cmd:=eq_type(cur_cs);
  6296. cur_chr:=equiv(cur_cs);
  6297. if cur_cmd>=outer_call then check_outer_validity;
  6298. @ Notice that a code like \.{\^\^8} becomes \.x if not followed by a hex digit.
  6299. @d is_hex(#)==(((#>="0")and(#<="9"))or((#>="a")and(#<="f")))
  6300. @d hex_to_cur_chr==
  6301.   if c<="9" then cur_chr:=c-"0" @+else cur_chr:=c-"a"+10;
  6302.   if cc<="9" then cur_chr:=16*cur_chr+cc-"0"
  6303.   else cur_chr:=16*cur_chr+cc-"a"+10
  6304. @<If this |sup_mark| starts an expanded character...@>=
  6305. begin if cur_chr=buffer[loc] then if loc<limit then
  6306.   begin c:=buffer[loc+1]; @+if c<@'200 then {yes we have an expanded char}
  6307.     begin loc:=loc+2; 
  6308.     if is_hex(c) then if loc<=limit then
  6309.       begin cc:=buffer[loc]; @+if is_hex(cc) then
  6310.         begin incr(loc); hex_to_cur_chr; goto reswitch;
  6311.         end;
  6312.       end;
  6313.     if c<@'100 then cur_chr:=c+@'100 @+else cur_chr:=c-@'100;
  6314.     goto reswitch;
  6315.     end;
  6316.   end;
  6317. state:=mid_line;
  6318. @ @<Process an active-character...@>=
  6319. begin cur_cs:=cur_chr+active_base;
  6320. cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs); state:=mid_line;
  6321. if cur_cmd>=outer_call then check_outer_validity;
  6322. @ Control sequence names are scanned only when they appear in some line of
  6323. a file; once they have been scanned the first time, their |eqtb| location
  6324. serves as a unique identification, so \TeX\ doesn't need to refer to the
  6325. original name any more except when it prints the equivalent in symbolic form.
  6326. The program that scans a control sequence has been written carefully
  6327. in order to avoid the blowups that might otherwise occur if a malicious
  6328. user tried something like `\.{\\catcode\'15=0}'. The algorithm might
  6329. look at |buffer[limit+1]|, but it never looks at |buffer[limit+2]|.
  6330. If expanded characters like `\.{\^\^A}' or `\.{\^\^df}'
  6331. appear in or just following
  6332. a control sequence name, they are converted to single characters in the
  6333. buffer and the process is repeated, slowly but surely.
  6334. @<Scan a control...@>=
  6335. begin if loc>limit then cur_cs:=null_cs {|state| is irrelevant in this case}
  6336. else  begin start_cs: k:=loc; cur_chr:=buffer[k]; cat:=cat_code(cur_chr);
  6337.   incr(k);
  6338.   if cat=letter then state:=skip_blanks
  6339.   else if cat=spacer then state:=skip_blanks
  6340.   else state:=mid_line;
  6341.   if (cat=letter)and(k<=limit) then
  6342.     @<Scan ahead in the buffer until finding a nonletter;
  6343.     if an expanded code is encountered, reduce it
  6344.     and |goto start_cs|; otherwise if a multiletter control
  6345.     sequence is found, adjust |cur_cs| and |loc|, and
  6346.     |goto found|@>
  6347.   else @<If an expanded code is present, reduce it and |goto start_cs|@>;
  6348.   cur_cs:=single_base+buffer[loc]; incr(loc);
  6349.   end;
  6350. found: cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  6351. if cur_cmd>=outer_call then check_outer_validity;
  6352. @ Whenever we reach the following piece of code, we will have
  6353. |cur_chr=buffer[k-1]| and |k<=limit+1| and |cat=cat_code(cur_chr)|. If an
  6354. expanded code like \.{\^\^A} or \.{\^\^df} appears in |buffer[(k-1)..(k+1)]|
  6355. or |buffer[(k-1)..(k+2)]|, we
  6356. will store the corresponding code in |buffer[k-1]| and shift the rest of
  6357. the buffer left two or three places.
  6358. @<If an expanded...@>=
  6359. begin if buffer[k]=cur_chr then @+if cat=sup_mark then @+if k<limit then
  6360.   begin c:=buffer[k+1]; @+if c<@'200 then {yes, one is indeed present}
  6361.     begin d:=2;
  6362.     if is_hex(c) then @+if k+2<=limit then
  6363.       begin cc:=buffer[k+2]; @+if is_hex(cc) then incr(d);
  6364.       end;
  6365.     if d>2 then
  6366.       begin hex_to_cur_chr; buffer[k-1]:=cur_chr;
  6367.       end
  6368.     else if c<@'100 then buffer[k-1]:=c+@'100
  6369.     else buffer[k-1]:=c-@'100;
  6370.     limit:=limit-d; first:=first-d;
  6371.     while k<=limit do
  6372.       begin buffer[k]:=buffer[k+d]; incr(k);
  6373.       end;
  6374.     goto start_cs;
  6375.     end;
  6376.   end;
  6377. @ @<Scan ahead in the buffer...@>=
  6378. begin repeat cur_chr:=buffer[k]; cat:=cat_code(cur_chr); incr(k);
  6379. until (cat<>letter)or(k>limit);
  6380. @<If an expanded...@>;
  6381. if cat<>letter then decr(k);
  6382.   {now |k| points to first nonletter}
  6383. if k>loc+1 then {multiletter control sequence has been scanned}
  6384.   begin cur_cs:=id_lookup(loc,k-loc); loc:=k; goto found;
  6385.   end;
  6386. @ Let's consider now what happens when |get_next| is looking at a token list.
  6387. @<Input from token list, |goto restart| if end of list or
  6388.   if a parameter needs to be expanded@>=
  6389. if loc<>null then {list not exhausted}
  6390. @^inner loop@>
  6391.   begin t:=info(loc); loc:=link(loc); {move to next}
  6392.   if t>=cs_token_flag then {a control sequence token}
  6393.     begin cur_cs:=t-cs_token_flag;
  6394.     cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  6395.     if cur_cmd>=outer_call then
  6396.       if cur_cmd=dont_expand then
  6397.         @<Get the next token, suppressing expansion@>
  6398.       else check_outer_validity;
  6399.     end
  6400.   else  begin cur_cmd:=t div @'400; cur_chr:=t mod @'400;
  6401.     case cur_cmd of
  6402.     left_brace: incr(align_state);
  6403.     right_brace: decr(align_state);
  6404.     out_param: @<Insert macro parameter and |goto restart|@>;
  6405.     othercases do_nothing
  6406.     endcases;
  6407.     end;
  6408.   end
  6409. else  begin {we are done with this token list}
  6410.   end_token_list; goto restart; {resume previous level}
  6411.   end
  6412. @ The present point in the program is reached only when the |expand|
  6413. routine has inserted a special marker into the input. In this special
  6414. case, |info(loc)| is known to be a control sequence token, and |link(loc)=null|.
  6415. @d no_expand_flag=257 {this characterizes a special variant of |relax|}
  6416. @<Get the next token, suppressing expansion@>=
  6417. begin cur_cs:=info(loc)-cs_token_flag; loc:=null;@/
  6418. cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  6419. if cur_cmd>max_command then
  6420.   begin cur_cmd:=relax; cur_chr:=no_expand_flag;
  6421.   end;
  6422. @ @<Insert macro parameter...@>=
  6423. begin begin_token_list(param_stack[param_start+cur_chr-1],parameter);
  6424. goto restart;
  6425. @ All of the easy branches of |get_next| have now been taken care of.
  6426. There is one more branch.
  6427. @d end_line_char_inactive == (end_line_char<0)or(end_line_char>255)
  6428. @<Move to next line of file, or |goto restart|...@>=
  6429. if name>17 then @<Read next line of file into |buffer|, or
  6430.   |goto restart| if the file has ended@>
  6431. else  begin if not terminal_input then {\.{\\read} line has ended}
  6432.     begin cur_cmd:=0; cur_chr:=0; return;
  6433.     end;
  6434.   if input_ptr>0 then {text was inserted during error recovery}
  6435.     begin end_file_reading; goto restart; {resume previous level}
  6436.     end;
  6437.   if selector<log_only then open_log_file;
  6438.   if interaction>nonstop_mode then
  6439.     begin if end_line_char_inactive then incr(limit);
  6440.     if limit=start then {previous line was empty}
  6441.       print_nl("(Please type a command or say `\end')");
  6442. @.Please type...@>
  6443.     print_ln; first:=start;
  6444.     prompt_input("*"); {input on-line into |buffer|}
  6445. @.*\relax@>
  6446.     limit:=last;
  6447.     if end_line_char_inactive then decr(limit)
  6448.     else  buffer[limit]:=end_line_char;
  6449.     first:=limit+1;
  6450.     loc:=start;
  6451.     end
  6452.   else fatal_error("*** (job aborted, no legal \end found)");
  6453. @.job aborted@>
  6454.     {nonstop mode, which is intended for overnight batch processing,
  6455.     never waits for on-line input}
  6456.   end
  6457. @ The global variable |force_eof| is normally |false|; it is set |true|
  6458. by an \.{\\endinput} command.
  6459. @<Glob...@>=
  6460. @!force_eof:boolean; {should the next \.{\\input} be aborted early?}
  6461. @ @<Read next line of file into |buffer|, or
  6462.   |goto restart| if the file has ended@>=
  6463. begin incr(line); first:=start;
  6464. if not force_eof then
  6465.   begin if input_ln(cur_file,true) then {not end of file}
  6466.     firm_up_the_line {this sets |limit|}
  6467.   else force_eof:=true;
  6468.   end;
  6469. if force_eof then
  6470.   begin print_char(")"); decr(open_parens);
  6471.   update_terminal; {show user that file has been read}
  6472.   force_eof:=false;
  6473.   end_file_reading; {resume previous level}
  6474.   check_outer_validity; goto restart;
  6475.   end;
  6476. if end_line_char_inactive then decr(limit)
  6477. else  buffer[limit]:=end_line_char;
  6478. first:=limit+1; loc:=start; {ready to read}
  6479. @ If the user has set the |pausing| parameter to some positive value,
  6480. and if nonstop mode has not been selected, each line of input is displayed
  6481. on the terminal and the transcript file, followed by `\.{=>}'.
  6482. \TeX\ waits for a response. If the response is simply |carriage_return|, the
  6483. line is accepted as it stands, otherwise the line typed is
  6484. used instead of the line in the file.
  6485. @p procedure firm_up_the_line;
  6486. var k:0..buf_size; {an index into |buffer|}
  6487. begin limit:=last;
  6488. if pausing>0 then if interaction>nonstop_mode then
  6489.   begin wake_up_terminal; print_ln;
  6490.   if start<limit then for k:=start to limit-1 do print(buffer[k]);
  6491.   first:=limit; prompt_input("=>"); {wait for user response}
  6492. @.=>@>
  6493.   if last>first then
  6494.     begin for k:=first to last-1 do {move line down in buffer}
  6495.       buffer[k+start-first]:=buffer[k];
  6496.     limit:=start+last-first;
  6497.     end;
  6498.   end;
  6499. @ Since |get_next| is used so frequently in \TeX, it is convenient
  6500. to define three related procedures that do a little more:
  6501. \yskip\hang|get_token| not only sets |cur_cmd| and |cur_chr|, it
  6502. also sets |cur_tok|, a packed halfword version of the current token.
  6503. \yskip\hang|get_x_token|, meaning ``get an expanded token,'' is like
  6504. |get_token|, but if the current token turns out to be a user-defined
  6505. control sequence (i.e., a macro call), or a conditional,
  6506. or something like \.{\\topmark} or \.{\\expandafter} or \.{\\csname},
  6507. it is eliminated from the input by beginning the expansion of the macro
  6508. or the evaluation of the conditional.
  6509. \yskip\hang|x_token| is like |get_x_token| except that it assumes that
  6510. |get_next| has already been called.
  6511. \yskip\noindent
  6512. In fact, these three procedures account for {\sl all\/} uses of |get_next|,
  6513. except for two places in the ``inner loop'' when |cur_tok| need not be set,
  6514. and except when the arguments to \.{\\ifx} are being scanned.
  6515. @ No new control sequences will be defined except during a call of
  6516. |get_token|, or when \.{\\csname} compresses a token list, because
  6517. |no_new_control_sequence| is always |true| at other times.
  6518. @p procedure get_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|}
  6519. begin no_new_control_sequence:=false; get_next; no_new_control_sequence:=true;
  6520. @^inner loop@>
  6521. if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
  6522. else cur_tok:=cs_token_flag+cur_cs;
  6523. @* \[25] Expanding the next token.
  6524. Only a dozen or so command codes |>max_command| can possibly be returned by
  6525. |get_next|; in increasing order, they are |undefined_cs|, |expand_after|,
  6526. |no_expand|, |input|, |if_test|, |fi_or_else|, |cs_name|, |convert|, |the|,
  6527. |top_bot_mark|, |call|, |long_call|, |outer_call|, |long_outer_call|, and
  6528. |end_template|.{\emergencystretch=40pt\par}
  6529. The |expand| subroutine is used when |cur_cmd>max_command|. It removes a
  6530. ``call'' or a conditional or one of the other special operations just
  6531. listed.  It follows that |expand| might invoke itself recursively. In all
  6532. cases, |expand| destroys the current token, but it sets things up so that
  6533. the next |get_next| will deliver the appropriate next token. The value of
  6534. |cur_tok| need not be known when |expand| is called.
  6535. Since several of the basic scanning routines communicate via global variables,
  6536. their values are saved as local variables of |expand| so that
  6537. recursive calls don't invalidate them.
  6538. @^recursion@>
  6539. @p@t\4@>@<Declare the procedure called |macro_call|@>@;@/
  6540. @t\4@>@<Declare the procedure called |insert_relax|@>@;@/
  6541. procedure@?pass_text; forward;@t\2@>
  6542. procedure@?start_input; forward;@t\2@>
  6543. procedure@?conditional; forward;@t\2@>
  6544. procedure@?get_x_token; forward;@t\2@>
  6545. procedure@?conv_toks; forward;@t\2@>
  6546. procedure@?ins_the_toks; forward;@t\2@>
  6547. procedure expand;
  6548. var t:halfword; {token that is being ``expanded after''}
  6549. @!p,@!q,@!r:pointer; {for list manipulation}
  6550. @!j:0..buf_size; {index into |buffer|}
  6551. @!cv_backup:integer; {to save the global quantity |cur_val|}
  6552. @!cvl_backup,@!radix_backup,@!co_backup:small_number;
  6553.   {to save |cur_val_level|, etc.}
  6554. @!backup_backup:pointer; {to save |link(backup_head)|}
  6555. @!save_scanner_status:small_number; {temporary storage of |scanner_status|}
  6556. begin cv_backup:=cur_val; cvl_backup:=cur_val_level; radix_backup:=radix;
  6557. co_backup:=cur_order; backup_backup:=link(backup_head);
  6558. if cur_cmd<call then @<Expand a nonmacro@>
  6559. else if cur_cmd<end_template then macro_call
  6560. else @<Insert a token containing |frozen_endv|@>;
  6561. cur_val:=cv_backup; cur_val_level:=cvl_backup; radix:=radix_backup;
  6562. cur_order:=co_backup; link(backup_head):=backup_backup;
  6563. @ @<Expand a nonmacro@>=
  6564. begin if tracing_commands>1 then show_cur_cmd_chr;
  6565. case cur_cmd of
  6566. top_bot_mark:@<Insert the \(a)appropriate mark text into the scanner@>;
  6567. expand_after:@<Expand the token after the next token@>;
  6568. no_expand:@<Suppress expansion of the next token@>;
  6569. cs_name:@<Manufacture a control sequence name@>;
  6570. convert:conv_toks; {this procedure is discussed in Part 27 below}
  6571. the:ins_the_toks; {this procedure is discussed in Part 27 below}
  6572. if_test:conditional; {this procedure is discussed in Part 28 below}
  6573. fi_or_else:@<Terminate the current conditional and skip to \.{\\fi}@>;
  6574. input:@<Initiate or terminate input from a file@>;
  6575. othercases @<Complain about an undefined macro@>
  6576. endcases;
  6577. @ It takes only a little shuffling to do what \TeX\ calls \.{\\expandafter}.
  6578. @<Expand the token after...@>=
  6579. begin get_token; t:=cur_tok; get_token;
  6580. if cur_cmd>max_command then expand@+else back_input;
  6581. cur_tok:=t; back_input;
  6582. @ The implementation of \.{\\noexpand} is a bit trickier, because it is
  6583. necessary to insert a special `|dont_expand|' marker into \TeX's reading
  6584. mechanism.  This special marker is processed by |get_next|, but it does
  6585. not slow down the inner loop.
  6586. Since \.{\\outer} macros might arise here, we must also
  6587. clear the |scanner_status| temporarily.
  6588. @<Suppress expansion...@>=
  6589. begin save_scanner_status:=scanner_status; scanner_status:=normal;
  6590. get_token; scanner_status:=save_scanner_status; t:=cur_tok;
  6591. back_input; {now |start| and |loc| point to the backed-up token |t|}
  6592. if t>=cs_token_flag then
  6593.   begin p:=get_avail; info(p):=cs_token_flag+frozen_dont_expand;
  6594.   link(p):=loc; start:=p; loc:=p;
  6595.   end;
  6596. @ @<Complain about an undefined macro@>=
  6597. begin print_err("Undefined control sequence");
  6598. @.Undefined control sequence@>
  6599. help5("The control sequence at the end of the top line")@/
  6600. ("of your error message was never \def'ed. If you have")@/
  6601. ("misspelled it (e.g., `\hobx'), type `I' and the correct")@/
  6602. ("spelling (e.g., `I\hbox'). Otherwise just continue,")@/
  6603. ("and I'll forget about whatever was undefined.");
  6604. error;
  6605. @ The |expand| procedure and some other routines that construct token
  6606. lists find it convenient to use the following macros, which are valid only if
  6607. the variables |p| and |q| are reserved for token-list building.
  6608. @d store_new_token(#)==begin q:=get_avail; link(p):=q; info(q):=#;
  6609.   p:=q; {|link(p)| is |null|}
  6610.   end
  6611. @d fast_store_new_token(#)==begin fast_get_avail(q); link(p):=q; info(q):=#;
  6612.   p:=q; {|link(p)| is |null|}
  6613.   end
  6614. @ @<Manufacture a control...@>=
  6615. begin r:=get_avail; p:=r; {head of the list of characters}
  6616. repeat get_x_token;
  6617. if cur_cs=0 then store_new_token(cur_tok);
  6618. until cur_cs<>0;
  6619. if cur_cmd<>end_cs_name then @<Complain about missing \.{\\endcsname}@>;
  6620. @<Look up the characters of list |r| in the hash table, and set |cur_cs|@>;
  6621. flush_list(r);
  6622. if eq_type(cur_cs)=undefined_cs then
  6623.   begin eq_define(cur_cs,relax,256); {N.B.: The |save_stack| might change}
  6624.   end; {the control sequence will now match `\.{\\relax}'}
  6625. cur_tok:=cur_cs+cs_token_flag; back_input;
  6626. @ @<Complain about missing \.{\\endcsname}@>=
  6627. begin print_err("Missing "); print_esc("endcsname"); print(" inserted");
  6628. @.Missing \\endcsname...@>
  6629. help2("The control sequence marked <to be read again> should")@/
  6630.   ("not appear between \csname and \endcsname.");
  6631. back_error;
  6632. @ @<Look up the characters of list |r| in the hash table...@>=
  6633. j:=first; p:=link(r);
  6634. while p<>null do
  6635.   begin if j>=max_buf_stack then
  6636.     begin max_buf_stack:=j+1;
  6637.     if max_buf_stack=buf_size then
  6638.       overflow("buffer size",buf_size);
  6639. @:TeX capacity exceeded buffer size}{\quad buffer size@>
  6640.     end;
  6641.   buffer[j]:=info(p) mod @'400; incr(j); p:=link(p);
  6642.   end;
  6643. if j>first+1 then
  6644.   begin no_new_control_sequence:=false; cur_cs:=id_lookup(first,j-first);
  6645.   no_new_control_sequence:=true;
  6646.   end
  6647. else if j=first then cur_cs:=null_cs {the list is empty}
  6648. else cur_cs:=single_base+buffer[first] {the list has length one}
  6649. @ An |end_template| command is effectively changed to an |endv| command
  6650. by the following code. (The reason for this is discussed below; the
  6651. |frozen_end_template| at the end of the template has passed the
  6652. |check_outer_validity| test, so its mission of error detection has been
  6653. accomplished.)
  6654. @<Insert a token containing |frozen_endv|@>=
  6655. begin cur_tok:=cs_token_flag+frozen_endv; back_input;
  6656. @ The processing of \.{\\input} involves the |start_input| subroutine,
  6657. which will be declared later; the processing of \.{\\endinput} is trivial.
  6658. @<Put each...@>=
  6659. primitive("input",input,0);@/
  6660. @!@:input_}{\.{\\input} primitive@>
  6661. primitive("endinput",input,1);@/
  6662. @!@:end_input_}{\.{\\endinput} primitive@>
  6663. @ @<Cases of |print_cmd_chr|...@>=
  6664. input: if chr_code=0 then print_esc("input")@+else print_esc("endinput");
  6665. @ @<Initiate or terminate input...@>=
  6666. if cur_chr>0 then force_eof:=true
  6667. else if name_in_progress then insert_relax
  6668. else start_input
  6669. @ Sometimes the expansion looks too far ahead, so we want to insert
  6670. a harmless \.{\\relax} into the user's input.
  6671. @<Declare the procedure called |insert_relax|@>=
  6672. procedure insert_relax;
  6673. begin cur_tok:=cs_token_flag+cur_cs; back_input;
  6674. cur_tok:=cs_token_flag+frozen_relax; back_input; token_type:=inserted;
  6675. @ Here is a recursive procedure that is \TeX's usual way to get the
  6676. next token of input. It has been slightly optimized to take account of
  6677. common cases.
  6678. @p procedure get_x_token; {sets |cur_cmd|, |cur_chr|, |cur_tok|,
  6679.   and expands macros}
  6680. label restart,done;
  6681. begin restart: get_next;
  6682. @^inner loop@>
  6683. if cur_cmd<=max_command then goto done;
  6684. if cur_cmd>=call then
  6685.   if cur_cmd<end_template then macro_call
  6686.   else  begin cur_cs:=frozen_endv; cur_cmd:=endv;
  6687.     goto done; {|cur_chr=null_list|}
  6688.     end
  6689. else expand;
  6690. goto restart;
  6691. done: if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
  6692. else cur_tok:=cs_token_flag+cur_cs;
  6693. @ The |get_x_token| procedure is equivalent to two consecutive
  6694. procedure calls: |get_next; x_token|.
  6695. @p procedure x_token; {|get_x_token| without the initial |get_next|}
  6696. begin while cur_cmd>max_command do
  6697.   begin expand;
  6698.   get_next;
  6699.   end;
  6700. if cur_cs=0 then cur_tok:=(cur_cmd*@'400)+cur_chr
  6701. else cur_tok:=cs_token_flag+cur_cs;
  6702. @ A control sequence that has been \.{\\def}'ed by the user is expanded by
  6703. \TeX's |macro_call| procedure.
  6704. Before we get into the details of |macro_call|, however, let's consider the
  6705. treatment of primitives like \.{\\topmark}, since they are essentially
  6706. macros without parameters. The token lists for such marks are kept in a
  6707. global array of five pointers; we refer to the individual entries of this
  6708. array by symbolic names |top_mark|, etc. The value of |top_mark| is either
  6709. |null| or a pointer to the reference count of a token list.
  6710. @d top_mark_code=0 {the mark in effect at the previous page break}
  6711. @d first_mark_code=1 {the first mark between |top_mark| and |bot_mark|}
  6712. @d bot_mark_code=2 {the mark in effect at the current page break}
  6713. @d split_first_mark_code=3 {the first mark found by \.{\\vsplit}}
  6714. @d split_bot_mark_code=4 {the last mark found by \.{\\vsplit}}
  6715. @d top_mark==cur_mark[top_mark_code]
  6716. @d first_mark==cur_mark[first_mark_code]
  6717. @d bot_mark==cur_mark[bot_mark_code]
  6718. @d split_first_mark==cur_mark[split_first_mark_code]
  6719. @d split_bot_mark==cur_mark[split_bot_mark_code]
  6720. @<Glob...@>=
  6721. @!cur_mark:array[top_mark_code..split_bot_mark_code] of pointer;
  6722.   {token lists for marks}
  6723. @ @<Set init...@>=
  6724. top_mark:=null; first_mark:=null; bot_mark:=null;
  6725. split_first_mark:=null; split_bot_mark:=null;
  6726. @ @<Put each...@>=
  6727. primitive("topmark",top_bot_mark,top_mark_code);
  6728. @!@:top_mark_}{\.{\\topmark} primitive@>
  6729. primitive("firstmark",top_bot_mark,first_mark_code);
  6730. @!@:first_mark_}{\.{\\firstmark} primitive@>
  6731. primitive("botmark",top_bot_mark,bot_mark_code);
  6732. @!@:bot_mark_}{\.{\\botmark} primitive@>
  6733. primitive("splitfirstmark",top_bot_mark,split_first_mark_code);
  6734. @!@:split_first_mark_}{\.{\\splitfirstmark} primitive@>
  6735. primitive("splitbotmark",top_bot_mark,split_bot_mark_code);
  6736. @!@:split_bot_mark_}{\.{\\splitbotmark} primitive@>
  6737. @ @<Cases of |print_cmd_chr|...@>=
  6738. top_bot_mark: case chr_code of
  6739.   first_mark_code: print_esc("firstmark");
  6740.   bot_mark_code: print_esc("botmark");
  6741.   split_first_mark_code: print_esc("splitfirstmark");
  6742.   split_bot_mark_code: print_esc("splitbotmark");
  6743.   othercases print_esc("topmark")
  6744.   endcases;
  6745. @ The following code is activated when |cur_cmd=top_bot_mark| and
  6746. when |cur_chr| is a code like |top_mark_code|.
  6747. @<Insert the \(a)appropriate mark text into the scanner@>=
  6748. begin if cur_mark[cur_chr]<>null then
  6749.   begin_token_list(cur_mark[cur_chr],mark_text);
  6750. @ Now let's consider |macro_call| itself, which is invoked when \TeX\ is
  6751. scanning a control sequence whose |cur_cmd| is either |call|, |long_call|,
  6752. |outer_call|, or |long_outer_call|.  The control sequence definition
  6753. appears in the token list whose reference count is in location |cur_chr|
  6754. of |mem|.
  6755. The global variable |long_state| will be set to |call| or to |long_call|,
  6756. depending on whether or not the control sequence disallows \.{\\par}
  6757. in its parameters. The |get_next| routine will set |long_state| to
  6758. |outer_call| and emit \.{\\par}, if a file ends or if an \.{\\outer}
  6759. control sequence occurs in the midst of an argument.
  6760. @<Glob...@>=
  6761. @!long_state:call..long_outer_call; {governs the acceptance of \.{\\par}}
  6762. @ The parameters, if any, must be scanned before the macro is expanded.
  6763. Parameters are token lists without reference counts. They are placed on
  6764. an auxiliary stack called |pstack| while they are being scanned, since
  6765. the |param_stack| may be losing entries during the matching process.
  6766. (Note that |param_stack| can't be gaining entries, since |macro_call| is
  6767. the only routine that puts anything onto |param_stack|, and it
  6768. is not recursive.)
  6769. @<Glob...@>=
  6770. @!pstack:array[0..8] of pointer; {arguments supplied to a macro}
  6771. @ After parameter scanning is complete, the parameters are moved to the
  6772. |param_stack|. Then the macro body is fed to the scanner; in other words,
  6773. |macro_call| places the defined text of the control sequence at the
  6774. top of\/ \TeX's input stack, so that |get_next| will proceed to read it
  6775. next.
  6776. The global variable |cur_cs| contains the |eqtb| address of the control sequence
  6777. being expanded, when |macro_call| begins. If this control sequence has not been
  6778. declared \.{\\long}, i.e., if its command code in the |eq_type| field is
  6779. not |long_call| or |long_outer_call|, its parameters are not allowed to contain
  6780. the control sequence \.{\\par}. If an illegal \.{\\par} appears, the macro
  6781. call is aborted, and the \.{\\par} will be rescanned.
  6782. @<Declare the procedure called |macro_call|@>=
  6783. procedure macro_call; {invokes a user-defined control sequence}
  6784. label exit, continue, done, done1, found;
  6785. var r:pointer; {current node in the macro's token list}
  6786. @!p:pointer; {current node in parameter token list being built}
  6787. @!q:pointer; {new node being put into the token list}
  6788. @!s:pointer; {backup pointer for parameter matching}
  6789. @!t:pointer; {cycle pointer for backup recovery}
  6790. @!u,@!v:pointer; {auxiliary pointers for backup recovery}
  6791. @!rbrace_ptr:pointer; {one step before the last |right_brace| token}
  6792. @!n:small_number; {the number of parameters scanned}
  6793. @!unbalance:halfword; {unmatched left braces in current parameter}
  6794. @!m:halfword; {the number of tokens or groups (usually)}
  6795. @!ref_count:pointer; {start of the token list}
  6796. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  6797. @!save_warning_index:pointer; {|warning_index| upon entry}
  6798. @!match_chr:ASCII_code; {character used in parameter}
  6799. begin save_scanner_status:=scanner_status; save_warning_index:=warning_index;
  6800. warning_index:=cur_cs; ref_count:=cur_chr; r:=link(ref_count); n:=0;
  6801. if tracing_macros>0 then @<Show the text of the macro being expanded@>;
  6802. if info(r)<>end_match_token then
  6803.   @<Scan the parameters and make |link(r)| point to the macro body; but
  6804.     |return| if an illegal \.{\\par} is detected@>;
  6805. @<Feed the macro body and its parameters to the scanner@>;
  6806. exit:scanner_status:=save_scanner_status; warning_index:=save_warning_index;
  6807. @ Before we put a new token list on the input stack, it is wise to clean off
  6808. all token lists that have recently been depleted. Then a user macro that ends
  6809. with a call to itself will not require unbounded stack space.
  6810. @<Feed the macro body and its parameters to the scanner@>=
  6811. while (state=token_list)and(loc=null) do end_token_list; {conserve stack space}
  6812. begin_token_list(ref_count,macro); name:=warning_index; loc:=link(r);
  6813. if n>0 then
  6814.   begin if param_ptr+n>max_param_stack then
  6815.     begin max_param_stack:=param_ptr+n;
  6816.     if max_param_stack>param_size then
  6817.       overflow("parameter stack size",param_size);
  6818. @:TeX capacity exceeded parameter stack size}{\quad parameter stack size@>
  6819.     end;
  6820.   for m:=0 to n-1 do param_stack[param_ptr+m]:=pstack[m];
  6821.   param_ptr:=param_ptr+n;
  6822.   end
  6823. @ At this point, the reader will find it advisable to review the explanation
  6824. of token list format that was presented earlier, since many aspects of that
  6825. format are of importance chiefly in the |macro_call| routine.
  6826. The token list might begin with a string of compulsory tokens before the
  6827. first |match| or |end_match|. In that case the macro name is supposed to be
  6828. followed by those tokens; the following program will set |s=null| to
  6829. represent this restriction. Otherwise |s| will be set to the first token of
  6830. a string that will delimit the next parameter.
  6831. @<Scan the parameters and make |link(r)| point to the macro body...@>=
  6832. begin scanner_status:=matching; unbalance:=0;
  6833. long_state:=eq_type(cur_cs);
  6834. if long_state>=outer_call then long_state:=long_state-2;
  6835. repeat link(temp_head):=null;
  6836. if (info(r)>match_token+255)or(info(r)<match_token) then s:=null
  6837. else  begin match_chr:=info(r)-match_token; s:=link(r); r:=s;
  6838.   p:=temp_head; m:=0;
  6839.   end;
  6840. @<Scan a parameter until its delimiter string has been found; or, if |s=null|,
  6841.   simply scan the delimiter string@>;@/
  6842. {now |info(r)| is a token whose command code is either |match| or |end_match|}
  6843. until info(r)=end_match_token;
  6844. @ If |info(r)| is a |match| or |end_match| command, it cannot be equal to
  6845. any token found by |get_token|. Therefore an undelimited parameter---i.e.,
  6846. a |match| that is immediately followed by |match| or |end_match|---will
  6847. always fail the test `|cur_tok=info(r)|' in the following algorithm.
  6848. @<Scan a parameter until its delimiter string has been found; or, ...@>=
  6849. continue: get_token; {set |cur_tok| to the next token of input}
  6850. if cur_tok=info(r) then
  6851.   @<Advance \(r)|r|; |goto found| if the parameter delimiter has been
  6852.     fully matched, otherwise |goto continue|@>;
  6853. @<Contribute the recently matched tokens to the current parameter, and
  6854.   |goto continue| if a partial match is still in effect;
  6855.   but abort if |s=null|@>;
  6856. if cur_tok=par_token then if long_state<>long_call then
  6857.   @<Report a runaway argument and abort@>;
  6858. if cur_tok<right_brace_limit then
  6859.   if cur_tok<left_brace_limit then
  6860.     @<Contribute an entire group to the current parameter@>
  6861.   else @<Report an extra right brace and |goto continue|@>
  6862. else @<Store the current token, but |goto continue| if it is
  6863.    a blank space that would become an undelimited parameter@>;
  6864. incr(m);
  6865. if info(r)>end_match_token then goto continue;
  6866. if info(r)<match_token then goto continue;
  6867. found: if s<>null then @<Tidy up the parameter just scanned, and tuck it away@>
  6868. @ @<Store the current token, but |goto continue| if it is...@>=
  6869. begin if cur_tok=space_token then
  6870.   if info(r)<=end_match_token then
  6871.     if info(r)>=match_token then goto continue;
  6872. store_new_token(cur_tok);
  6873. @ A slightly subtle point arises here: When the parameter delimiter ends
  6874. with `\.{\#\{}', the token list will have a left brace both before and
  6875. after the |end_match|\kern-.4pt. Only one of these should affect the
  6876. |align_state|, but both will be scanned, so we must make a correction.
  6877. @<Advance \(r)|r|; |goto found| if the parameter delimiter has been fully...@>=
  6878. begin r:=link(r);
  6879. if (info(r)>=match_token)and(info(r)<=end_match_token) then
  6880.   begin if cur_tok<left_brace_limit then decr(align_state);
  6881.   goto found;
  6882.   end
  6883. else goto continue;
  6884. @ @<Report an extra right brace and |goto continue|@>=
  6885. begin back_input; print_err("Argument of "); sprint_cs(warning_index);
  6886. @.Argument of \\x has...@>
  6887. print(" has an extra }");
  6888. help6("I've run across a `}' that doesn't seem to match anything.")@/
  6889.   ("For example, `\def\a#1{...}' and `\a}' would produce")@/
  6890.   ("this error. If you simply proceed now, the `\par' that")@/
  6891.   ("I've just inserted will cause me to report a runaway")@/
  6892.   ("argument that might be the root of the problem. But if")@/
  6893.   ("your `}' was spurious, just type `2' and it will go away.");
  6894. incr(align_state); long_state:=call; cur_tok:=par_token; ins_error;
  6895. end {a white lie; the \.{\\par} won't always trigger a runaway}
  6896. @ If |long_state=outer_call|, a runaway argument has already been reported.
  6897. @<Report a runaway argument and abort@>=
  6898. begin if long_state=call then
  6899.   begin runaway; print_err("Paragraph ended before ");
  6900. @.Paragraph ended before...@>
  6901.   sprint_cs(warning_index); print(" was complete");
  6902.   help3("I suspect you've forgotten a `}', causing me to apply this")@/
  6903.     ("control sequence to too much text. How can we recover?")@/
  6904.     ("My plan is to forget the whole thing and hope for the best.");
  6905.   back_error;
  6906.   end;
  6907. pstack[n]:=link(temp_head); align_state:=align_state-unbalance;
  6908. for m:=0 to n do flush_list(pstack[m]);
  6909. return;
  6910. @ When the following code becomes active, we have matched tokens from |s| to
  6911. the predecessor of |r|, and we have found that |cur_tok<>info(r)|. An
  6912. interesting situation now presents itself: If the parameter is to be
  6913. delimited by a string such as `\.{ab}', and if we have scanned `\.{aa}',
  6914. we want to contribute one `\.a' to the current parameter and resume
  6915. looking for a `\.b'. The program must account for such partial matches and
  6916. for others that can be quite complex.  But most of the time we have |s=r|
  6917. and nothing needs to be done.
  6918. Incidentally, it is possible for \.{\\par} tokens to sneak in to certain
  6919. parameters of non-\.{\\long} macros. For example, consider a case like
  6920. `\.{\\def\\a\#1\\par!\{...\}}' where the first \.{\\par} is not followed
  6921. by an exclamation point. In such situations it does not seem appropriate
  6922. to prohibit the \.{\\par}, so \TeX\ keeps quiet about this bending of
  6923. the rules.
  6924. @<Contribute the recently matched tokens to the current parameter...@>=
  6925. if s<>r then
  6926.   if s=null then @<Report an improper use of the macro and abort@>
  6927.   else  begin t:=s;
  6928.     repeat store_new_token(info(t)); incr(m); u:=link(t); v:=s;
  6929.     loop@+  begin if u=r then
  6930.         if cur_tok<>info(v) then goto done
  6931.         else  begin r:=link(v); goto continue;
  6932.           end;
  6933.       if info(u)<>info(v) then goto done;
  6934.       u:=link(u); v:=link(v);
  6935.       end;
  6936.     done: t:=link(t);
  6937.     until t=r;
  6938.     r:=s; {at this point, no tokens are recently matched}
  6939.     end
  6940. @ @<Report an improper use...@>=
  6941. begin print_err("Use of "); sprint_cs(warning_index);
  6942. @.Use of x doesn't match...@>
  6943. print(" doesn't match its definition");
  6944. help4("If you say, e.g., `\def\a1{...}', then you must always")@/
  6945.   ("put `1' after `\a', since control sequence names are")@/
  6946.   ("made up of letters only. The macro here has not been")@/
  6947.   ("followed by the required stuff, so I'm ignoring it.");
  6948. error; return;
  6949. @ @<Contribute an entire group to the current parameter@>=
  6950. begin unbalance:=1;
  6951. @^inner loop@>
  6952. loop@+  begin fast_store_new_token(cur_tok); get_token;
  6953.   if cur_tok=par_token then if long_state<>long_call then
  6954.     @<Report a runaway argument and abort@>;
  6955.   if cur_tok<right_brace_limit then
  6956.     if cur_tok<left_brace_limit then incr(unbalance)
  6957.     else  begin decr(unbalance);
  6958.       if unbalance=0 then goto done1;
  6959.       end;
  6960.   end;
  6961. done1: rbrace_ptr:=p; store_new_token(cur_tok);
  6962. @ If the parameter consists of a single group enclosed in braces, we must
  6963. strip off the enclosing braces. That's why |rbrace_ptr| was introduced.
  6964. @<Tidy up the parameter just scanned, and tuck it away@>=
  6965. begin if (m=1)and(info(p)<right_brace_limit)and(p<>temp_head) then
  6966.   begin link(rbrace_ptr):=null; free_avail(p);
  6967.   p:=link(temp_head); pstack[n]:=link(p); free_avail(p);
  6968.   end
  6969. else pstack[n]:=link(temp_head);
  6970. incr(n);
  6971. if tracing_macros>0 then
  6972.   begin begin_diagnostic; print_nl(match_chr); print_int(n);
  6973.   print("<-"); show_token_list(pstack[n-1],null,1000);
  6974.   end_diagnostic(false);
  6975.   end;
  6976. @ @<Show the text of the macro being expanded@>=
  6977. begin begin_diagnostic; print_ln; print_cs(warning_index);
  6978. token_show(ref_count); end_diagnostic(false);
  6979. @* \[26] Basic scanning subroutines.
  6980. Let's turn now to some procedures that \TeX\ calls upon frequently to digest
  6981. certain kinds of patterns in the input. Most of these are quite simple;
  6982. some are quite elaborate. Almost all of the routines call |get_x_token|,
  6983. which can cause them to be invoked recursively.
  6984. @^stomach@>
  6985. @^recursion@>
  6986. @ The |scan_left_brace| routine is called when a left brace is supposed to be
  6987. the next non-blank token. (The term ``left brace'' means, more precisely,
  6988. a character whose catcode is |left_brace|.) \TeX\ allows \.{\\relax} to
  6989. appear before the |left_brace|.
  6990. @p procedure scan_left_brace; {reads a mandatory |left_brace|}
  6991. begin @<Get the next non-blank non-relax non-call token@>;
  6992. if cur_cmd<>left_brace then
  6993.   begin print_err("Missing { inserted");
  6994. @.Missing \{ inserted@>
  6995.   help4("A left brace was mandatory here, so I've put one in.")@/
  6996.     ("You might want to delete and/or insert some corrections")@/
  6997.     ("so that I will find a matching right brace soon.")@/
  6998.     ("(If you're confused by all this, try typing `I}' now.)");
  6999.   back_error; cur_tok:=left_brace_token+"{"; cur_cmd:=left_brace;
  7000.   cur_chr:="{"; incr(align_state);
  7001.   end;
  7002. @ @<Get the next non-blank non-relax non-call token@>=
  7003. repeat get_x_token;
  7004. until (cur_cmd<>spacer)and(cur_cmd<>relax)
  7005. @ The |scan_optional_equals| routine looks for an optional `\.=' sign preceded
  7006. by optional spaces; `\.{\\relax}' is not ignored here.
  7007. @p procedure scan_optional_equals;
  7008. begin  @<Get the next non-blank non-call token@>;
  7009. if cur_tok<>other_token+"=" then back_input;
  7010. @ @<Get the next non-blank non-call token@>=
  7011. repeat get_x_token;
  7012. until cur_cmd<>spacer
  7013. @ In case you are getting bored, here is a slightly less trivial routine:
  7014. Given a string of lowercase letters, like `\.{pt}' or `\.{plus}' or
  7015. `\.{width}', the |scan_keyword| routine checks to see whether the next
  7016. tokens of input match this string. The match must be exact, except that
  7017. uppercase letters will match their lowercase counterparts; uppercase
  7018. equivalents are determined by subtracting |"a"-"A"|, rather than using the
  7019. |uc_code| table, since \TeX\ uses this routine only for its own limited
  7020. set of keywords.
  7021. If a match is found, the characters are effectively removed from the input
  7022. and |true| is returned. Otherwise |false| is returned, and the input
  7023. is left essentially unchanged (except for the fact that some macros
  7024. may have been expanded, etc.).
  7025. @^inner loop@>
  7026. @p function scan_keyword(@!s:str_number):boolean; {look for a given string}
  7027. label exit;
  7028. var p:pointer; {tail of the backup list}
  7029. @!q:pointer; {new node being added to the token list via |store_new_token|}
  7030. @!k:pool_pointer; {index into |str_pool|}
  7031. begin p:=backup_head; link(p):=null; k:=str_start[s];
  7032. while k<str_start[s+1] do
  7033.   begin get_x_token; {recursion is possible here}
  7034. @^recursion@>
  7035.   if (cur_cs=0)and@|
  7036.    ((cur_chr=so(str_pool[k]))or(cur_chr=so(str_pool[k])-"a"+"A")) then
  7037.     begin store_new_token(cur_tok); incr(k);
  7038.     end
  7039.   else if (cur_cmd<>spacer)or(p<>backup_head) then
  7040.     begin back_input;
  7041.     if p<>backup_head then back_list(link(backup_head));
  7042.     scan_keyword:=false; return;
  7043.     end;
  7044.   end;
  7045. flush_list(link(backup_head)); scan_keyword:=true;
  7046. exit:end;
  7047. @ Here is a procedure that sounds an alarm when mu and non-mu units
  7048. are being switched.
  7049. @p procedure mu_error;
  7050. begin print_err("Incompatible glue units");
  7051. @.Incompatible glue units@>
  7052. help1("I'm going to assume that 1mu=1pt when they're mixed.");
  7053. error;
  7054. @ The next routine `|scan_something_internal|' is used to fetch internal
  7055. numeric quantities like `\.{\\hsize}', and also to handle the `\.{\\the}'
  7056. when expanding constructions like `\.{\\the\\toks0}' and
  7057. `\.{\\the\\baselineskip}'. Soon we will be considering the |scan_int|
  7058. procedure, which calls |scan_something_internal|; on the other hand,
  7059. |scan_something_internal| also calls |scan_int|, for constructions like
  7060. `\.{\\catcode\`\\\$}' or `\.{\\fontdimen} \.3 \.{\\ff}'. So we
  7061. have to declare |scan_int| as a |forward| procedure. A few other
  7062. procedures are also declared at this point.
  7063. @p procedure@?scan_int; forward; {scans an integer value}
  7064. @t\4\4@>@<Declare procedures that scan restricted classes of integers@>@;
  7065. @t\4\4@>@<Declare procedures that scan font-related stuff@>
  7066. @ \TeX\ doesn't know exactly what to expect when |scan_something_internal|
  7067. begins.  For example, an integer or dimension or glue value could occur
  7068. immediately after `\.{\\hskip}'; and one can even say \.{\\the} with
  7069. respect to token lists in constructions like
  7070. `\.{\\xdef\\o\{\\the\\output\}}'.  On the other hand, only integers are
  7071. allowed after a construction like `\.{\\count}'. To handle the various
  7072. possibilities, |scan_something_internal| has a |level| parameter, which
  7073. tells the ``highest'' kind of quantity that |scan_something_internal| is
  7074. allowed to produce. Six levels are distinguished, namely |int_val|,
  7075. |dimen_val|, |glue_val|, |mu_val|, |ident_val|, and |tok_val|.
  7076. The output of |scan_something_internal| (and of the other routines
  7077. |scan_int|, |scan_dimen|, and |scan_glue| below) is put into the global
  7078. variable |cur_val|, and its level is put into |cur_val_level|. The highest
  7079. values of |cur_val_level| are special: |mu_val| is used only when
  7080. |cur_val| points to something in a ``muskip'' register, or to one of the
  7081. three parameters \.{\\thinmuskip}, \.{\\midmuskip}, \.{\\thickmuskip};
  7082. |ident_val| is used only when |cur_val| points to a font identifier;
  7083. |tok_val| is used only when |cur_val| points to |null| or to the reference
  7084. count of a token list. The last two cases are allowed only when
  7085. |scan_something_internal| is called with |level=tok_val|.
  7086. If the output is glue, |cur_val| will point to a glue specification, and
  7087. the reference count of that glue will have been updated to reflect this
  7088. reference; if the output is a nonempty token list, |cur_val| will point to
  7089. its reference count, but in this case the count will not have been updated.
  7090. Otherwise |cur_val| will contain the integer or scaled value in question.
  7091. @d int_val=0 {integer values}
  7092. @d dimen_val=1 {dimension values}
  7093. @d glue_val=2 {glue specifications}
  7094. @d mu_val=3 {math glue specifications}
  7095. @d ident_val=4 {font identifier}
  7096. @d tok_val=5 {token lists}
  7097. @<Glob...@>=
  7098. @!cur_val:integer; {value returned by numeric scanners}
  7099. @!cur_val_level:int_val..tok_val; {the ``level'' of this value}
  7100. @ The hash table is initialized with `\.{\\count}', `\.{\\dimen}', `\.{\\skip}',
  7101. and `\.{\\muskip}' all having |register| as their command code; they are
  7102. distinguished by the |chr_code|, which is either |int_val|, |dimen_val|,
  7103. |glue_val|, or |mu_val|.
  7104. @<Put each...@>=
  7105. primitive("count",register,int_val);
  7106. @!@:count_}{\.{\\count} primitive@>
  7107. primitive("dimen",register,dimen_val);
  7108. @!@:dimen_}{\.{\\dimen} primitive@>
  7109. primitive("skip",register,glue_val);
  7110. @!@:skip_}{\.{\\skip} primitive@>
  7111. primitive("muskip",register,mu_val);
  7112. @!@:mu_skip_}{\.{\\muskip} primitive@>
  7113. @ @<Cases of |print_cmd_chr|...@>=
  7114. register: if chr_code=int_val then print_esc("count")
  7115.   else if chr_code=dimen_val then print_esc("dimen")
  7116.   else if chr_code=glue_val then print_esc("skip")
  7117.   else print_esc("muskip");
  7118. @ OK, we're ready for |scan_something_internal| itself. A second parameter,
  7119. |negative|, is set |true| if the value that is found should be negated.
  7120. It is assumed that |cur_cmd| and |cur_chr| represent the first token of
  7121. the internal quantity to be scanned; an error will be signalled if
  7122. |cur_cmd<min_internal| or |cur_cmd>max_internal|.
  7123. @d scanned_result_end(#)==cur_val_level:=#;@+end
  7124. @d scanned_result(#)==@+begin cur_val:=#;scanned_result_end
  7125. @p procedure scan_something_internal(@!level:small_number;@!negative:boolean);
  7126.   {fetch an internal parameter}
  7127. var m:halfword; {|chr_code| part of the operand token}
  7128. @!p:0..nest_size; {index into |nest|}
  7129. begin m:=cur_chr;
  7130. case cur_cmd of
  7131. def_code: @<Fetch a character code from some table@>;
  7132. toks_register,assign_toks,def_family,set_font,def_font: @<Fetch a token list or
  7133.   font identifier, provided that |level=tok_val|@>;
  7134. assign_int: scanned_result(eqtb[m].int)(int_val);
  7135. assign_dimen: scanned_result(eqtb[m].sc)(dimen_val);
  7136. assign_glue: scanned_result(equiv(m))(glue_val);
  7137. assign_mu_glue: scanned_result(equiv(m))(mu_val);
  7138. set_aux: @<Fetch the |space_factor| or the |prev_depth|@>;
  7139. set_prev_graf: @<Fetch the |prev_graf|@>;
  7140. set_page_int:@<Fetch the |dead_cycles| or the |insert_penalties|@>;
  7141. set_page_dimen: @<Fetch something on the |page_so_far|@>;
  7142. set_shape: @<Fetch the |par_shape| size@>;
  7143. set_box_dimen: @<Fetch a box dimension@>;
  7144. char_given,math_given: scanned_result(cur_chr)(int_val);
  7145. assign_font_dimen: @<Fetch a font dimension@>;
  7146. assign_font_int: @<Fetch a font integer@>;
  7147. register: @<Fetch a register@>;
  7148. last_item: @<Fetch an item in the current node, if appropriate@>;
  7149. othercases @<Complain that \.{\\the} can't do this; give zero result@>
  7150. endcases;@/
  7151. while cur_val_level>level do @<Convert \(c)|cur_val| to a lower level@>;
  7152. @<Fix the reference count, if any, and negate |cur_val| if |negative|@>;
  7153. @ @<Fetch a character code from some table@>=
  7154. begin scan_char_num;
  7155. if m=math_code_base then scanned_result(ho(math_code(cur_val)))(int_val)
  7156. else if m<math_code_base then scanned_result(equiv(m+cur_val))(int_val)
  7157. else scanned_result(eqtb[m+cur_val].int)(int_val);
  7158. @ @<Fetch a token list...@>=
  7159. if level<>tok_val then
  7160.   begin print_err("Missing number, treated as zero");
  7161. @.Missing number...@>
  7162.   help3("A number should have been here; I inserted `0'.")@/
  7163.     ("(If you can't figure out why I needed to see a number,")@/
  7164.     ("look up `weird error' in the index to The TeXbook.)");
  7165. @:TeXbook}{\sl The \TeX book@>
  7166.   back_error; scanned_result(0)(dimen_val);
  7167.   end
  7168. else if cur_cmd<=assign_toks then
  7169.   begin if cur_cmd<assign_toks then {|cur_cmd=toks_register|}
  7170.     begin scan_eight_bit_int; m:=toks_base+cur_val;
  7171.     end;
  7172.   scanned_result(equiv(m))(tok_val);
  7173.   end
  7174. else  begin back_input; scan_font_ident;
  7175.   scanned_result(font_id_base+cur_val)(ident_val);
  7176.   end
  7177. @ Users refer to `\.{\\the\\spacefactor}' only in horizontal
  7178. mode, and to `\.{\\the\\prevdepth}' only in vertical mode; so we put the
  7179. associated mode in the modifier part of the |set_aux| command.
  7180. The |set_page_int| command has modifier 0 or 1, for `\.{\\deadcycles}' and
  7181. `\.{\\insertpenalties}', respectively. The |set_box_dimen| command is
  7182. modified by either |width_offset|, |height_offset|, or |depth_offset|.
  7183. And the |last_item| command is modified by either |int_val|, |dimen_val|,
  7184. |glue_val|, |input_line_no_code|, or |badness_code|.
  7185. @d input_line_no_code=glue_val+1 {code for \.{\\inputlineno}}
  7186. @d badness_code=glue_val+2 {code for \.{\\badness}}
  7187. @<Put each...@>=
  7188. primitive("spacefactor",set_aux,hmode);
  7189. @!@:space_factor_}{\.{\\spacefactor} primitive@>
  7190. primitive("prevdepth",set_aux,vmode);@/
  7191. @!@:prev_depth_}{\.{\\prevdepth} primitive@>
  7192. primitive("deadcycles",set_page_int,0);
  7193. @!@:dead_cycles_}{\.{\\deadcycles} primitive@>
  7194. primitive("insertpenalties",set_page_int,1);
  7195. @!@:insert_penalties_}{\.{\\insertpenalties} primitive@>
  7196. primitive("wd",set_box_dimen,width_offset);
  7197. @!@:wd_}{\.{\\wd} primitive@>
  7198. primitive("ht",set_box_dimen,height_offset);
  7199. @!@:ht_}{\.{\\ht} primitive@>
  7200. primitive("dp",set_box_dimen,depth_offset);
  7201. @!@:dp_}{\.{\\dp} primitive@>
  7202. primitive("lastpenalty",last_item,int_val);
  7203. @!@:last_penalty_}{\.{\\lastpenalty} primitive@>
  7204. primitive("lastkern",last_item,dimen_val);
  7205. @!@:last_kern_}{\.{\\lastkern} primitive@>
  7206. primitive("lastskip",last_item,glue_val);
  7207. @!@:last_skip_}{\.{\\lastskip} primitive@>
  7208. primitive("inputlineno",last_item,input_line_no_code);
  7209. @!@:input_line_no_}{\.{\\inputlineno} primitive@>
  7210. primitive("badness",last_item,badness_code);
  7211. @!@:badness_}{\.{\\badness} primitive@>
  7212. @ @<Cases of |print_cmd_chr|...@>=
  7213. set_aux: if chr_code=vmode then print_esc("prevdepth")
  7214. @+else print_esc("spacefactor");
  7215. set_page_int: if chr_code=0 then print_esc("deadcycles")
  7216. @+else print_esc("insertpenalties");
  7217. set_box_dimen: if chr_code=width_offset then print_esc("wd")
  7218. else if chr_code=height_offset then print_esc("ht")
  7219. else print_esc("dp");
  7220. last_item: case chr_code of
  7221.   int_val: print_esc("lastpenalty");
  7222.   dimen_val: print_esc("lastkern");
  7223.   glue_val: print_esc("lastskip");
  7224.   input_line_no_code: print_esc("inputlineno");
  7225.   othercases print_esc("badness")
  7226.   endcases;
  7227. @ @<Fetch the |space_factor| or the |prev_depth|@>=
  7228. if abs(mode)<>m then
  7229.   begin print_err("Improper "); print_cmd_chr(set_aux,m);
  7230. @.Improper \\spacefactor@>
  7231. @.Improper \\prevdepth@>
  7232.   help4("You can refer to \spacefactor only in horizontal mode;")@/
  7233.     ("you can refer to \prevdepth only in vertical mode; and")@/
  7234.     ("neither of these is meaningful inside \write. So")@/
  7235.     ("I'm forgetting what you said and using zero instead.");
  7236.   error;
  7237.   if level<>tok_val then scanned_result(0)(dimen_val)
  7238.   else scanned_result(0)(int_val);
  7239.   end
  7240. else if m=vmode then
  7241.   begin cur_val:=prev_depth; cur_val_level:=dimen_val;
  7242.   end
  7243. else begin cur_val:=space_factor; cur_val_level:=int_val;
  7244.   end
  7245. @ @<Fetch the |dead_cycles| or the |insert_penalties|@>=
  7246. begin if m=0 then cur_val:=dead_cycles@+else cur_val:=insert_penalties;
  7247. cur_val_level:=int_val;
  7248. @ @<Fetch a box dimension@>=
  7249. begin scan_eight_bit_int;
  7250. if box(cur_val)=null then cur_val:=0 @+else cur_val:=mem[box(cur_val)+m].sc;
  7251. cur_val_level:=dimen_val;
  7252. @ Inside an \.{\\output} routine, a user may wish to look at the page totals
  7253. that were present at the moment when output was triggered.
  7254. @d max_dimen==@'7777777777 {$2^{30}-1$}
  7255. @<Fetch something on the |page_so_far|@>=
  7256. begin if (page_contents=empty) and (not output_active) then
  7257.   if m=0 then cur_val:=max_dimen@+else cur_val:=0
  7258. else cur_val:=page_so_far[m];
  7259. cur_val_level:=dimen_val;
  7260. @ @<Fetch the |prev_graf|@>=
  7261. if mode=0 then scanned_result(0)(int_val) {|prev_graf=0| within \.{\\write}}
  7262. else begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
  7263.   while abs(nest[p].mode_field)<>vmode do decr(p);
  7264.   scanned_result(nest[p].pg_field)(int_val);
  7265.   end
  7266. @ @<Fetch the |par_shape| size@>=
  7267. begin if par_shape_ptr=null then cur_val:=0
  7268. else cur_val:=info(par_shape_ptr);
  7269. cur_val_level:=int_val;
  7270. @ Here is where \.{\\lastpenalty}, \.{\\lastkern}, and \.{\\lastskip} are
  7271. implemented. The reference count for \.{\\lastskip} will be updated later.
  7272. We also handle \.{\\inputlineno} and \.{\\badness} here, because they are
  7273. legal in similar contexts.
  7274. @<Fetch an item in the current node...@>=
  7275. if cur_chr>glue_val then
  7276.   begin if cur_chr=input_line_no_code then cur_val:=line
  7277.   else cur_val:=last_badness; {|cur_chr=badness_code|}
  7278.   cur_val_level:=int_val;
  7279.   end
  7280. else begin if cur_chr=glue_val then cur_val:=zero_glue@+else cur_val:=0;
  7281.   cur_val_level:=cur_chr;
  7282.   if not is_char_node(tail)and(mode<>0) then
  7283.     case cur_chr of
  7284.     int_val: if type(tail)=penalty_node then cur_val:=penalty(tail);
  7285.     dimen_val: if type(tail)=kern_node then cur_val:=width(tail);
  7286.     glue_val: if type(tail)=glue_node then
  7287.       begin cur_val:=glue_ptr(tail);
  7288.       if subtype(tail)=mu_glue then cur_val_level:=mu_val;
  7289.       end;
  7290.     end {there are no other cases}
  7291.   else if (mode=vmode)and(tail=head) then
  7292.     case cur_chr of
  7293.     int_val: cur_val:=last_penalty;
  7294.     dimen_val: cur_val:=last_kern;
  7295.     glue_val: if last_glue<>max_halfword then cur_val:=last_glue;
  7296.     end; {there are no other cases}
  7297.   end
  7298. @ @<Fetch a font dimension@>=
  7299. begin find_font_dimen(false); font_info[fmem_ptr].sc:=0;
  7300. scanned_result(font_info[cur_val].sc)(dimen_val);
  7301. @ @<Fetch a font integer@>=
  7302. begin scan_font_ident;
  7303. if m=0 then scanned_result(hyphen_char[cur_val])(int_val)
  7304. else scanned_result(skew_char[cur_val])(int_val);
  7305. @ @<Fetch a register@>=
  7306. begin scan_eight_bit_int;
  7307. case m of
  7308. int_val:cur_val:=count(cur_val);
  7309. dimen_val:cur_val:=dimen(cur_val);
  7310. glue_val: cur_val:=skip(cur_val);
  7311. mu_val: cur_val:=mu_skip(cur_val);
  7312. end; {there are no other cases}
  7313. cur_val_level:=m;
  7314. @ @<Complain that \.{\\the} can't do this; give zero result@>=
  7315. begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
  7316. @.You can't use x after ...@>
  7317. print("' after "); print_esc("the");
  7318. help1("I'm forgetting what you said and using zero instead.");
  7319. error;
  7320. if level<>tok_val then scanned_result(0)(dimen_val)
  7321. else scanned_result(0)(int_val);
  7322. @ When a |glue_val| changes to a |dimen_val|, we use the width component
  7323. of the glue; there is no need to decrease the reference count, since it
  7324. has not yet been increased.  When a |dimen_val| changes to an |int_val|,
  7325. we use scaled points so that the value doesn't actually change. And when a
  7326. |mu_val| changes to a |glue_val|, the value doesn't change either.
  7327. @<Convert \(c)|cur_val| to a lower level@>=
  7328. begin if cur_val_level=glue_val then cur_val:=width(cur_val)
  7329. else if cur_val_level=mu_val then mu_error;
  7330. decr(cur_val_level);
  7331. @ If |cur_val| points to a glue specification at this point, the reference
  7332. count for the glue does not yet include the reference by |cur_val|.
  7333. If |negative| is |true|, |cur_val_level| is known to be |<=mu_val|.
  7334. @<Fix the reference count, if any, ...@>=
  7335. if negative then
  7336.   if cur_val_level>=glue_val then
  7337.     begin cur_val:=new_spec(cur_val);
  7338.     @<Negate all three glue components of |cur_val|@>;
  7339.     end
  7340.   else negate(cur_val)
  7341. else if (cur_val_level>=glue_val)and(cur_val_level<=mu_val) then
  7342.   add_glue_ref(cur_val)
  7343. @ @<Negate all three...@>=
  7344. begin negate(width(cur_val));
  7345. negate(stretch(cur_val));
  7346. negate(shrink(cur_val));
  7347. @ Our next goal is to write the |scan_int| procedure, which scans anything that
  7348. \TeX\ treats as an integer. But first we might as well look at some simple
  7349. applications of |scan_int| that have already been made inside of
  7350. |scan_something_internal|.
  7351. @ @<Declare procedures that scan restricted classes of integers@>=
  7352. procedure scan_eight_bit_int;
  7353. begin scan_int;
  7354. if (cur_val<0)or(cur_val>255) then
  7355.   begin print_err("Bad register code");
  7356. @.Bad register code@>
  7357.   help2("A register number must be between 0 and 255.")@/
  7358.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7359.   end;
  7360. @ @<Declare procedures that scan restricted classes of integers@>=
  7361. procedure scan_char_num;
  7362. begin scan_int;
  7363. if (cur_val<0)or(cur_val>255) then
  7364.   begin print_err("Bad character code");
  7365. @.Bad character code@>
  7366.   help2("A character number must be between 0 and 255.")@/
  7367.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7368.   end;
  7369. @ While we're at it, we might as well deal with similar routines that
  7370. will be needed later.
  7371. @<Declare procedures that scan restricted classes of integers@>=
  7372. procedure scan_four_bit_int;
  7373. begin scan_int;
  7374. if (cur_val<0)or(cur_val>15) then
  7375.   begin print_err("Bad number");
  7376. @.Bad number@>
  7377.   help2("Since I expected to read a number between 0 and 15,")@/
  7378.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7379.   end;
  7380. @ @<Declare procedures that scan restricted classes of integers@>=
  7381. procedure scan_fifteen_bit_int;
  7382. begin scan_int;
  7383. if (cur_val<0)or(cur_val>@'77777) then
  7384.   begin print_err("Bad mathchar");
  7385. @.Bad mathchar@>
  7386.   help2("A mathchar number must be between 0 and 32767.")@/
  7387.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7388.   end;
  7389. @ @<Declare procedures that scan restricted classes of integers@>=
  7390. procedure scan_twenty_seven_bit_int;
  7391. begin scan_int;
  7392. if (cur_val<0)or(cur_val>@'777777777) then
  7393.   begin print_err("Bad delimiter code");
  7394. @.Bad delimiter code@>
  7395.   help2("A numeric delimiter code must be between 0 and 2^{27}-1.")@/
  7396.     ("I changed this one to zero."); int_error(cur_val); cur_val:=0;
  7397.   end;
  7398. @ An integer number can be preceded by any number of spaces and `\.+' or
  7399. `\.-' signs. Then comes either a decimal constant (i.e., radix 10), an
  7400. octal constant (i.e., radix 8, preceded by~\.\'), a hexadecimal constant
  7401. (radix 16, preceded by~\."), an alphabetic constant (preceded by~\.\`), or
  7402. an internal variable. After scanning is complete,
  7403. |cur_val| will contain the answer, which must be at most
  7404. $2^{31}-1=2147483647$ in absolute value. The value of |radix| is set to
  7405. 10, 8, or 16 in the cases of decimal, octal, or hexadecimal constants,
  7406. otherwise |radix| is set to zero. An optional space follows a constant.
  7407. @d octal_token=other_token+"'" {apostrophe, indicates an octal constant}
  7408. @d hex_token=other_token+"""" {double quote, indicates a hex constant}
  7409. @d alpha_token=other_token+"`" {reverse apostrophe, precedes alpha constants}
  7410. @d point_token=other_token+"." {decimal point}
  7411. @d continental_point_token=other_token+"," {decimal point, Eurostyle}
  7412. @<Glob...@>=
  7413. @!radix:small_number; {|scan_int| sets this to 8, 10, 16, or zero}
  7414. @ We initialize the following global variables just in case |expand|
  7415. comes into action before any of the basic scanning routines has assigned
  7416. them a value.
  7417. @<Set init...@>=
  7418. cur_val:=0; cur_val_level:=int_val; radix:=0; cur_order:=0;
  7419. @ The |scan_int| routine is used also to scan the integer part of a
  7420. fraction; for example, the `\.3' in `\.{3.14159}' will be found by
  7421. |scan_int|. The |scan_dimen| routine assumes that |cur_tok=point_token|
  7422. after the integer part of such a fraction has been scanned by |scan_int|,
  7423. and that the decimal point has been backed up to be scanned again.
  7424. @p procedure scan_int; {sets |cur_val| to an integer}
  7425. label done;
  7426. var negative:boolean; {should the answer be negated?}
  7427. @!m:integer; {|@t$2^{31}$@> div radix|, the threshold of danger}
  7428. @!d:small_number; {the digit just scanned}
  7429. @!vacuous:boolean; {have no digits appeared?}
  7430. @!OK_so_far:boolean; {has an error message been issued?}
  7431. begin radix:=0; OK_so_far:=true;@/
  7432. @<Get the next non-blank non-sign token; set |negative| appropriately@>;
  7433. if cur_tok=alpha_token then @<Scan an alphabetic character code into |cur_val|@>
  7434. else if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
  7435.   scan_something_internal(int_val,false)
  7436. else @<Scan a numeric constant@>;
  7437. if negative then negate(cur_val);
  7438. @ @<Get the next non-blank non-sign token...@>=
  7439. negative:=false;
  7440. repeat @<Get the next non-blank non-call token@>;
  7441. if cur_tok=other_token+"-" then
  7442.   begin negative := not negative; cur_tok:=other_token+"+";
  7443.   end;
  7444. until cur_tok<>other_token+"+"
  7445. @ A space is ignored after an alphabetic character constant, so that
  7446. such constants behave like numeric ones.
  7447. @<Scan an alphabetic character code into |cur_val|@>=
  7448. begin get_token; {suppress macro expansion}
  7449. if cur_tok<cs_token_flag then
  7450.   begin cur_val:=cur_chr;
  7451.   if cur_cmd<=right_brace then
  7452.     if cur_cmd=right_brace then incr(align_state)
  7453.     else decr(align_state);
  7454.   end
  7455. else if cur_tok<cs_token_flag+single_base then
  7456.   cur_val:=cur_tok-cs_token_flag-active_base
  7457. else cur_val:=cur_tok-cs_token_flag-single_base;
  7458. if cur_val>255 then
  7459.   begin print_err("Improper alphabetic constant");
  7460. @.Improper alphabetic constant@>
  7461.   help2("A one-character control sequence belongs after a ` mark.")@/
  7462.     ("So I'm essentially inserting \0 here.");
  7463.   cur_val:="0"; back_error;
  7464.   end
  7465. else @<Scan an optional space@>;
  7466. @ @<Scan an optional space@>=
  7467. begin get_x_token; if cur_cmd<>spacer then back_input;
  7468. @ @<Scan a numeric constant@>=
  7469. begin radix:=10; m:=214748364;
  7470. if cur_tok=octal_token then
  7471.   begin radix:=8; m:=@'2000000000; get_x_token;
  7472.   end
  7473. else if cur_tok=hex_token then
  7474.   begin radix:=16; m:=@'1000000000; get_x_token;
  7475.   end;
  7476. vacuous:=true; cur_val:=0;@/
  7477. @<Accumulate the constant until |cur_tok| is not a suitable digit@>;
  7478. if vacuous then @<Express astonishment that no number was here@>
  7479. else if cur_cmd<>spacer then back_input;
  7480. @ @d infinity==@'17777777777 {the largest positive value that \TeX\ knows}
  7481. @d zero_token=other_token+"0" {zero, the smallest digit}
  7482. @d A_token=letter_token+"A" {the smallest special hex digit}
  7483. @d other_A_token=other_token+"A" {special hex digit of type |other_char|}
  7484. @<Accumulate the constant...@>=
  7485. loop@+  begin if (cur_tok<zero_token+radix)and(cur_tok>=zero_token)and
  7486.     (cur_tok<=zero_token+9) then d:=cur_tok-zero_token
  7487.   else if radix=16 then
  7488.     if (cur_tok<=A_token+5)and(cur_tok>=A_token) then d:=cur_tok-A_token+10
  7489.     else if (cur_tok<=other_A_token+5)and(cur_tok>=other_A_token) then
  7490.       d:=cur_tok-other_A_token+10
  7491.     else goto done
  7492.   else goto done;
  7493.   vacuous:=false;
  7494.   if (cur_val>=m)and((cur_val>m)or(d>7)or(radix<>10)) then
  7495.     begin if OK_so_far then
  7496.       begin print_err("Number too big");
  7497. @.Number too big@>
  7498.       help2("I can only go up to 2147483647='17777777777=""7FFFFFFF,")@/
  7499.         ("so I'm using that number instead of yours.");
  7500.       error; cur_val:=infinity; OK_so_far:=false;
  7501.       end;
  7502.     end
  7503.   else cur_val:=cur_val*radix+d;
  7504.   get_x_token;
  7505.   end;
  7506. done:
  7507. @ @<Express astonishment...@>=
  7508. begin print_err("Missing number, treated as zero");
  7509. @.Missing number...@>
  7510. help3("A number should have been here; I inserted `0'.")@/
  7511.   ("(If you can't figure out why I needed to see a number,")@/
  7512.   ("look up `weird error' in the index to The TeXbook.)");
  7513. @:TeXbook}{\sl The \TeX book@>
  7514. back_error;
  7515. @ The |scan_dimen| routine is similar to |scan_int|, but it sets |cur_val| to
  7516. a |scaled| value, i.e., an integral number of sp. One of its main tasks
  7517. is therefore to interpret the abbreviations for various kinds of units and
  7518. to convert measurements to scaled points.
  7519. There are three parameters: |mu| is |true| if the finite units must be
  7520. `\.{mu}', while |mu| is |false| if `\.{mu}' units are disallowed;
  7521. |inf| is |true| if the infinite units `\.{fil}', `\.{fill}', `\.{filll}'
  7522. are permitted; and |shortcut| is |true| if |cur_val| already contains
  7523. an integer and only the units need to be considered.
  7524. The order of infinity that was found in the case of infinite glue is returned
  7525. in the global variable |cur_order|.
  7526. @<Glob...@>=
  7527. @!cur_order:glue_ord; {order of infinity found by |scan_dimen|}
  7528. @ Constructions like `\.{-\'77 pt}' are legal dimensions, so |scan_dimen|
  7529. may begin with |scan_int|. This explains why it is convenient to use
  7530. |scan_int| also for the integer part of a decimal fraction.
  7531. Several branches of |scan_dimen| work with |cur_val| as an integer and
  7532. with an auxiliary fraction |f|, so that the actual quantity of interest is
  7533. $|cur_val|+|f|/2^{16}$. At the end of the routine, this ``unpacked''
  7534. representation is put into the single word |cur_val|, which suddenly
  7535. switches significance from |integer| to |scaled|.
  7536. @d attach_fraction=88 {go here to pack |cur_val| and |f| into |cur_val|}
  7537. @d attach_sign=89 {go here when |cur_val| is correct except perhaps for sign}
  7538. @d scan_normal_dimen==scan_dimen(false,false,false)
  7539. @p procedure scan_dimen(@!mu,@!inf,@!shortcut:boolean);
  7540.   {sets |cur_val| to a dimension}
  7541. label done, done1, done2, found, not_found, attach_fraction, attach_sign;
  7542. var negative:boolean; {should the answer be negated?}
  7543. @!f:integer; {numerator of a fraction whose denominator is $2^{16}$}
  7544. @<Local variables for dimension calculations@>@;
  7545. begin f:=0; arith_error:=false; cur_order:=normal; negative:=false;
  7546. if not shortcut then
  7547.   begin @<Get the next non-blank non-sign...@>;
  7548.   if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
  7549.     @<Fetch an internal dimension and |goto attach_sign|,
  7550.       or fetch an internal integer@>
  7551.   else  begin back_input;
  7552.     if cur_tok=continental_point_token then cur_tok:=point_token;
  7553.     if cur_tok<>point_token then scan_int
  7554.     else  begin radix:=10; cur_val:=0;
  7555.       end;
  7556.     if cur_tok=continental_point_token then cur_tok:=point_token;
  7557.     if (radix=10)and(cur_tok=point_token) then @<Scan decimal fraction@>;
  7558.     end;
  7559.   end;
  7560. if cur_val<0 then {in this case |f=0|}
  7561.   begin negative := not negative; negate(cur_val);
  7562.   end;
  7563. @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$, where there
  7564.   are |x| sp per unit; |goto attach_sign| if the units are internal@>;
  7565. @<Scan an optional space@>;
  7566. attach_sign: if arith_error or(abs(cur_val)>=@'10000000000) then
  7567.   @<Report that this dimension is out of range@>;
  7568. if negative then negate(cur_val);
  7569. @ @<Fetch an internal dimension and |goto attach_sign|...@>=
  7570. if mu then
  7571.   begin scan_something_internal(mu_val,false);
  7572.   @<Coerce glue to a dimension@>;
  7573.   if cur_val_level=mu_val then goto attach_sign;
  7574.   if cur_val_level<>int_val then mu_error;
  7575.   end
  7576. else  begin scan_something_internal(dimen_val,false);
  7577.   if cur_val_level=dimen_val then goto attach_sign;
  7578.   end
  7579. @ @<Local variables for dimension calculations@>=
  7580. @!num,@!denom:1..65536; {conversion ratio for the scanned units}
  7581. @!k,@!kk:small_number; {number of digits in a decimal fraction}
  7582. @!p,@!q:pointer; {top of decimal digit stack}
  7583. @!v:scaled; {an internal dimension}
  7584. @!save_cur_val:integer; {temporary storage of |cur_val|}
  7585. @ The following code is executed when |scan_something_internal| was
  7586. called asking for |mu_val|, when we really wanted a ``mudimen'' instead
  7587. of ``muglue.''
  7588. @<Coerce glue to a dimension@>=
  7589. if cur_val_level>=glue_val then
  7590.   begin v:=width(cur_val); delete_glue_ref(cur_val); cur_val:=v;
  7591.   end
  7592. @ When the following code is executed, we have |cur_tok=point_token|, but this
  7593. token has been backed up using |back_input|; we must first discard it.
  7594. It turns out that a decimal point all by itself is equivalent to `\.{0.0}'.
  7595. Let's hope people don't use that fact.
  7596. @<Scan decimal fraction@>=
  7597. begin k:=0; p:=null; get_token; {|point_token| is being re-scanned}
  7598. loop@+  begin get_x_token;
  7599.   if (cur_tok>zero_token+9)or(cur_tok<zero_token) then goto done1;
  7600.   if k<17 then {digits for |k>=17| cannot affect the result}
  7601.     begin q:=get_avail; link(q):=p; info(q):=cur_tok-zero_token;
  7602.     p:=q; incr(k);
  7603.     end;
  7604.   end;
  7605. done1: for kk:=k downto 1 do
  7606.   begin dig[kk-1]:=info(p); q:=p; p:=link(p); free_avail(q);
  7607.   end;
  7608. f:=round_decimals(k);
  7609. if cur_cmd<>spacer then back_input;
  7610. @ Now comes the harder part: At this point in the program, |cur_val| is a
  7611. nonnegative integer and $f/2^{16}$ is a nonnegative fraction less than 1;
  7612. we want to multiply the sum of these two quantities by the appropriate
  7613. factor, based on the specified units, in order to produce a |scaled|
  7614. result, and we want to do the calculation with fixed point arithmetic that
  7615. does not overflow.
  7616. @<Scan units and set |cur_val| to $x\cdot(|cur_val|+f/2^{16})$...@>=
  7617. if inf then @<Scan for \(f)\.{fil} units; |goto attach_fraction| if found@>;
  7618. @<Scan for \(u)units that are internal dimensions;
  7619.   |goto attach_sign| with |cur_val| set if found@>;
  7620. if mu then @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>;
  7621. if scan_keyword("true") then @<Adjust \(f)for the magnification ratio@>;
  7622. @.true@>
  7623. if scan_keyword("pt") then goto attach_fraction; {the easy case}
  7624. @.pt@>
  7625. @<Scan for \(a)all other units and adjust |cur_val| and |f| accordingly;
  7626.   |goto done| in the case of scaled points@>;
  7627. attach_fraction: if cur_val>=@'40000 then arith_error:=true
  7628. else cur_val:=cur_val*unity+f;
  7629. done:
  7630. @ A specification like `\.{filllll}' or `\.{fill L L L}' will lead to two
  7631. error messages (one for each additional keyword \.{"l"}).
  7632. @<Scan for \(f)\.{fil} units...@>=
  7633. if scan_keyword("fil") then
  7634. @.fil@>
  7635.   begin cur_order:=fil;
  7636.   while scan_keyword("l") do
  7637.     begin if cur_order=filll then
  7638.       begin print_err("Illegal unit of measure (");
  7639. @.Illegal unit of measure@>
  7640.       print("replaced by filll)");
  7641.       help1("I dddon't go any higher than filll."); error;
  7642.       end
  7643.     else incr(cur_order);
  7644.     end;
  7645.   goto attach_fraction;
  7646.   end
  7647. @ @<Scan for \(u)units that are internal dimensions...@>=
  7648. save_cur_val:=cur_val;
  7649. @<Get the next non-blank non-call...@>;
  7650. if (cur_cmd<min_internal)or(cur_cmd>max_internal) then back_input
  7651. else  begin if mu then
  7652.     begin scan_something_internal(mu_val,false); @<Coerce glue...@>;
  7653.     if cur_val_level<>mu_val then mu_error;
  7654.     end
  7655.   else scan_something_internal(dimen_val,false);
  7656.   v:=cur_val; goto found;
  7657.   end;
  7658. if mu then goto not_found;
  7659. if scan_keyword("em") then v:=(@<The em width for |cur_font|@>)
  7660. @.em@>
  7661. else if scan_keyword("ex") then v:=(@<The x-height for |cur_font|@>)
  7662. @.ex@>
  7663. else goto not_found;
  7664. @<Scan an optional space@>;
  7665. found:cur_val:=nx_plus_y(save_cur_val,v,xn_over_d(v,f,@'200000));
  7666. goto attach_sign;
  7667. not_found:
  7668. @ @<Scan for \(m)\.{mu} units and |goto attach_fraction|@>=
  7669. if scan_keyword("mu") then goto attach_fraction
  7670. @.mu@>
  7671. else  begin print_err("Illegal unit of measure ("); print("mu inserted)");
  7672. @.Illegal unit of measure@>
  7673.   help4("The unit of measurement in math glue must be mu.")@/
  7674.     ("To recover gracefully from this error, it's best to")@/
  7675.     ("delete the erroneous units; e.g., type `2' to delete")@/
  7676.     ("two letters. (See Chapter 27 of The TeXbook.)");
  7677. @:TeXbook}{\sl The \TeX book@>
  7678.   error; goto attach_fraction;
  7679.   end
  7680. @ @<Adjust \(f)for the magnification ratio@>=
  7681. begin prepare_mag;
  7682. if mag<>1000 then
  7683.   begin cur_val:=xn_over_d(cur_val,1000,mag);
  7684.   f:=(1000*f+@'200000*remainder) div mag;
  7685.   cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
  7686.   end;
  7687. @ The necessary conversion factors can all be specified exactly as
  7688. fractions whose numerator and denominator are 32768 or less.
  7689. According to the definitions here, $\rm2660\,dd\approx1000.33297\,mm$;
  7690. this agrees well with the value $\rm1000.333\,mm$ cited by Bosshard
  7691. @^Bosshard, Hans Rudolf@>
  7692. in {\sl Technische Grundlagen zur Satzherstellung\/} (Bern, 1980).
  7693. @d set_conversion_end(#)== denom:=#; end
  7694. @d set_conversion(#)==@+begin num:=#; set_conversion_end
  7695. @<Scan for \(a)all other units and adjust |cur_val| and |f|...@>=
  7696. if scan_keyword("in") then set_conversion(7227)(100)
  7697. @.in@>
  7698. else if scan_keyword("pc") then set_conversion(12)(1)
  7699. @.pc@>
  7700. else if scan_keyword("cm") then set_conversion(7227)(254)
  7701. @.cm@>
  7702. else if scan_keyword("mm") then set_conversion(7227)(2540)
  7703. @.mm@>
  7704. else if scan_keyword("bp") then set_conversion(7227)(7200)
  7705. @.bp@>
  7706. else if scan_keyword("dd") then set_conversion(1238)(1157)
  7707. @.dd@>
  7708. else if scan_keyword("cc") then set_conversion(14856)(1157)
  7709. @.cc@>
  7710. else if scan_keyword("sp") then goto done
  7711. @.sp@>
  7712. else @<Complain about unknown unit and |goto done2|@>;
  7713. cur_val:=xn_over_d(cur_val,num,denom);
  7714. f:=(num*f+@'200000*remainder) div denom;@/
  7715. cur_val:=cur_val+(f div @'200000); f:=f mod @'200000;
  7716. done2:
  7717. @ @<Complain about unknown unit...@>=
  7718. begin print_err("Illegal unit of measure ("); print("pt inserted)");
  7719. @.Illegal unit of measure@>
  7720. help6("Dimensions can be in units of em, ex, in, pt, pc,")@/
  7721.   ("cm, mm, dd, cc, bp, or sp; but yours is a new one!")@/
  7722.   ("I'll assume that you meant to say pt, for printer's points.")@/
  7723.   ("To recover gracefully from this error, it's best to")@/
  7724.   ("delete the erroneous units; e.g., type `2' to delete")@/
  7725.   ("two letters. (See Chapter 27 of The TeXbook.)");
  7726. @:TeXbook}{\sl The \TeX book@>
  7727. error; goto done2;
  7728. @ @<Report that this dimension is out of range@>=
  7729. begin print_err("Dimension too large");
  7730. @.Dimension too large@>
  7731. help2("I can't work with sizes bigger than about 19 feet.")@/
  7732.   ("Continue and I'll use the largest value I can.");@/
  7733. error; cur_val:=max_dimen; arith_error:=false;
  7734. @ The final member of \TeX's value-scanning trio is |scan_glue|, which
  7735. makes |cur_val| point to a glue specification. The reference count of that
  7736. glue spec will take account of the fact that |cur_val| is pointing to~it.
  7737. The |level| parameter should be either |glue_val| or |mu_val|.
  7738. Since |scan_dimen| was so much more complex than |scan_int|, we might expect
  7739. |scan_glue| to be even worse. But fortunately, it is very simple, since
  7740. most of the work has already been done.
  7741. @p procedure scan_glue(@!level:small_number);
  7742.   {sets |cur_val| to a glue spec pointer}
  7743. label exit;
  7744. var negative:boolean; {should the answer be negated?}
  7745. @!q:pointer; {new glue specification}
  7746. @!mu:boolean; {does |level=mu_val|?}
  7747. begin mu:=(level=mu_val); @<Get the next non-blank non-sign...@>;
  7748. if (cur_cmd>=min_internal)and(cur_cmd<=max_internal) then
  7749.   begin scan_something_internal(level,negative);
  7750.   if cur_val_level>=glue_val then
  7751.     begin if cur_val_level<>level then mu_error;
  7752.     return;
  7753.     end;
  7754.   if cur_val_level=int_val then scan_dimen(mu,false,true)
  7755.   else if level=mu_val then mu_error;
  7756.   end
  7757. else  begin back_input; scan_dimen(mu,false,false);
  7758.   if negative then negate(cur_val);
  7759.   end;
  7760. @<Create a new glue specification whose width is |cur_val|; scan for its
  7761.   stretch and shrink components@>;
  7762. exit:end;
  7763. @ @<Create a new glue specification whose width is |cur_val|...@>=
  7764. q:=new_spec(zero_glue); width(q):=cur_val;
  7765. if scan_keyword("plus") then
  7766. @.plus@>
  7767.   begin scan_dimen(mu,true,false);
  7768.   stretch(q):=cur_val; stretch_order(q):=cur_order;
  7769.   end;
  7770. if scan_keyword("minus") then
  7771. @.minus@>
  7772.   begin scan_dimen(mu,true,false);
  7773.   shrink(q):=cur_val; shrink_order(q):=cur_order;
  7774.   end;
  7775. cur_val:=q
  7776. @ Here's a similar procedure that returns a pointer to a rule node. This
  7777. routine is called just after \TeX\ has seen \.{\\hrule} or \.{\\vrule};
  7778. therefore |cur_cmd| will be either |hrule| or |vrule|. The idea is to store
  7779. the default rule dimensions in the node, then to override them if
  7780. `\.{height}' or `\.{width}' or `\.{depth}' specifications are
  7781. found (in any order).
  7782. @d default_rule=26214 {0.4\thinspace pt}
  7783. @p function scan_rule_spec:pointer;
  7784. label reswitch;
  7785. var q:pointer; {the rule node being created}
  7786. begin q:=new_rule; {|width|, |depth|, and |height| all equal |null_flag| now}
  7787. if cur_cmd=vrule then width(q):=default_rule
  7788. else  begin height(q):=default_rule; depth(q):=0;
  7789.   end;
  7790. reswitch: if scan_keyword("width") then
  7791. @.width@>
  7792.   begin scan_normal_dimen; width(q):=cur_val; goto reswitch;
  7793.   end;
  7794. if scan_keyword("height") then
  7795. @.height@>
  7796.   begin scan_normal_dimen; height(q):=cur_val; goto reswitch;
  7797.   end;
  7798. if scan_keyword("depth") then
  7799. @.depth@>
  7800.   begin scan_normal_dimen; depth(q):=cur_val; goto reswitch;
  7801.   end;
  7802. scan_rule_spec:=q;
  7803. @* \[27] Building token lists.
  7804. The token lists for macros and for other things like \.{\\mark} and \.{\\output}
  7805. and \.{\\write} are produced by a procedure called |scan_toks|.
  7806. Before we get into the details of |scan_toks|, let's consider a much
  7807. simpler task, that of converting the current string into a token list.
  7808. The |str_toks| function does this; it classifies spaces as type |spacer|
  7809. and everything else as type |other_char|.
  7810. The token list created by |str_toks| begins at |link(temp_head)| and ends
  7811. at the value |p| that is returned. (If |p=temp_head|, the list is empty.)
  7812. @p function str_toks(@!b:pool_pointer):pointer;
  7813.   {changes the string |str_pool[b..pool_ptr]| to a token list}
  7814. var p:pointer; {tail of the token list}
  7815. @!q:pointer; {new node being added to the token list via |store_new_token|}
  7816. @!t:halfword; {token being appended}
  7817. @!k:pool_pointer; {index into |str_pool|}
  7818. begin str_room(1);
  7819. p:=temp_head; link(p):=null; k:=b;
  7820. while k<pool_ptr do
  7821.   begin t:=so(str_pool[k]);
  7822.   if t=" " then t:=space_token
  7823.   else t:=other_token+t;
  7824.   fast_store_new_token(t);
  7825.   incr(k);
  7826.   end;
  7827. pool_ptr:=b; str_toks:=p;
  7828. @ The main reason for wanting |str_toks| is the next function,
  7829. |the_toks|, which has similar input/output characteristics.
  7830. This procedure is supposed to scan something like `\.{\\skip\\count12}',
  7831. i.e., whatever can follow `\.{\\the}', and it constructs a token list
  7832. containing something like `\.{-3.0pt minus 0.5fill}'.
  7833. @p function the_toks:pointer;
  7834. var old_setting:0..max_selector; {holds |selector| setting}
  7835. @!p,@!q,@!r:pointer; {used for copying a token list}
  7836. @!b:pool_pointer; {base of temporary string}
  7837. begin get_x_token; scan_something_internal(tok_val,false);
  7838. if cur_val_level>=ident_val then @<Copy the token list@>
  7839. else begin old_setting:=selector; selector:=new_string; b:=pool_ptr;
  7840.   case cur_val_level of
  7841.   int_val:print_int(cur_val);
  7842.   dimen_val:begin print_scaled(cur_val); print("pt");
  7843.     end;
  7844.   glue_val: begin print_spec(cur_val,"pt"); delete_glue_ref(cur_val);
  7845.     end;
  7846.   mu_val: begin print_spec(cur_val,"mu"); delete_glue_ref(cur_val);
  7847.     end;
  7848.   end; {there are no other cases}
  7849.   selector:=old_setting; the_toks:=str_toks(b);
  7850.   end;
  7851. @ @<Copy the token list@>=
  7852. begin p:=temp_head; link(p):=null;
  7853. if cur_val_level=ident_val then store_new_token(cs_token_flag+cur_val)
  7854. else if cur_val<>null then
  7855.   begin r:=link(cur_val); {do not copy the reference count}
  7856.   while r<>null do
  7857.     begin fast_store_new_token(info(r)); r:=link(r);
  7858.     end;
  7859.   end;
  7860. the_toks:=p;
  7861. @ Here's part of the |expand| subroutine that we are now ready to complete:
  7862. @p procedure ins_the_toks;
  7863. begin link(garbage):=the_toks; ins_list(link(temp_head));
  7864. @ The primitives \.{\\number}, \.{\\romannumeral}, \.{\\string}, \.{\\meaning},
  7865. \.{\\fontname}, and \.{\\jobname} are defined as follows.
  7866. @d number_code=0 {command code for \.{\\number}}
  7867. @d roman_numeral_code=1 {command code for \.{\\romannumeral}}
  7868. @d string_code=2 {command code for \.{\\string}}
  7869. @d meaning_code=3 {command code for \.{\\meaning}}
  7870. @d font_name_code=4 {command code for \.{\\fontname}}
  7871. @d job_name_code=5 {command code for \.{\\jobname}}
  7872. @<Put each...@>=
  7873. primitive("number",convert,number_code);@/
  7874. @!@:number_}{\.{\\number} primitive@>
  7875. primitive("romannumeral",convert,roman_numeral_code);@/
  7876. @!@:roman_numeral_}{\.{\\romannumeral} primitive@>
  7877. primitive("string",convert,string_code);@/
  7878. @!@:string_}{\.{\\string} primitive@>
  7879. primitive("meaning",convert,meaning_code);@/
  7880. @!@:meaning_}{\.{\\meaning} primitive@>
  7881. primitive("fontname",convert,font_name_code);@/
  7882. @!@:font_name_}{\.{\\fontname} primitive@>
  7883. primitive("jobname",convert,job_name_code);@/
  7884. @!@:job_name_}{\.{\\jobname} primitive@>
  7885. @ @<Cases of |print_cmd_chr|...@>=
  7886. convert: case chr_code of
  7887.   number_code: print_esc("number");
  7888.   roman_numeral_code: print_esc("romannumeral");
  7889.   string_code: print_esc("string");
  7890.   meaning_code: print_esc("meaning");
  7891.   font_name_code: print_esc("fontname");
  7892.   othercases print_esc("jobname")
  7893.   endcases;
  7894. @ The procedure |conv_toks| uses |str_toks| to insert the token list
  7895. for |convert| functions into the scanner; `\.{\\outer}' control sequences
  7896. are allowed to follow `\.{\\string}' and `\.{\\meaning}'.
  7897. @p procedure conv_toks;
  7898. var old_setting:0..max_selector; {holds |selector| setting}
  7899. @!c:number_code..job_name_code; {desired type of conversion}
  7900. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  7901. @!b:pool_pointer; {base of temporary string}
  7902. begin c:=cur_chr; @<Scan the argument for command |c|@>;
  7903. old_setting:=selector; selector:=new_string; b:=pool_ptr;
  7904. @<Print the result of command |c|@>;
  7905. selector:=old_setting; link(garbage):=str_toks(b); ins_list(link(temp_head));
  7906. @ @<Scan the argument for command |c|@>=
  7907. case c of
  7908. number_code,roman_numeral_code: scan_int;
  7909. string_code, meaning_code: begin save_scanner_status:=scanner_status;
  7910.   scanner_status:=normal; get_token; scanner_status:=save_scanner_status;
  7911.   end;
  7912. font_name_code: scan_font_ident;
  7913. job_name_code: if job_name=0 then open_log_file;
  7914. end {there are no other cases}
  7915. @ @<Print the result of command |c|@>=
  7916. case c of
  7917. number_code: print_int(cur_val);
  7918. roman_numeral_code: print_roman_int(cur_val);
  7919. string_code:if cur_cs<>0 then sprint_cs(cur_cs)
  7920.   else print_char(cur_chr);
  7921. meaning_code: print_meaning;
  7922. font_name_code: begin print(font_name[cur_val]);
  7923.   if font_size[cur_val]<>font_dsize[cur_val] then
  7924.     begin print(" at "); print_scaled(font_size[cur_val]);
  7925.     print("pt");
  7926.     end;
  7927.   end;
  7928. job_name_code: print(job_name);
  7929. end {there are no other cases}
  7930. @ Now we can't postpone the difficulties any longer; we must bravely tackle
  7931. |scan_toks|. This function returns a pointer to the tail of a new token
  7932. list, and it also makes |def_ref| point to the reference count at the
  7933. head of that list.
  7934. There are two boolean parameters, |macro_def| and |xpand|. If |macro_def|
  7935. is true, the goal is to create the token list for a macro definition;
  7936. otherwise the goal is to create the token list for some other \TeX\
  7937. primitive: \.{\\mark}, \.{\\output}, \.{\\everypar}, \.{\\lowercase},
  7938. \.{\\uppercase}, \.{\\message}, \.{\\errmessage}, \.{\\write}, or
  7939. \.{\\special}. In the latter cases a left brace must be scanned next; this
  7940. left brace will not be part of the token list, nor will the matching right
  7941. brace that comes at the end. If |xpand| is false, the token list will
  7942. simply be copied from the input using |get_token|. Otherwise all expandable
  7943. tokens will be expanded until unexpandable tokens are left, except that
  7944. the results of expanding `\.{\\the}' are not expanded further.
  7945. If both |macro_def| and |xpand| are true, the expansion applies
  7946. only to the macro body (i.e., to the material following the first
  7947. |left_brace| character).
  7948. The value of |cur_cs| when |scan_toks| begins should be the |eqtb|
  7949. address of the control sequence to display in ``runaway'' error
  7950. messages.
  7951. @p function scan_toks(@!macro_def,@!xpand:boolean):pointer;
  7952. label found,done,done1,done2;
  7953. var t:halfword; {token representing the highest parameter number}
  7954. @!s:halfword; {saved token}
  7955. @!p:pointer; {tail of the token list being built}
  7956. @!q:pointer; {new node being added to the token list via |store_new_token|}
  7957. @!unbalance:halfword; {number of unmatched left braces}
  7958. @!hash_brace:halfword; {possible `\.{\#\{}' token}
  7959. begin if macro_def then scanner_status:=defining
  7960. @+else scanner_status:=absorbing;
  7961. warning_index:=cur_cs; def_ref:=get_avail; token_ref_count(def_ref):=null;
  7962. p:=def_ref; hash_brace:=0; t:=zero_token;
  7963. if macro_def then @<Scan and build the parameter part of the macro definition@>
  7964. else scan_left_brace; {remove the compulsory left brace}
  7965. @<Scan and build the body of the token list; |goto found| when finished@>;
  7966. found: scanner_status:=normal;
  7967. if hash_brace<>0 then store_new_token(hash_brace);
  7968. scan_toks:=p;
  7969. @ @<Scan and build the parameter part...@>=
  7970. begin loop begin get_token; {set |cur_cmd|, |cur_chr|, |cur_tok|}
  7971.   if cur_tok<right_brace_limit then goto done1;
  7972.   if cur_cmd=mac_param then
  7973.     @<If the next character is a parameter number, make |cur_tok|
  7974.       a |match| token; but if it is a left brace, store
  7975.       `|left_brace|, |end_match|', set |hash_brace|, and |goto done|@>;
  7976.   store_new_token(cur_tok);
  7977.   end;
  7978. done1: store_new_token(end_match_token);
  7979. if cur_cmd=right_brace then
  7980.   @<Express shock at the missing left brace; |goto found|@>;
  7981. done: end
  7982. @ @<Express shock...@>=
  7983. begin print_err("Missing { inserted"); incr(align_state);
  7984. @.Missing \{ inserted@>
  7985. help2("Where was the left brace? You said something like `\def\a}',")@/
  7986.   ("which I'm going to interpret as `\def\a{}'."); error; goto found;
  7987. @ @<If the next character is a parameter number...@>=
  7988. begin s:=match_token+cur_chr; get_token;
  7989. if cur_cmd=left_brace then
  7990.   begin hash_brace:=cur_tok;
  7991.   store_new_token(cur_tok); store_new_token(end_match_token);
  7992.   goto done;
  7993.   end;
  7994. if t=zero_token+9 then
  7995.   begin print_err("You already have nine parameters");
  7996. @.You already have nine...@>
  7997.   help1("I'm going to ignore the # sign you just used."); error;
  7998.   end
  7999. else  begin incr(t);
  8000.   if cur_tok<>t then
  8001.     begin print_err("Parameters must be numbered consecutively");
  8002. @.Parameters...consecutively@>
  8003.     help2("I've inserted the digit you should have used after the #.")@/
  8004.       ("Type `1' to delete what you did use."); back_error;
  8005.     end;
  8006.   cur_tok:=s;
  8007.   end;
  8008. @ @<Scan and build the body of the token list; |goto found| when finished@>=
  8009. unbalance:=1;
  8010. loop@+  begin if xpand then @<Expand the next part of the input@>
  8011.   else get_token;
  8012.   if cur_tok<right_brace_limit then
  8013.     if cur_cmd<right_brace then incr(unbalance)
  8014.     else  begin decr(unbalance);
  8015.       if unbalance=0 then goto found;
  8016.       end
  8017.   else if cur_cmd=mac_param then
  8018.     if macro_def then @<Look for parameter number or \.{\#\#}@>;
  8019.   store_new_token(cur_tok);
  8020.   end
  8021. @ Here we insert an entire token list created by |the_toks| without
  8022. expanding it further.
  8023. @<Expand the next part of the input@>=
  8024. begin loop begin get_next;
  8025.   if cur_cmd<=max_command then goto done2;
  8026.   if cur_cmd<>the then expand
  8027.   else  begin q:=the_toks;
  8028.     if link(temp_head)<>null then
  8029.       begin link(p):=link(temp_head); p:=q;
  8030.       end;
  8031.     end;
  8032.   end;
  8033. done2: x_token
  8034. @ @<Look for parameter number...@>=
  8035. begin s:=cur_tok;
  8036. if xpand then get_x_token else get_token;
  8037. if cur_cmd<>mac_param then
  8038.   if (cur_tok<=zero_token)or(cur_tok>t) then
  8039.     begin print_err("Illegal parameter number in definition of ");
  8040. @.Illegal parameter number...@>
  8041.     sprint_cs(warning_index);
  8042.     help3("You meant to type ## instead of #, right?")@/
  8043.     ("Or maybe a } was forgotten somewhere earlier, and things")@/
  8044.     ("are all screwed up? I'm going to assume that you meant ##.");
  8045.     back_error; cur_tok:=s;
  8046.     end
  8047.   else cur_tok:=out_param_token-"0"+cur_chr;
  8048. @ Another way to create a token list is via the \.{\\read} command. The
  8049. sixteen files potentially usable for reading appear in the following
  8050. global variables. The value of |read_open[n]| will be |closed| if
  8051. stream number |n| has not been opened or if it has been fully read;
  8052. |just_open| if an \.{\\openin} but not a \.{\\read} has been done;
  8053. and |normal| if it is open and ready to read the next line.
  8054. @d closed=2 {not open, or at end of file}
  8055. @d just_open=1 {newly opened, first line not yet read}
  8056. @<Glob...@>=
  8057. @!read_file:array[0..15] of alpha_file; {used for \.{\\read}}
  8058. @!read_open:array[0..16] of normal..closed; {state of |read_file[n]|}
  8059. @ @<Set init...@>=
  8060. for k:=0 to 16 do read_open[k]:=closed;
  8061. @ The |read_toks| procedure constructs a token list like that for any
  8062. macro definition, and makes |cur_val| point to it. Parameter |r| points
  8063. to the control sequence that will receive this token list.
  8064. @p procedure read_toks(@!n:integer;@!r:pointer);
  8065. label done;
  8066. var p:pointer; {tail of the token list}
  8067. @!q:pointer; {new node being added to the token list via |store_new_token|}
  8068. @!s:integer; {saved value of |align_state|}
  8069. @!m:small_number; {stream number}
  8070. begin scanner_status:=defining; warning_index:=r;
  8071. def_ref:=get_avail; token_ref_count(def_ref):=null;
  8072. p:=def_ref; {the reference count}
  8073. store_new_token(end_match_token);
  8074. if (n<0)or(n>15) then m:=16@+else m:=n;
  8075. s:=align_state; align_state:=1000000; {disable tab marks, etc.}
  8076. repeat @<Input and store tokens from the next line of the file@>;
  8077. until align_state=1000000;
  8078. cur_val:=def_ref; scanner_status:=normal; align_state:=s;
  8079. @ @<Input and store tokens from the next line of the file@>=
  8080. begin_file_reading; name:=m+1;
  8081. if read_open[m]=closed then @<Input for \.{\\read} from the terminal@>
  8082. else if read_open[m]=just_open then @<Input the first line of |read_file[m]|@>
  8083. else @<Input the next line of |read_file[m]|@>;
  8084. limit:=last;
  8085. if end_line_char_inactive then decr(limit)
  8086. else  buffer[limit]:=end_line_char;
  8087. first:=limit+1; loc:=start; state:=new_line;@/
  8088. loop@+  begin get_token;
  8089.   if cur_tok=0 then goto done;
  8090.     {|cur_cmd=cur_chr=0| will occur at the end of the line}
  8091.   if align_state<1000000 then {unmatched `\.\}' aborts the line}
  8092.     begin repeat get_token; until cur_tok=0;
  8093.     align_state:=1000000; goto done;
  8094.     end;
  8095.   store_new_token(cur_tok);
  8096.   end;
  8097. done: end_file_reading
  8098. @ Here we input on-line into the |buffer| array, prompting the user explicitly
  8099. if |n>=0|.  The value of |n| is set negative so that additional prompts
  8100. will not be given in the case of multi-line input.
  8101. @<Input for \.{\\read} from the terminal@>=
  8102. if interaction>nonstop_mode then
  8103.   if n<0 then prompt_input("")
  8104.   else  begin wake_up_terminal;
  8105.     print_ln; sprint_cs(r); prompt_input("="); n:=-1;
  8106.     end
  8107. else fatal_error("*** (cannot \read from terminal in nonstop modes)")
  8108. @.cannot \\read@>
  8109. @ The first line of a file must be treated specially, since |input_ln|
  8110. must be told not to start with |get|.
  8111. @^system dependencies@>
  8112. @<Input the first line of |read_file[m]|@>=
  8113. if input_ln(read_file[m],false) then read_open[m]:=normal
  8114. else  begin a_close(read_file[m]); read_open[m]:=closed;
  8115.   end
  8116. @ An empty line is appended at the end of a |read_file|.
  8117. @^empty line at end of file@>
  8118. @<Input the next line of |read_file[m]|@>=
  8119. begin if not input_ln(read_file[m],true) then
  8120.   begin a_close(read_file[m]); read_open[m]:=closed;
  8121.   if align_state<>1000000 then
  8122.     begin runaway;
  8123.     print_err("File ended within "); print_esc("read");
  8124. @.File ended within \\read@>
  8125.     help1("This \read has unbalanced braces.");
  8126.     align_state:=1000000; error;
  8127.     end;
  8128.   end;
  8129. @* \[28] Conditional processing.
  8130. We consider now the way \TeX\ handles various kinds of \.{\\if} commands.
  8131. @d if_char_code=0 { `\.{\\if}' }
  8132. @d if_cat_code=1 { `\.{\\ifcat}' }
  8133. @d if_int_code=2 { `\.{\\ifnum}' }
  8134. @d if_dim_code=3 { `\.{\\ifdim}' }
  8135. @d if_odd_code=4 { `\.{\\ifodd}' }
  8136. @d if_vmode_code=5 { `\.{\\ifvmode}' }
  8137. @d if_hmode_code=6 { `\.{\\ifhmode}' }
  8138. @d if_mmode_code=7 { `\.{\\ifmmode}' }
  8139. @d if_inner_code=8 { `\.{\\ifinner}' }
  8140. @d if_void_code=9 { `\.{\\ifvoid}' }
  8141. @d if_hbox_code=10 { `\.{\\ifhbox}' }
  8142. @d if_vbox_code=11 { `\.{\\ifvbox}' }
  8143. @d ifx_code=12 { `\.{\\ifx}' }
  8144. @d if_eof_code=13 { `\.{\\ifeof}' }
  8145. @d if_true_code=14 { `\.{\\iftrue}' }
  8146. @d if_false_code=15 { `\.{\\iffalse}' }
  8147. @d if_case_code=16 { `\.{\\ifcase}' }
  8148. @<Put each...@>=
  8149. primitive("if",if_test,if_char_code);
  8150. @!@:if_char_}{\.{\\if} primitive@>
  8151. primitive("ifcat",if_test,if_cat_code);
  8152. @!@:if_cat_code_}{\.{\\ifcat} primitive@>
  8153. primitive("ifnum",if_test,if_int_code);
  8154. @!@:if_int_}{\.{\\ifnum} primitive@>
  8155. primitive("ifdim",if_test,if_dim_code);
  8156. @!@:if_dim_}{\.{\\ifdim} primitive@>
  8157. primitive("ifodd",if_test,if_odd_code);
  8158. @!@:if_odd_}{\.{\\ifodd} primitive@>
  8159. primitive("ifvmode",if_test,if_vmode_code);
  8160. @!@:if_vmode_}{\.{\\ifvmode} primitive@>
  8161. primitive("ifhmode",if_test,if_hmode_code);
  8162. @!@:if_hmode_}{\.{\\ifhmode} primitive@>
  8163. primitive("ifmmode",if_test,if_mmode_code);
  8164. @!@:if_mmode_}{\.{\\ifmmode} primitive@>
  8165. primitive("ifinner",if_test,if_inner_code);
  8166. @!@:if_inner_}{\.{\\ifinner} primitive@>
  8167. primitive("ifvoid",if_test,if_void_code);
  8168. @!@:if_void_}{\.{\\ifvoid} primitive@>
  8169. primitive("ifhbox",if_test,if_hbox_code);
  8170. @!@:if_hbox_}{\.{\\ifhbox} primitive@>
  8171. primitive("ifvbox",if_test,if_vbox_code);
  8172. @!@:if_vbox_}{\.{\\ifvbox} primitive@>
  8173. primitive("ifx",if_test,ifx_code);
  8174. @!@:ifx_}{\.{\\ifx} primitive@>
  8175. primitive("ifeof",if_test,if_eof_code);
  8176. @!@:if_eof_}{\.{\\ifeof} primitive@>
  8177. primitive("iftrue",if_test,if_true_code);
  8178. @!@:if_true_}{\.{\\iftrue} primitive@>
  8179. primitive("iffalse",if_test,if_false_code);
  8180. @!@:if_false_}{\.{\\iffalse} primitive@>
  8181. primitive("ifcase",if_test,if_case_code);
  8182. @!@:if_case_}{\.{\\ifcase} primitive@>
  8183. @ @<Cases of |print_cmd_chr|...@>=
  8184. if_test: case chr_code of
  8185.   if_cat_code:print_esc("ifcat");
  8186.   if_int_code:print_esc("ifnum");
  8187.   if_dim_code:print_esc("ifdim");
  8188.   if_odd_code:print_esc("ifodd");
  8189.   if_vmode_code:print_esc("ifvmode");
  8190.   if_hmode_code:print_esc("ifhmode");
  8191.   if_mmode_code:print_esc("ifmmode");
  8192.   if_inner_code:print_esc("ifinner");
  8193.   if_void_code:print_esc("ifvoid");
  8194.   if_hbox_code:print_esc("ifhbox");
  8195.   if_vbox_code:print_esc("ifvbox");
  8196.   ifx_code:print_esc("ifx");
  8197.   if_eof_code:print_esc("ifeof");
  8198.   if_true_code:print_esc("iftrue");
  8199.   if_false_code:print_esc("iffalse");
  8200.   if_case_code:print_esc("ifcase");
  8201.   othercases print_esc("if")
  8202.   endcases;
  8203. @ Conditions can be inside conditions, and this nesting has a stack
  8204. that is independent of the |save_stack|.
  8205. Four global variables represent the top of the condition stack:
  8206. |cond_ptr| points to pushed-down entries, if any; |if_limit| specifies
  8207. the largest code of a |fi_or_else| command that is syntactically legal;
  8208. |cur_if| is the name of the current type of conditional; and |if_line|
  8209. is the line number at which it began.
  8210. If no conditions are currently in progress, the condition stack has the
  8211. special state |cond_ptr=null|, |if_limit=normal|, |cur_if=0|, |if_line=0|.
  8212. Otherwise |cond_ptr| points to a two-word node; the |type|, |subtype|, and
  8213. |link| fields of the first word contain |if_limit|, |cur_if|, and
  8214. |cond_ptr| at the next level, and the second word contains the
  8215. corresponding |if_line|.
  8216. @d if_node_size=2 {number of words in stack entry for conditionals}
  8217. @d if_line_field(#)==mem[#+1].int
  8218. @d if_code=1 {code for \.{\\if...} being evaluated}
  8219. @d fi_code=2 {code for \.{\\fi}}
  8220. @d else_code=3 {code for \.{\\else}}
  8221. @d or_code=4 {code for \.{\\or}}
  8222. @<Glob...@>=
  8223. @!cond_ptr:pointer; {top of the condition stack}
  8224. @!if_limit:normal..or_code; {upper bound on |fi_or_else| codes}
  8225. @!cur_if:small_number; {type of conditional being worked on}
  8226. @!if_line:integer; {line where that conditional began}
  8227. @ @<Set init...@>=
  8228. cond_ptr:=null; if_limit:=normal; cur_if:=0; if_line:=0;
  8229. @ @<Put each...@>=
  8230. primitive("fi",fi_or_else,fi_code);
  8231. @!@:fi_}{\.{\\fi} primitive@>
  8232. text(frozen_fi):="fi"; eqtb[frozen_fi]:=eqtb[cur_val];
  8233. primitive("or",fi_or_else,or_code);
  8234. @!@:or_}{\.{\\or} primitive@>
  8235. primitive("else",fi_or_else,else_code);
  8236. @!@:else_}{\.{\\else} primitive@>
  8237. @ @<Cases of |print_cmd_chr|...@>=
  8238. fi_or_else: if chr_code=fi_code then print_esc("fi")
  8239.   else if chr_code=or_code then print_esc("or")
  8240.   else print_esc("else");
  8241. @ When we skip conditional text, we keep track of the line number
  8242. where skipping began, for use in error messages.
  8243. @<Glob...@>=
  8244. @!skip_line:integer; {skipping began here}
  8245. @ Here is a procedure that ignores text until coming to an \.{\\or},
  8246. \.{\\else}, or \.{\\fi} at level zero of $\.{\\if}\ldots\.{\\fi}$
  8247. nesting. After it has acted, |cur_chr| will indicate the token that
  8248. was found, but |cur_tok| will not be set (because this makes the
  8249. procedure run faster).
  8250. @p procedure pass_text;
  8251. label done;
  8252. var l:integer; {level of $\.{\\if}\ldots\.{\\fi}$ nesting}
  8253. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  8254. begin save_scanner_status:=scanner_status; scanner_status:=skipping; l:=0;
  8255. skip_line:=line;
  8256. loop@+  begin get_next;
  8257.   if cur_cmd=fi_or_else then
  8258.     begin if l=0 then goto done;
  8259.     if cur_chr=fi_code then decr(l);
  8260.     end
  8261.   else if cur_cmd=if_test then incr(l);
  8262.   end;
  8263. done: scanner_status:=save_scanner_status;
  8264. @ When we begin to process a new \.{\\if}, we set |if_limit:=if_code|; then
  8265. if\/ \.{\\or} or \.{\\else} or \.{\\fi} occurs before the current \.{\\if}
  8266. condition has been evaluated, \.{\\relax} will be inserted.
  8267. For example, a sequence of commands like `\.{\\ifvoid1\\else...\\fi}'
  8268. would otherwise require something after the `\.1'.
  8269. @<Push the condition stack@>=
  8270. begin p:=get_node(if_node_size); link(p):=cond_ptr; type(p):=if_limit;
  8271. subtype(p):=cur_if; if_line_field(p):=if_line;
  8272. cond_ptr:=p; cur_if:=cur_chr; if_limit:=if_code; if_line:=line;
  8273. @ @<Pop the condition stack@>=
  8274. begin p:=cond_ptr; if_line:=if_line_field(p);
  8275. cur_if:=subtype(p); if_limit:=type(p); cond_ptr:=link(p);
  8276. free_node(p,if_node_size);
  8277. @ Here's a procedure that changes the |if_limit| code corresponding to
  8278. a given value of |cond_ptr|.
  8279. @p procedure change_if_limit(@!l:small_number;@!p:pointer);
  8280. label exit;
  8281. var q:pointer;
  8282. begin if p=cond_ptr then if_limit:=l {that's the easy case}
  8283. else  begin q:=cond_ptr;
  8284.   loop@+  begin if q=null then confusion("if");
  8285. @:this can't happen if}{\quad if@>
  8286.     if link(q)=p then
  8287.       begin type(q):=l; return;
  8288.       end;
  8289.     q:=link(q);
  8290.     end;
  8291.   end;
  8292. exit:end;
  8293. @ A condition is started when the |expand| procedure encounters
  8294. an |if_test| command; in that case |expand| reduces to |conditional|,
  8295. which is a recursive procedure.
  8296. @^recursion@>
  8297. @p procedure conditional;
  8298. label exit,common_ending;
  8299. var b:boolean; {is the condition true?}
  8300. @!r:"<"..">"; {relation to be evaluated}
  8301. @!m,@!n:integer; {to be tested against the second operand}
  8302. @!p,@!q:pointer; {for traversing token lists in \.{\\ifx} tests}
  8303. @!save_scanner_status:small_number; {|scanner_status| upon entry}
  8304. @!save_cond_ptr:pointer; {|cond_ptr| corresponding to this conditional}
  8305. @!this_if:small_number; {type of this conditional}
  8306. begin @<Push the condition stack@>;@+save_cond_ptr:=cond_ptr;this_if:=cur_chr;@/
  8307. @<Either process \.{\\ifcase} or set |b| to the value of a boolean condition@>;
  8308. if tracing_commands>1 then @<Display the value of |b|@>;
  8309. if b then
  8310.   begin change_if_limit(else_code,save_cond_ptr);
  8311.   return; {wait for \.{\\else} or \.{\\fi}}
  8312.   end;
  8313. @<Skip to \.{\\else} or \.{\\fi}, then |goto common_ending|@>;
  8314. common_ending: if cur_chr=fi_code then @<Pop the condition stack@>
  8315. else if_limit:=fi_code; {wait for \.{\\fi}}
  8316. exit:end;
  8317. @ In a construction like `\.{\\if\\iftrue abc\\else d\\fi}', the first
  8318. \.{\\else} that we come to after learning that the \.{\\if} is false is
  8319. not the \.{\\else} we're looking for. Hence the following curious
  8320. logic is needed.
  8321. @ @<Skip to \.{\\else} or \.{\\fi}...@>=
  8322. loop@+  begin pass_text;
  8323.   if cond_ptr=save_cond_ptr then
  8324.     begin if cur_chr<>or_code then goto common_ending;
  8325.     print_err("Extra "); print_esc("or");
  8326. @.Extra \\or@>
  8327.     help1("I'm ignoring this; it doesn't match any \if.");
  8328.     error;
  8329.     end
  8330.   else if cur_chr=fi_code then @<Pop the condition stack@>;
  8331.   end
  8332. @ @<Either process \.{\\ifcase} or set |b|...@>=
  8333. case this_if of
  8334. if_char_code, if_cat_code: @<Test if two characters match@>;
  8335. if_int_code, if_dim_code: @<Test relation between integers or dimensions@>;
  8336. if_odd_code: @<Test if an integer is odd@>;
  8337. if_vmode_code: b:=(abs(mode)=vmode);
  8338. if_hmode_code: b:=(abs(mode)=hmode);
  8339. if_mmode_code: b:=(abs(mode)=mmode);
  8340. if_inner_code: b:=(mode<0);
  8341. if_void_code, if_hbox_code, if_vbox_code: @<Test box register status@>;
  8342. ifx_code: @<Test if two tokens match@>;
  8343. if_eof_code: begin scan_four_bit_int; b:=(read_open[cur_val]=closed);
  8344.   end;
  8345. if_true_code: b:=true;
  8346. if_false_code: b:=false;
  8347. if_case_code: @<Select the appropriate case
  8348.   and |return| or |goto common_ending|@>;
  8349. end {there are no other cases}
  8350. @ @<Display the value of |b|@>=
  8351. begin begin_diagnostic;
  8352. if b then print("{true}")@+else print("{false}");
  8353. end_diagnostic(false);
  8354. @ Here we use the fact that |"<"|, |"="|, and |">"| are consecutive ASCII
  8355. codes.
  8356. @^ASCII code@>
  8357. @<Test relation between integers or dimensions@>=
  8358. begin if this_if=if_int_code then scan_int@+else scan_normal_dimen;
  8359. n:=cur_val; @<Get the next non-blank non-call...@>;
  8360. if (cur_tok>=other_token+"<")and(cur_tok<=other_token+">") then
  8361.   r:=cur_tok-other_token
  8362. else  begin print_err("Missing = inserted for ");
  8363. @.Missing = inserted@>
  8364.   print_cmd_chr(if_test,this_if);
  8365.   help1("I was expecting to see `<', `=', or `>'. Didn't.");
  8366.   back_error; r:="=";
  8367.   end;
  8368. if this_if=if_int_code then scan_int@+else scan_normal_dimen;
  8369. case r of
  8370. "<": b:=(n<cur_val);
  8371. "=": b:=(n=cur_val);
  8372. ">": b:=(n>cur_val);
  8373. @ @<Test if an integer is odd@>=
  8374. begin scan_int; b:=odd(cur_val);
  8375. @ @<Test box register status@>=
  8376. begin scan_eight_bit_int; p:=box(cur_val);
  8377. if this_if=if_void_code then b:=(p=null)
  8378. else if p=null then b:=false
  8379. else if this_if=if_hbox_code then b:=(type(p)=hlist_node)
  8380. else b:=(type(p)=vlist_node);
  8381. @ An active character will be treated as category 13 following
  8382. \.{\\if\\noexpand} or following \.{\\ifcat\\noexpand}. We use the fact that
  8383. active characters have the smallest tokens, among all control sequences.
  8384. @d get_x_token_or_active_char==@t@>@;
  8385.   begin get_x_token;
  8386.   if cur_cmd=relax then if cur_chr=no_expand_flag then
  8387.     begin cur_cmd:=active_char;
  8388.     cur_chr:=cur_tok-cs_token_flag-active_base;
  8389.     end;
  8390.   end
  8391. @<Test if two characters match@>=
  8392. begin get_x_token_or_active_char;
  8393. if (cur_cmd>active_char)or(cur_chr>255) then {not a character}
  8394.   begin m:=relax; n:=256;
  8395.   end
  8396. else  begin m:=cur_cmd; n:=cur_chr;
  8397.   end;
  8398. get_x_token_or_active_char;
  8399. if (cur_cmd>active_char)or(cur_chr>255) then
  8400.   begin cur_cmd:=relax; cur_chr:=256;
  8401.   end;
  8402. if this_if=if_char_code then b:=(n=cur_chr)@+else b:=(m=cur_cmd);
  8403. @ Note that `\.{\\ifx}' will declare two macros different if one is \\{long}
  8404. or \\{outer} and the other isn't, even though the texts of the macros are
  8405. the same.
  8406. We need to reset |scanner_status|, since \.{\\outer} control sequences
  8407. are allowed, but we might be scanning a macro definition or preamble.
  8408. @<Test if two tokens match@>=
  8409. begin save_scanner_status:=scanner_status; scanner_status:=normal;
  8410. get_next; n:=cur_cs; p:=cur_cmd; q:=cur_chr;
  8411. get_next; if cur_cmd<>p then b:=false
  8412. else if cur_cmd<call then b:=(cur_chr=q)
  8413. else @<Test if two macro texts match@>;
  8414. scanner_status:=save_scanner_status;
  8415. @ Note also that `\.{\\ifx}' decides that macros \.{\\a} and \.{\\b} are
  8416. different in examples like this:
  8417. $$\vbox{\halign{\.{#}\hfil&\qquad\.{#}\hfil\cr
  8418.   {}\\def\\a\{\\c\}&
  8419.   {}\\def\\c\{\}\cr
  8420.   {}\\def\\b\{\\d\}&
  8421.   {}\\def\\d\{\}\cr}}$$
  8422. @<Test if two macro texts match@>=
  8423. begin p:=link(cur_chr); q:=link(equiv(n)); {omit reference counts}
  8424. if p=q then b:=true
  8425. else begin while (p<>null)and(q<>null) do
  8426.     if info(p)<>info(q) then p:=null
  8427.     else  begin p:=link(p); q:=link(q);
  8428.       end;
  8429.   b:=((p=null)and(q=null));
  8430.   end;
  8431. @ @<Select the appropriate case and |return| or |goto common_ending|@>=
  8432. begin scan_int; n:=cur_val; {|n| is the number of cases to pass}
  8433. if tracing_commands>1 then
  8434.   begin begin_diagnostic; print("{case "); print_int(n); print_char("}");
  8435.   end_diagnostic(false);
  8436.   end;
  8437. while n<>0 do
  8438.   begin pass_text;
  8439.   if cond_ptr=save_cond_ptr then
  8440.     if cur_chr=or_code then decr(n)
  8441.     else goto common_ending
  8442.   else if cur_chr=fi_code then @<Pop the condition stack@>;
  8443.   end;
  8444. change_if_limit(or_code,save_cond_ptr);
  8445. return; {wait for \.{\\or}, \.{\\else}, or \.{\\fi}}
  8446. @ The processing of conditionals is complete except for the following
  8447. code, which is actually part of |expand|. It comes into play when
  8448. \.{\\or}, \.{\\else}, or \.{\\fi} is scanned.
  8449. @<Terminate the current conditional and skip to \.{\\fi}@>=
  8450. if cur_chr>if_limit then
  8451.   if if_limit=if_code then insert_relax {condition not yet evaluated}
  8452.   else  begin print_err("Extra "); print_cmd_chr(fi_or_else,cur_chr);
  8453. @.Extra \\or@>
  8454. @.Extra \\else@>
  8455. @.Extra \\fi@>
  8456.     help1("I'm ignoring this; it doesn't match any \if.");
  8457.     error;
  8458.     end
  8459. else  begin while cur_chr<>fi_code do pass_text; {skip to \.{\\fi}}
  8460.   @<Pop the condition stack@>;
  8461.   end
  8462. @* \[29] File names.
  8463. It's time now to fret about file names.  Besides the fact that different
  8464. operating systems treat files in different ways, we must cope with the
  8465. fact that completely different naming conventions are used by different
  8466. groups of people. The following programs show what is required for one
  8467. particular operating system; similar routines for other systems are not
  8468. difficult to devise.
  8469. @^fingers@>
  8470. @^system dependencies@>
  8471. \TeX\ assumes that a file name has three parts: the name proper; its
  8472. ``extension''; and a ``file area'' where it is found in an external file
  8473. system.  The extension of an input file or a write file is assumed to be
  8474. `\.{.tex}' unless otherwise specified; it is `\.{.log}' on the
  8475. transcript file that records each run of \TeX; it is `\.{.tfm}' on the font
  8476. metric files that describe characters in the fonts \TeX\ uses; it is
  8477. `\.{.dvi}' on the output files that specify typesetting information; and it
  8478. is `\.{.fmt}' on the format files written by \.{INITEX} to initialize \TeX.
  8479. The file area can be arbitrary on input files, but files are usually
  8480. output to the user's current area.  If an input file cannot be
  8481. found on the specified area, \TeX\ will look for it on a special system
  8482. area; this special area is intended for commonly used input files like
  8483. \.{webhdr.tex}.
  8484. Simple uses of \TeX\ refer only to file names that have no explicit
  8485. extension or area. For example, a person usually says `\.{\\input} \.{paper}'
  8486. or `\.{\\font\\tenrm} \.= \.{helvetica}' instead of `\.{\\input}
  8487. \.{paper.new}' or `\.{\\font\\tenrm} \.= \.{<csd.knuth>test}'. Simple file
  8488. names are best, because they make the \TeX\ source files portable;
  8489. whenever a file name consists entirely of letters and digits, it should be
  8490. treated in the same way by all implementations of \TeX. However, users
  8491. need the ability to refer to other files in their environment, especially
  8492. when responding to error messages concerning unopenable files; therefore
  8493. we want to let them use the syntax that appears in their favorite
  8494. operating system.
  8495. @ In order to isolate the system-dependent aspects of file names, the
  8496. @^system dependencies@>
  8497. system-independent parts of \TeX\ are expressed in terms
  8498. of three system-dependent
  8499. procedures called |begin_name|, |more_name|, and |end_name|. In
  8500. essence, if the user-specified characters of the file name are $c_1\ldots c_n$,
  8501. the system-independent driver program does the operations
  8502. $$|begin_name|;\,|more_name|(c_1);\,\ldots\,;|more_name|(c_n);
  8503. \,|end_name|.$$
  8504. These three procedures communicate with each other via global variables.
  8505. Afterwards the file name will appear in the string pool as three strings
  8506. called |cur_name|\penalty10000\hskip-.05em,
  8507. |cur_area|, and |cur_ext|; the latter two are null (i.e.,
  8508. |""|), unless they were explicitly specified by the user.
  8509. Actually the situation is slightly more complicated, because \TeX\ needs
  8510. to know when the file name ends. The |more_name| routine is a function
  8511. (with side effects) that returns |true| on the calls |more_name|$(c_1)$,
  8512. \dots, |more_name|$(c_{n-1})$. The final call |more_name|$(c_n)$
  8513. returns |false|; or, it returns |true| and the token following $c_n$ is
  8514. something like `\.{\\hbox}' (i.e., not a character). In other words,
  8515. |more_name| is supposed to return |true| unless it is sure that the
  8516. file name has been completely scanned; and |end_name| is supposed to be able
  8517. to finish the assembly of |cur_name|, |cur_area|, and |cur_ext| regardless of
  8518. whether $|more_name|(c_n)$ returned |true| or |false|.
  8519. @<Glob...@>=
  8520. @!cur_name:str_number; {name of file just scanned}
  8521. @!cur_area:str_number; {file area just scanned, or \.{""}}
  8522. @!cur_ext:str_number; {file extension just scanned, or \.{""}}
  8523. @ The file names we shall deal with for illustrative purposes have the
  8524. following structure:  If the name contains `\.>' or `\.:', the file area
  8525. consists of all characters up to and including the final such character;
  8526. otherwise the file area is null.  If the remaining file name contains
  8527. `\..', the file extension consists of all such characters from the first
  8528. remaining `\..' to the end, otherwise the file extension is null.
  8529. @^system dependencies@>
  8530. We can scan such file names easily by using two global variables that keep track
  8531. of the occurrences of area and extension delimiters:
  8532. @<Glob...@>=
  8533. @!area_delimiter:pool_pointer; {the most recent `\.>' or `\.:', if any}
  8534. @!ext_delimiter:pool_pointer; {the relevant `\..', if any}
  8535. @ Input files that can't be found in the user's area may appear in a standard
  8536. system area called |TEX_area|. Font metric files whose areas are not given
  8537. explicitly are assumed to appear in a standard system area called
  8538. |TEX_font_area|.  These system area names will, of course, vary from place
  8539. to place.
  8540. @^system dependencies@>
  8541. @d TEX_area=="TeXinputs:"
  8542. @.TeXinputs@>
  8543. @d TEX_font_area=="TeXfonts:"
  8544. @.TeXfonts@>
  8545. @ Here now is the first of the system-dependent routines for file name scanning.
  8546. @^system dependencies@>
  8547. @p procedure begin_name;
  8548. begin area_delimiter:=0; ext_delimiter:=0;
  8549. @ And here's the second. The string pool might change as the file name is
  8550. being scanned, since a new \.{\\csname} might be entered; therefore we keep
  8551. |area_delimiter| and |ext_delimiter| relative to the beginning of the current
  8552. string, instead of assigning an absolute address like |pool_ptr| to them.
  8553. @^system dependencies@>
  8554. @p function more_name(@!c:ASCII_code):boolean;
  8555. begin if c=" " then more_name:=false
  8556. else  begin str_room(1); append_char(c); {contribute |c| to the current string}
  8557.   if (c=">")or(c=":") then
  8558.     begin area_delimiter:=cur_length; ext_delimiter:=0;
  8559.     end
  8560.   else if (c=".")and(ext_delimiter=0) then ext_delimiter:=cur_length;
  8561.   more_name:=true;
  8562.   end;
  8563. @ The third.
  8564. @^system dependencies@>
  8565. @p procedure end_name;
  8566. begin if str_ptr+3>max_strings then
  8567.   overflow("number of strings",max_strings-init_str_ptr);
  8568. @:TeX capacity exceeded number of strings}{\quad number of strings@>
  8569. if area_delimiter=0 then cur_area:=""
  8570. else  begin cur_area:=str_ptr;
  8571.   str_start[str_ptr+1]:=str_start[str_ptr]+area_delimiter; incr(str_ptr);
  8572.   end;
  8573. if ext_delimiter=0 then
  8574.   begin cur_ext:=""; cur_name:=make_string;
  8575.   end
  8576. else  begin cur_name:=str_ptr;
  8577.   str_start[str_ptr+1]:=str_start[str_ptr]+ext_delimiter-area_delimiter-1;
  8578.   incr(str_ptr); cur_ext:=make_string;
  8579.   end;
  8580. @ Conversely, here is a routine that takes three strings and prints a file
  8581. name that might have produced them. (The routine is system dependent, because
  8582. some operating systems put the file area last instead of first.)
  8583. @^system dependencies@>
  8584. @<Basic printing...@>=
  8585. procedure print_file_name(@!n,@!a,@!e:integer);
  8586. begin slow_print(a); slow_print(n); slow_print(e);
  8587. @ Another system-dependent routine is needed to convert three internal
  8588. \TeX\ strings
  8589. into the |name_of_file| value that is used to open files. The present code
  8590. allows both lowercase and uppercase letters in the file name.
  8591. @^system dependencies@>
  8592. @d append_to_name(#)==begin c:=#; incr(k);
  8593.   if k<=file_name_size then name_of_file[k]:=xchr[c];
  8594.   end
  8595. @p procedure pack_file_name(@!n,@!a,@!e:str_number);
  8596. var k:integer; {number of positions filled in |name_of_file|}
  8597. @!c: ASCII_code; {character being packed}
  8598. @!j:pool_pointer; {index into |str_pool|}
  8599. begin k:=0;
  8600. for j:=str_start[a] to str_start[a+1]-1 do append_to_name(so(str_pool[j]));
  8601. for j:=str_start[n] to str_start[n+1]-1 do append_to_name(so(str_pool[j]));
  8602. for j:=str_start[e] to str_start[e+1]-1 do append_to_name(so(str_pool[j]));
  8603. if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
  8604. for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
  8605. @ A messier routine is also needed, since format file names must be scanned
  8606. before \TeX's string mechanism has been initialized. We shall use the
  8607. global variable |TEX_format_default| to supply the text for default system areas
  8608. and extensions related to format files.
  8609. @^system dependencies@>
  8610. @d format_default_length=20 {length of the |TEX_format_default| string}
  8611. @d format_area_length=11 {length of its area part}
  8612. @d format_ext_length=4 {length of its `\.{.fmt}' part}
  8613. @d format_extension=".fmt" {the extension, as a \.{WEB} constant}
  8614. @<Glob...@>=
  8615. @!TEX_format_default:packed array[1..format_default_length] of char;
  8616. @ @<Set init...@>=
  8617. TEX_format_default:='TeXformats:plain.fmt';
  8618. @.TeXformats@>
  8619. @.plain@>
  8620. @^system dependencies@>
  8621. @ @<Check the ``constant'' values for consistency@>=
  8622. if format_default_length>file_name_size then bad:=31;
  8623. @ Here is the messy routine that was just mentioned. It sets |name_of_file|
  8624. from the first |n| characters of |TEX_format_default|, followed by
  8625. |buffer[a..b]|, followed by the last |format_ext_length| characters of
  8626. |TEX_format_default|.
  8627. We dare not give error messages here, since \TeX\ calls this routine before
  8628. the |error| routine is ready to roll. Instead, we simply drop excess characters,
  8629. since the error will be detected in another way when a strange file name
  8630. isn't found.
  8631. @^system dependencies@>
  8632. @p procedure pack_buffered_name(@!n:small_number;@!a,@!b:integer);
  8633. var k:integer; {number of positions filled in |name_of_file|}
  8634. @!c: ASCII_code; {character being packed}
  8635. @!j:integer; {index into |buffer| or |TEX_format_default|}
  8636. begin if n+b-a+1+format_ext_length>file_name_size then
  8637.   b:=a+file_name_size-n-1-format_ext_length;
  8638. k:=0;
  8639. for j:=1 to n do append_to_name(xord[TEX_format_default[j]]);
  8640. for j:=a to b do append_to_name(buffer[j]);
  8641. for j:=format_default_length-format_ext_length+1 to format_default_length do
  8642.   append_to_name(xord[TEX_format_default[j]]);
  8643. if k<=file_name_size then name_length:=k@+else name_length:=file_name_size;
  8644. for k:=name_length+1 to file_name_size do name_of_file[k]:=' ';
  8645. @ Here is the only place we use |pack_buffered_name|. This part of the program
  8646. becomes active when a ``virgin'' \TeX\ is trying to get going, just after
  8647. the preliminary initialization, or when the user is substituting another
  8648. format file by typing `\.\&' after the initial `\.{**}' prompt.  The buffer
  8649. contains the first line of input in |buffer[loc..(last-1)]|, where
  8650. |loc<last| and |buffer[loc]<>" "|.
  8651. @<Declare the function called |open_fmt_file|@>=
  8652. function open_fmt_file:boolean;
  8653. label found,exit;
  8654. var j:0..buf_size; {the first space after the format file name}
  8655. begin j:=loc;
  8656. if buffer[loc]="&" then
  8657.   begin incr(loc); j:=loc; buffer[last]:=" ";
  8658.   while buffer[j]<>" " do incr(j);
  8659.   pack_buffered_name(0,loc,j-1); {try first without the system file area}
  8660.   if w_open_in(fmt_file) then goto found;
  8661.   pack_buffered_name(format_area_length,loc,j-1);
  8662.     {now try the system format file area}
  8663.   if w_open_in(fmt_file) then goto found;
  8664.   wake_up_terminal;
  8665.   wterm_ln('Sorry, I can''t find that format;',' will try PLAIN.');
  8666. @.Sorry, I can't find...@>
  8667.   update_terminal;
  8668.   end;
  8669.   {now pull out all the stops: try for the system \.{plain} file}
  8670. pack_buffered_name(format_default_length-format_ext_length,1,0);
  8671. if not w_open_in(fmt_file) then
  8672.   begin wake_up_terminal;
  8673.   wterm_ln('I can''t find the PLAIN format file!');
  8674. @.I can't find PLAIN...@>
  8675. @.plain@>
  8676.   open_fmt_file:=false; return;
  8677.   end;
  8678. found:loc:=j; open_fmt_file:=true;
  8679. exit:end;
  8680. @ Operating systems often make it possible to determine the exact name (and
  8681. possible version number) of a file that has been opened. The following routine,
  8682. which simply makes a \TeX\ string from the value of |name_of_file|, should
  8683. ideally be changed to deduce the full name of file~|f|, which is the file
  8684. most recently opened, if it is possible to do this in a \PASCAL\ program.
  8685. @^system dependencies@>
  8686. This routine might be called after string memory has overflowed, hence
  8687. we dare not use `|str_room|'.
  8688. @p function make_name_string:str_number;
  8689. var k:1..file_name_size; {index into |name_of_file|}
  8690. begin if (pool_ptr+name_length>pool_size)or(str_ptr=max_strings)or
  8691.  (cur_length>0) then
  8692.   make_name_string:="?"
  8693. else  begin for k:=1 to name_length do append_char(xord[name_of_file[k]]);
  8694.   make_name_string:=make_string;
  8695.   end;
  8696. function a_make_name_string(var f:alpha_file):str_number;
  8697. begin a_make_name_string:=make_name_string;
  8698. function b_make_name_string(var f:byte_file):str_number;
  8699. begin b_make_name_string:=make_name_string;
  8700. function w_make_name_string(var f:word_file):str_number;
  8701. begin w_make_name_string:=make_name_string;
  8702. @ Now let's consider the ``driver''
  8703. routines by which \TeX\ deals with file names
  8704. in a system-independent manner.  First comes a procedure that looks for a
  8705. file name in the input by calling |get_x_token| for the information.
  8706. @p procedure scan_file_name;
  8707. label done;
  8708. begin name_in_progress:=true; begin_name;
  8709. @<Get the next non-blank non-call...@>;
  8710. loop@+begin if (cur_cmd>other_char)or(cur_chr>255) then {not a character}
  8711.     begin back_input; goto done;
  8712.     end;
  8713.   if not more_name(cur_chr) then goto done;
  8714.   get_x_token;
  8715.   end;
  8716. done: end_name; name_in_progress:=false;
  8717. @ The global variable |name_in_progress| is used to prevent recursive
  8718. use of |scan_file_name|, since the |begin_name| and other procedures
  8719. communicate via global variables. Recursion would arise only by
  8720. devious tricks like `\.{\\input\\input f}'; such attempts at sabotage
  8721. must be thwarted. Furthermore, |name_in_progress| prevents \.{\\input}
  8722. @^recursion@>
  8723. from being initiated when a font size specification is being scanned.
  8724. Another global variable, |job_name|, contains the file name that was first
  8725. \.{\\input} by the user. This name is extended by `\.{.log}' and `\.{.dvi}'
  8726. and `\.{.fmt}' in the names of \TeX's output files.
  8727. @<Glob...@>=
  8728. @!name_in_progress:boolean; {is a file name being scanned?}
  8729. @!job_name:str_number; {principal file name}
  8730. @!log_opened:boolean; {has the transcript file been opened?}
  8731. @ Initially |job_name=0|; it becomes nonzero as soon as the true name is known.
  8732. We have |job_name=0| if and only if the `\.{log}' file has not been opened,
  8733. except of course for a short time just after |job_name| has become nonzero.
  8734. @<Initialize the output...@>=
  8735. job_name:=0; name_in_progress:=false; log_opened:=false;
  8736. @ Here is a routine that manufactures the output file names, assuming that
  8737. |job_name<>0|. It ignores and changes the current settings of |cur_area|
  8738. and |cur_ext|.
  8739. @d pack_cur_name==pack_file_name(cur_name,cur_area,cur_ext)
  8740. @p procedure pack_job_name(@!s:str_number); {|s = ".log"|, |".dvi"|, or
  8741.   |format_extension|}
  8742. begin cur_area:=""; cur_ext:=s;
  8743. cur_name:=job_name; pack_cur_name;
  8744. @ If some trouble arises when \TeX\ tries to open a file, the following
  8745. routine calls upon the user to supply another file name. Parameter~|s|
  8746. is used in the error message to identify the type of file; parameter~|e|
  8747. is the default extension if none is given. Upon exit from the routine,
  8748. variables |cur_name|, |cur_area|, |cur_ext|, and |name_of_file| are
  8749. ready for another attempt at file opening.
  8750. @p procedure prompt_file_name(@!s,@!e:str_number);
  8751. label done;
  8752. var k:0..buf_size; {index into |buffer|}
  8753. begin if interaction=scroll_mode then wake_up_terminal;
  8754. if s="input file name" then print_err("I can't find file `")
  8755. @.I can't find file x@>
  8756. else print_err("I can't write on file `");
  8757. @.I can't write on file x@>
  8758. print_file_name(cur_name,cur_area,cur_ext); print("'.");
  8759. if e=".tex" then show_context;
  8760. print_nl("Please type another "); print(s);
  8761. @.Please type...@>
  8762. if interaction<scroll_mode then
  8763.   fatal_error("*** (job aborted, file error in nonstop mode)");
  8764. @.job aborted, file error...@>
  8765. clear_terminal; prompt_input(": "); @<Scan file name in the buffer@>;
  8766. if cur_ext="" then cur_ext:=e;
  8767. pack_cur_name;
  8768. @ @<Scan file name in the buffer@>=
  8769. begin begin_name; k:=first;
  8770. while (buffer[k]=" ")and(k<last) do incr(k);
  8771. loop@+  begin if k=last then goto done;
  8772.   if not more_name(buffer[k]) then goto done;
  8773.   incr(k);
  8774.   end;
  8775. done:end_name;
  8776. @ Here's an example of how these conventions are used. Whenever it is time to
  8777. ship out a box of stuff, we shall use the macro |ensure_dvi_open|.
  8778. @d ensure_dvi_open==if output_file_name=0 then
  8779.   begin if job_name=0 then open_log_file;
  8780.   pack_job_name(".dvi");
  8781.   while not b_open_out(dvi_file) do
  8782.     prompt_file_name("file name for output",".dvi");
  8783.   output_file_name:=b_make_name_string(dvi_file);
  8784.   end
  8785. @<Glob...@>=
  8786. @!dvi_file: byte_file; {the device-independent output goes here}
  8787. @!output_file_name: str_number; {full name of the output file}
  8788. @!log_name:str_number; {full name of the log file}
  8789. @ @<Initialize the output...@>=output_file_name:=0;
  8790. @ The |open_log_file| routine is used to open the transcript file and to help
  8791. it catch up to what has previously been printed on the terminal.
  8792. @p procedure open_log_file;
  8793. var old_setting:0..max_selector; {previous |selector| setting}
  8794. @!k:0..buf_size; {index into |months| and |buffer|}
  8795. @!l:0..buf_size; {end of first input line}
  8796. @!months:packed array [1..36] of char; {abbreviations of month names}
  8797. begin old_setting:=selector;
  8798. if job_name=0 then job_name:="texput";
  8799. @.texput@>
  8800. pack_job_name(".log");
  8801. while not a_open_out(log_file) do @<Try to get a different log file name@>;
  8802. log_name:=a_make_name_string(log_file);
  8803. selector:=log_only; log_opened:=true;
  8804. @<Print the banner line, including the date and time@>;
  8805. input_stack[input_ptr]:=cur_input; {make sure bottom level is in memory}
  8806. print_nl("**");
  8807. @.**@>
  8808. l:=input_stack[0].limit_field; {last position of first line}
  8809. if buffer[l]=end_line_char then decr(l);
  8810. for k:=1 to l do print(buffer[k]);
  8811. print_ln; {now the transcript file contains the first line of input}
  8812. selector:=old_setting+2; {|log_only| or |term_and_log|}
  8813. @ Sometimes |open_log_file| is called at awkward moments when \TeX\ is
  8814. unable to print error messages or even to |show_context|.
  8815. The |prompt_file_name| routine can result in a |fatal_error|, but the |error|
  8816. routine will not be invoked because |log_opened| will be false.
  8817. The normal idea of |batch_mode| is that nothing at all should be written
  8818. on the terminal. However, in the unusual case that
  8819. no log file could be opened, we make an exception and allow
  8820. an explanatory message to be seen.
  8821. Incidentally, the program always refers to the log file as a `\.{transcript
  8822. file}', because some systems cannot use the extension `\.{.log}' for
  8823. this file.
  8824. @<Try to get a different log file name@>=
  8825. begin selector:=term_only;
  8826. prompt_file_name("transcript file name",".log");
  8827. @ @<Print the banner...@>=
  8828. begin wlog(banner);
  8829. slow_print(format_ident); print("  ");
  8830. print_int(day); print_char(" ");
  8831. months:='JANFEBMARAPRMAYJUNJULAUGSEPOCTNOVDEC';
  8832. for k:=3*month-2 to 3*month do wlog(months[k]);
  8833. print_char(" "); print_int(year); print_char(" ");
  8834. print_two(time div 60); print_char(":"); print_two(time mod 60);
  8835. @ Let's turn now to the procedure that is used to initiate file reading
  8836. when an `\.{\\input}' command is being processed.
  8837. @p procedure start_input; {\TeX\ will \.{\\input} something}
  8838. label done;
  8839. begin scan_file_name; {set |cur_name| to desired file name}
  8840. if cur_ext="" then cur_ext:=".tex";
  8841. pack_cur_name;
  8842. loop@+  begin begin_file_reading; {set up |cur_file| and new level of input}
  8843.   if a_open_in(cur_file) then goto done;
  8844.   if cur_area="" then
  8845.     begin pack_file_name(cur_name,TEX_area,cur_ext);
  8846.     if a_open_in(cur_file) then goto done;
  8847.     end;
  8848.   end_file_reading; {remove the level that didn't work}
  8849.   prompt_file_name("input file name",".tex");
  8850.   end;
  8851. done: name:=a_make_name_string(cur_file);
  8852. if job_name=0 then
  8853.   begin job_name:=cur_name; open_log_file;
  8854.   end; {|open_log_file| doesn't |show_context|, so |limit|
  8855.     and |loc| needn't be set to meaningful values yet}
  8856. if term_offset+length(name)>max_print_line-2 then print_ln
  8857. else if (term_offset>0)or(file_offset>0) then print_char(" ");
  8858. print_char("("); incr(open_parens); slow_print(name); update_terminal;
  8859. state:=new_line;
  8860. if name=str_ptr-1 then {we can conserve string pool space now}
  8861.   begin flush_string; name:=cur_name;
  8862.   end;
  8863. @<Read the first line of the new file@>;
  8864. @ Here we have to remember to tell the |input_ln| routine not to
  8865. start with a |get|. If the file is empty, it is considered to
  8866. contain a single blank line.
  8867. @^system dependencies@>
  8868. @^empty line at end of file@>
  8869. @<Read the first line...@>=
  8870. begin line:=1;
  8871. if input_ln(cur_file,false) then do_nothing;
  8872. firm_up_the_line;
  8873. if end_line_char_inactive then decr(limit)
  8874. else  buffer[limit]:=end_line_char;
  8875. first:=limit+1; loc:=start;
  8876. @* \[30] Font metric data.
  8877. \TeX\ gets its knowledge about fonts from font metric files, also called
  8878. \.{TFM} files; the `\.T' in `\.{TFM}' stands for \TeX,
  8879. but other programs know about them too.
  8880. @:TFM files}{\.{TFM} files@>
  8881. @^font metric files@>
  8882. The information in a \.{TFM} file appears in a sequence of 8-bit bytes.
  8883. Since the number of bytes is always a multiple of 4, we could
  8884. also regard the file as a sequence of 32-bit words, but \TeX\ uses the
  8885. byte interpretation. The format of \.{TFM} files was designed by
  8886. Lyle Ramshaw in 1980. The intent is to convey a lot of different kinds
  8887. @^Ramshaw, Lyle Harold@>
  8888. of information in a compact but useful form.
  8889. @<Glob...@>=
  8890. @!tfm_file:byte_file;
  8891. @ The first 24 bytes (6 words) of a \.{TFM} file contain twelve 16-bit
  8892. integers that give the lengths of the various subsequent portions
  8893. of the file. These twelve integers are, in order:
  8894. $$\vbox{\halign{\hfil#&$\null=\null$#\hfil\cr
  8895. |lf|&length of the entire file, in words;\cr
  8896. |lh|&length of the header data, in words;\cr
  8897. |bc|&smallest character code in the font;\cr
  8898. |ec|&largest character code in the font;\cr
  8899. |nw|&number of words in the width table;\cr
  8900. |nh|&number of words in the height table;\cr
  8901. |nd|&number of words in the depth table;\cr
  8902. |ni|&number of words in the italic correction table;\cr
  8903. |nl|&number of words in the lig/kern table;\cr
  8904. |nk|&number of words in the kern table;\cr
  8905. |ne|&number of words in the extensible character table;\cr
  8906. |np|&number of font parameter words.\cr}}$$
  8907. They are all nonnegative and less than $2^{15}$. We must have |bc-1<=ec<=255|,
  8908. $$\hbox{|lf=6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np|.}$$
  8909. Note that a font may contain as many as 256 characters (if |bc=0| and |ec=255|),
  8910. and as few as 0 characters (if |bc=ec+1|).
  8911. Incidentally, when two or more 8-bit bytes are combined to form an integer of
  8912. 16 or more bits, the most significant bytes appear first in the file.
  8913. This is called BigEndian order.
  8914. @!@^BigEndian order@>
  8915. @ The rest of the \.{TFM} file may be regarded as a sequence of ten data
  8916. arrays having the informal specification
  8917. $$\def\arr$[#1]#2${\&{array} $[#1]$ \&{of} #2}
  8918. \vbox{\halign{\hfil\\{#}&$\,:\,$\arr#\hfil\cr
  8919. header&|[0..lh-1]@t\\{stuff}@>|\cr
  8920. char\_info&|[bc..ec]char_info_word|\cr
  8921. width&|[0..nw-1]fix_word|\cr
  8922. height&|[0..nh-1]fix_word|\cr
  8923. depth&|[0..nd-1]fix_word|\cr
  8924. italic&|[0..ni-1]fix_word|\cr
  8925. lig\_kern&|[0..nl-1]lig_kern_command|\cr
  8926. kern&|[0..nk-1]fix_word|\cr
  8927. exten&|[0..ne-1]extensible_recipe|\cr
  8928. param&|[1..np]fix_word|\cr}}$$
  8929. The most important data type used here is a |@!fix_word|, which is
  8930. a 32-bit representation of a binary fraction. A |fix_word| is a signed
  8931. quantity, with the two's complement of the entire word used to represent
  8932. negation. Of the 32 bits in a |fix_word|, exactly 12 are to the left of the
  8933. binary point; thus, the largest |fix_word| value is $2048-2^{-20}$, and
  8934. the smallest is $-2048$. We will see below, however, that all but two of
  8935. the |fix_word| values must lie between $-16$ and $+16$.
  8936. @ The first data array is a block of header information, which contains
  8937. general facts about the font. The header must contain at least two words,
  8938. |header[0]| and |header[1]|, whose meaning is explained below.
  8939. Additional header information of use to other software routines might
  8940. also be included, but \TeX82 does not need to know about such details.
  8941. For example, 16 more words of header information are in use at the Xerox
  8942. Palo Alto Research Center; the first ten specify the character coding
  8943. scheme used (e.g., `\.{XEROX text}' or `\.{TeX math symbols}'), the next five
  8944. give the font identifier (e.g., `\.{HELVETICA}' or `\.{CMSY}'), and the
  8945. last gives the ``face byte.'' The program that converts \.{DVI} files
  8946. to Xerox printing format gets this information by looking at the \.{TFM}
  8947. file, which it needs to read anyway because of other information that
  8948. is not explicitly repeated in \.{DVI}~format.
  8949. \yskip\hang|header[0]| is a 32-bit check sum that \TeX\ will copy into
  8950. the \.{DVI} output file. Later on when the \.{DVI} file is printed,
  8951. possibly on another computer, the actual font that gets used is supposed
  8952. to have a check sum that agrees with the one in the \.{TFM} file used by
  8953. \TeX. In this way, users will be warned about potential incompatibilities.
  8954. (However, if the check sum is zero in either the font file or the \.{TFM}
  8955. file, no check is made.)  The actual relation between this check sum and
  8956. the rest of the \.{TFM} file is not important; the check sum is simply an
  8957. identification number with the property that incompatible fonts almost
  8958. always have distinct check sums.
  8959. @^check sum@>
  8960. \yskip\hang|header[1]| is a |fix_word| containing the design size of
  8961. the font, in units of \TeX\ points. This number must be at least 1.0; it is
  8962. fairly arbitrary, but usually the design size is 10.0 for a ``10 point''
  8963. font, i.e., a font that was designed to look best at a 10-point size,
  8964. whatever that really means. When a \TeX\ user asks for a font
  8965. `\.{at} $\delta$ \.{pt}', the effect is to override the design size
  8966. and replace it by $\delta$, and to multiply the $x$ and~$y$ coordinates
  8967. of the points in the font image by a factor of $\delta$ divided by the
  8968. design size.  {\sl All other dimensions in the\/ \.{TFM} file are
  8969. |fix_word|\kern-1pt\ numbers in design-size units}, with the exception of
  8970. |param[1]| (which denotes the slant ratio). Thus, for example, the value
  8971. of |param[6]|, which defines the \.{em} unit, is often the |fix_word| value
  8972. $2^{20}=1.0$, since many fonts have a design size equal to one em.
  8973. The other dimensions must be less than 16 design-size units in absolute
  8974. value; thus, |header[1]| and |param[1]| are the only |fix_word|
  8975. entries in the whole \.{TFM} file whose first byte might be something
  8976. besides 0 or 255.
  8977. @ Next comes the |char_info| array, which contains one |@!char_info_word|
  8978. per character. Each word in this part of the file contains six fields
  8979. packed into four bytes as follows.
  8980. \yskip\hang first byte: |@!width_index| (8 bits)\par
  8981. \hang second byte: |@!height_index| (4 bits) times 16, plus |@!depth_index|
  8982.   (4~bits)\par
  8983. \hang third byte: |@!italic_index| (6 bits) times 4, plus |@!tag|
  8984.   (2~bits)\par
  8985. \hang fourth byte: |@!remainder| (8 bits)\par
  8986. \yskip\noindent
  8987. The actual width of a character is \\{width}|[width_index]|, in design-size
  8988. units; this is a device for compressing information, since many characters
  8989. have the same width. Since it is quite common for many characters
  8990. to have the same height, depth, or italic correction, the \.{TFM} format
  8991. imposes a limit of 16 different heights, 16 different depths, and
  8992. 64 different italic corrections.
  8993. @!@^italic correction@>
  8994. The italic correction of a character has two different uses.
  8995. (a)~In ordinary text, the italic correction is added to the width only if
  8996. the \TeX\ user specifies `\.{\\/}' after the character.
  8997. (b)~In math formulas, the italic correction is always added to the width,
  8998. except with respect to the positioning of subscripts.
  8999. Incidentally, the relation $\\{width}[0]=\\{height}[0]=\\{depth}[0]=
  9000. \\{italic}[0]=0$ should always hold, so that an index of zero implies a
  9001. value of zero.  The |width_index| should never be zero unless the
  9002. character does not exist in the font, since a character is valid if and
  9003. only if it lies between |bc| and |ec| and has a nonzero |width_index|.
  9004. @ The |tag| field in a |char_info_word| has four values that explain how to
  9005. interpret the |remainder| field.
  9006. \yskip\hang|tag=0| (|no_tag|) means that |remainder| is unused.\par
  9007. \hang|tag=1| (|lig_tag|) means that this character has a ligature/kerning
  9008. program starting at position |remainder| in the |lig_kern| array.\par
  9009. \hang|tag=2| (|list_tag|) means that this character is part of a chain of
  9010. characters of ascending sizes, and not the largest in the chain.  The
  9011. |remainder| field gives the character code of the next larger character.\par
  9012. \hang|tag=3| (|ext_tag|) means that this character code represents an
  9013. extensible character, i.e., a character that is built up of smaller pieces
  9014. so that it can be made arbitrarily large. The pieces are specified in
  9015. |@!exten[remainder]|.\par
  9016. \yskip\noindent
  9017. Characters with |tag=2| and |tag=3| are treated as characters with |tag=0|
  9018. unless they are used in special circumstances in math formulas. For example,
  9019. the \.{\\sum} operation looks for a |list_tag|, and the \.{\\left}
  9020. operation looks for both |list_tag| and |ext_tag|.
  9021. @d no_tag=0 {vanilla character}
  9022. @d lig_tag=1 {character has a ligature/kerning program}
  9023. @d list_tag=2 {character has a successor in a charlist}
  9024. @d ext_tag=3 {character is extensible}
  9025. @ The |lig_kern| array contains instructions in a simple programming language
  9026. that explains what to do for special letter pairs. Each word in this array is a
  9027. |@!lig_kern_command| of four bytes.
  9028. \yskip\hang first byte: |skip_byte|, indicates that this is the final program
  9029.   step if the byte is 128 or more, otherwise the next step is obtained by
  9030.   skipping this number of intervening steps.\par
  9031. \hang second byte: |next_char|, ``if |next_char| follows the current character,
  9032.   then perform the operation and stop, otherwise continue.''\par
  9033. \hang third byte: |op_byte|, indicates a ligature step if less than~128,
  9034.   a kern step otherwise.\par
  9035. \hang fourth byte: |remainder|.\par
  9036. \yskip\noindent
  9037. In a kern step, an
  9038. additional space equal to |kern[256*(op_byte-128)+remainder]| is inserted
  9039. between the current character and |next_char|. This amount is
  9040. often negative, so that the characters are brought closer together
  9041. by kerning; but it might be positive.
  9042. There are eight kinds of ligature steps, having |op_byte| codes $4a+2b+c$ where
  9043. $0\le a\le b+c$ and $0\le b,c\le1$. The character whose code is
  9044. |remainder| is inserted between the current character and |next_char|;
  9045. then the current character is deleted if $b=0$, and |next_char| is
  9046. deleted if $c=0$; then we pass over $a$~characters to reach the next
  9047. current character (which may have a ligature/kerning program of its own).
  9048. If the very first instruction of the |lig_kern| array has |skip_byte=255|,
  9049. the |next_char| byte is the so-called right boundary character of this font;
  9050. the value of |next_char| need not lie between |bc| and~|ec|.
  9051. If the very last instruction of the |lig_kern| array has |skip_byte=255|,
  9052. there is a special ligature/kerning program for a left boundary character,
  9053. beginning at location |256*op_byte+remainder|.
  9054. The interpretation is that \TeX\ puts implicit boundary characters
  9055. before and after each consecutive string of characters from the same font.
  9056. These implicit characters do not appear in the output, but they can affect
  9057. ligatures and kerning.
  9058. If the very first instruction of a character's |lig_kern| program has
  9059. |skip_byte>128|, the program actually begins in location
  9060. |256*op_byte+remainder|. This feature allows access to large |lig_kern|
  9061. arrays, because the first instruction must otherwise
  9062. appear in a location |<=255|.
  9063. Any instruction with |skip_byte>128| in the |lig_kern| array must satisfy
  9064. the condition
  9065. $$\hbox{|256*op_byte+remainder<nl|.}$$
  9066. If such an instruction is encountered during
  9067. normal program execution, it denotes an unconditional halt; no ligature
  9068. or kerning command is performed.
  9069. @d stop_flag==qi(128) {value indicating `\.{STOP}' in a lig/kern program}
  9070. @d kern_flag==qi(128) {op code for a kern step}
  9071. @d skip_byte(#)==#.b0
  9072. @d next_char(#)==#.b1
  9073. @d op_byte(#)==#.b2
  9074. @d rem_byte(#)==#.b3
  9075. @ Extensible characters are specified by an |@!extensible_recipe|, which
  9076. consists of four bytes called |@!top|, |@!mid|, |@!bot|, and |@!rep| (in this
  9077. order). These bytes are the character codes of individual pieces used to
  9078. build up a large symbol.  If |top|, |mid|, or |bot| are zero, they are not
  9079. present in the built-up result. For example, an extensible vertical line is
  9080. like an extensible bracket, except that the top and bottom pieces are missing.
  9081. Let $T$, $M$, $B$, and $R$ denote the respective pieces, or an empty box
  9082. if the piece isn't present. Then the extensible characters have the form
  9083. $TR^kMR^kB$ from top to bottom, for some |k>=0|, unless $M$ is absent;
  9084. in the latter case we can have $TR^kB$ for both even and odd values of~|k|.
  9085. The width of the extensible character is the width of $R$; and the
  9086. height-plus-depth is the sum of the individual height-plus-depths of the
  9087. components used, since the pieces are butted together in a vertical list.
  9088. @d ext_top(#)==#.b0 {|top| piece in a recipe}
  9089. @d ext_mid(#)==#.b1 {|mid| piece in a recipe}
  9090. @d ext_bot(#)==#.b2 {|bot| piece in a recipe}
  9091. @d ext_rep(#)==#.b3 {|rep| piece in a recipe}
  9092. @ The final portion of a \.{TFM} file is the |param| array, which is another
  9093. sequence of |fix_word| values.
  9094. \yskip\hang|param[1]=slant| is the amount of italic slant, which is used
  9095. to help position accents. For example, |slant=.25| means that when you go
  9096. up one unit, you also go .25 units to the right. The |slant| is a pure
  9097. number; it's the only |fix_word| other than the design size itself that is
  9098. not scaled by the design size.
  9099. \hang|param[2]=space| is the normal spacing between words in text.
  9100. Note that character |" "| in the font need not have anything to do with
  9101. blank spaces.
  9102. \hang|param[3]=space_stretch| is the amount of glue stretching between words.
  9103. \hang|param[4]=space_shrink| is the amount of glue shrinking between words.
  9104. \hang|param[5]=x_height| is the size of one ex in the font; it is also
  9105. the height of letters for which accents don't have to be raised or lowered.
  9106. \hang|param[6]=quad| is the size of one em in the font.
  9107. \hang|param[7]=extra_space| is the amount added to |param[2]| at the
  9108. ends of sentences.
  9109. \yskip\noindent
  9110. If fewer than seven parameters are present, \TeX\ sets the missing parameters
  9111. to zero. Fonts used for math symbols are required to have
  9112. additional parameter information, which is explained later.
  9113. @d slant_code=1
  9114. @d space_code=2
  9115. @d space_stretch_code=3
  9116. @d space_shrink_code=4
  9117. @d x_height_code=5
  9118. @d quad_code=6
  9119. @d extra_space_code=7
  9120. @ So that is what \.{TFM} files hold. Since \TeX\ has to absorb such information
  9121. about lots of fonts, it stores most of the data in a large array called
  9122. |font_info|. Each item of |font_info| is a |memory_word|; the |fix_word|
  9123. data gets converted into |scaled| entries, while everything else goes into
  9124. words of type |four_quarters|.
  9125. When the user defines \.{\\font\\f}, say, \TeX\ assigns an internal number
  9126. to the user's font~\.{\\f}. Adding this number to |font_id_base| gives the
  9127. |eqtb| location of a ``frozen'' control sequence that will always select
  9128. the font.
  9129. @<Types...@>=
  9130. @!internal_font_number=font_base..font_max; {|font| in a |char_node|}
  9131. @!font_index=0..font_mem_size; {index into |font_info|}
  9132. @ Here now is the (rather formidable) array of font arrays.
  9133. @d non_char==qi(256) {a |halfword| code that can't match a real character}
  9134. @d non_address==font_mem_size {a spurious |font_index|}
  9135. @<Glob...@>=
  9136. @!font_info:array[font_index] of memory_word;
  9137.   {the big collection of font data}
  9138. @!fmem_ptr:font_index; {first unused word of |font_info|}
  9139. @!font_ptr:internal_font_number; {largest internal font number in use}
  9140. @!font_check:array[internal_font_number] of four_quarters; {check sum}
  9141. @!font_size:array[internal_font_number] of scaled; {``at'' size}
  9142. @!font_dsize:array[internal_font_number] of scaled; {``design'' size}
  9143. @!font_params:array[internal_font_number] of halfword; {how many font
  9144.   parameters are present}
  9145. @!font_name:array[internal_font_number] of str_number; {name of the font}
  9146. @!font_area:array[internal_font_number] of str_number; {area of the font}
  9147. @!font_bc:array[internal_font_number] of eight_bits;
  9148.   {beginning (smallest) character code}
  9149. @!font_ec:array[internal_font_number] of eight_bits;
  9150.   {ending (largest) character code}
  9151. @!font_glue:array[internal_font_number] of pointer;
  9152.   {glue specification for interword space, |null| if not allocated}
  9153. @!font_used:array[internal_font_number] of boolean;
  9154.   {has a character from this font actually appeared in the output?}
  9155. @!hyphen_char:array[internal_font_number] of integer;
  9156.   {current \.{\\hyphenchar} values}
  9157. @!skew_char:array[internal_font_number] of integer;
  9158.   {current \.{\\skewchar} values}
  9159. @!bchar_label:array[internal_font_number] of font_index;
  9160.   {start of |lig_kern| program for left boundary character,
  9161.   |non_address| if there is none}
  9162. @!font_bchar:array[internal_font_number] of min_quarterword..non_char;
  9163.   {right boundary character, |non_char| if there is none}
  9164. @!font_false_bchar:array[internal_font_number] of min_quarterword..non_char;
  9165.   {|font_bchar| if it doesn't exist in the font, otherwise |non_char|}
  9166. @ Besides the arrays just enumerated, we have directory arrays that make it
  9167. easy to get at the individual entries in |font_info|. For example, the
  9168. |char_info| data for character |c| in font |f| will be in
  9169. |font_info[char_base[f]+c].qqqq|; and if |w| is the |width_index|
  9170. part of this word (the |b0| field), the width of the character is
  9171. |font_info[width_base[f]+w].sc|. (These formulas assume that
  9172. |min_quarterword| has already been added to |c| and to |w|, since \TeX\
  9173. stores its quarterwords that way.)
  9174. @<Glob...@>=
  9175. @!char_base:array[internal_font_number] of integer;
  9176.   {base addresses for |char_info|}
  9177. @!width_base:array[internal_font_number] of integer;
  9178.   {base addresses for widths}
  9179. @!height_base:array[internal_font_number] of integer;
  9180.   {base addresses for heights}
  9181. @!depth_base:array[internal_font_number] of integer;
  9182.   {base addresses for depths}
  9183. @!italic_base:array[internal_font_number] of integer;
  9184.   {base addresses for italic corrections}
  9185. @!lig_kern_base:array[internal_font_number] of integer;
  9186.   {base addresses for ligature/kerning programs}
  9187. @!kern_base:array[internal_font_number] of integer;
  9188.   {base addresses for kerns}
  9189. @!exten_base:array[internal_font_number] of integer;
  9190.   {base addresses for extensible recipes}
  9191. @!param_base:array[internal_font_number] of integer;
  9192.   {base addresses for font parameters}
  9193. @ @<Set init...@>=
  9194. for k:=font_base to font_max do font_used[k]:=false;
  9195. @ \TeX\ always knows at least one font, namely the null font. It has no
  9196. characters, and its seven parameters are all equal to zero.
  9197. @<Initialize table...@>=
  9198. font_ptr:=null_font; fmem_ptr:=7;
  9199. font_name[null_font]:="nullfont"; font_area[null_font]:="";
  9200. hyphen_char[null_font]:="-"; skew_char[null_font]:=-1;
  9201. bchar_label[null_font]:=non_address;
  9202. font_bchar[null_font]:=non_char; font_false_bchar[null_font]:=non_char;
  9203. font_bc[null_font]:=1; font_ec[null_font]:=0;
  9204. font_size[null_font]:=0; font_dsize[null_font]:=0;
  9205. char_base[null_font]:=0; width_base[null_font]:=0;
  9206. height_base[null_font]:=0; depth_base[null_font]:=0;
  9207. italic_base[null_font]:=0; lig_kern_base[null_font]:=0;
  9208. kern_base[null_font]:=0; exten_base[null_font]:=0;
  9209. font_glue[null_font]:=null; font_params[null_font]:=7;
  9210. param_base[null_font]:=-1;
  9211. for k:=0 to 6 do font_info[k].sc:=0;
  9212. @ @<Put each...@>=
  9213. primitive("nullfont",set_font,null_font);
  9214. @!@:null_font_}{\.{\\nullfont} primitive@>
  9215. text(frozen_null_font):="nullfont"; eqtb[frozen_null_font]:=eqtb[cur_val];
  9216. @ Of course we want to define macros that suppress the detail of how font
  9217. information is actually packed, so that we don't have to write things like
  9218. $$\hbox{|font_info[width_base[f]+font_info[char_base[f]+c].qqqq.b0].sc|}$$
  9219. too often. The \.{WEB} definitions here make |char_info(f)(c)| the
  9220. |four_quarters| word of font information corresponding to character
  9221. |c| of font |f|. If |q| is such a word, |char_width(f)(q)| will be
  9222. the character's width; hence the long formula above is at least
  9223. abbreviated to
  9224. $$\hbox{|char_width(f)(char_info(f)(c))|.}$$
  9225. Usually, of course, we will fetch |q| first and look at several of its
  9226. fields at the same time.
  9227. The italic correction of a character will be denoted by
  9228. |char_italic(f)(q)|, so it is analogous to |char_width|.  But we will get
  9229. at the height and depth in a slightly different way, since we usually want
  9230. to compute both height and depth if we want either one.  The value of
  9231. |height_depth(q)| will be the 8-bit quantity
  9232. $$b=|height_index|\times16+|depth_index|,$$ and if |b| is such a byte we
  9233. will write |char_height(f)(b)| and |char_depth(f)(b)| for the height and
  9234. depth of the character |c| for which |q=char_info(f)(c)|. Got that?
  9235. The tag field will be called |char_tag(q)|; the remainder byte will be
  9236. called |rem_byte(q)|, using a macro that we have already defined above.
  9237. Access to a character's |width|, |height|, |depth|, and |tag| fields is
  9238. part of \TeX's inner loop, so we want these macros to produce code that is
  9239. as fast as possible under the circumstances.
  9240. @^inner loop@>
  9241. @d char_info_end(#)==#].qqqq
  9242. @d char_info(#)==font_info[char_base[#]+char_info_end
  9243. @d char_width_end(#)==#.b0].sc
  9244. @d char_width(#)==font_info[width_base[#]+char_width_end
  9245. @d char_exists(#)==(#.b0>min_quarterword)
  9246. @d char_italic_end(#)==(qo(#.b2)) div 4].sc
  9247. @d char_italic(#)==font_info[italic_base[#]+char_italic_end
  9248. @d height_depth(#)==qo(#.b1)
  9249. @d char_height_end(#)==(#) div 16].sc
  9250. @d char_height(#)==font_info[height_base[#]+char_height_end
  9251. @d char_depth_end(#)==(#) mod 16].sc
  9252. @d char_depth(#)==font_info[depth_base[#]+char_depth_end
  9253. @d char_tag(#)==((qo(#.b2)) mod 4)
  9254. @ The global variable |null_character| is set up to be a word of
  9255. |char_info| for a character that doesn't exist. Such a word provides a
  9256. convenient way to deal with erroneous situations.
  9257. @<Glob...@>=
  9258. @!null_character:four_quarters; {nonexistent character information}
  9259. @ @<Set init...@>=
  9260. null_character.b0:=min_quarterword; null_character.b1:=min_quarterword;
  9261. null_character.b2:=min_quarterword; null_character.b3:=min_quarterword;
  9262. @ Here are some macros that help process ligatures and kerns.
  9263. We write |char_kern(f)(j)| to find the amount of kerning specified by
  9264. kerning command~|j| in font~|f|. If |j| is the |char_info| for a character
  9265. with a ligature/kern program, the first instruction of that program is either
  9266. |i=font_info[lig_kern_start(f)(j)]| or |font_info[lig_kern_restart(f)(i)]|,
  9267. depending on whether or not |skip_byte(i)<=stop_flag|.
  9268. The constant |kern_base_offset| should be simplified, for \PASCAL\ compilers
  9269. that do not do local optimization.
  9270. @^system dependencies@>
  9271. @d char_kern_end(#)==256*op_byte(#)+rem_byte(#)].sc
  9272. @d char_kern(#)==font_info[kern_base[#]+char_kern_end
  9273. @d kern_base_offset==256*(128+min_quarterword)
  9274. @d lig_kern_start(#)==lig_kern_base[#]+rem_byte {beginning of lig/kern program}
  9275. @d lig_kern_restart_end(#)==256*op_byte(#)+rem_byte(#)+32768-kern_base_offset
  9276. @d lig_kern_restart(#)==lig_kern_base[#]+lig_kern_restart_end
  9277. @ Font parameters are referred to as |slant(f)|, |space(f)|, etc.
  9278. @d param_end(#)==param_base[#]].sc
  9279. @d param(#)==font_info[#+param_end
  9280. @d slant==param(slant_code) {slant to the right, per unit distance upward}
  9281. @d space==param(space_code) {normal space between words}
  9282. @d space_stretch==param(space_stretch_code) {stretch between words}
  9283. @d space_shrink==param(space_shrink_code) {shrink between words}
  9284. @d x_height==param(x_height_code) {one ex}
  9285. @d quad==param(quad_code) {one em}
  9286. @d extra_space==param(extra_space_code) {additional space at end of sentence}
  9287. @<The em width for |cur_font|@>=quad(cur_font)
  9288. @ @<The x-height for |cur_font|@>=x_height(cur_font)
  9289. @ \TeX\ checks the information of a \.{TFM} file for validity as the
  9290. file is being read in, so that no further checks will be needed when
  9291. typesetting is going on. The somewhat tedious subroutine that does this
  9292. is called |read_font_info|. It has four parameters: the user font
  9293. identifier~|u|, the file name and area strings |nom| and |aire|, and the
  9294. ``at'' size~|s|. If |s|~is negative, it's the negative of a scale factor
  9295. to be applied to the design size; |s=-1000| is the normal case.
  9296. Otherwise |s| will be substituted for the design size; in this
  9297. case, |s| must be positive and less than $2048\rm\,pt$
  9298. (i.e., it must be less than $2^{27}$ when considered as an integer).
  9299. The subroutine opens and closes a global file variable called |tfm_file|.
  9300. It returns the value of the internal font number that was just loaded.
  9301. If an error is detected, an error message is issued and no font
  9302. information is stored; |null_font| is returned in this case.
  9303. @d bad_tfm=11 {label for |read_font_info|}
  9304. @d abort==goto bad_tfm {do this when the \.{TFM} data is wrong}
  9305. @p function read_font_info(@!u:pointer;@!nom,@!aire:str_number;
  9306.   @!s:scaled):internal_font_number; {input a \.{TFM} file}
  9307. label done,bad_tfm,not_found;
  9308. var k:font_index; {index into |font_info|}
  9309. @!file_opened:boolean; {was |tfm_file| successfully opened?}
  9310. @!lf,@!lh,@!bc,@!ec,@!nw,@!nh,@!nd,@!ni,@!nl,@!nk,@!ne,@!np:halfword;
  9311.   {sizes of subfiles}
  9312. @!f:internal_font_number; {the new font's number}
  9313. @!g:internal_font_number; {the number to return}
  9314. @!a,@!b,@!c,@!d:eight_bits; {byte variables}
  9315. @!qw:four_quarters;@!sw:scaled; {accumulators}
  9316. @!bch_label:integer; {left boundary start location, or infinity}
  9317. @!bchar:0..256; {right boundary character, or 256}
  9318. @!z:scaled; {the design size or the ``at'' size}
  9319. @!alpha:integer;@!beta:1..16;
  9320.   {auxiliary quantities used in fixed-point multiplication}
  9321. begin g:=null_font;@/
  9322. @<Read and check the font data; |abort| if the \.{TFM} file is
  9323.   malformed; if there's no room for this font, say so and |goto
  9324.   done|; otherwise |incr(font_ptr)| and |goto done|@>;
  9325. bad_tfm: @<Report that the font won't be loaded@>;
  9326. done: if file_opened then b_close(tfm_file);
  9327. read_font_info:=g;
  9328. @ There are programs called \.{TFtoPL} and \.{PLtoTF} that convert
  9329. between the \.{TFM} format and a symbolic property-list format
  9330. that can be easily edited. These programs contain extensive
  9331. diagnostic information, so \TeX\ does not have to bother giving
  9332. precise details about why it rejects a particular \.{TFM} file.
  9333. @.TFtoPL@> @.PLtoTF@>
  9334. @d start_font_error_message==print_err("Font "); sprint_cs(u);
  9335.   print_char("="); print_file_name(nom,aire,"");
  9336.   if s>=0 then
  9337.     begin print(" at "); print_scaled(s); print("pt");
  9338.     end
  9339.   else if s<>-1000 then
  9340.     begin print(" scaled "); print_int(-s);
  9341.     end
  9342. @<Report that the font won't be loaded@>=
  9343. start_font_error_message;
  9344. @.Font x=xx not loadable...@>
  9345. if file_opened then print(" not loadable: Bad metric (TFM) file")
  9346. else print(" not loadable: Metric (TFM) file not found");
  9347. help5("I wasn't able to read the size data for this font,")@/
  9348. ("so I will ignore the font specification.")@/
  9349. ("[Wizards can fix TFM files using TFtoPL/PLtoTF.]")@/
  9350. ("You might try inserting a different font spec;")@/
  9351. ("e.g., type `I\font<same font id>=<substitute font name>'.");
  9352. error
  9353. @ @<Read and check...@>=
  9354. @<Open |tfm_file| for input@>;
  9355. @<Read the {\.{TFM}} size fields@>;
  9356. @<Use size fields to allocate font information@>;
  9357. @<Read the {\.{TFM}} header@>;
  9358. @<Read character data@>;
  9359. @<Read box dimensions@>;
  9360. @<Read ligature/kern program@>;
  9361. @<Read extensible character recipes@>;
  9362. @<Read font parameters@>;
  9363. @<Make final adjustments and |goto done|@>
  9364. @ @<Open |tfm_file| for input@>=
  9365. file_opened:=false;
  9366. if aire="" then pack_file_name(nom,TEX_font_area,".tfm")
  9367. else pack_file_name(nom,aire,".tfm");
  9368. if not b_open_in(tfm_file) then abort;
  9369. file_opened:=true
  9370. @ Note: A malformed \.{TFM} file might be shorter than it claims to be;
  9371. thus |eof(tfm_file)| might be true when |read_font_info| refers to
  9372. |tfm_file^| or when it says |get(tfm_file)|. If such circumstances
  9373. cause system error messages, you will have to defeat them somehow,
  9374. for example by defining |fget| to be `\ignorespaces|begin get(tfm_file);|
  9375. |if eof(tfm_file) then abort; end|\unskip'.
  9376. @^system dependencies@>
  9377. @d fget==get(tfm_file)
  9378. @d fbyte==tfm_file^
  9379. @d read_sixteen(#)==begin #:=fbyte;
  9380.   if #>127 then abort;
  9381.   fget; #:=#*@'400+fbyte;
  9382.   end
  9383. @d store_four_quarters(#)==begin fget; a:=fbyte; qw.b0:=qi(a);
  9384.   fget; b:=fbyte; qw.b1:=qi(b);
  9385.   fget; c:=fbyte; qw.b2:=qi(c);
  9386.   fget; d:=fbyte; qw.b3:=qi(d);
  9387.   #:=qw;
  9388.   end
  9389. @ @<Read the {\.{TFM}} size fields@>=
  9390. begin read_sixteen(lf);
  9391. fget; read_sixteen(lh);
  9392. fget; read_sixteen(bc);
  9393. fget; read_sixteen(ec);
  9394. if (bc>ec+1)or(ec>255) then abort;
  9395. if bc>255 then {|bc=256| and |ec=255|}
  9396.   begin bc:=1; ec:=0;
  9397.   end;
  9398. fget; read_sixteen(nw);
  9399. fget; read_sixteen(nh);
  9400. fget; read_sixteen(nd);
  9401. fget; read_sixteen(ni);
  9402. fget; read_sixteen(nl);
  9403. fget; read_sixteen(nk);
  9404. fget; read_sixteen(ne);
  9405. fget; read_sixteen(np);
  9406. if lf<>6+lh+(ec-bc+1)+nw+nh+nd+ni+nl+nk+ne+np then abort;
  9407. @ The preliminary settings of the index-offset variables |char_base|,
  9408. |width_base|, |lig_kern_base|, |kern_base|, and |exten_base| will be
  9409. corrected later by subtracting |min_quarterword| from them; and we will
  9410. subtract 1 from |param_base| too. It's best to forget about such anomalies
  9411. until later.
  9412. @<Use size fields to allocate font information@>=
  9413. lf:=lf-6-lh; {|lf| words should be loaded into |font_info|}
  9414. if np<7 then lf:=lf+7-np; {at least seven parameters will appear}
  9415. if (font_ptr=font_max)or(fmem_ptr+lf>font_mem_size) then
  9416.   @<Apologize for not loading the font, |goto done|@>;
  9417. f:=font_ptr+1;
  9418. char_base[f]:=fmem_ptr-bc;
  9419. width_base[f]:=char_base[f]+ec+1;
  9420. height_base[f]:=width_base[f]+nw;
  9421. depth_base[f]:=height_base[f]+nh;
  9422. italic_base[f]:=depth_base[f]+nd;
  9423. lig_kern_base[f]:=italic_base[f]+ni;
  9424. kern_base[f]:=lig_kern_base[f]+nl-kern_base_offset;
  9425. exten_base[f]:=kern_base[f]+kern_base_offset+nk;
  9426. param_base[f]:=exten_base[f]+ne
  9427. @ @<Apologize for not loading...@>=
  9428. begin start_font_error_message;
  9429. print(" not loaded: Not enough room left");
  9430. @.Font x=xx not loaded...@>
  9431. help4("I'm afraid I won't be able to make use of this font,")@/
  9432. ("because my memory for character-size data is too small.")@/
  9433. ("If you're really stuck, ask a wizard to enlarge me.")@/
  9434. ("Or maybe try `I\font<same font id>=<name of loaded font>'.");
  9435. error; goto done;
  9436. @ Only the first two words of the header are needed by \TeX82.
  9437. @<Read the {\.{TFM}} header@>=
  9438. begin if lh<2 then abort;
  9439. store_four_quarters(font_check[f]);
  9440. fget; read_sixteen(z); {this rejects a negative design size}
  9441. fget; z:=z*@'400+fbyte; fget; z:=(z*@'20)+(fbyte div@'20);
  9442. if z<unity then abort;
  9443. while lh>2 do
  9444.   begin fget;fget;fget;fget;decr(lh); {ignore the rest of the header}
  9445.   end;
  9446. font_dsize[f]:=z;
  9447. if s<>-1000 then
  9448.   if s>=0 then z:=s
  9449.   else z:=xn_over_d(z,-s,1000);
  9450. font_size[f]:=z;
  9451. @ @<Read character data@>=
  9452. for k:=fmem_ptr to width_base[f]-1 do
  9453.   begin store_four_quarters(font_info[k].qqqq);
  9454.   if (a>=nw)or(b div @'20>=nh)or(b mod @'20>=nd)or
  9455.     (c div 4>=ni) then abort;
  9456.   case c mod 4 of
  9457.   lig_tag: if d>=nl then abort;
  9458.   ext_tag: if d>=ne then abort;
  9459.   list_tag: @<Check for charlist cycle@>;
  9460.   othercases do_nothing {|no_tag|}
  9461.   endcases;
  9462.   end
  9463. @ We want to make sure that there is no cycle of characters linked together
  9464. by |list_tag| entries, since such a cycle would get \TeX\ into an endless
  9465. loop. If such a cycle exists, the routine here detects it when processing
  9466. the largest character code in the cycle.
  9467. @d check_byte_range(#)==begin if (#<bc)or(#>ec) then abort@+end
  9468. @d current_character_being_worked_on==k+bc-fmem_ptr
  9469. @<Check for charlist cycle@>=
  9470. begin check_byte_range(d);
  9471. while d<current_character_being_worked_on do
  9472.   begin qw:=char_info(f)(d);
  9473.   {N.B.: not |qi(d)|, since |char_base[f]| hasn't been adjusted yet}
  9474.   if char_tag(qw)<>list_tag then goto not_found;
  9475.   d:=qo(rem_byte(qw)); {next character on the list}
  9476.   end;
  9477. if d=current_character_being_worked_on then abort; {yes, there's a cycle}
  9478. not_found:end
  9479. @ A |fix_word| whose four bytes are $(a,b,c,d)$ from left to right represents
  9480. the number
  9481. $$x=\left\{\vcenter{\halign{$#$,\hfil\qquad&if $#$\hfil\cr
  9482. b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=0;\cr
  9483. -16+b\cdot2^{-4}+c\cdot2^{-12}+d\cdot2^{-20}&a=255.\cr}}\right.$$
  9484. (No other choices of |a| are allowed, since the magnitude of a number in
  9485. design-size units must be less than 16.)  We want to multiply this
  9486. quantity by the integer~|z|, which is known to be less than $2^{27}$.
  9487. If $|z|<2^{23}$, the individual multiplications $b\cdot z$,
  9488. $c\cdot z$, $d\cdot z$ cannot overflow; otherwise we will divide |z| by 2,
  9489. 4, 8, or 16, to obtain a multiplier less than $2^{23}$, and we can
  9490. compensate for this later. If |z| has thereby been replaced by
  9491. $|z|^\prime=|z|/2^e$, let $\beta=2^{4-e}$; we shall compute
  9492. $$\lfloor(b+c\cdot2^{-8}+d\cdot2^{-16})\,z^\prime/\beta\rfloor$$
  9493. if $a=0$, or the same quantity minus $\alpha=2^{4+e}z^\prime$ if $a=255$.
  9494. This calculation must be done exactly, in order to guarantee portability
  9495. of \TeX\ between computers.
  9496. @d store_scaled(#)==begin fget; a:=fbyte; fget; b:=fbyte;
  9497.   fget; c:=fbyte; fget; d:=fbyte;@/
  9498.   sw:=(((((d*z)div@'400)+(c*z))div@'400)+(b*z))div beta;
  9499.   if a=0 then #:=sw@+else if a=255 then #:=sw-alpha@+else abort;
  9500.   end
  9501. @<Read box dimensions@>=
  9502. begin @<Replace |z| by $|z|^\prime$ and compute $\alpha,\beta$@>;
  9503. for k:=width_base[f] to lig_kern_base[f]-1 do
  9504.   store_scaled(font_info[k].sc);
  9505. if font_info[width_base[f]].sc<>0 then abort; {\\{width}[0] must be zero}
  9506. if font_info[height_base[f]].sc<>0 then abort; {\\{height}[0] must be zero}
  9507. if font_info[depth_base[f]].sc<>0 then abort; {\\{depth}[0] must be zero}
  9508. if font_info[italic_base[f]].sc<>0 then abort; {\\{italic}[0] must be zero}
  9509. @ @<Replace |z|...@>=
  9510. begin alpha:=16;
  9511. while z>=@'40000000 do
  9512.   begin z:=z div 2; alpha:=alpha+alpha;
  9513.   end;
  9514. beta:=256 div alpha; alpha:=alpha*z;
  9515. @ @d check_existence(#)==@t@>@;@/
  9516.   begin check_byte_range(#);
  9517.   qw:=char_info(f)(#); {N.B.: not |qi(#)|}
  9518.   if not char_exists(qw) then abort;
  9519.   end
  9520. @<Read ligature/kern program@>=
  9521. bch_label:=@'77777; bchar:=256;
  9522. if nl>0 then
  9523.   begin for k:=lig_kern_base[f] to kern_base[f]+kern_base_offset-1 do
  9524.     begin store_four_quarters(font_info[k].qqqq);
  9525.     if a>128 then
  9526.       begin if 256*c+d>=nl then abort;
  9527.       if a=255 then if k=lig_kern_base[f] then bchar:=b;
  9528.       end
  9529.     else begin if b<>bchar then check_existence(b);
  9530.       if c<128 then check_existence(d) {check ligature}
  9531.       else if 256*(c-128)+d>=nk then abort; {check kern}
  9532.       if a<128 then if k-lig_kern_base[f]+a+1>=nl then abort;
  9533.       end;
  9534.     end;
  9535.   if a=255 then bch_label:=256*c+d;
  9536.   end;
  9537. for k:=kern_base[f]+kern_base_offset to exten_base[f]-1 do
  9538.   store_scaled(font_info[k].sc);
  9539. @ @<Read extensible character recipes@>=
  9540. for k:=exten_base[f] to param_base[f]-1 do
  9541.   begin store_four_quarters(font_info[k].qqqq);
  9542.   if a<>0 then check_existence(a);
  9543.   if b<>0 then check_existence(b);
  9544.   if c<>0 then check_existence(c);
  9545.   check_existence(d);
  9546.   end
  9547. @ We check to see that the \.{TFM} file doesn't end prematurely; but
  9548. no error message is given for files having more than |lf| words.
  9549. @<Read font parameters@>=
  9550. begin for k:=1 to np do
  9551.   if k=1 then {the |slant| parameter is a pure number}
  9552.     begin fget; sw:=fbyte; if sw>127 then sw:=sw-256;
  9553.     fget; sw:=sw*@'400+fbyte; fget; sw:=sw*@'400+fbyte;
  9554.     fget; font_info[param_base[f]].sc:=
  9555.       (sw*@'20)+(fbyte div@'20);
  9556.     end
  9557.   else store_scaled(font_info[param_base[f]+k-1].sc);
  9558. if eof(tfm_file) then abort;
  9559. for k:=np+1 to 7 do font_info[param_base[f]+k-1].sc:=0;
  9560. @ Now to wrap it up, we have checked all the necessary things about the \.{TFM}
  9561. file, and all we need to do is put the finishing touches on the data for
  9562. the new font.
  9563. @d adjust(#)==#[f]:=qo(#[f])
  9564.   {correct for the excess |min_quarterword| that was added}
  9565. @<Make final adjustments...@>=
  9566. if np>=7 then font_params[f]:=np@+else font_params[f]:=7;
  9567. hyphen_char[f]:=default_hyphen_char; skew_char[f]:=default_skew_char;
  9568. if bch_label<nl then bchar_label[f]:=bch_label+lig_kern_base[f]
  9569. else bchar_label[f]:=non_address;
  9570. font_bchar[f]:=qi(bchar);
  9571. font_false_bchar[f]:=qi(bchar);
  9572. if bchar<=ec then if bchar>=bc then
  9573.   begin qw:=char_info(f)(bchar); {N.B.: not |qi(bchar)|}
  9574.   if char_exists(qw) then font_false_bchar[f]:=non_char;
  9575.   end;
  9576. font_name[f]:=nom;
  9577. font_area[f]:=aire;
  9578. font_bc[f]:=bc; font_ec[f]:=ec; font_glue[f]:=null;
  9579. adjust(char_base); adjust(width_base); adjust(lig_kern_base);
  9580. adjust(kern_base); adjust(exten_base);
  9581. decr(param_base[f]);
  9582. fmem_ptr:=fmem_ptr+lf; font_ptr:=f; g:=f; goto done
  9583. @ Before we forget about the format of these tables, let's deal with two
  9584. of \TeX's basic scanning routines related to font information.
  9585. @<Declare procedures that scan font-related stuff@>=
  9586. procedure scan_font_ident;
  9587. var f:internal_font_number;
  9588. @!m:halfword;
  9589. begin @<Get the next non-blank non-call...@>;
  9590. if cur_cmd=def_font then f:=cur_font
  9591. else if cur_cmd=set_font then f:=cur_chr
  9592. else if cur_cmd=def_family then
  9593.   begin m:=cur_chr; scan_four_bit_int; f:=equiv(m+cur_val);
  9594.   end
  9595. else  begin print_err("Missing font identifier");
  9596. @.Missing font identifier@>
  9597.   help2("I was looking for a control sequence whose")@/
  9598.   ("current meaning has been defined by \font.");
  9599.   back_error; f:=null_font;
  9600.   end;
  9601. cur_val:=f;
  9602. @ The following routine is used to implement `\.{\\fontdimen} |n| |f|'.
  9603. The boolean parameter |writing| is set |true| if the calling program
  9604. intends to change the parameter value.
  9605. @<Declare procedures that scan font-related stuff@>=
  9606. procedure find_font_dimen(@!writing:boolean);
  9607.   {sets |cur_val| to |font_info| location}
  9608. var f:internal_font_number;
  9609. @!n:integer; {the parameter number}
  9610. begin scan_int; n:=cur_val; scan_font_ident; f:=cur_val;
  9611. if n<=0 then cur_val:=fmem_ptr
  9612. else  begin if writing and(n<=space_shrink_code)and@|
  9613.     (n>=space_code)and(font_glue[f]<>null) then
  9614.     begin delete_glue_ref(font_glue[f]);
  9615.     font_glue[f]:=null;
  9616.     end;
  9617.   if n>font_params[f] then
  9618.     if f<font_ptr then cur_val:=fmem_ptr
  9619.     else @<Increase the number of parameters in the last font@>
  9620.   else cur_val:=n+param_base[f];
  9621.   end;
  9622. @<Issue an error message if |cur_val=fmem_ptr|@>;
  9623. @ @<Issue an error message if |cur_val=fmem_ptr|@>=
  9624. if cur_val=fmem_ptr then
  9625.   begin print_err("Font "); print_esc(font_id_text(f));
  9626.   print(" has only "); print_int(font_params[f]);
  9627.   print(" fontdimen parameters");
  9628. @.Font x has only...@>
  9629.   help2("To increase the number of font parameters, you must")@/
  9630.     ("use \fontdimen immediately after the \font is loaded.");
  9631.   error;
  9632.   end
  9633. @ @<Increase the number of parameters...@>=
  9634. begin repeat if fmem_ptr=font_mem_size then
  9635.   overflow("font memory",font_mem_size);
  9636. @:TeX capacity exceeded font memory}{\quad font memory@>
  9637. font_info[fmem_ptr].sc:=0; incr(fmem_ptr); incr(font_params[f]);
  9638. until n=font_params[f];
  9639. cur_val:=fmem_ptr-1; {this equals |param_base[f]+font_params[f]|}
  9640. @ When \TeX\ wants to typeset a character that doesn't exist, the
  9641. character node is not created; thus the output routine can assume
  9642. that characters exist when it sees them. The following procedure
  9643. prints a warning message unless the user has suppressed it.
  9644. @p procedure char_warning(@!f:internal_font_number;@!c:eight_bits);
  9645. begin if tracing_lost_chars>0 then
  9646.   begin begin_diagnostic;
  9647.   print_nl("Missing character: There is no ");
  9648. @.Missing character@>
  9649.   print_ASCII(c); print(" in font ");
  9650.   slow_print(font_name[f]); print_char("!"); end_diagnostic(false);
  9651.   end;
  9652. @ Here is a function that returns a pointer to a character node for a
  9653. given character in a given font. If that character doesn't exist,
  9654. |null| is returned instead.
  9655. @p function new_character(@!f:internal_font_number;@!c:eight_bits):pointer;
  9656. label exit;
  9657. var p:pointer; {newly allocated node}
  9658. begin if font_bc[f]<=c then if font_ec[f]>=c then
  9659.   if char_exists(char_info(f)(qi(c))) then
  9660.     begin p:=get_avail; font(p):=f; character(p):=qi(c);
  9661.     new_character:=p; return;
  9662.     end;
  9663. char_warning(f,c);
  9664. new_character:=null;
  9665. exit:end;
  9666. @* \[31] Device-independent file format.
  9667. The most important output produced by a run of \TeX\ is the ``device
  9668. independent'' (\.{DVI}) file that specifies where characters and rules
  9669. are to appear on printed pages. The form of these files was designed by
  9670. David R. Fuchs in 1979. Almost any reasonable typesetting device can be
  9671. @^Fuchs, David Raymond@>
  9672. @:DVI_files}{\.{DVI} files@>
  9673. driven by a program that takes \.{DVI} files as input, and dozens of such
  9674. \.{DVI}-to-whatever programs have been written. Thus, it is possible to
  9675. print the output of \TeX\ on many different kinds of equipment, using \TeX\
  9676. as a device-independent ``front end.''
  9677. A \.{DVI} file is a stream of 8-bit bytes, which may be regarded as a
  9678. series of commands in a machine-like language. The first byte of each command
  9679. is the operation code, and this code is followed by zero or more bytes
  9680. that provide parameters to the command. The parameters themselves may consist
  9681. of several consecutive bytes; for example, the `|set_rule|' command has two
  9682. parameters, each of which is four bytes long. Parameters are usually
  9683. regarded as nonnegative integers; but four-byte-long parameters,
  9684. and shorter parameters that denote distances, can be
  9685. either positive or negative. Such parameters are given in two's complement
  9686. notation. For example, a two-byte-long distance parameter has a value between
  9687. $-2^{15}$ and $2^{15}-1$. As in \.{TFM} files, numbers that occupy
  9688. more than one byte position appear in BigEndian order.
  9689. A \.{DVI} file consists of a ``preamble,'' followed by a sequence of one
  9690. or more ``pages,'' followed by a ``postamble.'' The preamble is simply a
  9691. |pre| command, with its parameters that define the dimensions used in the
  9692. file; this must come first.  Each ``page'' consists of a |bop| command,
  9693. followed by any number of other commands that tell where characters are to
  9694. be placed on a physical page, followed by an |eop| command. The pages
  9695. appear in the order that \TeX\ generated them. If we ignore |nop| commands
  9696. and \\{fnt\_def} commands (which are allowed between any two commands in
  9697. the file), each |eop| command is immediately followed by a |bop| command,
  9698. or by a |post| command; in the latter case, there are no more pages in the
  9699. file, and the remaining bytes form the postamble.  Further details about
  9700. the postamble will be explained later.
  9701. Some parameters in \.{DVI} commands are ``pointers.'' These are four-byte
  9702. quantities that give the location number of some other byte in the file;
  9703. the first byte is number~0, then comes number~1, and so on. For example,
  9704. one of the parameters of a |bop| command points to the previous |bop|;
  9705. this makes it feasible to read the pages in backwards order, in case the
  9706. results are being directed to a device that stacks its output face up.
  9707. Suppose the preamble of a \.{DVI} file occupies bytes 0 to 99. Now if the
  9708. first page occupies bytes 100 to 999, say, and if the second
  9709. page occupies bytes 1000 to 1999, then the |bop| that starts in byte 1000
  9710. points to 100 and the |bop| that starts in byte 2000 points to 1000. (The
  9711. very first |bop|, i.e., the one starting in byte 100, has a pointer of~$-1$.)
  9712. @ The \.{DVI} format is intended to be both compact and easily interpreted
  9713. by a machine. Compactness is achieved by making most of the information
  9714. implicit instead of explicit. When a \.{DVI}-reading program reads the
  9715. commands for a page, it keeps track of several quantities: (a)~The current
  9716. font |f| is an integer; this value is changed only
  9717. by \\{fnt} and \\{fnt\_num} commands. (b)~The current position on the page
  9718. is given by two numbers called the horizontal and vertical coordinates,
  9719. |h| and |v|. Both coordinates are zero at the upper left corner of the page;
  9720. moving to the right corresponds to increasing the horizontal coordinate, and
  9721. moving down corresponds to increasing the vertical coordinate. Thus, the
  9722. coordinates are essentially Cartesian, except that vertical directions are
  9723. flipped; the Cartesian version of |(h,v)| would be |(h,-v)|.  (c)~The
  9724. current spacing amounts are given by four numbers |w|, |x|, |y|, and |z|,
  9725. where |w| and~|x| are used for horizontal spacing and where |y| and~|z|
  9726. are used for vertical spacing. (d)~There is a stack containing
  9727. |(h,v,w,x,y,z)| values; the \.{DVI} commands |push| and |pop| are used to
  9728. change the current level of operation. Note that the current font~|f| is
  9729. not pushed and popped; the stack contains only information about
  9730. positioning.
  9731. The values of |h|, |v|, |w|, |x|, |y|, and |z| are signed integers having up
  9732. to 32 bits, including the sign. Since they represent physical distances,
  9733. there is a small unit of measurement such that increasing |h| by~1 means
  9734. moving a certain tiny distance to the right. The actual unit of
  9735. measurement is variable, as explained below; \TeX\ sets things up so that
  9736. its \.{DVI} output is in sp units, i.e., scaled points, in agreement with
  9737. all the |scaled| dimensions in \TeX's data structures.
  9738. @ Here is a list of all the commands that may appear in a \.{DVI} file. Each
  9739. command is specified by its symbolic name (e.g., |bop|), its opcode byte
  9740. (e.g., 139), and its parameters (if any). The parameters are followed
  9741. by a bracketed number telling how many bytes they occupy; for example,
  9742. `|p[4]|' means that parameter |p| is four bytes long.
  9743. \yskip\hang|set_char_0| 0. Typeset character number~0 from font~|f|
  9744. such that the reference point of the character is at |(h,v)|. Then
  9745. increase |h| by the width of that character. Note that a character may
  9746. have zero or negative width, so one cannot be sure that |h| will advance
  9747. after this command; but |h| usually does increase.
  9748. \yskip\hang\\{set\_char\_1} through \\{set\_char\_127} (opcodes 1 to 127).
  9749. Do the operations of |set_char_0|; but use the character whose number
  9750. matches the opcode, instead of character~0.
  9751. \yskip\hang|set1| 128 |c[1]|. Same as |set_char_0|, except that character
  9752. number~|c| is typeset. \TeX82 uses this command for characters in the
  9753. range |128<=c<256|.
  9754. \yskip\hang|@!set2| 129 |c[2]|. Same as |set1|, except that |c|~is two
  9755. bytes long, so it is in the range |0<=c<65536|. \TeX82 never uses this
  9756. command, but it should come in handy for extensions of \TeX\ that deal
  9757. with oriental languages.
  9758. @^oriental characters@>@^Chinese characters@>@^Japanese characters@>
  9759. \yskip\hang|@!set3| 130 |c[3]|. Same as |set1|, except that |c|~is three
  9760. bytes long, so it can be as large as $2^{24}-1$. Not even the Chinese
  9761. language has this many characters, but this command might prove useful
  9762. in some yet unforeseen extension.
  9763. \yskip\hang|@!set4| 131 |c[4]|. Same as |set1|, except that |c|~is four
  9764. bytes long. Imagine that.
  9765. \yskip\hang|set_rule| 132 |a[4]| |b[4]|. Typeset a solid black rectangle
  9766. of height~|a| and width~|b|, with its bottom left corner at |(h,v)|. Then
  9767. set |h:=h+b|. If either |a<=0| or |b<=0|, nothing should be typeset. Note
  9768. that if |b<0|, the value of |h| will decrease even though nothing else happens.
  9769. See below for details about how to typeset rules so that consistency with
  9770. \MF\ is guaranteed.
  9771. \yskip\hang|@!put1| 133 |c[1]|. Typeset character number~|c| from font~|f|
  9772. such that the reference point of the character is at |(h,v)|. (The `put'
  9773. commands are exactly like the `set' commands, except that they simply put out a
  9774. character or a rule without moving the reference point afterwards.)
  9775. \yskip\hang|@!put2| 134 |c[2]|. Same as |set2|, except that |h| is not changed.
  9776. \yskip\hang|@!put3| 135 |c[3]|. Same as |set3|, except that |h| is not changed.
  9777. \yskip\hang|@!put4| 136 |c[4]|. Same as |set4|, except that |h| is not changed.
  9778. \yskip\hang|put_rule| 137 |a[4]| |b[4]|. Same as |set_rule|, except that
  9779. |h| is not changed.
  9780. \yskip\hang|nop| 138. No operation, do nothing. Any number of |nop|'s
  9781. may occur between \.{DVI} commands, but a |nop| cannot be inserted between
  9782. a command and its parameters or between two parameters.
  9783. \yskip\hang|bop| 139 $c_0[4]$ $c_1[4]$ $\ldots$ $c_9[4]$ $p[4]$. Beginning
  9784. of a page: Set |(h,v,w,x,y,z):=(0,0,0,0,0,0)| and set the stack empty. Set
  9785. the current font |f| to an undefined value.  The ten $c_i$ parameters hold
  9786. the values of \.{\\count0} $\ldots$ \.{\\count9} in \TeX\ at the time
  9787. \.{\\shipout} was invoked for this page; they can be used to identify
  9788. pages, if a user wants to print only part of a \.{DVI} file. The parameter
  9789. |p| points to the previous |bop| in the file; the first
  9790. |bop| has $p=-1$.
  9791. \yskip\hang|eop| 140.  End of page: Print what you have read since the
  9792. previous |bop|. At this point the stack should be empty. (The \.{DVI}-reading
  9793. programs that drive most output devices will have kept a buffer of the
  9794. material that appears on the page that has just ended. This material is
  9795. largely, but not entirely, in order by |v| coordinate and (for fixed |v|) by
  9796. |h|~coordinate; so it usually needs to be sorted into some order that is
  9797. appropriate for the device in question.)
  9798. \yskip\hang|push| 141. Push the current values of |(h,v,w,x,y,z)| onto the
  9799. top of the stack; do not change any of these values. Note that |f| is
  9800. not pushed.
  9801. \yskip\hang|pop| 142. Pop the top six values off of the stack and assign
  9802. them respectively to |(h,v,w,x,y,z)|. The number of pops should never
  9803. exceed the number of pushes, since it would be highly embarrassing if the
  9804. stack were empty at the time of a |pop| command.
  9805. \yskip\hang|right1| 143 |b[1]|. Set |h:=h+b|, i.e., move right |b| units.
  9806. The parameter is a signed number in two's complement notation, |-128<=b<128|;
  9807. if |b<0|, the reference point moves left.
  9808. \yskip\hang|right2| 144 |b[2]|. Same as |right1|, except that |b| is a
  9809. two-byte quantity in the range |-32768<=b<32768|.
  9810. \yskip\hang|right3| 145 |b[3]|. Same as |right1|, except that |b| is a
  9811. three-byte quantity in the range |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
  9812. \yskip\hang|right4| 146 |b[4]|. Same as |right1|, except that |b| is a
  9813. four-byte quantity in the range |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
  9814. \yskip\hang|w0| 147. Set |h:=h+w|; i.e., move right |w| units. With luck,
  9815. this parameterless command will usually suffice, because the same kind of motion
  9816. will occur several times in succession; the following commands explain how
  9817. |w| gets particular values.
  9818. \yskip\hang|w1| 148 |b[1]|. Set |w:=b| and |h:=h+b|. The value of |b| is a
  9819. signed quantity in two's complement notation, |-128<=b<128|. This command
  9820. changes the current |w|~spacing and moves right by |b|.
  9821. \yskip\hang|@!w2| 149 |b[2]|. Same as |w1|, but |b| is two bytes long,
  9822. |-32768<=b<32768|.
  9823. \yskip\hang|@!w3| 150 |b[3]|. Same as |w1|, but |b| is three bytes long,
  9824. |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
  9825. \yskip\hang|@!w4| 151 |b[4]|. Same as |w1|, but |b| is four bytes long,
  9826. |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
  9827. \yskip\hang|x0| 152. Set |h:=h+x|; i.e., move right |x| units. The `|x|'
  9828. commands are like the `|w|' commands except that they involve |x| instead
  9829. of |w|.
  9830. \yskip\hang|x1| 153 |b[1]|. Set |x:=b| and |h:=h+b|. The value of |b| is a
  9831. signed quantity in two's complement notation, |-128<=b<128|. This command
  9832. changes the current |x|~spacing and moves right by |b|.
  9833. \yskip\hang|@!x2| 154 |b[2]|. Same as |x1|, but |b| is two bytes long,
  9834. |-32768<=b<32768|.
  9835. \yskip\hang|@!x3| 155 |b[3]|. Same as |x1|, but |b| is three bytes long,
  9836. |@t$-2^{23}$@><=b<@t$2^{23}$@>|.
  9837. \yskip\hang|@!x4| 156 |b[4]|. Same as |x1|, but |b| is four bytes long,
  9838. |@t$-2^{31}$@><=b<@t$2^{31}$@>|.
  9839. \yskip\hang|down1| 157 |a[1]|. Set |v:=v+a|, i.e., move down |a| units.
  9840. The parameter is a signed number in two's complement notation, |-128<=a<128|;
  9841. if |a<0|, the reference point moves up.
  9842. \yskip\hang|@!down2| 158 |a[2]|. Same as |down1|, except that |a| is a
  9843. two-byte quantity in the range |-32768<=a<32768|.
  9844. \yskip\hang|@!down3| 159 |a[3]|. Same as |down1|, except that |a| is a
  9845. three-byte quantity in the range |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
  9846. \yskip\hang|@!down4| 160 |a[4]|. Same as |down1|, except that |a| is a
  9847. four-byte quantity in the range |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
  9848. \yskip\hang|y0| 161. Set |v:=v+y|; i.e., move down |y| units. With luck,
  9849. this parameterless command will usually suffice, because the same kind of motion
  9850. will occur several times in succession; the following commands explain how
  9851. |y| gets particular values.
  9852. \yskip\hang|y1| 162 |a[1]|. Set |y:=a| and |v:=v+a|. The value of |a| is a
  9853. signed quantity in two's complement notation, |-128<=a<128|. This command
  9854. changes the current |y|~spacing and moves down by |a|.
  9855. \yskip\hang|@!y2| 163 |a[2]|. Same as |y1|, but |a| is two bytes long,
  9856. |-32768<=a<32768|.
  9857. \yskip\hang|@!y3| 164 |a[3]|. Same as |y1|, but |a| is three bytes long,
  9858. |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
  9859. \yskip\hang|@!y4| 165 |a[4]|. Same as |y1|, but |a| is four bytes long,
  9860. |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
  9861. \yskip\hang|z0| 166. Set |v:=v+z|; i.e., move down |z| units. The `|z|' commands
  9862. are like the `|y|' commands except that they involve |z| instead of |y|.
  9863. \yskip\hang|z1| 167 |a[1]|. Set |z:=a| and |v:=v+a|. The value of |a| is a
  9864. signed quantity in two's complement notation, |-128<=a<128|. This command
  9865. changes the current |z|~spacing and moves down by |a|.
  9866. \yskip\hang|@!z2| 168 |a[2]|. Same as |z1|, but |a| is two bytes long,
  9867. |-32768<=a<32768|.
  9868. \yskip\hang|@!z3| 169 |a[3]|. Same as |z1|, but |a| is three bytes long,
  9869. |@t$-2^{23}$@><=a<@t$2^{23}$@>|.
  9870. \yskip\hang|@!z4| 170 |a[4]|. Same as |z1|, but |a| is four bytes long,
  9871. |@t$-2^{31}$@><=a<@t$2^{31}$@>|.
  9872. \yskip\hang|fnt_num_0| 171. Set |f:=0|. Font 0 must previously have been
  9873. defined by a \\{fnt\_def} instruction, as explained below.
  9874. \yskip\hang\\{fnt\_num\_1} through \\{fnt\_num\_63} (opcodes 172 to 234). Set
  9875. |f:=1|, \dots, \hbox{|f:=63|}, respectively.
  9876. \yskip\hang|fnt1| 235 |k[1]|. Set |f:=k|. \TeX82 uses this command for font
  9877. numbers in the range |64<=k<256|.
  9878. \yskip\hang|@!fnt2| 236 |k[2]|. Same as |fnt1|, except that |k|~is two
  9879. bytes long, so it is in the range |0<=k<65536|. \TeX82 never generates this
  9880. command, but large font numbers may prove useful for specifications of
  9881. color or texture, or they may be used for special fonts that have fixed
  9882. numbers in some external coding scheme.
  9883. \yskip\hang|@!fnt3| 237 |k[3]|. Same as |fnt1|, except that |k|~is three
  9884. bytes long, so it can be as large as $2^{24}-1$.
  9885. \yskip\hang|@!fnt4| 238 |k[4]|. Same as |fnt1|, except that |k|~is four
  9886. bytes long; this is for the really big font numbers (and for the negative ones).
  9887. \yskip\hang|xxx1| 239 |k[1]| |x[k]|. This command is undefined in
  9888. general; it functions as a $(k+2)$-byte |nop| unless special \.{DVI}-reading
  9889. programs are being used. \TeX82 generates |xxx1| when a short enough
  9890. \.{\\special} appears, setting |k| to the number of bytes being sent. It
  9891. is recommended that |x| be a string having the form of a keyword followed
  9892. by possible parameters relevant to that keyword.
  9893. \yskip\hang|@!xxx2| 240 |k[2]| |x[k]|. Like |xxx1|, but |0<=k<65536|.
  9894. \yskip\hang|@!xxx3| 241 |k[3]| |x[k]|. Like |xxx1|, but |0<=k<@t$2^{24}$@>|.
  9895. \yskip\hang|xxx4| 242 |k[4]| |x[k]|. Like |xxx1|, but |k| can be ridiculously
  9896. large. \TeX82 uses |xxx4| when sending a string of length 256 or more.
  9897. \yskip\hang|fnt_def1| 243 |k[1]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9898. Define font |k|, where |0<=k<256|; font definitions will be explained shortly.
  9899. \yskip\hang|@!fnt_def2| 244 |k[2]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9900. Define font |k|, where |0<=k<65536|.
  9901. \yskip\hang|@!fnt_def3| 245 |k[3]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9902. Define font |k|, where |0<=k<@t$2^{24}$@>|.
  9903. \yskip\hang|@!fnt_def4| 246 |k[4]| |c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.
  9904. Define font |k|, where |@t$-2^{31}$@><=k<@t$2^{31}$@>|.
  9905. \yskip\hang|pre| 247 |i[1]| |num[4]| |den[4]| |mag[4]| |k[1]| |x[k]|.
  9906. Beginning of the preamble; this must come at the very beginning of the
  9907. file. Parameters |i|, |num|, |den|, |mag|, |k|, and |x| are explained below.
  9908. \yskip\hang|post| 248. Beginning of the postamble, see below.
  9909. \yskip\hang|post_post| 249. Ending of the postamble, see below.
  9910. \yskip\noindent Commands 250--255 are undefined at the present time.
  9911. @ @d set_char_0=0 {typeset character 0 and move right}
  9912. @d set1=128 {typeset a character and move right}
  9913. @d set_rule=132 {typeset a rule and move right}
  9914. @d put_rule=137 {typeset a rule}
  9915. @d nop=138 {no operation}
  9916. @d bop=139 {beginning of page}
  9917. @d eop=140 {ending of page}
  9918. @d push=141 {save the current positions}
  9919. @d pop=142 {restore previous positions}
  9920. @d right1=143 {move right}
  9921. @d w0=147 {move right by |w|}
  9922. @d w1=148 {move right and set |w|}
  9923. @d x0=152 {move right by |x|}
  9924. @d x1=153 {move right and set |x|}
  9925. @d down1=157 {move down}
  9926. @d y0=161 {move down by |y|}
  9927. @d y1=162 {move down and set |y|}
  9928. @d z0=166 {move down by |z|}
  9929. @d z1=167 {move down and set |z|}
  9930. @d fnt_num_0=171 {set current font to 0}
  9931. @d fnt1=235 {set current font}
  9932. @d xxx1=239 {extension to \.{DVI} primitives}
  9933. @d xxx4=242 {potentially long extension to \.{DVI} primitives}
  9934. @d fnt_def1=243 {define the meaning of a font number}
  9935. @d pre=247 {preamble}
  9936. @d post=248 {postamble beginning}
  9937. @d post_post=249 {postamble ending}
  9938. @ The preamble contains basic information about the file as a whole. As
  9939. stated above, there are six parameters:
  9940. $$\hbox{|@!i[1]| |@!num[4]| |@!den[4]| |@!mag[4]| |@!k[1]| |@!x[k]|.}$$
  9941. The |i| byte identifies \.{DVI} format; currently this byte is always set
  9942. to~2. (The value |i=3| is currently used for an extended format that
  9943. allows a mixture of right-to-left and left-to-right typesetting.
  9944. Some day we will set |i=4|, when \.{DVI} format makes another
  9945. incompatible change---perhaps in the year 2048.)
  9946. The next two parameters, |num| and |den|, are positive integers that define
  9947. the units of measurement; they are the numerator and denominator of a
  9948. fraction by which all dimensions in the \.{DVI} file could be multiplied
  9949. in order to get lengths in units of $10^{-7}$ meters. Since $\rm 7227{pt} =
  9950. 254{cm}$, and since \TeX\ works with scaled points where there are $2^{16}$
  9951. sp in a point, \TeX\ sets
  9952. $|num|/|den|=(254\cdot10^5)/(7227\cdot2^{16})=25400000/473628672$.
  9953. @^sp@>
  9954. The |mag| parameter is what \TeX\ calls \.{\\mag}, i.e., 1000 times the
  9955. desired magnification. The actual fraction by which dimensions are
  9956. multiplied is therefore $|mag|\cdot|num|/1000|den|$. Note that if a \TeX\
  9957. source document does not call for any `\.{true}' dimensions, and if you
  9958. change it only by specifying a different \.{\\mag} setting, the \.{DVI}
  9959. file that \TeX\ creates will be completely unchanged except for the value
  9960. of |mag| in the preamble and postamble. (Fancy \.{DVI}-reading programs allow
  9961. users to override the |mag|~setting when a \.{DVI} file is being printed.)
  9962. Finally, |k| and |x| allow the \.{DVI} writer to include a comment, which is not
  9963. interpreted further. The length of comment |x| is |k|, where |0<=k<256|.
  9964. @d id_byte=2 {identifies the kind of \.{DVI} files described here}
  9965. @ Font definitions for a given font number |k| contain further parameters
  9966. $$\hbox{|c[4]| |s[4]| |d[4]| |a[1]| |l[1]| |n[a+l]|.}$$
  9967. The four-byte value |c| is the check sum that \TeX\ found in the \.{TFM}
  9968. file for this font; |c| should match the check sum of the font found by
  9969. programs that read this \.{DVI} file.
  9970. @^check sum@>
  9971. Parameter |s| contains a fixed-point scale factor that is applied to
  9972. the character widths in font |k|; font dimensions in \.{TFM} files and
  9973. other font files are relative to this quantity, which is called the
  9974. ``at size'' elsewhere in this documentation. The value of |s| is
  9975. always positive and less than $2^{27}$. It is given in the same units
  9976. as the other \.{DVI} dimensions, i.e., in sp when \TeX82 has made the
  9977. file.  Parameter |d| is similar to |s|; it is the ``design size,'' and
  9978. (like~|s|) it is given in \.{DVI} units. Thus, font |k| is to be used
  9979. at $|mag|\cdot s/1000d$ times its normal size.
  9980. The remaining part of a font definition gives the external name of the font,
  9981. which is an ASCII string of length |a+l|. The number |a| is the length
  9982. of the ``area'' or directory, and |l| is the length of the font name itself;
  9983. the standard local system font area is supposed to be used when |a=0|.
  9984. The |n| field contains the area in its first |a| bytes.
  9985. Font definitions must appear before the first use of a particular font number.
  9986. Once font |k| is defined, it must not be defined again; however, we
  9987. shall see below that font definitions appear in the postamble as well as
  9988. in the pages, so in this sense each font number is defined exactly twice,
  9989. if at all. Like |nop| commands, font definitions can
  9990. appear before the first |bop|, or between an |eop| and a |bop|.
  9991. @ Sometimes it is desirable to make horizontal or vertical rules line up
  9992. precisely with certain features in characters of a font. It is possible to
  9993. guarantee the correct matching between \.{DVI} output and the characters
  9994. generated by \MF\ by adhering to the following principles: (1)~The \MF\
  9995. characters should be positioned so that a bottom edge or left edge that is
  9996. supposed to line up with the bottom or left edge of a rule appears at the
  9997. reference point, i.e., in row~0 and column~0 of the \MF\ raster. This
  9998. ensures that the position of the rule will not be rounded differently when
  9999. the pixel size is not a perfect multiple of the units of measurement in
  10000. the \.{DVI} file. (2)~A typeset rule of height $a>0$ and width $b>0$
  10001. should be equivalent to a \MF-generated character having black pixels in
  10002. precisely those raster positions whose \MF\ coordinates satisfy
  10003. |0<=x<@t$\alpha$@>b| and |0<=y<@t$\alpha$@>a|, where $\alpha$ is the number
  10004. of pixels per \.{DVI} unit.
  10005. @:METAFONT}{\MF@>
  10006. @^alignment of rules with characters@>
  10007. @^rules aligning with characters@>
  10008. @ The last page in a \.{DVI} file is followed by `|post|'; this command
  10009. introduces the postamble, which summarizes important facts that \TeX\ has
  10010. accumulated about the file, making it possible to print subsets of the data
  10011. with reasonable efficiency. The postamble has the form
  10012. $$\vbox{\halign{\hbox{#\hfil}\cr
  10013.   |post| |p[4]| |num[4]| |den[4]| |mag[4]| |l[4]| |u[4]| |s[2]| |t[2]|\cr
  10014.   $\langle\,$font definitions$\,\rangle$\cr
  10015.   |post_post| |q[4]| |i[1]| 223's$[{\G}4]$\cr}}$$
  10016. Here |p| is a pointer to the final |bop| in the file. The next three
  10017. parameters, |num|, |den|, and |mag|, are duplicates of the quantities that
  10018. appeared in the preamble.
  10019. Parameters |l| and |u| give respectively the height-plus-depth of the tallest
  10020. page and the width of the widest page, in the same units as other dimensions
  10021. of the file. These numbers might be used by a \.{DVI}-reading program to
  10022. position individual ``pages'' on large sheets of film or paper; however,
  10023. the standard convention for output on normal size paper is to position each
  10024. page so that the upper left-hand corner is exactly one inch from the left
  10025. and the top. Experience has shown that it is unwise to design \.{DVI}-to-printer
  10026. software that attempts cleverly to center the output; a fixed position of
  10027. the upper left corner is easiest for users to understand and to work with.
  10028. Therefore |l| and~|u| are often ignored.
  10029. Parameter |s| is the maximum stack depth (i.e., the largest excess of
  10030. |push| commands over |pop| commands) needed to process this file. Then
  10031. comes |t|, the total number of pages (|bop| commands) present.
  10032. The postamble continues with font definitions, which are any number of
  10033. \\{fnt\_def} commands as described above, possibly interspersed with |nop|
  10034. commands. Each font number that is used in the \.{DVI} file must be defined
  10035. exactly twice: Once before it is first selected by a \\{fnt} command, and once
  10036. in the postamble.
  10037. @ The last part of the postamble, following the |post_post| byte that
  10038. signifies the end of the font definitions, contains |q|, a pointer to the
  10039. |post| command that started the postamble.  An identification byte, |i|,
  10040. comes next; this currently equals~2, as in the preamble.
  10041. The |i| byte is followed by four or more bytes that are all equal to
  10042. the decimal number 223 (i.e., @'337 in octal). \TeX\ puts out four to seven of
  10043. these trailing bytes, until the total length of the file is a multiple of
  10044. four bytes, since this works out best on machines that pack four bytes per
  10045. word; but any number of 223's is allowed, as long as there are at least four
  10046. of them. In effect, 223 is a sort of signature that is added at the very end.
  10047. @^Fuchs, David Raymond@>
  10048. This curious way to finish off a \.{DVI} file makes it feasible for
  10049. \.{DVI}-reading programs to find the postamble first, on most computers,
  10050. even though \TeX\ wants to write the postamble last. Most operating
  10051. systems permit random access to individual words or bytes of a file, so
  10052. the \.{DVI} reader can start at the end and skip backwards over the 223's
  10053. until finding the identification byte. Then it can back up four bytes, read
  10054. |q|, and move to byte |q| of the file. This byte should, of course,
  10055. contain the value 248 (|post|); now the postamble can be read, so the
  10056. \.{DVI} reader can discover all the information needed for typesetting the
  10057. pages. Note that it is also possible to skip through the \.{DVI} file at
  10058. reasonably high speed to locate a particular page, if that proves
  10059. desirable. This saves a lot of time, since \.{DVI} files used in production
  10060. jobs tend to be large.
  10061. Unfortunately, however, standard \PASCAL\ does not include the ability to
  10062. @^system dependencies@>
  10063. access a random position in a file, or even to determine the length of a file.
  10064. Almost all systems nowadays provide the necessary capabilities, so \.{DVI}
  10065. format has been designed to work most efficiently with modern operating systems.
  10066. But if \.{DVI} files have to be processed under the restrictions of standard
  10067. \PASCAL, one can simply read them from front to back, since the necessary
  10068. header information is present in the preamble and in the font definitions.
  10069. (The |l| and |u| and |s| and |t| parameters, which appear only in the
  10070. postamble, are ``frills'' that are handy but not absolutely necessary.)
  10071. @* \[32] Shipping pages out.
  10072. After considering \TeX's eyes and stomach, we come now to the bowels.
  10073. @^bowels@>
  10074. The |ship_out| procedure is given a pointer to a box; its mission is
  10075. to describe that box in \.{DVI} form, outputting a ``page'' to |dvi_file|.
  10076. The \.{DVI} coordinates $(h,v)=(0,0)$ should correspond to the upper left
  10077. corner of the box being shipped.
  10078. Since boxes can be inside of boxes inside of boxes, the main work of
  10079. |ship_out| is done by two mutually recursive routines, |hlist_out|
  10080. and |vlist_out|, which traverse the hlists and vlists inside of horizontal
  10081. and vertical boxes.
  10082. As individual pages are being processed, we need to accumulate
  10083. information about the entire set of pages, since such statistics must be
  10084. reported in the postamble. The global variables |total_pages|, |max_v|,
  10085. |max_h|, |max_push|, and |last_bop| are used to record this information.
  10086. The variable |doing_leaders| is |true| while leaders are being output.
  10087. The variable |dead_cycles| contains the number of times an output routine
  10088. has been initiated since the last |ship_out|.
  10089. A few additional global variables are also defined here for use in
  10090. |vlist_out| and |hlist_out|. They could have been local variables, but
  10091. that would waste stack space when boxes are deeply nested, since the
  10092. values of these variables are not needed during recursive calls.
  10093. @^recursion@>
  10094. @<Glob...@>=
  10095. @!total_pages:integer; {the number of pages that have been shipped out}
  10096. @!max_v:scaled; {maximum height-plus-depth of pages shipped so far}
  10097. @!max_h:scaled; {maximum width of pages shipped so far}
  10098. @!max_push:integer; {deepest nesting of |push| commands encountered so far}
  10099. @!last_bop:integer; {location of previous |bop| in the \.{DVI} output}
  10100. @!dead_cycles:integer; {recent outputs that didn't ship anything out}
  10101. @!doing_leaders:boolean; {are we inside a leader box?}
  10102. @!c,@!f:quarterword; {character and font in current |char_node|}
  10103. @!rule_ht,@!rule_dp,@!rule_wd:scaled; {size of current rule being output}
  10104. @!g:pointer; {current glue specification}
  10105. @!lq,@!lr:integer; {quantities used in calculations for leaders}
  10106. @ @<Set init...@>=
  10107. total_pages:=0; max_v:=0; max_h:=0; max_push:=0; last_bop:=-1;
  10108. doing_leaders:=false; dead_cycles:=0; cur_s:=-1;
  10109. @ The \.{DVI} bytes are output to a buffer instead of being written directly
  10110. to the output file. This makes it possible to reduce the overhead of
  10111. subroutine calls, thereby measurably speeding up the computation, since
  10112. output of \.{DVI} bytes is part of \TeX's inner loop. And it has another
  10113. advantage as well, since we can change instructions in the buffer in order to
  10114. make the output more compact. For example, a `|down2|' command can be
  10115. changed to a `|y2|', thereby making a subsequent `|y0|' command possible,
  10116. saving two bytes.
  10117. The output buffer is divided into two parts of equal size; the bytes found
  10118. in |dvi_buf[0..half_buf-1]| constitute the first half, and those in
  10119. |dvi_buf[half_buf..dvi_buf_size-1]| constitute the second. The global
  10120. variable |dvi_ptr| points to the position that will receive the next
  10121. output byte. When |dvi_ptr| reaches |dvi_limit|, which is always equal
  10122. to one of the two values |half_buf| or |dvi_buf_size|, the half buffer that
  10123. is about to be invaded next is sent to the output and |dvi_limit| is
  10124. changed to its other value. Thus, there is always at least a half buffer's
  10125. worth of information present, except at the very beginning of the job.
  10126. Bytes of the \.{DVI} file are numbered sequentially starting with 0;
  10127. the next byte to be generated will be number |dvi_offset+dvi_ptr|.
  10128. A byte is present in the buffer only if its number is |>=dvi_gone|.
  10129. @<Types...@>=
  10130. @!dvi_index=0..dvi_buf_size; {an index into the output buffer}
  10131. @ Some systems may find it more efficient to make |dvi_buf| a |packed|
  10132. array, since output of four bytes at once may be facilitated.
  10133. @^system dependencies@>
  10134. @<Glob...@>=
  10135. @!dvi_buf:array[dvi_index] of eight_bits; {buffer for \.{DVI} output}
  10136. @!half_buf:dvi_index; {half of |dvi_buf_size|}
  10137. @!dvi_limit:dvi_index; {end of the current half buffer}
  10138. @!dvi_ptr:dvi_index; {the next available buffer address}
  10139. @!dvi_offset:integer; {|dvi_buf_size| times the number of times the
  10140.   output buffer has been fully emptied}
  10141. @!dvi_gone:integer; {the number of bytes already output to |dvi_file|}
  10142. @ Initially the buffer is all in one piece; we will output half of it only
  10143. after it first fills up.
  10144. @<Set init...@>=
  10145. half_buf:=dvi_buf_size div 2; dvi_limit:=dvi_buf_size; dvi_ptr:=0;
  10146. dvi_offset:=0; dvi_gone:=0;
  10147. @ The actual output of |dvi_buf[a..b]| to |dvi_file| is performed by calling
  10148. |write_dvi(a,b)|. For best results, this procedure should be optimized to
  10149. run as fast as possible on each particular system, since it is part of
  10150. \TeX's inner loop. It is safe to assume that |a| and |b+1| will both be
  10151. multiples of 4 when |write_dvi(a,b)| is called; therefore it is possible on
  10152. many machines to use efficient methods to pack four bytes per word and to
  10153. output an array of words with one system call.
  10154. @^system dependencies@>
  10155. @^inner loop@>
  10156. @^defecation@>
  10157. @p procedure write_dvi(@!a,@!b:dvi_index);
  10158. var k:dvi_index;
  10159. begin for k:=a to b do write(dvi_file,dvi_buf[k]);
  10160. @ To put a byte in the buffer without paying the cost of invoking a procedure
  10161. each time, we use the macro |dvi_out|.
  10162. @d dvi_out(#)==@+begin dvi_buf[dvi_ptr]:=#; incr(dvi_ptr);
  10163.   if dvi_ptr=dvi_limit then dvi_swap;
  10164.   end
  10165. @p procedure dvi_swap; {outputs half of the buffer}
  10166. begin if dvi_limit=dvi_buf_size then
  10167.   begin write_dvi(0,half_buf-1); dvi_limit:=half_buf;
  10168.   dvi_offset:=dvi_offset+dvi_buf_size; dvi_ptr:=0;
  10169.   end
  10170. else  begin write_dvi(half_buf,dvi_buf_size-1); dvi_limit:=dvi_buf_size;
  10171.   end;
  10172. dvi_gone:=dvi_gone+half_buf;
  10173. @ Here is how we clean out the buffer when \TeX\ is all through; |dvi_ptr|
  10174. will be a multiple of~4.
  10175. @<Empty the last bytes out of |dvi_buf|@>=
  10176. if dvi_limit=half_buf then write_dvi(half_buf,dvi_buf_size-1);
  10177. if dvi_ptr>0 then write_dvi(0,dvi_ptr-1)
  10178. @ The |dvi_four| procedure outputs four bytes in two's complement notation,
  10179. without risking arithmetic overflow.
  10180. @p procedure dvi_four(@!x:integer);
  10181. begin if x>=0 then dvi_out(x div @'100000000)
  10182. else  begin x:=x+@'10000000000;
  10183.   x:=x+@'10000000000;
  10184.   dvi_out((x div @'100000000) + 128);
  10185.   end;
  10186. x:=x mod @'100000000; dvi_out(x div @'200000);
  10187. x:=x mod @'200000; dvi_out(x div @'400);
  10188. dvi_out(x mod @'400);
  10189. @ A mild optimization of the output is performed by the |dvi_pop|
  10190. routine, which issues a |pop| unless it is possible to cancel a
  10191. `|push| |pop|' pair. The parameter to |dvi_pop| is the byte address
  10192. following the old |push| that matches the new |pop|.
  10193. @p procedure dvi_pop(@!l:integer);
  10194. begin if (l=dvi_offset+dvi_ptr)and(dvi_ptr>0) then decr(dvi_ptr)
  10195. else dvi_out(pop);
  10196. @ Here's a procedure that outputs a font definition. Since \TeX82 uses at
  10197. most 256 different fonts per job, |fnt_def1| is always used as the command code.
  10198. @p procedure dvi_font_def(@!f:internal_font_number);
  10199. var k:pool_pointer; {index into |str_pool|}
  10200. begin dvi_out(fnt_def1);
  10201. dvi_out(f-font_base-1);@/
  10202. dvi_out(qo(font_check[f].b0));
  10203. dvi_out(qo(font_check[f].b1));
  10204. dvi_out(qo(font_check[f].b2));
  10205. dvi_out(qo(font_check[f].b3));@/
  10206. dvi_four(font_size[f]);
  10207. dvi_four(font_dsize[f]);@/
  10208. dvi_out(length(font_area[f]));
  10209. dvi_out(length(font_name[f]));
  10210. @<Output the font name whose internal number is |f|@>;
  10211. @ @<Output the font name whose internal number is |f|@>=
  10212. for k:=str_start[font_area[f]] to str_start[font_area[f]+1]-1 do
  10213.   dvi_out(so(str_pool[k]));
  10214. for k:=str_start[font_name[f]] to str_start[font_name[f]+1]-1 do
  10215.   dvi_out(so(str_pool[k]))
  10216. @ Versions of \TeX\ intended for small computers might well choose to omit
  10217. the ideas in the next few parts of this program, since it is not really
  10218. necessary to optimize the \.{DVI} code by making use of the |w0|, |x0|,
  10219. |y0|, and |z0| commands. Furthermore, the algorithm that we are about to
  10220. describe does not pretend to give an optimum reduction in the length
  10221. of the \.{DVI} code; after all, speed is more important than compactness.
  10222. But the method is surprisingly effective, and it takes comparatively little
  10223. time.
  10224. We can best understand the basic idea by first considering a simpler problem
  10225. that has the same essential characteristics. Given a sequence of digits,
  10226. say $3\,1\,4\,1\,5\,9\,2\,6\,5\,3\,5\,8\,9$, we want to assign subscripts
  10227. $d$, $y$, or $z$ to each digit so as to maximize the number of ``$y$-hits''
  10228. and ``$z$-hits''; a $y$-hit is an instance of two appearances of the same
  10229. digit with the subscript $y$, where no $y$'s intervene between the two
  10230. appearances, and a $z$-hit is defined similarly. For example, the sequence
  10231. above could be decorated with subscripts as follows:
  10232. $$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.$$
  10233. There are three $y$-hits ($1_y\ldots1_y$ and $5_y\ldots5_y\ldots5_y$) and
  10234. one $z$-hit ($3_z\ldots3_z$); there are no $d$-hits, since the two appearances
  10235. of $9_d$ have $d$'s between them, but we don't count $d$-hits so it doesn't
  10236. matter how many there are. These subscripts are analogous to the \.{DVI}
  10237. commands called \\{down}, $y$, and $z$, and the digits are analogous to
  10238. different amounts of vertical motion; a $y$-hit or $z$-hit corresponds to
  10239. the opportunity to use the one-byte commands |y0| or |z0| in a \.{DVI} file.
  10240. \TeX's method of assigning subscripts works like this: Append a new digit,
  10241. say $\delta$, to the right of the sequence. Now look back through the
  10242. sequence until one of the following things happens: (a)~You see
  10243. $\delta_y$ or $\delta_z$, and this was the first time you encountered a
  10244. $y$ or $z$ subscript, respectively.  Then assign $y$ or $z$ to the new
  10245. $\delta$; you have scored a hit. (b)~You see $\delta_d$, and no $y$
  10246. subscripts have been encountered so far during this search.  Then change
  10247. the previous $\delta_d$ to $\delta_y$ (this corresponds to changing a
  10248. command in the output buffer), and assign $y$ to the new $\delta$; it's
  10249. another hit.  (c)~You see $\delta_d$, and a $y$ subscript has been seen
  10250. but not a $z$.  Change the previous $\delta_d$ to $\delta_z$ and assign
  10251. $z$ to the new $\delta$. (d)~You encounter both $y$ and $z$ subscripts
  10252. before encountering a suitable $\delta$, or you scan all the way to the
  10253. front of the sequence. Assign $d$ to the new $\delta$; this assignment may
  10254. be changed later.
  10255. The subscripts $3_z\,1_y\,4_d\ldots\,$ in the example above were, in fact,
  10256. produced by this procedure, as the reader can verify. (Go ahead and try it.)
  10257. @ In order to implement such an idea, \TeX\ maintains a stack of pointers
  10258. to the \\{down}, $y$, and $z$ commands that have been generated for the
  10259. current page. And there is a similar stack for \\{right}, |w|, and |x|
  10260. commands. These stacks are called the down stack and right stack, and their
  10261. top elements are maintained in the variables |down_ptr| and |right_ptr|.
  10262. Each entry in these stacks contains four fields: The |width| field is
  10263. the amount of motion down or to the right; the |location| field is the
  10264. byte number of the \.{DVI} command in question (including the appropriate
  10265. |dvi_offset|); the |link| field points to the next item below this one
  10266. on the stack; and the |info| field encodes the options for possible change
  10267. in the \.{DVI} command.
  10268. @d movement_node_size=3 {number of words per entry in the down and right stacks}
  10269. @d location(#)==mem[#+2].int {\.{DVI} byte number for a movement command}
  10270. @<Glob...@>=
  10271. @!down_ptr,@!right_ptr:pointer; {heads of the down and right stacks}
  10272. @ @<Set init...@>=
  10273. down_ptr:=null; right_ptr:=null;
  10274. @ Here is a subroutine that produces a \.{DVI} command for some specified
  10275. downward or rightward motion. It has two parameters: |w| is the amount
  10276. of motion, and |o| is either |down1| or |right1|. We use the fact that
  10277. the command codes have convenient arithmetic properties: |y1-down1=w1-right1|
  10278. and |z1-down1=x1-right1|.
  10279. @p procedure movement(@!w:scaled;@!o:eight_bits);
  10280. label exit,found,not_found,2,1;
  10281. var mstate:small_number; {have we seen a |y| or |z|?}
  10282. @!p,@!q:pointer; {current and top nodes on the stack}
  10283. @!k:integer; {index into |dvi_buf|, modulo |dvi_buf_size|}
  10284. begin q:=get_node(movement_node_size); {new node for the top of the stack}
  10285. width(q):=w; location(q):=dvi_offset+dvi_ptr;
  10286. if o=down1 then
  10287.   begin link(q):=down_ptr; down_ptr:=q;
  10288.   end
  10289. else  begin link(q):=right_ptr; right_ptr:=q;
  10290.   end;
  10291. @<Look at the other stack entries until deciding what sort of \.{DVI} command
  10292.   to generate; |goto found| if node |p| is a ``hit''@>;
  10293. @<Generate a |down| or |right| command for |w| and |return|@>;
  10294. found: @<Generate a |y0| or |z0| command in order to reuse a previous
  10295.   appearance of~|w|@>;
  10296. exit:end;
  10297. @ The |info| fields in the entries of the down stack or the right stack
  10298. have six possible settings: |y_here| or |z_here| mean that the \.{DVI}
  10299. command refers to |y| or |z|, respectively (or to |w| or |x|, in the
  10300. case of horizontal motion); |yz_OK| means that the \.{DVI} command is
  10301. \\{down} (or \\{right}) but can be changed to either |y| or |z| (or
  10302. to either |w| or |x|); |y_OK| means that it is \\{down} and can be changed
  10303. to |y| but not |z|; |z_OK| is similar; and |d_fixed| means it must stay
  10304. \\{down}.
  10305. The four settings |yz_OK|, |y_OK|, |z_OK|, |d_fixed| would not need to
  10306. be distinguished from each other if we were simply solving the
  10307. digit-subscripting problem mentioned above. But in \TeX's case there is
  10308. a complication because of the nested structure of |push| and |pop|
  10309. commands. Suppose we add parentheses to the digit-subscripting problem,
  10310. redefining hits so that $\delta_y\ldots \delta_y$ is a hit if all $y$'s between
  10311. the $\delta$'s are enclosed in properly nested parentheses, and if the
  10312. parenthesis level of the right-hand $\delta_y$ is deeper than or equal to
  10313. that of the left-hand one. Thus, `(' and `)' correspond to `|push|'
  10314. and `|pop|'. Now if we want to assign a subscript to the final 1 in the
  10315. sequence
  10316. $$2_y\,7_d\,1_d\,(\,8_z\,2_y\,8_z\,)\,1$$
  10317. we cannot change the previous $1_d$ to $1_y$, since that would invalidate
  10318. the $2_y\ldots2_y$ hit. But we can change it to $1_z$, scoring a hit
  10319. since the intervening $8_z$'s are enclosed in parentheses.
  10320. The program below removes movement nodes that are introduced after a |push|,
  10321. before it outputs the corresponding |pop|.
  10322. @d y_here=1 {|info| when the movement entry points to a |y| command}
  10323. @d z_here=2 {|info| when the movement entry points to a |z| command}
  10324. @d yz_OK=3 {|info| corresponding to an unconstrained \\{down} command}
  10325. @d y_OK=4 {|info| corresponding to a \\{down} that can't become a |z|}
  10326. @d z_OK=5 {|info| corresponding to a \\{down} that can't become a |y|}
  10327. @d d_fixed=6 {|info| corresponding to a \\{down} that can't change}
  10328. @ When the |movement| procedure gets to the label |found|, the value of
  10329. |info(p)| will be either |y_here| or |z_here|. If it is, say, |y_here|,
  10330. the procedure generates a |y0| command (or a |w0| command), and marks
  10331. all |info| fields between |q| and |p| so that |y| is not OK in that range.
  10332. @<Generate a |y0| or |z0| command...@>=
  10333. info(q):=info(p);
  10334. if info(q)=y_here then
  10335.   begin dvi_out(o+y0-down1); {|y0| or |w0|}
  10336.   while link(q)<>p do
  10337.     begin q:=link(q);
  10338.     case info(q) of
  10339.     yz_OK: info(q):=z_OK;
  10340.     y_OK: info(q):=d_fixed;
  10341.     othercases do_nothing
  10342.     endcases;
  10343.     end;
  10344.   end
  10345. else  begin dvi_out(o+z0-down1); {|z0| or |x0|}
  10346.   while link(q)<>p do
  10347.     begin q:=link(q);
  10348.     case info(q) of
  10349.     yz_OK: info(q):=y_OK;
  10350.     z_OK: info(q):=d_fixed;
  10351.     othercases do_nothing
  10352.     endcases;
  10353.     end;
  10354.   end
  10355. @ @<Generate a |down| or |right|...@>=
  10356. info(q):=yz_OK;
  10357. if abs(w)>=@'40000000 then
  10358.   begin dvi_out(o+3); {|down4| or |right4|}
  10359.   dvi_four(w); return;
  10360.   end;
  10361. if abs(w)>=@'100000 then
  10362.   begin dvi_out(o+2); {|down3| or |right3|}
  10363.   if w<0 then w:=w+@'100000000;
  10364.   dvi_out(w div @'200000); w:=w mod @'200000; goto 2;
  10365.   end;
  10366. if abs(w)>=@'200 then
  10367.   begin dvi_out(o+1); {|down2| or |right2|}
  10368.   if w<0 then w:=w+@'200000;
  10369.   goto 2;
  10370.   end;
  10371. dvi_out(o); {|down1| or |right1|}
  10372. if w<0 then w:=w+@'400;
  10373. goto 1;
  10374. 2: dvi_out(w div @'400);
  10375. 1: dvi_out(w mod @'400); return
  10376. @ As we search through the stack, we are in one of three states,
  10377. |y_seen|, |z_seen|, or |none_seen|, depending on whether we have
  10378. encountered |y_here| or |z_here| nodes. These states are encoded as
  10379. multiples of 6, so that they can be added to the |info| fields for quick
  10380. decision-making.
  10381. @^inner loop@>
  10382. @d none_seen=0 {no |y_here| or |z_here| nodes have been encountered yet}
  10383. @d y_seen=6 {we have seen |y_here| but not |z_here|}
  10384. @d z_seen=12 {we have seen |z_here| but not |y_here|}
  10385. @<Look at the other stack entries until deciding...@>=
  10386. p:=link(q); mstate:=none_seen;
  10387. while p<>null do
  10388.   begin if width(p)=w then @<Consider a node with matching width;
  10389.     |goto found| if it's a hit@>
  10390.   else  case mstate+info(p) of
  10391.     none_seen+y_here: mstate:=y_seen;
  10392.     none_seen+z_here: mstate:=z_seen;
  10393.     y_seen+z_here,z_seen+y_here: goto not_found;
  10394.     othercases do_nothing
  10395.     endcases;
  10396.   p:=link(p);
  10397.   end;
  10398. not_found:
  10399. @ We might find a valid hit in a |y| or |z| byte that is already gone
  10400. from the buffer. But we can't change bytes that are gone forever; ``the
  10401. moving finger writes, $\ldots\,\,$.''
  10402. @<Consider a node with matching width...@>=
  10403. case mstate+info(p) of
  10404. none_seen+yz_OK,none_seen+y_OK,z_seen+yz_OK,z_seen+y_OK:@t@>@;@/
  10405.   if location(p)<dvi_gone then goto not_found
  10406.   else @<Change buffered instruction to |y| or |w| and |goto found|@>;
  10407. none_seen+z_OK,y_seen+yz_OK,y_seen+z_OK:@t@>@;@/
  10408.   if location(p)<dvi_gone then goto not_found
  10409.   else @<Change buffered instruction to |z| or |x| and |goto found|@>;
  10410. none_seen+y_here,none_seen+z_here,y_seen+z_here,z_seen+y_here: goto found;
  10411. othercases do_nothing
  10412. endcases
  10413. @ @<Change buffered instruction to |y| or |w| and |goto found|@>=
  10414. begin k:=location(p)-dvi_offset;
  10415. if k<0 then k:=k+dvi_buf_size;
  10416. dvi_buf[k]:=dvi_buf[k]+y1-down1;
  10417. info(p):=y_here; goto found;
  10418. @ @<Change buffered instruction to |z| or |x| and |goto found|@>=
  10419. begin k:=location(p)-dvi_offset;
  10420. if k<0 then k:=k+dvi_buf_size;
  10421. dvi_buf[k]:=dvi_buf[k]+z1-down1;
  10422. info(p):=z_here; goto found;
  10423. @ In case you are wondering when all the movement nodes are removed from
  10424. \TeX's memory, the answer is that they are recycled just before
  10425. |hlist_out| and |vlist_out| finish outputting a box. This restores the
  10426. down and right stacks to the state they were in before the box was output,
  10427. except that some |info|'s may have become more restrictive.
  10428. @p procedure prune_movements(@!l:integer);
  10429.   {delete movement nodes with |location>=l|}
  10430. label done,exit;
  10431. var p:pointer; {node being deleted}
  10432. begin while down_ptr<>null do
  10433.   begin if location(down_ptr)<l then goto done;
  10434.   p:=down_ptr; down_ptr:=link(p); free_node(p,movement_node_size);
  10435.   end;
  10436. done: while right_ptr<>null do
  10437.   begin if location(right_ptr)<l then return;
  10438.   p:=right_ptr; right_ptr:=link(p); free_node(p,movement_node_size);
  10439.   end;
  10440. exit:end;
  10441. @ The actual distances by which we want to move might be computed as the
  10442. sum of several separate movements. For example, there might be several
  10443. glue nodes in succession, or we might want to move right by the width of
  10444. some box plus some amount of glue. More importantly, the baselineskip
  10445. distances are computed in terms of glue together with the depth and
  10446. height of adjacent boxes, and we want the \.{DVI} file to lump these
  10447. three quantities together into a single motion.
  10448. Therefore, \TeX\ maintains two pairs of global variables: |dvi_h| and |dvi_v|
  10449. are the |h| and |v| coordinates corresponding to the commands actually
  10450. output to the \.{DVI} file, while |cur_h| and |cur_v| are the coordinates
  10451. corresponding to the current state of the output routines. Coordinate
  10452. changes will accumulate in |cur_h| and |cur_v| without being reflected
  10453. in the output, until such a change becomes necessary or desirable; we
  10454. can call the |movement| procedure whenever we want to make |dvi_h=cur_h|
  10455. or |dvi_v=cur_v|.
  10456. The current font reflected in the \.{DVI} output is called |dvi_f|;
  10457. there is no need for a `\\{cur\_f}' variable.
  10458. The depth of nesting of |hlist_out| and |vlist_out| is called |cur_s|;
  10459. this is essentially the depth of |push| commands in the \.{DVI} output.
  10460. @d synch_h==if cur_h<>dvi_h then
  10461.     begin movement(cur_h-dvi_h,right1); dvi_h:=cur_h;
  10462.     end
  10463. @d synch_v==if cur_v<>dvi_v then
  10464.     begin movement(cur_v-dvi_v,down1); dvi_v:=cur_v;
  10465.     end
  10466. @<Glob...@>=
  10467. @!dvi_h,@!dvi_v:scaled; {a \.{DVI} reader program thinks we are here}
  10468. @!cur_h,@!cur_v:scaled; {\TeX\ thinks we are here}
  10469. @!dvi_f:internal_font_number; {the current font}
  10470. @!cur_s:integer; {current depth of output box nesting, initially $-1$}
  10471. @ @<Initialize variables as |ship_out| begins@>=
  10472. dvi_h:=0; dvi_v:=0; cur_h:=h_offset; dvi_f:=null_font;
  10473. ensure_dvi_open;
  10474. if total_pages=0 then
  10475.   begin dvi_out(pre); dvi_out(id_byte); {output the preamble}
  10476. @^preamble of \.{DVI} file@>
  10477.   dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
  10478.   prepare_mag; dvi_four(mag); {magnification factor is frozen}
  10479.   old_setting:=selector; selector:=new_string;
  10480.   print(" TeX output "); print_int(year); print_char(".");
  10481.   print_two(month); print_char("."); print_two(day);
  10482.   print_char(":"); print_two(time div 60);
  10483.   print_two(time mod 60);
  10484.   selector:=old_setting; dvi_out(cur_length);
  10485.   for s:=str_start[str_ptr] to pool_ptr-1 do dvi_out(so(str_pool[s]));
  10486.   pool_ptr:=str_start[str_ptr]; {flush the current string}
  10487.   end
  10488. @ When |hlist_out| is called, its duty is to output the box represented
  10489. by the |hlist_node| pointed to by |temp_ptr|. The reference point of that
  10490. box has coordinates |(cur_h,cur_v)|.
  10491. Similarly, when |vlist_out| is called, its duty is to output the box represented
  10492. by the |vlist_node| pointed to by |temp_ptr|. The reference point of that
  10493. box has coordinates |(cur_h,cur_v)|.
  10494. @^recursion@>
  10495. @p procedure@?vlist_out; forward; {|hlist_out| and |vlist_out| are mutually
  10496.   recursive}
  10497. @ The recursive procedures |hlist_out| and |vlist_out| each have local variables
  10498. |save_h| and |save_v| to hold the values of |dvi_h| and |dvi_v| just before
  10499. entering a new level of recursion.  In effect, the values of |save_h| and
  10500. |save_v| on \TeX's run-time stack correspond to the values of |h| and |v|
  10501. that a \.{DVI}-reading program will push onto its coordinate stack.
  10502. @d move_past=13 {go to this label when advancing past glue or a rule}
  10503. @d fin_rule=14 {go to this label to finish processing a rule}
  10504. @d next_p=15 {go to this label when finished with node |p|}
  10505. @p @t\4@>@<Declare procedures needed in |hlist_out|, |vlist_out|@>@t@>@/
  10506. procedure hlist_out; {output an |hlist_node| box}
  10507. label reswitch, move_past, fin_rule, next_p;
  10508. var base_line: scaled; {the baseline coordinate for this box}
  10509. @!left_edge: scaled; {the left coordinate for this box}
  10510. @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
  10511. @!this_box: pointer; {pointer to containing box}
  10512. @!g_order: glue_ord; {applicable order of infinity for glue}
  10513. @!g_sign: normal..shrinking; {selects type of glue}
  10514. @!p:pointer; {current position in the hlist}
  10515. @!save_loc:integer; {\.{DVI} byte location upon entry}
  10516. @!leader_box:pointer; {the leader box being replicated}
  10517. @!leader_wd:scaled; {width of leader box being replicated}
  10518. @!lx:scaled; {extra space between leader boxes}
  10519. @!outer_doing_leaders:boolean; {were we doing leaders?}
  10520. @!edge:scaled; {left edge of sub-box, or right edge of leader space}
  10521. begin this_box:=temp_ptr; g_order:=glue_order(this_box);
  10522. g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
  10523. incr(cur_s);
  10524. if cur_s>0 then dvi_out(push);
  10525. if cur_s>max_push then max_push:=cur_s;
  10526. save_loc:=dvi_offset+dvi_ptr; base_line:=cur_v; left_edge:=cur_h;
  10527. while p<>null do @<Output node |p| for |hlist_out| and move to the next node,
  10528.   maintaining the condition |cur_v=base_line|@>;
  10529. prune_movements(save_loc);
  10530. if cur_s>0 then dvi_pop(save_loc);
  10531. decr(cur_s);
  10532. @ We ought to give special care to the efficiency of one part of |hlist_out|,
  10533. since it belongs to \TeX's inner loop. When a |char_node| is encountered,
  10534. we save a little time by processing several nodes in succession until
  10535. reaching a non-|char_node|. The program uses the fact that |set_char_0=0|.
  10536. @^inner loop@>
  10537. @<Output node |p| for |hlist_out|...@>=
  10538. reswitch: if is_char_node(p) then
  10539.   begin synch_h; synch_v;
  10540.   repeat f:=font(p); c:=character(p);
  10541.   if f<>dvi_f then @<Change font |dvi_f| to |f|@>;
  10542.   if c>=qi(128) then dvi_out(set1);
  10543.   dvi_out(qo(c));@/
  10544.   cur_h:=cur_h+char_width(f)(char_info(f)(c));
  10545.   p:=link(p);
  10546.   until not is_char_node(p);
  10547.   dvi_h:=cur_h;
  10548.   end
  10549. else @<Output the non-|char_node| |p| for |hlist_out|
  10550.     and move to the next node@>
  10551. @ @<Change font |dvi_f| to |f|@>=
  10552. begin if not font_used[f] then
  10553.   begin dvi_font_def(f); font_used[f]:=true;
  10554.   end;
  10555. if f<=64+font_base then dvi_out(f-font_base-1+fnt_num_0)
  10556. else  begin dvi_out(fnt1); dvi_out(f-font_base-1);
  10557.   end;
  10558. dvi_f:=f;
  10559. @ @<Output the non-|char_node| |p| for |hlist_out|...@>=
  10560. begin case type(p) of
  10561. hlist_node,vlist_node:@<Output a box in an hlist@>;
  10562. rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
  10563.   goto fin_rule;
  10564.   end;
  10565. whatsit_node: @<Output the whatsit node |p| in an hlist@>;
  10566. glue_node: @<Move right or output leaders@>;
  10567. kern_node,math_node:cur_h:=cur_h+width(p);
  10568. ligature_node: @<Make node |p| look like a |char_node| and |goto reswitch|@>;
  10569. othercases do_nothing
  10570. endcases;@/
  10571. goto next_p;
  10572. fin_rule: @<Output a rule in an hlist@>;
  10573. move_past: cur_h:=cur_h+rule_wd;
  10574. next_p:p:=link(p);
  10575. @ @<Output a box in an hlist@>=
  10576. if list_ptr(p)=null then cur_h:=cur_h+width(p)
  10577. else  begin save_h:=dvi_h; save_v:=dvi_v;
  10578.   cur_v:=base_line+shift_amount(p); {shift the box down}
  10579.   temp_ptr:=p; edge:=cur_h;
  10580.   if type(p)=vlist_node then vlist_out@+else hlist_out;
  10581.   dvi_h:=save_h; dvi_v:=save_v;
  10582.   cur_h:=edge+width(p); cur_v:=base_line;
  10583.   end
  10584. @ @<Output a rule in an hlist@>=
  10585. if is_running(rule_ht) then rule_ht:=height(this_box);
  10586. if is_running(rule_dp) then rule_dp:=depth(this_box);
  10587. rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
  10588. if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
  10589.   begin synch_h; cur_v:=base_line+rule_dp; synch_v;
  10590.   dvi_out(set_rule); dvi_four(rule_ht); dvi_four(rule_wd);
  10591.   cur_v:=base_line; dvi_h:=dvi_h+rule_wd;
  10592.   end
  10593. @ @<Move right or output leaders@>=
  10594. begin g:=glue_ptr(p); rule_wd:=width(g);
  10595. if g_sign<>normal then
  10596.   begin if g_sign=stretching then
  10597.     begin if stretch_order(g)=g_order then
  10598.       rule_wd:=rule_wd+round(float(glue_set(this_box))*stretch(g));
  10599. @^real multiplication@>
  10600.     end
  10601.   else  begin if shrink_order(g)=g_order then
  10602.       rule_wd:=rule_wd-round(float(glue_set(this_box))*shrink(g));
  10603.     end;
  10604.   end;
  10605. if subtype(p)>=a_leaders then
  10606.   @<Output leaders in an hlist, |goto fin_rule| if a rule
  10607.     or to |next_p| if done@>;
  10608. goto move_past;
  10609. @ @<Output leaders in an hlist...@>=
  10610. begin leader_box:=leader_ptr(p);
  10611. if type(leader_box)=rule_node then
  10612.   begin rule_ht:=height(leader_box); rule_dp:=depth(leader_box);
  10613.   goto fin_rule;
  10614.   end;
  10615. leader_wd:=width(leader_box);
  10616. if (leader_wd>0)and(rule_wd>0) then
  10617.   begin rule_wd:=rule_wd+10; {compensate for floating-point rounding}
  10618.   edge:=cur_h+rule_wd; lx:=0;
  10619.   @<Let |cur_h| be the position of the first box, and set |leader_wd+lx|
  10620.     to the spacing between corresponding parts of boxes@>;
  10621.   while cur_h+leader_wd<=edge do
  10622.     @<Output a leader box at |cur_h|,
  10623.       then advance |cur_h| by |leader_wd+lx|@>;
  10624.   cur_h:=edge-10; goto next_p;
  10625.   end;
  10626. @ The calculations related to leaders require a bit of care. First, in the
  10627. case of |a_leaders| (aligned leaders), we want to move |cur_h| to
  10628. |left_edge| plus the smallest multiple of |leader_wd| for which the result
  10629. is not less than the current value of |cur_h|; i.e., |cur_h| should become
  10630. $|left_edge|+|leader_wd|\times\lceil
  10631. (|cur_h|-|left_edge|)/|leader_wd|\rceil$.  The program here should work in
  10632. all cases even though some implementations of \PASCAL\ give nonstandard
  10633. results for the |div| operation when |cur_h| is less than |left_edge|.
  10634. In the case of |c_leaders| (centered leaders), we want to increase |cur_h|
  10635. by half of the excess space not occupied by the leaders; and in the
  10636. case of |x_leaders| (expanded leaders) we increase |cur_h|
  10637. by $1/(q+1)$ of this excess space, where $q$ is the number of times the
  10638. leader box will be replicated. Slight inaccuracies in the division might
  10639. accumulate; half of this rounding error is placed at each end of the leaders.
  10640. @<Let |cur_h| be the position of the first box, ...@>=
  10641. if subtype(p)=a_leaders then
  10642.   begin save_h:=cur_h;
  10643.   cur_h:=left_edge+leader_wd*((cur_h-left_edge)@!div leader_wd);
  10644.   if cur_h<save_h then cur_h:=cur_h+leader_wd;
  10645.   end
  10646. else  begin lq:=rule_wd div leader_wd; {the number of box copies}
  10647.   lr:=rule_wd mod leader_wd; {the remaining space}
  10648.   if subtype(p)=c_leaders then cur_h:=cur_h+(lr div 2)
  10649.   else  begin lx:=(2*lr+lq+1) div (2*lq+2); {round|(lr/(lq+1))|}
  10650.     cur_h:=cur_h+((lr-(lq-1)*lx) div 2);
  10651.     end;
  10652.   end
  10653. @ The `\\{synch}' operations here are intended to decrease the number of
  10654. bytes needed to specify horizontal and vertical motion in the \.{DVI} output.
  10655. @<Output a leader box at |cur_h|, ...@>=
  10656. begin cur_v:=base_line+shift_amount(leader_box); synch_v; save_v:=dvi_v;@/
  10657. synch_h; save_h:=dvi_h; temp_ptr:=leader_box;
  10658. outer_doing_leaders:=doing_leaders; doing_leaders:=true;
  10659. if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
  10660. doing_leaders:=outer_doing_leaders;
  10661. dvi_v:=save_v; dvi_h:=save_h; cur_v:=base_line;
  10662. cur_h:=save_h+leader_wd+lx;
  10663. @ The |vlist_out| routine is similar to |hlist_out|, but a bit simpler.
  10664. @p procedure vlist_out; {output a |vlist_node| box}
  10665. label move_past, fin_rule, next_p;
  10666. var left_edge: scaled; {the left coordinate for this box}
  10667. @!top_edge: scaled; {the top coordinate for this box}
  10668. @!save_h,@!save_v: scaled; {what |dvi_h| and |dvi_v| should pop to}
  10669. @!this_box: pointer; {pointer to containing box}
  10670. @!g_order: glue_ord; {applicable order of infinity for glue}
  10671. @!g_sign: normal..shrinking; {selects type of glue}
  10672. @!p:pointer; {current position in the vlist}
  10673. @!save_loc:integer; {\.{DVI} byte location upon entry}
  10674. @!leader_box:pointer; {the leader box being replicated}
  10675. @!leader_ht:scaled; {height of leader box being replicated}
  10676. @!lx:scaled; {extra space between leader boxes}
  10677. @!outer_doing_leaders:boolean; {were we doing leaders?}
  10678. @!edge:scaled; {bottom boundary of leader space}
  10679. begin this_box:=temp_ptr; g_order:=glue_order(this_box);
  10680. g_sign:=glue_sign(this_box); p:=list_ptr(this_box);
  10681. incr(cur_s);
  10682. if cur_s>0 then dvi_out(push);
  10683. if cur_s>max_push then max_push:=cur_s;
  10684. save_loc:=dvi_offset+dvi_ptr; left_edge:=cur_h; cur_v:=cur_v-height(this_box);
  10685. top_edge:=cur_v;
  10686. while p<>null do @<Output node |p| for |vlist_out| and move to the next node,
  10687.   maintaining the condition |cur_h=left_edge|@>;
  10688. prune_movements(save_loc);
  10689. if cur_s>0 then dvi_pop(save_loc);
  10690. decr(cur_s);
  10691. @ @<Output node |p| for |vlist_out|...@>=
  10692. begin if is_char_node(p) then confusion("vlistout")
  10693. @:this can't happen vlistout}{\quad vlistout@>
  10694. else @<Output the non-|char_node| |p| for |vlist_out|@>;
  10695. next_p:p:=link(p);
  10696. @ @<Output the non-|char_node| |p| for |vlist_out|@>=
  10697. begin case type(p) of
  10698. hlist_node,vlist_node:@<Output a box in a vlist@>;
  10699. rule_node: begin rule_ht:=height(p); rule_dp:=depth(p); rule_wd:=width(p);
  10700.   goto fin_rule;
  10701.   end;
  10702. whatsit_node: @<Output the whatsit node |p| in a vlist@>;
  10703. glue_node: @<Move down or output leaders@>;
  10704. kern_node:cur_v:=cur_v+width(p);
  10705. othercases do_nothing
  10706. endcases;@/
  10707. goto next_p;
  10708. fin_rule: @<Output a rule in a vlist, |goto next_p|@>;
  10709. move_past: cur_v:=cur_v+rule_ht;
  10710. @ The |synch_v| here allows the \.{DVI} output to use one-byte commands
  10711. for adjusting |v| in most cases, since the baselineskip distance will
  10712. usually be constant.
  10713. @<Output a box in a vlist@>=
  10714. if list_ptr(p)=null then cur_v:=cur_v+height(p)+depth(p)
  10715. else  begin cur_v:=cur_v+height(p); synch_v;
  10716.   save_h:=dvi_h; save_v:=dvi_v;
  10717.   cur_h:=left_edge+shift_amount(p); {shift the box right}
  10718.   temp_ptr:=p;
  10719.   if type(p)=vlist_node then vlist_out@+else hlist_out;
  10720.   dvi_h:=save_h; dvi_v:=save_v;
  10721.   cur_v:=save_v+depth(p); cur_h:=left_edge;
  10722.   end
  10723. @ @<Output a rule in a vlist...@>=
  10724. if is_running(rule_wd) then rule_wd:=width(this_box);
  10725. rule_ht:=rule_ht+rule_dp; {this is the rule thickness}
  10726. cur_v:=cur_v+rule_ht;
  10727. if (rule_ht>0)and(rule_wd>0) then {we don't output empty rules}
  10728.   begin synch_h; synch_v;
  10729.   dvi_out(put_rule); dvi_four(rule_ht); dvi_four(rule_wd);
  10730.   end;
  10731. goto next_p
  10732. @ @<Move down or output leaders@>=
  10733. begin g:=glue_ptr(p); rule_ht:=width(g);
  10734. if g_sign<>normal then
  10735.   begin if g_sign=stretching then
  10736.     begin if stretch_order(g)=g_order then
  10737.       rule_ht:=rule_ht+round(float(glue_set(this_box))*stretch(g));
  10738. @^real multiplication@>
  10739.     end
  10740.   else  begin if shrink_order(g)=g_order then
  10741.       rule_ht:=rule_ht-round(float(glue_set(this_box))*shrink(g));
  10742.     end;
  10743.   end;
  10744. if subtype(p)>=a_leaders then
  10745.   @<Output leaders in a vlist, |goto fin_rule| if a rule
  10746.     or to |next_p| if done@>;
  10747. goto move_past;
  10748. @ @<Output leaders in a vlist...@>=
  10749. begin leader_box:=leader_ptr(p);
  10750. if type(leader_box)=rule_node then
  10751.   begin rule_wd:=width(leader_box); rule_dp:=0;
  10752.   goto fin_rule;
  10753.   end;
  10754. leader_ht:=height(leader_box)+depth(leader_box);
  10755. if (leader_ht>0)and(rule_ht>0) then
  10756.   begin rule_ht:=rule_ht+10; {compensate for floating-point rounding}
  10757.   edge:=cur_v+rule_ht; lx:=0;
  10758.   @<Let |cur_v| be the position of the first box, and set |leader_ht+lx|
  10759.     to the spacing between corresponding parts of boxes@>;
  10760.   while cur_v+leader_ht<=edge do
  10761.     @<Output a leader box at |cur_v|,
  10762.       then advance |cur_v| by |leader_ht+lx|@>;
  10763.   cur_v:=edge-10; goto next_p;
  10764.   end;
  10765. @ @<Let |cur_v| be the position of the first box, ...@>=
  10766. if subtype(p)=a_leaders then
  10767.   begin save_v:=cur_v;
  10768.   cur_v:=top_edge+leader_ht*((cur_v-top_edge)@!div leader_ht);
  10769.   if cur_v<save_v then cur_v:=cur_v+leader_ht;
  10770.   end
  10771. else  begin lq:=rule_ht div leader_ht; {the number of box copies}
  10772.   lr:=rule_ht mod leader_ht; {the remaining space}
  10773.   if subtype(p)=c_leaders then cur_v:=cur_v+(lr div 2)
  10774.   else  begin lx:=(2*lr+lq+1) div (2*lq+2); {round|(lr/(lq+1))|}
  10775.     cur_v:=cur_v+((lr-(lq-1)*lx) div 2);
  10776.     end;
  10777.   end
  10778. @ When we reach this part of the program, |cur_v| indicates the top of a
  10779. leader box, not its baseline.
  10780. @<Output a leader box at |cur_v|, ...@>=
  10781. begin cur_h:=left_edge+shift_amount(leader_box); synch_h; save_h:=dvi_h;@/
  10782. cur_v:=cur_v+height(leader_box); synch_v; save_v:=dvi_v;
  10783. temp_ptr:=leader_box;
  10784. outer_doing_leaders:=doing_leaders; doing_leaders:=true;
  10785. if type(leader_box)=vlist_node then vlist_out@+else hlist_out;
  10786. doing_leaders:=outer_doing_leaders;
  10787. dvi_v:=save_v; dvi_h:=save_h; cur_h:=left_edge;
  10788. cur_v:=save_v-height(leader_box)+leader_ht+lx;
  10789. @ The |hlist_out| and |vlist_out| procedures are now complete, so we are
  10790. ready for the |ship_out| routine that gets them started in the first place.
  10791. @p procedure ship_out(@!p:pointer); {output the box |p|}
  10792. label done;
  10793. var page_loc:integer; {location of the current |bop|}
  10794. @!j,@!k:0..9; {indices to first ten count registers}
  10795. @!s:pool_pointer; {index into |str_pool|}
  10796. @!old_setting:0..max_selector; {saved |selector| setting}
  10797. begin if tracing_output>0 then
  10798.   begin print_nl(""); print_ln;
  10799.   print("Completed box being shipped out");
  10800. @.Completed box...@>
  10801.   end;
  10802. if term_offset>max_print_line-9 then print_ln
  10803. else if (term_offset>0)or(file_offset>0) then print_char(" ");
  10804. print_char("["); j:=9;
  10805. while (count(j)=0)and(j>0) do decr(j);
  10806. for k:=0 to j do
  10807.   begin print_int(count(k));
  10808.   if k<j then print_char(".");
  10809.   end;
  10810. update_terminal;
  10811. if tracing_output>0 then
  10812.   begin print_char("]");
  10813.   begin_diagnostic; show_box(p); end_diagnostic(true);
  10814.   end;
  10815. @<Ship box |p| out@>;
  10816. if tracing_output<=0 then print_char("]");
  10817. dead_cycles:=0;
  10818. update_terminal; {progress report}
  10819. @<Flush the box from memory, showing statistics if requested@>;
  10820. @ @<Flush the box from memory, showing statistics if requested@>=
  10821. @!stat if tracing_stats>1 then
  10822.   begin print_nl("Memory usage before: ");
  10823. @.Memory usage...@>
  10824.   print_int(var_used); print_char("&");
  10825.   print_int(dyn_used); print_char(";");
  10826.   end;
  10827. tats@/
  10828. flush_node_list(p);
  10829. @!stat if tracing_stats>1 then
  10830.   begin print(" after: ");
  10831.   print_int(var_used); print_char("&");
  10832.   print_int(dyn_used); print("; still untouched: ");
  10833.   print_int(hi_mem_min-lo_mem_max-1); print_ln;
  10834.   end;
  10835. @ @<Ship box |p| out@>=
  10836. @<Update the values of |max_h| and |max_v|; but if the page is too large,
  10837.   |goto done|@>;
  10838. @<Initialize variables as |ship_out| begins@>;
  10839. page_loc:=dvi_offset+dvi_ptr;
  10840. dvi_out(bop);
  10841. for k:=0 to 9 do dvi_four(count(k));
  10842. dvi_four(last_bop); last_bop:=page_loc;
  10843. cur_v:=height(p)+v_offset; temp_ptr:=p;
  10844. if type(p)=vlist_node then vlist_out@+else hlist_out;
  10845. dvi_out(eop); incr(total_pages); cur_s:=-1;
  10846. done:
  10847. @ Sometimes the user will generate a huge page because other error messages
  10848. are being ignored. Such pages are not output to the \.{dvi} file, since they
  10849. may confuse the printing software.
  10850. @<Update the values of |max_h| and |max_v|; but if the page is too large...@>=
  10851. if (height(p)>max_dimen)or@|(depth(p)>max_dimen)or@|
  10852.    (height(p)+depth(p)+v_offset>max_dimen)or@|
  10853.    (width(p)+h_offset>max_dimen) then
  10854.   begin print_err("Huge page cannot be shipped out");
  10855. @.Huge page...@>
  10856.   help2("The page just created is more than 18 feet tall or")@/
  10857.    ("more than 18 feet wide, so I suspect something went wrong.");
  10858.   error;
  10859.   if tracing_output<=0 then
  10860.     begin begin_diagnostic;
  10861.     print_nl("The following box has been deleted:");
  10862. @.The following...deleted@>
  10863.     show_box(p);
  10864.     end_diagnostic(true);
  10865.     end;
  10866.   goto done;
  10867.   end;
  10868. if height(p)+depth(p)+v_offset>max_v then max_v:=height(p)+depth(p)+v_offset;
  10869. if width(p)+h_offset>max_h then max_h:=width(p)+h_offset
  10870. @ At the end of the program, we must finish things off by writing the
  10871. post\-amble. If |total_pages=0|, the \.{DVI} file was never opened.
  10872. If |total_pages>=65536|, the \.{DVI} file will lie.
  10873. An integer variable |k| will be declared for use by this routine.
  10874. @<Finish the \.{DVI} file@>=
  10875. while cur_s>-1 do
  10876.   begin if cur_s>0 then dvi_out(pop)
  10877.   else  begin dvi_out(eop); incr(total_pages);
  10878.     end;
  10879.   decr(cur_s);
  10880.   end;
  10881. if total_pages=0 then print_nl("No pages of output.")
  10882. @.No pages of output@>
  10883. else  begin dvi_out(post); {beginning of the postamble}
  10884.   dvi_four(last_bop); last_bop:=dvi_offset+dvi_ptr-5; {|post| location}
  10885.   dvi_four(25400000); dvi_four(473628672); {conversion ratio for sp}
  10886.   prepare_mag; dvi_four(mag); {magnification factor}
  10887.   dvi_four(max_v); dvi_four(max_h);@/
  10888.   dvi_out(max_push div 256); dvi_out(max_push mod 256);@/
  10889.   dvi_out((total_pages div 256) mod 256); dvi_out(total_pages mod 256);@/
  10890.   @<Output the font definitions for all fonts that were used@>;
  10891.   dvi_out(post_post); dvi_four(last_bop); dvi_out(id_byte);@/
  10892.   k:=4+((dvi_buf_size-dvi_ptr) mod 4); {the number of 223's}
  10893.   while k>0 do
  10894.     begin dvi_out(223); decr(k);
  10895.     end;
  10896.   @<Empty the last bytes out of |dvi_buf|@>;
  10897.   print_nl("Output written on "); slow_print(output_file_name);
  10898. @.Output written on x@>
  10899.   print(" ("); print_int(total_pages); print(" page");
  10900.   if total_pages<>1 then print_char("s");
  10901.   print(", "); print_int(dvi_offset+dvi_ptr); print(" bytes).");
  10902.   b_close(dvi_file);
  10903.   end
  10904. @ @<Output the font definitions...@>=
  10905. while font_ptr>font_base do
  10906.   begin if font_used[font_ptr] then dvi_font_def(font_ptr);
  10907.   decr(font_ptr);
  10908.   end
  10909. @* \[33] Packaging.
  10910. We're essentially done with the parts of \TeX\ that are concerned with
  10911. the input (|get_next|) and the output (|ship_out|). So it's time to
  10912. get heavily into the remaining part, which does the real work of typesetting.
  10913. After lists are constructed, \TeX\ wraps them up and puts them into boxes.
  10914. Two major subroutines are given the responsibility for this task: |hpack|
  10915. applies to horizontal lists (hlists) and |vpack| applies to vertical lists
  10916. (vlists). The main duty of |hpack| and |vpack| is to compute the dimensions
  10917. of the resulting boxes, and to adjust the glue if one of those dimensions
  10918. is pre-specified. The computed sizes normally enclose all of the material
  10919. inside the new box; but some items may stick out if negative glue is used,
  10920. if the box is overfull, or if a \.{\\vbox} includes other boxes that have
  10921. been shifted left.
  10922. The subroutine call |hpack(p,w,m)| returns a pointer to an |hlist_node|
  10923. for a box containing the hlist that starts at |p|. Parameter |w| specifies
  10924. a width; and parameter |m| is either `|exactly|' or `|additional|'.  Thus,
  10925. |hpack(p,w,exactly)| produces a box whose width is exactly |w|, while
  10926. |hpack(p,w,additional)| yields a box whose width is the natural width plus
  10927. |w|.  It is convenient to define a macro called `|natural|' to cover the
  10928. most common case, so that we can say |hpack(p,natural)| to get a box that
  10929. has the natural width of list |p|.
  10930. Similarly, |vpack(p,w,m)| returns a pointer to a |vlist_node| for a
  10931. box containing the vlist that starts at |p|. In this case |w| represents
  10932. a height instead of a width; the parameter |m| is interpreted as in |hpack|.
  10933. @d exactly=0 {a box dimension is pre-specified}
  10934. @d additional=1 {a box dimension is increased from the natural one}
  10935. @d natural==0,additional {shorthand for parameters to |hpack| and |vpack|}
  10936. @ The parameters to |hpack| and |vpack| correspond to \TeX's primitives
  10937. like `\.{\\hbox} \.{to} \.{300pt}', `\.{\\hbox} \.{spread} \.{10pt}'; note
  10938. that `\.{\\hbox}' with no dimension following it is equivalent to
  10939. `\.{\\hbox} \.{spread} \.{0pt}'.  The |scan_spec| subroutine scans such
  10940. constructions in the user's input, including the mandatory left brace that
  10941. follows them, and it puts the specification onto |save_stack| so that the
  10942. desired box can later be obtained by executing the following code:
  10943. $$\vbox{\halign{#\hfil\cr
  10944. |save_ptr:=save_ptr-2;|\cr
  10945. |hpack(p,saved(1),saved(0)).|\cr}}$$
  10946. Special care is necessary to ensure that the special |save_stack| codes
  10947. are placed just below the new group code, because scanning can change
  10948. |save_stack| when \.{\\csname} appears.
  10949. @p procedure scan_spec(@!c:group_code;@!three_codes:boolean);
  10950.   {scans a box specification and left brace}
  10951. label found;
  10952. var @!s:integer; {temporarily saved value}
  10953. @!spec_code:exactly..additional;
  10954. begin if three_codes then s:=saved(0);
  10955. if scan_keyword("to") then spec_code:=exactly
  10956. @.to@>
  10957. else if scan_keyword("spread") then spec_code:=additional
  10958. @.spread@>
  10959. else  begin spec_code:=additional; cur_val:=0;
  10960.   goto found;
  10961.   end;
  10962. scan_normal_dimen;
  10963. found: if three_codes then
  10964.   begin saved(0):=s; incr(save_ptr);
  10965.   end;
  10966. saved(0):=spec_code; saved(1):=cur_val; save_ptr:=save_ptr+2;
  10967. new_save_level(c); scan_left_brace;
  10968. @ To figure out the glue setting, |hpack| and |vpack| determine how much
  10969. stretchability and shrinkability are present, considering all four orders
  10970. of infinity. The highest order of infinity that has a nonzero coefficient
  10971. is then used as if no other orders were present.
  10972. For example, suppose that the given list contains six glue nodes with
  10973. the respective stretchabilities 3pt, 8fill, 5fil, 6pt, $-3$fil, $-8$fill.
  10974. Then the total is essentially 2fil; and if a total additional space of 6pt
  10975. is to be achieved by stretching, the actual amounts of stretch will be
  10976. 0pt, 0pt, 15pt, 0pt, $-9$pt, and 0pt, since only `fil' glue will be
  10977. considered. (The `fill' glue is therefore not really stretching infinitely
  10978. with respect to `fil'; nobody would actually want that to happen.)
  10979. The arrays |total_stretch| and |total_shrink| are used to determine how much
  10980. glue of each kind is present. A global variable |last_badness| is used
  10981. to implement \.{\\badness}.
  10982. @<Glob...@>=
  10983. @!total_stretch, @!total_shrink: array[glue_ord] of scaled;
  10984.   {glue found by |hpack| or |vpack|}
  10985. @!last_badness:integer; {badness of the most recently packaged box}
  10986. @ If the global variable |adjust_tail| is non-null, the |hpack| routine
  10987. also removes all occurrences of |ins_node|, |mark_node|, and |adjust_node|
  10988. items and appends the resulting material onto the list that ends at
  10989. location |adjust_tail|.
  10990. @< Glob...@>=
  10991. @!adjust_tail:pointer; {tail of adjustment list}
  10992. @ @<Set init...@>=adjust_tail:=null; last_badness:=0;
  10993. @ Here now is |hpack|, which contains few if any surprises.
  10994. @p function hpack(@!p:pointer;@!w:scaled;@!m:small_number):pointer;
  10995. label reswitch, common_ending, exit;
  10996. var r:pointer; {the box node that will be returned}
  10997. @!q:pointer; {trails behind |p|}
  10998. @!h,@!d,@!x:scaled; {height, depth, and natural width}
  10999. @!s:scaled; {shift amount}
  11000. @!g:pointer; {points to a glue specification}
  11001. @!o:glue_ord; {order of infinity}
  11002. @!f:internal_font_number; {the font in a |char_node|}
  11003. @!i:four_quarters; {font information about a |char_node|}
  11004. @!hd:eight_bits; {height and depth indices for a character}
  11005. begin last_badness:=0; r:=get_node(box_node_size); type(r):=hlist_node;
  11006. subtype(r):=min_quarterword; shift_amount(r):=0;
  11007. q:=r+list_offset; link(q):=p;@/
  11008. h:=0; @<Clear dimensions to zero@>;
  11009. while p<>null do @<Examine node |p| in the hlist, taking account of its effect
  11010.   on the dimensions of the new box, or moving it to the adjustment list;
  11011.   then advance |p| to the next node@>;
  11012. if adjust_tail<>null then link(adjust_tail):=null;
  11013. height(r):=h; depth(r):=d;@/
  11014. @<Determine the value of |width(r)| and the appropriate glue setting;
  11015.   then |return| or |goto common_ending|@>;
  11016. common_ending: @<Finish issuing a diagnostic message
  11017.       for an overfull or underfull hbox@>;
  11018. exit: hpack:=r;
  11019. @ @<Clear dimensions to zero@>=
  11020. d:=0; x:=0;
  11021. total_stretch[normal]:=0; total_shrink[normal]:=0;
  11022. total_stretch[fil]:=0; total_shrink[fil]:=0;
  11023. total_stretch[fill]:=0; total_shrink[fill]:=0;
  11024. total_stretch[filll]:=0; total_shrink[filll]:=0
  11025. @ @<Examine node |p| in the hlist, taking account of its effect...@>=
  11026. @^inner loop@>
  11027. begin reswitch: while is_char_node(p) do
  11028.   @<Incorporate character dimensions into the dimensions of
  11029.     the hbox that will contain~it, then move to the next node@>;
  11030. if p<>null then
  11031.   begin case type(p) of
  11032.   hlist_node,vlist_node,rule_node,unset_node:
  11033.     @<Incorporate box dimensions into the dimensions of
  11034.       the hbox that will contain~it@>;
  11035.   ins_node,mark_node,adjust_node: if adjust_tail<>null then
  11036.     @<Transfer node |p| to the adjustment list@>;
  11037.   whatsit_node:@<Incorporate a whatsit node into an hbox@>;
  11038.   glue_node:@<Incorporate glue into the horizontal totals@>;
  11039.   kern_node,math_node: x:=x+width(p);
  11040.   ligature_node: @<Make node |p| look like a |char_node|
  11041.     and |goto reswitch|@>;
  11042.   othercases do_nothing
  11043.   endcases;@/
  11044.   p:=link(p);
  11045.   end;
  11046. @ @<Make node |p| look like a |char_node| and |goto reswitch|@>=
  11047. begin mem[lig_trick]:=mem[lig_char(p)]; link(lig_trick):=link(p);
  11048. p:=lig_trick; goto reswitch;
  11049. @ The code here implicitly uses the fact that running dimensions are
  11050. indicated by |null_flag|, which will be ignored in the calculations
  11051. because it is a highly negative number.
  11052. @<Incorporate box dimensions into the dimensions of the hbox...@>=
  11053. begin x:=x+width(p);
  11054. if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
  11055. if height(p)-s>h then h:=height(p)-s;
  11056. if depth(p)+s>d then d:=depth(p)+s;
  11057. @ The following code is part of \TeX's inner loop; i.e., adding another
  11058. character of text to the user's input will cause each of these instructions
  11059. to be exercised one more time.
  11060. @^inner loop@>
  11061. @<Incorporate character dimensions into the dimensions of the hbox...@>=
  11062. begin f:=font(p); i:=char_info(f)(character(p)); hd:=height_depth(i);
  11063. x:=x+char_width(f)(i);@/
  11064. s:=char_height(f)(hd);@+if s>h then h:=s;
  11065. s:=char_depth(f)(hd);@+if s>d then d:=s;
  11066. p:=link(p);
  11067. @ Although node |q| is not necessarily the immediate predecessor of node |p|,
  11068. it always points to some node in the list preceding |p|. Thus, we can delete
  11069. nodes by moving |q| when necessary. The algorithm takes linear time, and the
  11070. extra computation does not intrude on the inner loop unless it is necessary
  11071. to make a deletion.
  11072. @<Transfer node |p| to the adjustment list@>=
  11073. begin while link(q)<>p do q:=link(q);
  11074. if type(p)=adjust_node then
  11075.   begin link(adjust_tail):=adjust_ptr(p);
  11076.   while link(adjust_tail)<>null do adjust_tail:=link(adjust_tail);
  11077.   p:=link(p); free_node(link(q),small_node_size);
  11078.   end
  11079. else  begin link(adjust_tail):=p; adjust_tail:=p; p:=link(p);
  11080.   end;
  11081. link(q):=p; p:=q;
  11082. @ @<Incorporate glue into the horizontal totals@>=
  11083. begin g:=glue_ptr(p); x:=x+width(g);@/
  11084. o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
  11085. o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
  11086. if subtype(p)>=a_leaders then
  11087.   begin g:=leader_ptr(p);
  11088.   if height(g)>h then h:=height(g);
  11089.   if depth(g)>d then d:=depth(g);
  11090.   end;
  11091. @ When we get to the present part of the program, |x| is the natural width
  11092. of the box being packaged.
  11093. @<Determine the value of |width(r)| and the appropriate glue setting...@>=
  11094. if m=additional then w:=x+w;
  11095. width(r):=w; x:=w-x; {now |x| is the excess to be made up}
  11096. if x=0 then
  11097.   begin glue_sign(r):=normal; glue_order(r):=normal;
  11098.   set_glue_ratio_zero(glue_set(r));
  11099.   return;
  11100.   end
  11101. else if x>0 then @<Determine horizontal glue stretch setting, then |return|
  11102.     or \hbox{|goto common_ending|}@>
  11103. else @<Determine horizontal glue shrink setting, then |return|
  11104.     or \hbox{|goto common_ending|}@>
  11105. @ @<Determine horizontal glue stretch setting...@>=
  11106. begin @<Determine the stretch order@>;
  11107. glue_order(r):=o; glue_sign(r):=stretching;
  11108. if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
  11109. @^real division@>
  11110. else  begin glue_sign(r):=normal;
  11111.   set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
  11112.   end;
  11113. if o=normal then if list_ptr(r)<>null then
  11114.   @<Report an underfull hbox and |goto common_ending|, if this box
  11115.     is sufficiently bad@>;
  11116. return;
  11117. @ @<Determine the stretch order@>=
  11118. if total_stretch[filll]<>0 then o:=filll
  11119. else if total_stretch[fill]<>0 then o:=fill
  11120. else if total_stretch[fil]<>0 then o:=fil
  11121. else o:=normal
  11122. @ @<Report an underfull hbox and |goto common_ending|, if...@>=
  11123. begin last_badness:=badness(x,total_stretch[normal]);
  11124. if last_badness>hbadness then
  11125.   begin print_ln;
  11126.   if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
  11127.   print(" \hbox (badness "); print_int(last_badness);
  11128. @.Underfull \\hbox...@>
  11129. @.Loose \\hbox...@>
  11130.   goto common_ending;
  11131.   end;
  11132. @ In order to provide a decent indication of where an overfull or underfull
  11133. box originated, we use a global variable |pack_begin_line| that is
  11134. set nonzero only when |hpack| is being called by the paragraph builder
  11135. or the alignment finishing routine.
  11136. @<Glob...@>=
  11137. @!pack_begin_line:integer; {source file line where the current paragraph
  11138.   or alignment began; a negative value denotes alignment}
  11139. @ @<Set init...@>=
  11140. pack_begin_line:=0;
  11141. @ @<Finish issuing a diagnostic message for an overfull or underfull hbox@>=
  11142. if output_active then print(") has occurred while \output is active")
  11143. else  begin if pack_begin_line<>0 then
  11144.     begin if pack_begin_line>0 then print(") in paragraph at lines ")
  11145.     else print(") in alignment at lines ");
  11146.     print_int(abs(pack_begin_line));
  11147.     print("--");
  11148.     end
  11149.   else print(") detected at line ");
  11150.   print_int(line);
  11151.   end;
  11152. print_ln;@/
  11153. font_in_short_display:=null_font; short_display(list_ptr(r)); print_ln;@/
  11154. begin_diagnostic; show_box(r); end_diagnostic(true)
  11155. @ @<Determine horizontal glue shrink setting...@>=
  11156. begin @<Determine the shrink order@>;
  11157. glue_order(r):=o; glue_sign(r):=shrinking;
  11158. if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
  11159. @^real division@>
  11160. else  begin glue_sign(r):=normal;
  11161.   set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
  11162.   end;
  11163. if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
  11164.   begin last_badness:=1000000;
  11165.   set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
  11166.   @<Report an overfull hbox and |goto common_ending|, if this box
  11167.     is sufficiently bad@>;
  11168.   end
  11169. else if o=normal then if list_ptr(r)<>null then
  11170.   @<Report a tight hbox and |goto common_ending|, if this box
  11171.     is sufficiently bad@>;
  11172. return;
  11173. @ @<Determine the shrink order@>=
  11174. if total_shrink[filll]<>0 then o:=filll
  11175. else if total_shrink[fill]<>0 then o:=fill
  11176. else if total_shrink[fil]<>0 then o:=fil
  11177. else o:=normal
  11178. @ @<Report an overfull hbox and |goto common_ending|, if...@>=
  11179. if (-x-total_shrink[normal]>hfuzz)or(hbadness<100) then
  11180.   begin if (overfull_rule>0)and(-x-total_shrink[normal]>hfuzz) then
  11181.     begin while link(q)<>null do q:=link(q);
  11182.     link(q):=new_rule;
  11183.     width(link(q)):=overfull_rule;
  11184.     end;
  11185.   print_ln; print_nl("Overfull \hbox (");
  11186. @.Overfull \\hbox...@>
  11187.   print_scaled(-x-total_shrink[normal]); print("pt too wide");
  11188.   goto common_ending;
  11189.   end
  11190. @ @<Report a tight hbox and |goto common_ending|, if...@>=
  11191. begin last_badness:=badness(-x,total_shrink[normal]);
  11192. if last_badness>hbadness then
  11193.   begin print_ln; print_nl("Tight \hbox (badness "); print_int(last_badness);
  11194. @.Tight \\hbox...@>
  11195.   goto common_ending;
  11196.   end;
  11197. @ The |vpack| subroutine is actually a special case of a slightly more
  11198. general routine called |vpackage|, which has four parameters. The fourth
  11199. parameter, which is |max_dimen| in the case of |vpack|, specifies the
  11200. maximum depth of the page box that is constructed. The depth is first
  11201. computed by the normal rules; if it exceeds this limit, the reference
  11202. point is simply moved down until the limiting depth is attained.
  11203. @d vpack(#)==vpackage(#,max_dimen) {special case of unconstrained depth}
  11204. @p function vpackage(@!p:pointer;@!h:scaled;@!m:small_number;@!l:scaled):
  11205.   pointer;
  11206. label common_ending, exit;
  11207. var r:pointer; {the box node that will be returned}
  11208. @!w,@!d,@!x:scaled; {width, depth, and natural height}
  11209. @!s:scaled; {shift amount}
  11210. @!g:pointer; {points to a glue specification}
  11211. @!o:glue_ord; {order of infinity}
  11212. begin last_badness:=0; r:=get_node(box_node_size); type(r):=vlist_node;
  11213. subtype(r):=min_quarterword; shift_amount(r):=0;
  11214. list_ptr(r):=p;@/
  11215. w:=0; @<Clear dimensions to zero@>;
  11216. while p<>null do @<Examine node |p| in the vlist, taking account of its effect
  11217.   on the dimensions of the new box; then advance |p| to the next node@>;
  11218. width(r):=w;
  11219. if d>l then
  11220.   begin x:=x+d-l; depth(r):=l;
  11221.   end
  11222. else depth(r):=d;
  11223. @<Determine the value of |height(r)| and the appropriate glue setting;
  11224.   then |return| or |goto common_ending|@>;
  11225. common_ending: @<Finish issuing a diagnostic message
  11226.       for an overfull or underfull vbox@>;
  11227. exit: vpackage:=r;
  11228. @ @<Examine node |p| in the vlist, taking account of its effect...@>=
  11229. begin if is_char_node(p) then confusion("vpack")
  11230. @:this can't happen vpack}{\quad vpack@>
  11231. else  case type(p) of
  11232.   hlist_node,vlist_node,rule_node,unset_node:
  11233.     @<Incorporate box dimensions into the dimensions of
  11234.       the vbox that will contain~it@>;
  11235.   whatsit_node:@<Incorporate a whatsit node into a vbox@>;
  11236.   glue_node: @<Incorporate glue into the vertical totals@>;
  11237.   kern_node: begin x:=x+d+width(p); d:=0;
  11238.     end;
  11239.   othercases do_nothing
  11240.   endcases;
  11241. p:=link(p);
  11242. @ @<Incorporate box dimensions into the dimensions of the vbox...@>=
  11243. begin x:=x+d+height(p); d:=depth(p);
  11244. if type(p)>=rule_node then s:=0 @+else s:=shift_amount(p);
  11245. if width(p)+s>w then w:=width(p)+s;
  11246. @ @<Incorporate glue into the vertical totals@>=
  11247. begin x:=x+d; d:=0;@/
  11248. g:=glue_ptr(p); x:=x+width(g);@/
  11249. o:=stretch_order(g); total_stretch[o]:=total_stretch[o]+stretch(g);
  11250. o:=shrink_order(g); total_shrink[o]:=total_shrink[o]+shrink(g);
  11251. if subtype(p)>=a_leaders then
  11252.   begin g:=leader_ptr(p);
  11253.   if width(g)>w then w:=width(g);
  11254.   end;
  11255. @ When we get to the present part of the program, |x| is the natural height
  11256. of the box being packaged.
  11257. @<Determine the value of |height(r)| and the appropriate glue setting...@>=
  11258. if m=additional then h:=x+h;
  11259. height(r):=h; x:=h-x; {now |x| is the excess to be made up}
  11260. if x=0 then
  11261.   begin glue_sign(r):=normal; glue_order(r):=normal;
  11262.   set_glue_ratio_zero(glue_set(r));
  11263.   return;
  11264.   end
  11265. else if x>0 then @<Determine vertical glue stretch setting, then |return|
  11266.     or \hbox{|goto common_ending|}@>
  11267. else @<Determine vertical glue shrink setting, then |return|
  11268.     or \hbox{|goto common_ending|}@>
  11269. @ @<Determine vertical glue stretch setting...@>=
  11270. begin @<Determine the stretch order@>;
  11271. glue_order(r):=o; glue_sign(r):=stretching;
  11272. if total_stretch[o]<>0 then glue_set(r):=unfloat(x/total_stretch[o])
  11273. @^real division@>
  11274. else  begin glue_sign(r):=normal;
  11275.   set_glue_ratio_zero(glue_set(r)); {there's nothing to stretch}
  11276.   end;
  11277. if o=normal then if list_ptr(r)<>null then
  11278.   @<Report an underfull vbox and |goto common_ending|, if this box
  11279.     is sufficiently bad@>;
  11280. return;
  11281. @ @<Report an underfull vbox and |goto common_ending|, if...@>=
  11282. begin last_badness:=badness(x,total_stretch[normal]);
  11283. if last_badness>vbadness then
  11284.   begin print_ln;
  11285.   if last_badness>100 then print_nl("Underfull")@+else print_nl("Loose");
  11286.   print(" \vbox (badness "); print_int(last_badness);
  11287. @.Underfull \\vbox...@>
  11288. @.Loose \\vbox...@>
  11289.   goto common_ending;
  11290.   end;
  11291. @ @<Finish issuing a diagnostic message for an overfull or underfull vbox@>=
  11292. if output_active then print(") has occurred while \output is active")
  11293. else  begin if pack_begin_line<>0 then {it's actually negative}
  11294.     begin print(") in alignment at lines ");
  11295.     print_int(abs(pack_begin_line));
  11296.     print("--");
  11297.     end
  11298.   else print(") detected at line ");
  11299.   print_int(line);
  11300.   print_ln;@/
  11301.   end;
  11302. begin_diagnostic; show_box(r); end_diagnostic(true)
  11303. @ @<Determine vertical glue shrink setting...@>=
  11304. begin @<Determine the shrink order@>;
  11305. glue_order(r):=o; glue_sign(r):=shrinking;
  11306. if total_shrink[o]<>0 then glue_set(r):=unfloat((-x)/total_shrink[o])
  11307. @^real division@>
  11308. else  begin glue_sign(r):=normal;
  11309.   set_glue_ratio_zero(glue_set(r)); {there's nothing to shrink}
  11310.   end;
  11311. if (total_shrink[o]<-x)and(o=normal)and(list_ptr(r)<>null) then
  11312.   begin last_badness:=1000000;
  11313.   set_glue_ratio_one(glue_set(r)); {use the maximum shrinkage}
  11314.   @<Report an overfull vbox and |goto common_ending|, if this box
  11315.     is sufficiently bad@>;
  11316.   end
  11317. else if o=normal then if list_ptr(r)<>null then
  11318.   @<Report a tight vbox and |goto common_ending|, if this box
  11319.     is sufficiently bad@>;
  11320. return;
  11321. @ @<Report an overfull vbox and |goto common_ending|, if...@>=
  11322. if (-x-total_shrink[normal]>vfuzz)or(vbadness<100) then
  11323.   begin print_ln; print_nl("Overfull \vbox (");
  11324. @.Overfull \\vbox...@>
  11325.   print_scaled(-x-total_shrink[normal]); print("pt too high");
  11326.   goto common_ending;
  11327.   end
  11328. @ @<Report a tight vbox and |goto common_ending|, if...@>=
  11329. begin last_badness:=badness(-x,total_shrink[normal]);
  11330. if last_badness>vbadness then
  11331.   begin print_ln; print_nl("Tight \vbox (badness "); print_int(last_badness);
  11332. @.Tight \\vbox...@>
  11333.   goto common_ending;
  11334.   end;
  11335. @ When a box is being appended to the current vertical list, the
  11336. baselineskip calculation is handled by the |append_to_vlist| routine.
  11337. @p procedure append_to_vlist(@!b:pointer);
  11338. var d:scaled; {deficiency of space between baselines}
  11339. @!p:pointer; {a new glue specification}
  11340. begin if prev_depth>ignore_depth then
  11341.   begin d:=width(baseline_skip)-prev_depth-height(b);
  11342.   if d<line_skip_limit then p:=new_param_glue(line_skip_code)
  11343.   else  begin p:=new_skip_param(baseline_skip_code);
  11344.     width(temp_ptr):=d; {|temp_ptr=glue_ptr(p)|}
  11345.     end;
  11346.   link(tail):=p; tail:=p;
  11347.   end;
  11348. link(tail):=b; tail:=b; prev_depth:=depth(b);
  11349. @* \[34] Data structures for math mode.
  11350. When \TeX\ reads a formula that is enclosed between \.\$'s, it constructs an
  11351. {\sl mlist}, which is essentially a tree structure representing that
  11352. formula.  An mlist is a linear sequence of items, but we can regard it as
  11353. a tree structure because mlists can appear within mlists. For example, many
  11354. of the entries can be subscripted or superscripted, and such ``scripts''
  11355. are mlists in their own right.
  11356. An entire formula is parsed into such a tree before any of the actual
  11357. typesetting is done, because the current style of type is usually not
  11358. known until the formula has been fully scanned. For example, when the
  11359. formula `\.{\$a+b \\over c+d\$}' is being read, there is no way to tell
  11360. that `\.{a+b}' will be in script size until `\.{\\over}' has appeared.
  11361. During the scanning process, each element of the mlist being built is
  11362. classified as a relation, a binary operator, an open parenthesis, etc.,
  11363. or as a construct like `\.{\\sqrt}' that must be built up. This classification
  11364. appears in the mlist data structure.
  11365. After a formula has been fully scanned, the mlist is converted to an hlist
  11366. so that it can be incorporated into the surrounding text. This conversion is
  11367. controlled by a recursive procedure that decides all of the appropriate
  11368. styles by a ``top-down'' process starting at the outermost level and working
  11369. in towards the subformulas. The formula is ultimately pasted together using
  11370. combinations of horizontal and vertical boxes, with glue and penalty nodes
  11371. inserted as necessary.
  11372. An mlist is represented internally as a linked list consisting chiefly
  11373. of ``noads'' (pronounced ``no-adds''), to distinguish them from the somewhat
  11374. similar ``nodes'' in hlists and vlists. Certain kinds of ordinary nodes are
  11375. allowed to appear in mlists together with the noads; \TeX\ tells the difference
  11376. by means of the |type| field, since a noad's |type| is always greater than
  11377. that of a node. An mlist does not contain character nodes, hlist nodes, vlist
  11378. nodes, math nodes, ligature nodes, mark nodes, insert nodes, adjust nodes,
  11379. or unset nodes; in particular, each mlist item appears in the
  11380. variable-size part of |mem|, so the |type| field is always present.
  11381. @ Each noad is four or more words long. The first word contains the |type|
  11382. and |subtype| and |link| fields that are already so familiar to us; the
  11383. second, third, and fourth words are called the noad's |nucleus|, |subscr|,
  11384. and |supscr| fields.
  11385. Consider, for example, the simple formula `\.{\$x\^2\$}', which would be
  11386. parsed into an mlist containing a single element called an |ord_noad|.
  11387. The |nucleus| of this noad is a representation of `\.x', the |subscr| is
  11388. empty, and the |supscr| is a representation of `\.2'.
  11389. The |nucleus|, |subscr|, and |supscr| fields are further broken into
  11390. subfields. If |p| points to a noad, and if |q| is one of its principal
  11391. fields (e.g., |q=subscr(p)|), there are several possibilities for the
  11392. subfields, depending on the |math_type| of |q|.
  11393. \yskip\hang|math_type(q)=math_char| means that |fam(q)| refers to one of
  11394. the sixteen font families, and |character(q)| is the number of a character
  11395. within a font of that family, as in a character node.
  11396. \yskip\hang|math_type(q)=math_text_char| is similar, but the character is
  11397. unsubscripted and unsuperscripted and it is followed immediately by another
  11398. character from the same font. (This |math_type| setting appears only
  11399. briefly during the processing; it is used to suppress unwanted italic
  11400. corrections.)
  11401. \yskip\hang|math_type(q)=empty| indicates a field with no value (the
  11402. corresponding attribute of noad |p| is not present).
  11403. \yskip\hang|math_type(q)=sub_box| means that |info(q)| points to a box
  11404. node (either an |hlist_node| or a |vlist_node|) that should be used as the
  11405. value of the field.  The |shift_amount| in the subsidiary box node is the
  11406. amount by which that box will be shifted downward.
  11407. \yskip\hang|math_type(q)=sub_mlist| means that |info(q)| points to
  11408. an mlist; the mlist must be converted to an hlist in order to obtain
  11409. the value of this field.
  11410. \yskip\noindent In the latter case, we might have |info(q)=null|. This
  11411. is not the same as |math_type(q)=empty|; for example, `\.{\$P\_\{\}\$}'
  11412. and `\.{\$P\$}' produce different results (the former will not have the
  11413. ``italic correction'' added to the width of |P|, but the ``script skip''
  11414. will be added).
  11415. The definitions of subfields given here are evidently wasteful of space,
  11416. since a halfword is being used for the |math_type| although only three
  11417. bits would be needed. However, there are hardly ever many noads present at
  11418. once, since they are soon converted to nodes that take up even more space,
  11419. so we can afford to represent them in whatever way simplifies the
  11420. programming.
  11421. @d noad_size=4 {number of words in a normal noad}
  11422. @d nucleus(#)==#+1 {the |nucleus| field of a noad}
  11423. @d supscr(#)==#+2 {the |supscr| field of a noad}
  11424. @d subscr(#)==#+3 {the |subscr| field of a noad}
  11425. @d math_type==link {a |halfword| in |mem|}
  11426. @d fam==font {a |quarterword| in |mem|}
  11427. @d math_char=1 {|math_type| when the attribute is simple}
  11428. @d sub_box=2 {|math_type| when the attribute is a box}
  11429. @d sub_mlist=3 {|math_type| when the attribute is a formula}
  11430. @d math_text_char=4 {|math_type| when italic correction is dubious}
  11431. @ Each portion of a formula is classified as Ord, Op, Bin, Rel, Ope,
  11432. Clo, Pun, or Inn, for purposes of spacing and line breaking. An
  11433. |ord_noad|, |op_noad|, |bin_noad|, |rel_noad|, |open_noad|, |close_noad|,
  11434. |punct_noad|, or |inner_noad| is used to represent portions of the various
  11435. types. For example, an `\.=' sign in a formula leads to the creation of a
  11436. |rel_noad| whose |nucleus| field is a representation of an equals sign
  11437. (usually |fam=0|, |character=@'75|).  A formula preceded by \.{\\mathrel}
  11438. also results in a |rel_noad|.  When a |rel_noad| is followed by an
  11439. |op_noad|, say, and possibly separated by one or more ordinary nodes (not
  11440. noads), \TeX\ will insert a penalty node (with the current |rel_penalty|)
  11441. just after the formula that corresponds to the |rel_noad|, unless there
  11442. already was a penalty immediately following; and a ``thick space'' will be
  11443. inserted just before the formula that corresponds to the |op_noad|.
  11444. A noad of type |ord_noad|, |op_noad|, \dots, |inner_noad| usually
  11445. has a |subtype=normal|. The only exception is that an |op_noad| might
  11446. have |subtype=limits| or |no_limits|, if the normal positioning of
  11447. limits has been overridden for this operator.
  11448. @d ord_noad=unset_node+3 {|type| of a noad classified Ord}
  11449. @d op_noad=ord_noad+1 {|type| of a noad classified Op}
  11450. @d bin_noad=ord_noad+2 {|type| of a noad classified Bin}
  11451. @d rel_noad=ord_noad+3 {|type| of a noad classified Rel}
  11452. @d open_noad=ord_noad+4 {|type| of a noad classified Ope}
  11453. @d close_noad=ord_noad+5 {|type| of a noad classified Clo}
  11454. @d punct_noad=ord_noad+6 {|type| of a noad classified Pun}
  11455. @d inner_noad=ord_noad+7 {|type| of a noad classified Inn}
  11456. @d limits=1 {|subtype| of |op_noad| whose scripts are to be above, below}
  11457. @d no_limits=2 {|subtype| of |op_noad| whose scripts are to be normal}
  11458. @ A |radical_noad| is five words long; the fifth word is the |left_delimiter|
  11459. field, which usually represents a square root sign.
  11460. A |fraction_noad| is six words long; it has a |right_delimiter| field
  11461. as well as a |left_delimiter|.
  11462. Delimiter fields are of type |four_quarters|, and they have four subfields
  11463. called |small_fam|, |small_char|, |large_fam|, |large_char|. These subfields
  11464. represent variable-size delimiters by giving the ``small'' and ``large''
  11465. starting characters, as explained in Chapter~17 of {\sl The \TeX book}.
  11466. @:TeXbook}{\sl The \TeX book@>
  11467. A |fraction_noad| is actually quite different from all other noads. Not
  11468. only does it have six words, it has |thickness|, |denominator|, and
  11469. |numerator| fields instead of |nucleus|, |subscr|, and |supscr|. The
  11470. |thickness| is a scaled value that tells how thick to make a fraction
  11471. rule; however, the special value |default_code| is used to stand for the
  11472. |default_rule_thickness| of the current size. The |numerator| and
  11473. |denominator| point to mlists that define a fraction; we always have
  11474. $$\hbox{|math_type(numerator)=math_type(denominator)=sub_mlist|}.$$ The
  11475. |left_delimiter| and |right_delimiter| fields specify delimiters that will
  11476. be placed at the left and right of the fraction. In this way, a
  11477. |fraction_noad| is able to represent all of \TeX's operators \.{\\over},
  11478. \.{\\atop}, \.{\\above}, \.{\\overwithdelims}, \.{\\atopwithdelims}, and
  11479.  \.{\\abovewithdelims}.
  11480. @d left_delimiter(#)==#+4 {first delimiter field of a noad}
  11481. @d right_delimiter(#)==#+5 {second delimiter field of a fraction noad}
  11482. @d radical_noad=inner_noad+1 {|type| of a noad for square roots}
  11483. @d radical_noad_size=5 {number of |mem| words in a radical noad}
  11484. @d fraction_noad=radical_noad+1 {|type| of a noad for generalized fractions}
  11485. @d fraction_noad_size=6 {number of |mem| words in a fraction noad}
  11486. @d small_fam(#)==mem[#].qqqq.b0 {|fam| for ``small'' delimiter}
  11487. @d small_char(#)==mem[#].qqqq.b1 {|character| for ``small'' delimiter}
  11488. @d large_fam(#)==mem[#].qqqq.b2 {|fam| for ``large'' delimiter}
  11489. @d large_char(#)==mem[#].qqqq.b3 {|character| for ``large'' delimiter}
  11490. @d thickness==width {|thickness| field in a fraction noad}
  11491. @d default_code==@'10000000000 {denotes |default_rule_thickness|}
  11492. @d numerator==supscr {|numerator| field in a fraction noad}
  11493. @d denominator==subscr {|denominator| field in a fraction noad}
  11494. @ The global variable |empty_field| is set up for initialization of empty
  11495. fields in new noads. Similarly, |null_delimiter| is for the initialization
  11496. of delimiter fields.
  11497. @<Glob...@>=
  11498. @!empty_field:two_halves;
  11499. @!null_delimiter:four_quarters;
  11500. @ @<Set init...@>=
  11501. empty_field.rh:=empty; empty_field.lh:=null;@/
  11502. null_delimiter.b0:=0; null_delimiter.b1:=min_quarterword;@/
  11503. null_delimiter.b2:=0; null_delimiter.b3:=min_quarterword;
  11504. @ The |new_noad| function creates an |ord_noad| that is completely null.
  11505. @p function new_noad:pointer;
  11506. var p:pointer;
  11507. begin p:=get_node(noad_size);
  11508. type(p):=ord_noad; subtype(p):=normal;
  11509. mem[nucleus(p)].hh:=empty_field;
  11510. mem[subscr(p)].hh:=empty_field;
  11511. mem[supscr(p)].hh:=empty_field;
  11512. new_noad:=p;
  11513. @ A few more kinds of noads will complete the set: An |under_noad| has its
  11514. nucleus underlined; an |over_noad| has it overlined. An |accent_noad| places
  11515. an accent over its nucleus; the accent character appears as
  11516. |fam(accent_chr(p))| and |character(accent_chr(p))|. A |vcenter_noad|
  11517. centers its nucleus vertically with respect to the axis of the formula;
  11518. in such noads we always have |math_type(nucleus(p))=sub_box|.
  11519. And finally, we have |left_noad| and |right_noad| types, to implement
  11520. \TeX's \.{\\left} and \.{\\right}. The |nucleus| of such noads is
  11521. replaced by a |delimiter| field; thus, for example, `\.{\\left(}' produces
  11522. a |left_noad| such that |delimiter(p)| holds the family and character
  11523. codes for all left parentheses. A |left_noad| never appears in an mlist
  11524. except as the first element, and a |right_noad| never appears in an mlist
  11525. except as the last element; furthermore, we either have both a |left_noad|
  11526. and a |right_noad|, or neither one is present. The |subscr| and |supscr|
  11527. fields are always |empty| in a |left_noad| and a |right_noad|.
  11528. @d under_noad=fraction_noad+1 {|type| of a noad for underlining}
  11529. @d over_noad=under_noad+1 {|type| of a noad for overlining}
  11530. @d accent_noad=over_noad+1 {|type| of a noad for accented subformulas}
  11531. @d accent_noad_size=5 {number of |mem| words in an accent noad}
  11532. @d accent_chr(#)==#+4 {the |accent_chr| field of an accent noad}
  11533. @d vcenter_noad=accent_noad+1 {|type| of a noad for \.{\\vcenter}}
  11534. @d left_noad=vcenter_noad+1 {|type| of a noad for \.{\\left}}
  11535. @d right_noad=left_noad+1 {|type| of a noad for \.{\\right}}
  11536. @d delimiter==nucleus {|delimiter| field in left and right noads}
  11537. @d scripts_allowed(#)==(type(#)>=ord_noad)and(type(#)<left_noad)
  11538. @ Math formulas can also contain instructions like \.{\\textstyle} that
  11539. override \TeX's normal style rules. A |style_node| is inserted into the
  11540. data structure to record such instructions; it is three words long, so it
  11541. is considered a node instead of a noad. The |subtype| is either |display_style|
  11542. or |text_style| or |script_style| or |script_script_style|. The
  11543. second and third words of a |style_node| are not used, but they are
  11544. present because a |choice_node| is converted to a |style_node|.
  11545. \TeX\ uses even numbers 0, 2, 4, 6 to encode the basic styles
  11546. |display_style|, \dots, |script_script_style|, and adds~1 to get the
  11547. ``cramped'' versions of these styles. This gives a numerical order that
  11548. is backwards from the convention of Appendix~G in {\sl The \TeX book\/};
  11549. i.e., a smaller style has a larger numerical value.
  11550. @:TeXbook}{\sl The \TeX book@>
  11551. @d style_node=unset_node+1 {|type| of a style node}
  11552. @d style_node_size=3 {number of words in a style node}
  11553. @d display_style=0 {|subtype| for \.{\\displaystyle}}
  11554. @d text_style=2 {|subtype| for \.{\\textstyle}}
  11555. @d script_style=4 {|subtype| for \.{\\scriptstyle}}
  11556. @d script_script_style=6 {|subtype| for \.{\\scriptscriptstyle}}
  11557. @d cramped=1 {add this to an uncramped style if you want to cramp it}
  11558. @p function new_style(@!s:small_number):pointer; {create a style node}
  11559. var p:pointer; {the new node}
  11560. begin p:=get_node(style_node_size); type(p):=style_node;
  11561. subtype(p):=s; width(p):=0; depth(p):=0; {the |width| and |depth| are not used}
  11562. new_style:=p;
  11563. @ Finally, the \.{\\mathchoice} primitive creates a |choice_node|, which
  11564. has special subfields |display_mlist|, |text_mlist|, |script_mlist|,
  11565. and |script_script_mlist| pointing to the mlists for each style.
  11566. @d choice_node=unset_node+2 {|type| of a choice node}
  11567. @d display_mlist(#)==info(#+1) {mlist to be used in display style}
  11568. @d text_mlist(#)==link(#+1) {mlist to be used in text style}
  11569. @d script_mlist(#)==info(#+2) {mlist to be used in script style}
  11570. @d script_script_mlist(#)==link(#+2) {mlist to be used in scriptscript style}
  11571. @p function new_choice:pointer; {create a choice node}
  11572. var p:pointer; {the new node}
  11573. begin p:=get_node(style_node_size); type(p):=choice_node;
  11574. subtype(p):=0; {the |subtype| is not used}
  11575. display_mlist(p):=null; text_mlist(p):=null; script_mlist(p):=null;
  11576. script_script_mlist(p):=null;
  11577. new_choice:=p;
  11578. @ Let's consider now the previously unwritten part of |show_node_list|
  11579. that displays the things that can only be present in mlists; this
  11580. program illustrates how to access the data structures just defined.
  11581. In the context of the following program, |p| points to a node or noad that
  11582. should be displayed, and the current string contains the ``recursion history''
  11583. that leads to this point. The recursion history consists of a dot for each
  11584. outer level in which |p| is subsidiary to some node, or in which |p| is
  11585. subsidiary to the |nucleus| field of some noad; the dot is replaced by
  11586. `\.\_' or `\.\^' or `\./' or `\.\\' if |p| is descended from the |subscr|
  11587. or |supscr| or |denominator| or |numerator| fields of noads. For example,
  11588. the current string would be `\.{.\^.\_/}' if |p| points to the |ord_noad| for
  11589. |x| in the (ridiculous) formula
  11590. `\.{\$\\sqrt\{a\^\{\\mathinner\{b\_\{c\\over x+y\}\}\}\}\$}'.
  11591. @<Cases of |show_node_list| that arise...@>=
  11592. style_node:print_style(subtype(p));
  11593. choice_node:@<Display choice node |p|@>;
  11594. ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
  11595.   radical_noad,over_noad,under_noad,vcenter_noad,accent_noad,
  11596.   left_noad,right_noad:@<Display normal noad |p|@>;
  11597. fraction_noad:@<Display fraction noad |p|@>;
  11598. @ Here are some simple routines used in the display of noads.
  11599. @<Declare procedures needed for displaying the elements of mlists@>=
  11600. procedure print_fam_and_char(@!p:pointer); {prints family and character}
  11601. begin print_esc("fam"); print_int(fam(p)); print_char(" ");
  11602. print_ASCII(qo(character(p)));
  11603. procedure print_delimiter(@!p:pointer); {prints a delimiter as 24-bit hex value}
  11604. var a:integer; {accumulator}
  11605. begin a:=small_fam(p)*256+qo(small_char(p));
  11606. a:=a*@"1000+large_fam(p)*256+qo(large_char(p));
  11607. if a<0 then print_int(a) {this should never happen}
  11608. else print_hex(a);
  11609. @ The next subroutine will descend to another level of recursion when a
  11610. subsidiary mlist needs to be displayed. The parameter |c| indicates what
  11611. character is to become part of the recursion history. An empty mlist is
  11612. distinguished from a field with |math_type(p)=empty|, because these are
  11613. not equivalent (as explained above).
  11614. @^recursion@>
  11615. @<Declare procedures needed for displaying...@>=
  11616. procedure@?show_info; forward;@t\2@>@?{|show_node_list(info(temp_ptr))|}
  11617. procedure print_subsidiary_data(@!p:pointer;@!c:ASCII_code);
  11618.   {display a noad field}
  11619. begin if cur_length>=depth_threshold then
  11620.   begin if math_type(p)<>empty then print(" []");
  11621.   end
  11622. else  begin append_char(c); {include |c| in the recursion history}
  11623.   temp_ptr:=p; {prepare for |show_info| if recursion is needed}
  11624.   case math_type(p) of
  11625.   math_char: begin print_ln; print_current_string; print_fam_and_char(p);
  11626.     end;
  11627.   sub_box: show_info; {recursive call}
  11628.   sub_mlist: if info(p)=null then
  11629.       begin print_ln; print_current_string; print("{}");
  11630.       end
  11631.     else show_info; {recursive call}
  11632.   othercases do_nothing {|empty|}
  11633.   endcases;@/
  11634.   flush_char; {remove |c| from the recursion history}
  11635.   end;
  11636. @ The inelegant introduction of |show_info| in the code above seems better
  11637. than the alternative of using \PASCAL's strange |forward| declaration for a
  11638. procedure with parameters. The \PASCAL\ convention about dropping parameters
  11639. from a post-|forward| procedure is, frankly, so intolerable to the author
  11640. of \TeX\ that he would rather stoop to communication via a global temporary
  11641. variable. (A similar stoopidity occurred with respect to |hlist_out| and
  11642. |vlist_out| above, and it will occur with respect to |mlist_to_hlist| below.)
  11643. @^Knuth, Donald Ervin@>
  11644. @:PASCAL}{\PASCAL@>
  11645. @p procedure show_info; {the reader will kindly forgive this}
  11646. begin show_node_list(info(temp_ptr));
  11647. @ @<Declare procedures needed for displaying...@>=
  11648. procedure print_style(@!c:integer);
  11649. begin case c div 2 of
  11650. 0: print_esc("displaystyle"); {|display_style=0|}
  11651. 1: print_esc("textstyle"); {|text_style=2|}
  11652. 2: print_esc("scriptstyle"); {|script_style=4|}
  11653. 3: print_esc("scriptscriptstyle"); {|script_script_style=6|}
  11654. othercases print("Unknown style!")
  11655. endcases;
  11656. @ @<Display choice node |p|@>=
  11657. begin print_esc("mathchoice");
  11658. append_char("D"); show_node_list(display_mlist(p)); flush_char;
  11659. append_char("T"); show_node_list(text_mlist(p)); flush_char;
  11660. append_char("S"); show_node_list(script_mlist(p)); flush_char;
  11661. append_char("s"); show_node_list(script_script_mlist(p)); flush_char;
  11662. @ @<Display normal noad |p|@>=
  11663. begin case type(p) of
  11664. ord_noad: print_esc("mathord");
  11665. op_noad: print_esc("mathop");
  11666. bin_noad: print_esc("mathbin");
  11667. rel_noad: print_esc("mathrel");
  11668. open_noad: print_esc("mathopen");
  11669. close_noad: print_esc("mathclose");
  11670. punct_noad: print_esc("mathpunct");
  11671. inner_noad: print_esc("mathinner");
  11672. over_noad: print_esc("overline");
  11673. under_noad: print_esc("underline");
  11674. vcenter_noad: print_esc("vcenter");
  11675. radical_noad: begin print_esc("radical"); print_delimiter(left_delimiter(p));
  11676.   end;
  11677. accent_noad: begin print_esc("accent"); print_fam_and_char(accent_chr(p));
  11678.   end;
  11679. left_noad: begin print_esc("left"); print_delimiter(nucleus(p));
  11680.   end;
  11681. right_noad: begin print_esc("right"); print_delimiter(nucleus(p));
  11682.   end;
  11683. if subtype(p)<>normal then
  11684.   if subtype(p)=limits then print_esc("limits")
  11685.   else print_esc("nolimits");
  11686. if type(p)<left_noad then print_subsidiary_data(nucleus(p),".");
  11687. print_subsidiary_data(supscr(p),"^");
  11688. print_subsidiary_data(subscr(p),"_");
  11689. @ @<Display fraction noad |p|@>=
  11690. begin print_esc("fraction, thickness ");
  11691. if thickness(p)=default_code then print("= default")
  11692. else print_scaled(thickness(p));
  11693. if (small_fam(left_delimiter(p))<>0)or@+
  11694.   (small_char(left_delimiter(p))<>min_quarterword)or@|
  11695.   (large_fam(left_delimiter(p))<>0)or@|
  11696.   (large_char(left_delimiter(p))<>min_quarterword) then
  11697.   begin print(", left-delimiter "); print_delimiter(left_delimiter(p));
  11698.   end;
  11699. if (small_fam(right_delimiter(p))<>0)or@|
  11700.   (small_char(right_delimiter(p))<>min_quarterword)or@|
  11701.   (large_fam(right_delimiter(p))<>0)or@|
  11702.   (large_char(right_delimiter(p))<>min_quarterword) then
  11703.   begin print(", right-delimiter "); print_delimiter(right_delimiter(p));
  11704.   end;
  11705. print_subsidiary_data(numerator(p),"\");
  11706. print_subsidiary_data(denominator(p),"/");
  11707. @ That which can be displayed can also be destroyed.
  11708. @<Cases of |flush_node_list| that arise...@>=
  11709. style_node: begin free_node(p,style_node_size); goto done;
  11710.   end;
  11711. choice_node:begin flush_node_list(display_mlist(p));
  11712.   flush_node_list(text_mlist(p));
  11713.   flush_node_list(script_mlist(p));
  11714.   flush_node_list(script_script_mlist(p));
  11715.   free_node(p,style_node_size); goto done;
  11716.   end;
  11717. ord_noad,op_noad,bin_noad,rel_noad,open_noad,close_noad,punct_noad,inner_noad,
  11718.   radical_noad,over_noad,under_noad,vcenter_noad,accent_noad:@t@>@;@/
  11719.   begin if math_type(nucleus(p))>=sub_box then
  11720.     flush_node_list(info(nucleus(p)));
  11721.   if math_type(supscr(p))>=sub_box then
  11722.     flush_node_list(info(supscr(p)));
  11723.   if math_type(subscr(p))>=sub_box then
  11724.     flush_node_list(info(subscr(p)));
  11725.   if type(p)=radical_noad then free_node(p,radical_noad_size)
  11726.   else if type(p)=accent_noad then free_node(p,accent_noad_size)
  11727.   else free_node(p,noad_size);
  11728.   goto done;
  11729.   end;
  11730. left_noad,right_noad: begin free_node(p,noad_size); goto done;
  11731.   end;
  11732. fraction_noad: begin flush_node_list(info(numerator(p)));
  11733.   flush_node_list(info(denominator(p)));
  11734.   free_node(p,fraction_noad_size); goto done;
  11735.   end;
  11736. @* \[35] Subroutines for math mode.
  11737. In order to convert mlists to hlists, i.e., noads to nodes, we need several
  11738. subroutines that are conveniently dealt with now.
  11739. Let us first introduce the macros that make it easy to get at the parameters and
  11740. other font information. A size code, which is a multiple of 16, is added to a
  11741. family number to get an index into the table of internal font numbers
  11742. for each combination of family and size.  (Be alert: Size codes get
  11743. larger as the type gets smaller.)
  11744. @d text_size=0 {size code for the largest size in a family}
  11745. @d script_size=16 {size code for the medium size in a family}
  11746. @d script_script_size=32 {size code for the smallest size in a family}
  11747. @<Basic printing procedures@>=
  11748. procedure print_size(@!s:integer);
  11749. begin if s=0 then print_esc("textfont")
  11750. else if s=script_size then print_esc("scriptfont")
  11751. else print_esc("scriptscriptfont");
  11752. @ Before an mlist is converted to an hlist, \TeX\ makes sure that
  11753. the fonts in family~2 have enough parameters to be math-symbol
  11754. fonts, and that the fonts in family~3 have enough parameters to be
  11755. math-extension fonts. The math-symbol parameters are referred to by using the
  11756. following macros, which take a size code as their parameter; for example,
  11757. |num1(cur_size)| gives the value of the |num1| parameter for the current size.
  11758. @^parameters for symbols@>
  11759. @^font parameters@>
  11760. @d mathsy_end(#)==fam_fnt(2+#)]].sc
  11761. @d mathsy(#)==font_info[#+param_base[mathsy_end
  11762. @d math_x_height==mathsy(5) {height of `\.x'}
  11763. @d math_quad==mathsy(6) {\.{18mu}}
  11764. @d num1==mathsy(8) {numerator shift-up in display styles}
  11765. @d num2==mathsy(9) {numerator shift-up in non-display, non-\.{\\atop}}
  11766. @d num3==mathsy(10) {numerator shift-up in non-display \.{\\atop}}
  11767. @d denom1==mathsy(11) {denominator shift-down in display styles}
  11768. @d denom2==mathsy(12) {denominator shift-down in non-display styles}
  11769. @d sup1==mathsy(13) {superscript shift-up in uncramped display style}
  11770. @d sup2==mathsy(14) {superscript shift-up in uncramped non-display}
  11771. @d sup3==mathsy(15) {superscript shift-up in cramped styles}
  11772. @d sub1==mathsy(16) {subscript shift-down if superscript is absent}
  11773. @d sub2==mathsy(17) {subscript shift-down if superscript is present}
  11774. @d sup_drop==mathsy(18) {superscript baseline below top of large box}
  11775. @d sub_drop==mathsy(19) {subscript baseline below bottom of large box}
  11776. @d delim1==mathsy(20) {size of \.{\\atopwithdelims} delimiters
  11777.   in display styles}
  11778. @d delim2==mathsy(21) {size of \.{\\atopwithdelims} delimiters in non-displays}
  11779. @d axis_height==mathsy(22) {height of fraction lines above the baseline}
  11780. @d total_mathsy_params=22
  11781. @ The math-extension parameters have similar macros, but the size code is
  11782. omitted (since it is always |cur_size| when we refer to such parameters).
  11783. @^parameters for symbols@>
  11784. @^font parameters@>
  11785. @d mathex(#)==font_info[#+param_base[fam_fnt(3+cur_size)]].sc
  11786. @d default_rule_thickness==mathex(8) {thickness of \.{\\over} bars}
  11787. @d big_op_spacing1==mathex(9) {minimum clearance above a displayed op}
  11788. @d big_op_spacing2==mathex(10) {minimum clearance below a displayed op}
  11789. @d big_op_spacing3==mathex(11) {minimum baselineskip above displayed op}
  11790. @d big_op_spacing4==mathex(12) {minimum baselineskip below displayed op}
  11791. @d big_op_spacing5==mathex(13) {padding above and below displayed limits}
  11792. @d total_mathex_params=13
  11793. @ We also need to compute the change in style between mlists and their
  11794. subsidiaries. The following macros define the subsidiary style for
  11795. an overlined nucleus (|cramped_style|), for a subscript or a superscript
  11796. (|sub_style| or |sup_style|), or for a numerator or denominator (|num_style|
  11797. or |denom_style|).
  11798. @d cramped_style(#)==2*(# div 2)+cramped {cramp the style}
  11799. @d sub_style(#)==2*(# div 4)+script_style+cramped {smaller and cramped}
  11800. @d sup_style(#)==2*(# div 4)+script_style+(# mod 2) {smaller}
  11801. @d num_style(#)==#+2-2*(# div 6) {smaller unless already script-script}
  11802. @d denom_style(#)==2*(# div 2)+cramped+2-2*(# div 6) {smaller, cramped}
  11803. @ When the style changes, the following piece of program computes associated
  11804. information:
  11805. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>=
  11806. begin if cur_style<script_style then cur_size:=text_size
  11807. else cur_size:=16*((cur_style-text_style) div 2);
  11808. cur_mu:=x_over_n(math_quad(cur_size),18);
  11809. @ Here is a function that returns a pointer to a rule node having a given
  11810. thickness |t|. The rule will extend horizontally to the boundary of the vlist
  11811. that eventually contains it.
  11812. @p function fraction_rule(@!t:scaled):pointer;
  11813.   {construct the bar for a fraction}
  11814. var p:pointer; {the new node}
  11815. begin p:=new_rule; height(p):=t; depth(p):=0; fraction_rule:=p;
  11816. @ The |overbar| function returns a pointer to a vlist box that consists of
  11817. a given box |b|, above which has been placed a kern of height |k| under a
  11818. fraction rule of thickness |t| under additional space of height |t|.
  11819. @p function overbar(@!b:pointer;@!k,@!t:scaled):pointer;
  11820. var p,@!q:pointer; {nodes being constructed}
  11821. begin p:=new_kern(k); link(p):=b; q:=fraction_rule(t); link(q):=p;
  11822. p:=new_kern(t); link(p):=q; overbar:=vpack(p,natural);
  11823. @ The |var_delimiter| function, which finds or constructs a sufficiently
  11824. large delimiter, is the most interesting of the auxiliary functions that
  11825. currently concern us. Given a pointer |d| to a delimiter field in some noad,
  11826. together with a size code |s| and a vertical distance |v|, this function
  11827. returns a pointer to a box that contains the smallest variant of |d| whose
  11828. height plus depth is |v| or more. (And if no variant is large enough, it
  11829. returns the largest available variant.) In particular, this routine will
  11830. construct arbitrarily large delimiters from extensible components, if
  11831. |d| leads to such characters.
  11832. The value returned is a box whose |shift_amount| has been set so that
  11833. the box is vertically centered with respect to the axis in the given size.
  11834. If a built-up symbol is returned, the height of the box before shifting
  11835. will be the height of its topmost component.
  11836. @p@t\4@>@<Declare subprocedures for |var_delimiter|@>
  11837. function var_delimiter(@!d:pointer;@!s:small_number;@!v:scaled):pointer;
  11838. label found,continue;
  11839. var b:pointer; {the box that will be constructed}
  11840. @!f,@!g: internal_font_number; {best-so-far and tentative font codes}
  11841. @!c,@!x,@!y: quarterword; {best-so-far and tentative character codes}
  11842. @!m,@!n: integer; {the number of extensible pieces}
  11843. @!u: scaled; {height-plus-depth of a tentative character}
  11844. @!w: scaled; {largest height-plus-depth so far}
  11845. @!q: four_quarters; {character info}
  11846. @!hd: eight_bits; {height-depth byte}
  11847. @!r: four_quarters; {extensible pieces}
  11848. @!z: small_number; {runs through font family members}
  11849. @!large_attempt: boolean; {are we trying the ``large'' variant?}
  11850. begin f:=null_font; w:=0; large_attempt:=false;
  11851. z:=small_fam(d); x:=small_char(d);
  11852. loop@+  begin @<Look at the variants of |(z,x)|; set |f| and |c| whenever
  11853.     a better character is found; |goto found| as soon as a
  11854.     large enough variant is encountered@>;
  11855.   if large_attempt then goto found; {there were none large enough}
  11856.   large_attempt:=true; z:=large_fam(d); x:=large_char(d);
  11857.   end;
  11858. found: if f<>null_font then
  11859.   @<Make variable |b| point to a box for |(f,c)|@>
  11860. else  begin b:=new_null_box;
  11861.   width(b):=null_delimiter_space; {use this width if no delimiter was found}
  11862.   end;
  11863. shift_amount(b):=half(height(b)-depth(b)) - axis_height(s);
  11864. var_delimiter:=b;
  11865. @ The search process is complicated slightly by the facts that some of the
  11866. characters might not be present in some of the fonts, and they might not
  11867. be probed in increasing order of height.
  11868. @<Look at the variants of |(z,x)|; set |f| and |c|...@>=
  11869. if (z<>0)or(x<>min_quarterword) then
  11870.   begin z:=z+s+16;
  11871.   repeat z:=z-16; g:=fam_fnt(z);
  11872.   if g<>null_font then
  11873.     @<Look at the list of characters starting with |x| in
  11874.       font |g|; set |f| and |c| whenever
  11875.       a better character is found; |goto found| as soon as a
  11876.       large enough variant is encountered@>;
  11877.   until z<16;
  11878.   end
  11879. @ @<Look at the list of characters starting with |x|...@>=
  11880. begin y:=x;
  11881. if (qo(y)>=font_bc[g])and(qo(y)<=font_ec[g]) then
  11882.   begin continue: q:=char_info(g)(y);
  11883.   if char_exists(q) then
  11884.     begin if char_tag(q)=ext_tag then
  11885.       begin f:=g; c:=y; goto found;
  11886.       end;
  11887.     hd:=height_depth(q);
  11888.     u:=char_height(g)(hd)+char_depth(g)(hd);
  11889.     if u>w then
  11890.       begin f:=g; c:=y; w:=u;
  11891.       if u>=v then goto found;
  11892.       end;
  11893.     if char_tag(q)=list_tag then
  11894.       begin y:=rem_byte(q); goto continue;
  11895.       end;
  11896.     end;
  11897.   end;
  11898. @ Here is a subroutine that creates a new box, whose list contains a
  11899. single character, and whose width includes the italic correction for
  11900. that character. The height or depth of the box will be negative, if
  11901. the height or depth of the character is negative; thus, this routine
  11902. may deliver a slightly different result than |hpack| would produce.
  11903. @<Declare subprocedures for |var_delimiter|@>=
  11904. function char_box(@!f:internal_font_number;@!c:quarterword):pointer;
  11905. var q:four_quarters;
  11906. @!hd:eight_bits; {|height_depth| byte}
  11907. @!b,@!p:pointer; {the new box and its character node}
  11908. begin q:=char_info(f)(c); hd:=height_depth(q);
  11909. b:=new_null_box; width(b):=char_width(f)(q)+char_italic(f)(q);
  11910. height(b):=char_height(f)(hd); depth(b):=char_depth(f)(hd);
  11911. p:=get_avail; character(p):=c; font(p):=f; list_ptr(b):=p; char_box:=b;
  11912. @ When the following code is executed, |char_tag(q)| will be equal to
  11913. |ext_tag| if and only if a built-up symbol is supposed to be returned.
  11914. @<Make variable |b| point to a box for |(f,c)|@>=
  11915. if char_tag(q)=ext_tag then
  11916.   @<Construct an extensible character in a new box |b|,
  11917.     using recipe |rem_byte(q)| and font |f|@>
  11918. else b:=char_box(f,c)
  11919. @ When we build an extensible character, it's handy to have the
  11920. following subroutine, which puts a given character on top
  11921. of the characters already in box |b|:
  11922. @<Declare subprocedures for |var_delimiter|@>=
  11923. procedure stack_into_box(@!b:pointer;@!f:internal_font_number;
  11924.   @!c:quarterword);
  11925. var p:pointer; {new node placed into |b|}
  11926. begin p:=char_box(f,c); link(p):=list_ptr(b); list_ptr(b):=p;
  11927. height(b):=height(p);
  11928. @ Another handy subroutine computes the height plus depth of
  11929. a given character:
  11930. @<Declare subprocedures for |var_delimiter|@>=
  11931. function height_plus_depth(@!f:internal_font_number;@!c:quarterword):scaled;
  11932. var q:four_quarters;
  11933. @!hd:eight_bits; {|height_depth| byte}
  11934. begin q:=char_info(f)(c); hd:=height_depth(q);
  11935. height_plus_depth:=char_height(f)(hd)+char_depth(f)(hd);
  11936. @ @<Construct an extensible...@>=
  11937. begin b:=new_null_box;
  11938. type(b):=vlist_node;
  11939. r:=font_info[exten_base[f]+rem_byte(q)].qqqq;@/
  11940. @<Compute the minimum suitable height, |w|, and the corresponding
  11941.   number of extension steps, |n|; also set |width(b)|@>;
  11942. c:=ext_bot(r);
  11943. if c<>min_quarterword then stack_into_box(b,f,c);
  11944. c:=ext_rep(r);
  11945. for m:=1 to n do stack_into_box(b,f,c);
  11946. c:=ext_mid(r);
  11947. if c<>min_quarterword then
  11948.   begin stack_into_box(b,f,c); c:=ext_rep(r);
  11949.   for m:=1 to n do stack_into_box(b,f,c);
  11950.   end;
  11951. c:=ext_top(r);
  11952. if c<>min_quarterword then stack_into_box(b,f,c);
  11953. depth(b):=w-height(b);
  11954. @ The width of an extensible character is the width of the repeatable
  11955. module. If this module does not have positive height plus depth,
  11956. we don't use any copies of it, otherwise we use as few as possible
  11957. (in groups of two if there is a middle part).
  11958. @<Compute the minimum suitable height, |w|, and...@>=
  11959. c:=ext_rep(r); u:=height_plus_depth(f,c);
  11960. w:=0; q:=char_info(f)(c); width(b):=char_width(f)(q)+char_italic(f)(q);@/
  11961. c:=ext_bot(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
  11962. c:=ext_mid(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
  11963. c:=ext_top(r);@+if c<>min_quarterword then w:=w+height_plus_depth(f,c);
  11964. n:=0;
  11965. if u>0 then while w<v do
  11966.   begin w:=w+u; incr(n);
  11967.   if ext_mid(r)<>min_quarterword then w:=w+u;
  11968.   end
  11969. @ The next subroutine is much simpler; it is used for numerators and
  11970. denominators of fractions as well as for displayed operators and
  11971. their limits above and below. It takes a given box~|b| and
  11972. changes it so that the new box is centered in a box of width~|w|.
  11973. The centering is done by putting \.{\\hss} glue at the left and right
  11974. of the list inside |b|, then packaging the new box; thus, the
  11975. actual box might not really be centered, if it already contains
  11976. infinite glue.
  11977. The given box might contain a single character whose italic correction
  11978. has been added to the width of the box; in this case a compensating
  11979. kern is inserted.
  11980. @p function rebox(@!b:pointer;@!w:scaled):pointer;
  11981. var p:pointer; {temporary register for list manipulation}
  11982. @!f:internal_font_number; {font in a one-character box}
  11983. @!v:scaled; {width of a character without italic correction}
  11984. begin if (width(b)<>w)and(list_ptr(b)<>null) then
  11985.   begin if type(b)=vlist_node then b:=hpack(b,natural);
  11986.   p:=list_ptr(b);
  11987.   if (is_char_node(p))and(link(p)=null) then
  11988.     begin f:=font(p); v:=char_width(f)(char_info(f)(character(p)));
  11989.     if v<>width(b) then link(p):=new_kern(width(b)-v);
  11990.     end;
  11991.   free_node(b,box_node_size);
  11992.   b:=new_glue(ss_glue); link(b):=p;
  11993.   while link(p)<>null do p:=link(p);
  11994.   link(p):=new_glue(ss_glue);
  11995.   rebox:=hpack(b,w,exactly);
  11996.   end
  11997. else  begin width(b):=w; rebox:=b;
  11998.   end;
  11999. @ Here is a subroutine that creates a new glue specification from another
  12000. one that is expressed in `\.{mu}', given the value of the math unit.
  12001. @d mu_mult(#)==nx_plus_y(n,#,xn_over_d(#,f,@'200000))
  12002. @p function math_glue(@!g:pointer;@!m:scaled):pointer;
  12003. var p:pointer; {the new glue specification}
  12004. @!n:integer; {integer part of |m|}
  12005. @!f:scaled; {fraction part of |m|}
  12006. begin n:=x_over_n(m,@'200000); f:=remainder;@/
  12007. if f<0 then
  12008.   begin decr(n); f:=f+@'200000;
  12009.   end;
  12010. p:=get_node(glue_spec_size);
  12011. width(p):=mu_mult(width(g)); {convert \.{mu} to \.{pt}}
  12012. stretch_order(p):=stretch_order(g);
  12013. if stretch_order(p)=normal then stretch(p):=mu_mult(stretch(g))
  12014. else stretch(p):=stretch(g);
  12015. shrink_order(p):=shrink_order(g);
  12016. if shrink_order(p)=normal then shrink(p):=mu_mult(shrink(g))
  12017. else shrink(p):=shrink(g);
  12018. math_glue:=p;
  12019. @ The |math_kern| subroutine removes |mu_glue| from a kern node, given
  12020. the value of the math unit.
  12021. @p procedure math_kern(@!p:pointer;@!m:scaled);
  12022. var @!n:integer; {integer part of |m|}
  12023. @!f:scaled; {fraction part of |m|}
  12024. begin if subtype(p)=mu_glue then
  12025.   begin n:=x_over_n(m,@'200000); f:=remainder;@/
  12026.   if f<0 then
  12027.     begin decr(n); f:=f+@'200000;
  12028.     end;
  12029.   width(p):=mu_mult(width(p)); subtype(p):=normal;
  12030.   end;
  12031. @ Sometimes it is necessary to destroy an mlist. The following
  12032. subroutine empties the current list, assuming that |abs(mode)=mmode|.
  12033. @p procedure flush_math;
  12034. begin flush_node_list(link(head)); flush_node_list(incompleat_noad);
  12035. link(head):=null; tail:=head; incompleat_noad:=null;
  12036. @* \[36] Typesetting math formulas.
  12037. \TeX's most important routine for dealing with formulas is called
  12038. |mlist_to_hlist|.  After a formula has been scanned and represented as an
  12039. mlist, this routine converts it to an hlist that can be placed into a box
  12040. or incorporated into the text of a paragraph. There are three implicit
  12041. parameters, passed in global variables: |cur_mlist| points to the first
  12042. node or noad in the given mlist (and it might be |null|); |cur_style| is a
  12043. style code; and |mlist_penalties| is |true| if penalty nodes for potential
  12044. line breaks are to be inserted into the resulting hlist. After
  12045. |mlist_to_hlist| has acted, |link(temp_head)| points to the translated hlist.
  12046. Since mlists can be inside mlists, the procedure is recursive. And since this
  12047. is not part of \TeX's inner loop, the program has been written in a manner
  12048. that stresses compactness over efficiency.
  12049. @^recursion@>
  12050. @<Glob...@>=
  12051. @!cur_mlist:pointer; {beginning of mlist to be translated}
  12052. @!cur_style:small_number; {style code at current place in the list}
  12053. @!cur_size:small_number; {size code corresponding to |cur_style|}
  12054. @!cur_mu:scaled; {the math unit width corresponding to |cur_size|}
  12055. @!mlist_penalties:boolean; {should |mlist_to_hlist| insert penalties?}
  12056. @ The recursion in |mlist_to_hlist| is due primarily to a subroutine
  12057. called |clean_box| that puts a given noad field into a box using a given
  12058. math style; |mlist_to_hlist| can call |clean_box|, which can call
  12059. |mlist_to_hlist|.
  12060. @^recursion@>
  12061. The box returned by |clean_box| is ``clean'' in the
  12062. sense that its |shift_amount| is zero.
  12063. @p procedure@?mlist_to_hlist; forward;@t\2@>@/
  12064. function clean_box(@!p:pointer;@!s:small_number):pointer;
  12065. label found;
  12066. var q:pointer; {beginning of a list to be boxed}
  12067. @!save_style:small_number; {|cur_style| to be restored}
  12068. @!x:pointer; {box to be returned}
  12069. @!r:pointer; {temporary pointer}
  12070. begin case math_type(p) of
  12071. math_char: begin cur_mlist:=new_noad; mem[nucleus(cur_mlist)]:=mem[p];
  12072.   end;
  12073. sub_box: begin q:=info(p); goto found;
  12074.   end;
  12075. sub_mlist: cur_mlist:=info(p);
  12076. othercases begin q:=new_null_box; goto found;
  12077.   end
  12078. endcases;@/
  12079. save_style:=cur_style; cur_style:=s; mlist_penalties:=false;@/
  12080. mlist_to_hlist; q:=link(temp_head); {recursive call}
  12081. cur_style:=save_style; {restore the style}
  12082. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12083. found: if is_char_node(q)or(q=null) then x:=hpack(q,natural)
  12084.   else if (link(q)=null)and(type(q)<=vlist_node)and(shift_amount(q)=0) then
  12085.     x:=q {it's already clean}
  12086.   else x:=hpack(q,natural);
  12087. @<Simplify a trivial box@>;
  12088. clean_box:=x;
  12089. @ Here we save memory space in a common case.
  12090. @<Simplify a trivial box@>=
  12091. q:=list_ptr(x);
  12092. if is_char_node(q) then
  12093.   begin r:=link(q);
  12094.   if r<>null then if link(r)=null then
  12095.    if not is_char_node(r) then if type(r)=kern_node then
  12096.     begin free_node(r,small_node_size); link(q):=null;
  12097.     end;
  12098.   end
  12099. @ It is convenient to have a procedure that converts a |math_char|
  12100. field to an ``unpacked'' form. The |fetch| routine sets |cur_f|, |cur_c|,
  12101. and |cur_i| to the font code, character code, and character information bytes of
  12102. a given noad field. It also takes care of issuing error messages for
  12103. nonexistent characters; in such cases, |char_exists(cur_i)| will be |false|
  12104. after |fetch| has acted, and the field will also have been reset to |empty|.
  12105. @p procedure fetch(@!a:pointer); {unpack the |math_char| field |a|}
  12106. begin cur_c:=character(a); cur_f:=fam_fnt(fam(a)+cur_size);
  12107. if cur_f=null_font then
  12108.   @<Complain about an undefined family and set |cur_i| null@>
  12109. else  begin if (qo(cur_c)>=font_bc[cur_f])and(qo(cur_c)<=font_ec[cur_f]) then
  12110.     cur_i:=char_info(cur_f)(cur_c)
  12111.   else cur_i:=null_character;
  12112.   if not(char_exists(cur_i)) then
  12113.     begin char_warning(cur_f,qo(cur_c));
  12114.     math_type(a):=empty;
  12115.     end;
  12116.   end;
  12117. @ @<Complain about an undefined family...@>=
  12118. begin print_err(""); print_size(cur_size); print_char(" ");
  12119. print_int(fam(a)); print(" is undefined (character ");
  12120. print_ASCII(qo(cur_c)); print_char(")");
  12121. help4("Somewhere in the math formula just ended, you used the")@/
  12122. ("stated character from an undefined font family. For example,")@/
  12123. ("plain TeX doesn't allow \it or \sl in subscripts. Proceed,")@/
  12124. ("and I'll try to forget that I needed that character.");
  12125. error; cur_i:=null_character; math_type(a):=empty;
  12126. @ The outputs of |fetch| are placed in global variables.
  12127. @<Glob...@>=
  12128. @!cur_f:internal_font_number; {the |font| field of a |math_char|}
  12129. @!cur_c:quarterword; {the |character| field of a |math_char|}
  12130. @!cur_i:four_quarters; {the |char_info| of a |math_char|,
  12131.   or a lig/kern instruction}
  12132. @ We need to do a lot of different things, so |mlist_to_hlist| makes two
  12133. passes over the given mlist.
  12134. The first pass does most of the processing: It removes ``mu'' spacing from
  12135. glue, it recursively evaluates all subsidiary mlists so that only the
  12136. top-level mlist remains to be handled, it puts fractions and square roots
  12137. and such things into boxes, it attaches subscripts and superscripts, and
  12138. it computes the overall height and depth of the top-level mlist so that
  12139. the size of delimiters for a |left_noad| and a |right_noad| will be known.
  12140. The hlist resulting from each noad is recorded in that noad's |new_hlist|
  12141. field, an integer field that replaces the |nucleus| or |thickness|.
  12142. @^recursion@>
  12143. The second pass eliminates all noads and inserts the correct glue and
  12144. penalties between nodes.
  12145. @d new_hlist(#)==mem[nucleus(#)].int {the translation of an mlist}
  12146. @ Here is the overall plan of |mlist_to_hlist|, and the list of its
  12147. local variables.
  12148. @d done_with_noad=80 {go here when a noad has been fully translated}
  12149. @d done_with_node=81 {go here when a node has been fully converted}
  12150. @d check_dimensions=82 {go here to update |max_h| and |max_d|}
  12151. @d delete_q=83 {go here to delete |q| and move to the next node}
  12152. @p@t\4@>@<Declare math construction procedures@>
  12153. procedure mlist_to_hlist;
  12154. label reswitch, check_dimensions, done_with_noad, done_with_node, delete_q,
  12155.   done;
  12156. var mlist:pointer; {beginning of the given list}
  12157. @!penalties:boolean; {should penalty nodes be inserted?}
  12158. @!style:small_number; {the given style}
  12159. @!save_style:small_number; {holds |cur_style| during recursion}
  12160. @!q:pointer; {runs through the mlist}
  12161. @!r:pointer; {the most recent noad preceding |q|}
  12162. @!r_type:small_number; {the |type| of noad |r|, or |op_noad| if |r=null|}
  12163. @!t:small_number; {the effective |type| of noad |q| during the second pass}
  12164. @!p,@!x,@!y,@!z: pointer; {temporary registers for list construction}
  12165. @!pen:integer; {a penalty to be inserted}
  12166. @!s:small_number; {the size of a noad to be deleted}
  12167. @!max_h,@!max_d:scaled; {maximum height and depth of the list translated so far}
  12168. @!delta:scaled; {offset between subscript and superscript}
  12169. begin mlist:=cur_mlist; penalties:=mlist_penalties;
  12170. style:=cur_style; {tuck global parameters away as local variables}
  12171. q:=mlist; r:=null; r_type:=op_noad; max_h:=0; max_d:=0;
  12172. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12173. while q<>null do @<Process node-or-noad |q| as much as possible in preparation
  12174.     for the second pass of |mlist_to_hlist|, then move to the next
  12175.     item in the mlist@>;
  12176. @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
  12177. @<Make a second pass over the mlist, removing all noads and inserting the
  12178.   proper spacing and penalties@>;
  12179. @ We use the fact that no character nodes appear in an mlist, hence
  12180. the field |type(q)| is always present.
  12181. @<Process node-or-noad...@>=
  12182. begin @<Do first-pass processing based on |type(q)|; |goto done_with_noad|
  12183.   if a noad has been fully processed, |goto check_dimensions| if it
  12184.   has been translated into |new_hlist(q)|, or |goto done_with_node|
  12185.   if a node has been fully processed@>;
  12186. check_dimensions: z:=hpack(new_hlist(q),natural);
  12187. if height(z)>max_h then max_h:=height(z);
  12188. if depth(z)>max_d then max_d:=depth(z);
  12189. free_node(z,box_node_size);
  12190. done_with_noad: r:=q; r_type:=type(r);
  12191. done_with_node: q:=link(q);
  12192. @ One of the things we must do on the first pass is change a |bin_noad| to
  12193. an |ord_noad| if the |bin_noad| is not in the context of a binary operator.
  12194. The values of |r| and |r_type| make this fairly easy.
  12195. @<Do first-pass processing...@>=
  12196. reswitch: delta:=0;
  12197. case type(q) of
  12198. bin_noad: case r_type of
  12199.   bin_noad,op_noad,rel_noad,open_noad,punct_noad,left_noad:
  12200.     begin type(q):=ord_noad; goto reswitch;
  12201.     end;
  12202.   othercases do_nothing
  12203.   endcases;
  12204. rel_noad,close_noad,punct_noad,right_noad: begin@t@>@;@/
  12205.   @<Convert \(a)a final |bin_noad| to an |ord_noad|@>;
  12206.   if type(q)=right_noad then goto done_with_noad;
  12207.   end;
  12208. @t\4@>@<Cases for noads that can follow a |bin_noad|@>@;
  12209. @t\4@>@<Cases for nodes that can appear in an mlist, after which we
  12210.   |goto done_with_node|@>@;
  12211. othercases confusion("mlist1")
  12212. @:this can't happen mlist1}{\quad mlist1@>
  12213. endcases;@/
  12214. @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>
  12215. @ @<Convert \(a)a final |bin_noad| to an |ord_noad|@>=
  12216. if r_type=bin_noad then type(r):=ord_noad
  12217. @ @<Cases for nodes that can appear in an mlist...@>=
  12218. style_node: begin cur_style:=subtype(q);
  12219.   @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12220.   goto done_with_node;
  12221.   end;
  12222. choice_node: @<Change this node to a style node followed by the correct choice,
  12223.    then |goto done_with_node|@>;
  12224. ins_node,mark_node,adjust_node,
  12225.   whatsit_node,penalty_node,disc_node: goto done_with_node;
  12226. rule_node: begin if height(q)>max_h then max_h:=height(q);
  12227.   if depth(q)>max_d then max_d:=depth(q); goto done_with_node;
  12228.   end;
  12229. glue_node: begin @<Convert \(m)math glue to ordinary glue@>;
  12230.   goto done_with_node;
  12231.   end;
  12232. kern_node: begin math_kern(q,cur_mu); goto done_with_node;
  12233.   end;
  12234. @ @d choose_mlist(#)==begin p:=#(q); #(q):=null;@+end
  12235. @<Change this node to a style node...@>=
  12236. begin case cur_style div 2 of
  12237. 0: choose_mlist(display_mlist); {|display_style=0|}
  12238. 1: choose_mlist(text_mlist); {|text_style=2|}
  12239. 2: choose_mlist(script_mlist); {|script_style=4|}
  12240. 3: choose_mlist(script_script_mlist); {|script_script_style=6|}
  12241. end; {there are no other cases}
  12242. flush_node_list(display_mlist(q));
  12243. flush_node_list(text_mlist(q));
  12244. flush_node_list(script_mlist(q));
  12245. flush_node_list(script_script_mlist(q));@/
  12246. type(q):=style_node; subtype(q):=cur_style; width(q):=0; depth(q):=0;
  12247. if p<>null then
  12248.   begin z:=link(q); link(q):=p;
  12249.   while link(p)<>null do p:=link(p);
  12250.   link(p):=z;
  12251.   end;
  12252. goto done_with_node;
  12253. @ Conditional math glue (`\.{\\nonscript}') results in a |glue_node|
  12254. pointing to |zero_glue|, with |subtype(q)=cond_math_glue|; in such a case
  12255. the node following will be eliminated if it is a glue or kern node and if the
  12256. current size is different from |text_size|. Unconditional math glue
  12257. (`\.{\\muskip}') is converted to normal glue by multiplying the dimensions
  12258. by |cur_mu|.
  12259. @!@:non_script_}{\.{\\nonscript} primitive@>
  12260. @<Convert \(m)math glue to ordinary glue@>=
  12261. if subtype(q)=mu_glue then
  12262.   begin x:=glue_ptr(q);
  12263.   y:=math_glue(x,cur_mu); delete_glue_ref(x); glue_ptr(q):=y;
  12264.   subtype(q):=normal;
  12265.   end
  12266. else if (cur_size<>text_size)and(subtype(q)=cond_math_glue) then
  12267.   begin p:=link(q);
  12268.   if p<>null then if (type(p)=glue_node)or(type(p)=kern_node) then
  12269.       begin link(q):=link(p); link(p):=null; flush_node_list(p);
  12270.       end;
  12271.   end
  12272. @ @<Cases for noads that can follow a |bin_noad|@>=
  12273. left_noad: goto done_with_noad;
  12274. fraction_noad: begin make_fraction(q); goto check_dimensions;
  12275.   end;
  12276. op_noad: begin delta:=make_op(q);
  12277.   if subtype(q)=limits then goto check_dimensions;
  12278.   end;
  12279. ord_noad: make_ord(q);
  12280. open_noad,inner_noad: do_nothing;
  12281. radical_noad: make_radical(q);
  12282. over_noad: make_over(q);
  12283. under_noad: make_under(q);
  12284. accent_noad: make_math_accent(q);
  12285. vcenter_noad: make_vcenter(q);
  12286. @ Most of the actual construction work of |mlist_to_hlist| is done
  12287. by procedures with names
  12288. like |make_fraction|, |make_radical|, etc. To illustrate
  12289. the general setup of such procedures, let's begin with a couple of
  12290. simple ones.
  12291. @<Declare math...@>=
  12292. procedure make_over(@!q:pointer);
  12293. begin info(nucleus(q)):=@|
  12294.   overbar(clean_box(nucleus(q),cramped_style(cur_style)),@|
  12295.   3*default_rule_thickness,default_rule_thickness);
  12296. math_type(nucleus(q)):=sub_box;
  12297. @ @<Declare math...@>=
  12298. procedure make_under(@!q:pointer);
  12299. var p,@!x,@!y: pointer; {temporary registers for box construction}
  12300. @!delta:scaled; {overall height plus depth}
  12301. begin x:=clean_box(nucleus(q),cur_style);
  12302. p:=new_kern(3*default_rule_thickness); link(x):=p;
  12303. link(p):=fraction_rule(default_rule_thickness);
  12304. y:=vpack(x,natural);
  12305. delta:=height(y)+depth(y)+default_rule_thickness;
  12306. height(y):=height(x); depth(y):=delta-height(y);
  12307. info(nucleus(q)):=y; math_type(nucleus(q)):=sub_box;
  12308. @ @<Declare math...@>=
  12309. procedure make_vcenter(@!q:pointer);
  12310. var v:pointer; {the box that should be centered vertically}
  12311. @!delta:scaled; {its height plus depth}
  12312. begin v:=info(nucleus(q));
  12313. if type(v)<>vlist_node then confusion("vcenter");
  12314. @:this can't happen vcenter}{\quad vcenter@>
  12315. delta:=height(v)+depth(v);
  12316. height(v):=axis_height(cur_size)+half(delta);
  12317. depth(v):=delta-height(v);
  12318. @ According to the rules in the \.{DVI} file specifications, we ensure alignment
  12319. @^square roots@>
  12320. between a square root sign and the rule above its nucleus by assuming that the
  12321. baseline of the square-root symbol is the same as the bottom of the rule. The
  12322. height of the square-root symbol will be the thickness of the rule, and the
  12323. depth of the square-root symbol should exceed or equal the height-plus-depth
  12324. of the nucleus plus a certain minimum clearance~|clr|. The symbol will be
  12325. placed so that the actual clearance is |clr| plus half the excess.
  12326. @<Declare math...@>=
  12327. procedure make_radical(@!q:pointer);
  12328. var x,@!y:pointer; {temporary registers for box construction}
  12329. @!delta,@!clr:scaled; {dimensions involved in the calculation}
  12330. begin x:=clean_box(nucleus(q),cramped_style(cur_style));
  12331. if cur_style<text_style then {display style}
  12332.   clr:=default_rule_thickness+(abs(math_x_height(cur_size)) div 4)
  12333. else  begin clr:=default_rule_thickness; clr:=clr + (abs(clr) div 4);
  12334.   end;
  12335. y:=var_delimiter(left_delimiter(q),cur_size,height(x)+depth(x)+clr+
  12336.   default_rule_thickness);
  12337. delta:=depth(y)-(height(x)+depth(x)+clr);
  12338. if delta>0 then clr:=clr+half(delta); {increase the actual clearance}
  12339. shift_amount(y):=-(height(x)+clr);
  12340. link(y):=overbar(x,clr,height(y));
  12341. info(nucleus(q)):=hpack(y,natural); math_type(nucleus(q)):=sub_box;
  12342. @ Slants are not considered when placing accents in math mode. The accenter is
  12343. centered over the accentee, and the accent width is treated as zero with
  12344. respect to the size of the final box.
  12345. @<Declare math...@>=
  12346. procedure make_math_accent(@!q:pointer);
  12347. label done,done1;
  12348. var p,@!x,@!y:pointer; {temporary registers for box construction}
  12349. @!a:integer; {address of lig/kern instruction}
  12350. @!c:quarterword; {accent character}
  12351. @!f:internal_font_number; {its font}
  12352. @!i:four_quarters; {its |char_info|}
  12353. @!s:scaled; {amount to skew the accent to the right}
  12354. @!h:scaled; {height of character being accented}
  12355. @!delta:scaled; {space to remove between accent and accentee}
  12356. @!w:scaled; {width of the accentee, not including sub/superscripts}
  12357. begin fetch(accent_chr(q));
  12358. if char_exists(cur_i) then
  12359.   begin i:=cur_i; c:=cur_c; f:=cur_f;@/
  12360.   @<Compute the amount of skew@>;
  12361.   x:=clean_box(nucleus(q),cramped_style(cur_style)); w:=width(x); h:=height(x);
  12362.   @<Switch to a larger accent if available and appropriate@>;
  12363.   if h<x_height(f) then delta:=h@+else delta:=x_height(f);
  12364.   if (math_type(supscr(q))<>empty)or(math_type(subscr(q))<>empty) then
  12365.     if math_type(nucleus(q))=math_char then
  12366.       @<Swap the subscript and superscript into box |x|@>;
  12367.   y:=char_box(f,c);
  12368.   shift_amount(y):=s+half(w-width(y));
  12369.   width(y):=0; p:=new_kern(-delta); link(p):=x; link(y):=p;
  12370.   y:=vpack(y,natural); width(y):=width(x);
  12371.   if height(y)<h then @<Make the height of box |y| equal to |h|@>;
  12372.   info(nucleus(q)):=y;
  12373.   math_type(nucleus(q)):=sub_box;
  12374.   end;
  12375. @ @<Make the height of box |y|...@>=
  12376. begin p:=new_kern(h-height(y)); link(p):=list_ptr(y); list_ptr(y):=p;
  12377. height(y):=h;
  12378. @ @<Switch to a larger accent if available and appropriate@>=
  12379. loop@+  begin if char_tag(i)<>list_tag then goto done;
  12380.   y:=rem_byte(i);
  12381.   i:=char_info(f)(y);
  12382.   if not char_exists(i) then goto done;
  12383.   if char_width(f)(i)>w then goto done;
  12384.   c:=y;
  12385.   end;
  12386. done:
  12387. @ @<Compute the amount of skew@>=
  12388. s:=0;
  12389. if math_type(nucleus(q))=math_char then
  12390.   begin fetch(nucleus(q));
  12391.   if char_tag(cur_i)=lig_tag then
  12392.     begin a:=lig_kern_start(cur_f)(cur_i);
  12393.     cur_i:=font_info[a].qqqq;
  12394.     if skip_byte(cur_i)>stop_flag then
  12395.       begin a:=lig_kern_restart(cur_f)(cur_i);
  12396.       cur_i:=font_info[a].qqqq;
  12397.       end;
  12398.     loop@+ begin if qo(next_char(cur_i))=skew_char[cur_f] then
  12399.         begin if op_byte(cur_i)>=kern_flag then
  12400.           if skip_byte(cur_i)<=stop_flag then s:=char_kern(cur_f)(cur_i);
  12401.         goto done1;
  12402.         end;
  12403.       if skip_byte(cur_i)>=stop_flag then goto done1;
  12404.       a:=a+qo(skip_byte(cur_i))+1;
  12405.       cur_i:=font_info[a].qqqq;
  12406.       end;
  12407.     end;
  12408.   end;
  12409. done1:
  12410. @ @<Swap the subscript and superscript into box |x|@>=
  12411. begin flush_node_list(x); x:=new_noad;
  12412. mem[nucleus(x)]:=mem[nucleus(q)];
  12413. mem[supscr(x)]:=mem[supscr(q)];
  12414. mem[subscr(x)]:=mem[subscr(q)];@/
  12415. mem[supscr(q)].hh:=empty_field;
  12416. mem[subscr(q)].hh:=empty_field;@/
  12417. math_type(nucleus(q)):=sub_mlist; info(nucleus(q)):=x;
  12418. x:=clean_box(nucleus(q),cur_style); delta:=delta+height(x)-h; h:=height(x);
  12419. @ The |make_fraction| procedure is a bit different because it sets
  12420. |new_hlist(q)| directly rather than making a sub-box.
  12421. @<Declare math...@>=
  12422. procedure make_fraction(@!q:pointer);
  12423. var p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
  12424. @!delta,@!delta1,@!delta2,@!shift_up,@!shift_down,@!clr:scaled;
  12425.   {dimensions for box calculations}
  12426. begin if thickness(q)=default_code then thickness(q):=default_rule_thickness;
  12427. @<Create equal-width boxes |x| and |z| for the numerator and denominator,
  12428.   and compute the default amounts |shift_up| and |shift_down| by which they
  12429.   are displaced from the baseline@>;
  12430. if thickness(q)=0 then @<Adjust \(s)|shift_up| and |shift_down| for the case
  12431.   of no fraction line@>
  12432. else @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>;
  12433. @<Construct a vlist box for the fraction, according to |shift_up| and
  12434.   |shift_down|@>;
  12435. @<Put the \(f)fraction into a box with its delimiters, and make |new_hlist(q)|
  12436.   point to it@>;
  12437. @ @<Create equal-width boxes |x| and |z| for the numerator and denom...@>=
  12438. x:=clean_box(numerator(q),num_style(cur_style));
  12439. z:=clean_box(denominator(q),denom_style(cur_style));
  12440. if width(x)<width(z) then x:=rebox(x,width(z))
  12441. else z:=rebox(z,width(x));
  12442. if cur_style<text_style then {text style}
  12443.   begin shift_up:=num1(cur_size); shift_down:=denom1(cur_size);
  12444.   end
  12445. else  begin shift_down:=denom2(cur_size);
  12446.   if thickness(q)<>0 then shift_up:=num2(cur_size)
  12447.   else shift_up:=num3(cur_size);
  12448.   end
  12449. @ The numerator and denominator must be separated by a certain minimum
  12450. clearance, called |clr| in the following program. The difference between
  12451. |clr| and the actual clearance is |2delta|.
  12452. @<Adjust \(s)|shift_up| and |shift_down| for the case of no fraction line@>=
  12453. begin if cur_style<text_style then clr:=7*default_rule_thickness
  12454. else clr:=3*default_rule_thickness;
  12455. delta:=half(clr-((shift_up-depth(x))-(height(z)-shift_down)));
  12456. if delta>0 then
  12457.   begin shift_up:=shift_up+delta;
  12458.   shift_down:=shift_down+delta;
  12459.   end;
  12460. @ In the case of a fraction line, the minimum clearance depends on the actual
  12461. thickness of the line.
  12462. @<Adjust \(s)|shift_up| and |shift_down| for the case of a fraction line@>=
  12463. begin if cur_style<text_style then clr:=3*thickness(q)
  12464. else clr:=thickness(q);
  12465. delta:=half(thickness(q));
  12466. delta1:=clr-((shift_up-depth(x))-(axis_height(cur_size)+delta));
  12467. delta2:=clr-((axis_height(cur_size)-delta)-(height(z)-shift_down));
  12468. if delta1>0 then shift_up:=shift_up+delta1;
  12469. if delta2>0 then shift_down:=shift_down+delta2;
  12470. @ @<Construct a vlist box for the fraction...@>=
  12471. v:=new_null_box; type(v):=vlist_node;
  12472. height(v):=shift_up+height(x); depth(v):=depth(z)+shift_down;
  12473. width(v):=width(x); {this also equals |width(z)|}
  12474. if thickness(q)=0 then
  12475.   begin p:=new_kern((shift_up-depth(x))-(height(z)-shift_down));
  12476.   link(p):=z;
  12477.   end
  12478. else  begin y:=fraction_rule(thickness(q));@/
  12479.   p:=new_kern((axis_height(cur_size)-delta)-@|(height(z)-shift_down));@/
  12480.   link(y):=p; link(p):=z;@/
  12481.   p:=new_kern((shift_up-depth(x))-(axis_height(cur_size)+delta));
  12482.   link(p):=y;
  12483.   end;
  12484. link(x):=p; list_ptr(v):=x
  12485. @ @<Put the \(f)fraction into a box with its delimiters...@>=
  12486. if cur_style<text_style then delta:=delim1(cur_size)
  12487. else delta:=delim2(cur_size);
  12488. x:=var_delimiter(left_delimiter(q), cur_size, delta); link(x):=v;@/
  12489. z:=var_delimiter(right_delimiter(q), cur_size, delta); link(v):=z;@/
  12490. new_hlist(q):=hpack(x,natural)
  12491. @ If the nucleus of an |op_noad| is a single character, it is to be
  12492. centered vertically with respect to the axis, after first being enlarged
  12493. (via a character list in the font) if we are in display style.  The normal
  12494. convention for placing displayed limits is to put them above and below the
  12495. operator in display style.
  12496. The italic correction is removed from the character if there is a subscript
  12497. and the limits are not being displayed. The |make_op|
  12498. routine returns the value that should be used as an offset between
  12499. subscript and superscript.
  12500. After |make_op| has acted, |subtype(q)| will be |limits| if and only if
  12501. the limits have been set above and below the operator. In that case,
  12502. |new_hlist(q)| will already contain the desired final box.
  12503. @<Declare math...@>=
  12504. function make_op(@!q:pointer):scaled;
  12505. var delta:scaled; {offset between subscript and superscript}
  12506. @!p,@!v,@!x,@!y,@!z:pointer; {temporary registers for box construction}
  12507. @!c:quarterword;@+@!i:four_quarters; {registers for character examination}
  12508. @!shift_up,@!shift_down:scaled; {dimensions for box calculation}
  12509. begin if (subtype(q)=normal)and(cur_style<text_style) then
  12510.   subtype(q):=limits;
  12511. if math_type(nucleus(q))=math_char then
  12512.   begin fetch(nucleus(q));
  12513.   if (cur_style<text_style)and(char_tag(cur_i)=list_tag) then {make it larger}
  12514.     begin c:=rem_byte(cur_i); i:=char_info(cur_f)(c);
  12515.     if char_exists(i) then
  12516.       begin cur_c:=c; cur_i:=i; character(nucleus(q)):=c;
  12517.       end;
  12518.     end;
  12519.   delta:=char_italic(cur_f)(cur_i); x:=clean_box(nucleus(q),cur_style);
  12520.   if (math_type(subscr(q))<>empty)and(subtype(q)<>limits) then
  12521.     width(x):=width(x)-delta; {remove italic correction}
  12522.   shift_amount(x):=half(height(x)-depth(x)) - axis_height(cur_size);
  12523.     {center vertically}
  12524.   math_type(nucleus(q)):=sub_box; info(nucleus(q)):=x;
  12525.   end
  12526. else delta:=0;
  12527. if subtype(q)=limits then
  12528.   @<Construct a box with limits above and below it, skewed by |delta|@>;
  12529. make_op:=delta;
  12530. @ The following program builds a vlist box |v| for displayed limits. The
  12531. width of the box is not affected by the fact that the limits may be skewed.
  12532. @<Construct a box with limits above and below it...@>=
  12533. begin x:=clean_box(supscr(q),sup_style(cur_style));
  12534. y:=clean_box(nucleus(q),cur_style);
  12535. z:=clean_box(subscr(q),sub_style(cur_style));
  12536. v:=new_null_box; type(v):=vlist_node; width(v):=width(y);
  12537. if width(x)>width(v) then width(v):=width(x);
  12538. if width(z)>width(v) then width(v):=width(z);
  12539. x:=rebox(x,width(v)); y:=rebox(y,width(v)); z:=rebox(z,width(v));@/
  12540. shift_amount(x):=half(delta); shift_amount(z):=-shift_amount(x);
  12541. height(v):=height(y); depth(v):=depth(y);
  12542. @<Attach the limits to |y| and adjust |height(v)|, |depth(v)| to
  12543.   account for their presence@>;
  12544. new_hlist(q):=v;
  12545. @ We use |shift_up| and |shift_down| in the following program for the
  12546. amount of glue between the displayed operator |y| and its limits |x| and
  12547. |z|. The vlist inside box |v| will consist of |x| followed by |y| followed
  12548. by |z|, with kern nodes for the spaces between and around them.
  12549. @<Attach the limits to |y| and adjust |height(v)|, |depth(v)|...@>=
  12550. if math_type(supscr(q))=empty then
  12551.   begin free_node(x,box_node_size); list_ptr(v):=y;
  12552.   end
  12553. else  begin shift_up:=big_op_spacing3-depth(x);
  12554.   if shift_up<big_op_spacing1 then shift_up:=big_op_spacing1;
  12555.   p:=new_kern(shift_up); link(p):=y; link(x):=p;@/
  12556.   p:=new_kern(big_op_spacing5); link(p):=x; list_ptr(v):=p;
  12557.   height(v):=height(v)+big_op_spacing5+height(x)+depth(x)+shift_up;
  12558.   end;
  12559. if math_type(subscr(q))=empty then free_node(z,box_node_size)
  12560. else  begin shift_down:=big_op_spacing4-height(z);
  12561.   if shift_down<big_op_spacing2 then shift_down:=big_op_spacing2;
  12562.   p:=new_kern(shift_down); link(y):=p; link(p):=z;@/
  12563.   p:=new_kern(big_op_spacing5); link(z):=p;
  12564.   depth(v):=depth(v)+big_op_spacing5+height(z)+depth(z)+shift_down;
  12565.   end
  12566. @ A ligature found in a math formula does not create a |ligature_node|, because
  12567. there is no question of hyphenation afterwards; the ligature will simply be
  12568. stored in an ordinary |char_node|, after residing in an |ord_noad|.
  12569. The |math_type| is converted to |math_text_char| here if we would not want to
  12570. apply an italic correction to the current character unless it belongs
  12571. to a math font (i.e., a font with |space=0|).
  12572. No boundary characters enter into these ligatures.
  12573. @<Declare math...@>=
  12574. procedure make_ord(@!q:pointer);
  12575. label restart,exit;
  12576. var a:integer; {address of lig/kern instruction}
  12577. @!p,@!r:pointer; {temporary registers for list manipulation}
  12578. begin restart:@t@>@;@/
  12579. if math_type(subscr(q))=empty then if math_type(supscr(q))=empty then
  12580.  if math_type(nucleus(q))=math_char then
  12581.   begin p:=link(q);
  12582.   if p<>null then if (type(p)>=ord_noad)and(type(p)<=punct_noad) then
  12583.     if math_type(nucleus(p))=math_char then
  12584.     if fam(nucleus(p))=fam(nucleus(q)) then
  12585.       begin math_type(nucleus(q)):=math_text_char;
  12586.       fetch(nucleus(q));
  12587.       if char_tag(cur_i)=lig_tag then
  12588.         begin a:=lig_kern_start(cur_f)(cur_i);
  12589.         cur_c:=character(nucleus(p));
  12590.         cur_i:=font_info[a].qqqq;
  12591.         if skip_byte(cur_i)>stop_flag then
  12592.           begin a:=lig_kern_restart(cur_f)(cur_i);
  12593.           cur_i:=font_info[a].qqqq;
  12594.           end;
  12595.         loop@+ begin @<If instruction |cur_i| is a kern with |cur_c|, attach
  12596.             the kern after~|q|; or if it is a ligature with |cur_c|, combine
  12597.             noads |q| and~|p| appropriately; then |return| if the cursor has
  12598.             moved past a noad, or |goto restart|@>;
  12599.           if skip_byte(cur_i)>=stop_flag then return;
  12600.           a:=a+qo(skip_byte(cur_i))+1;
  12601.           cur_i:=font_info[a].qqqq;
  12602.           end;
  12603.         end;
  12604.       end;
  12605.   end;
  12606. exit:end;
  12607. @ Note that a ligature between an |ord_noad| and another kind of noad
  12608. is replaced by an |ord_noad|, when the two noads collapse into one.
  12609. But we could make a parenthesis (say) change shape when it follows
  12610. certain letters. Presumably a font designer will define such
  12611. ligatures only when this convention makes sense.
  12612. \chardef\?='174 % vertical line to indicate character retention
  12613. @<If instruction |cur_i| is a kern with |cur_c|, ...@>=
  12614. if next_char(cur_i)=cur_c then if skip_byte(cur_i)<=stop_flag then
  12615.   if op_byte(cur_i)>=kern_flag then
  12616.     begin p:=new_kern(char_kern(cur_f)(cur_i));
  12617.     link(p):=link(q); link(q):=p; return;
  12618.     end
  12619.   else  begin check_interrupt; {allow a way out of infinite ligature loop}
  12620.     case op_byte(cur_i) of
  12621.   qi(1),qi(5): character(nucleus(q)):=rem_byte(cur_i); {\.{=:\?}, \.{=:\?>}}
  12622.   qi(2),qi(6): character(nucleus(p)):=rem_byte(cur_i); {\.{\?=:}, \.{\?=:>}}
  12623.   qi(3),qi(7),qi(11):begin r:=new_noad; {\.{\?=:\?}, \.{\?=:\?>}, \.{\?=:\?>>}}
  12624.       character(nucleus(r)):=rem_byte(cur_i);
  12625.       fam(nucleus(r)):=fam(nucleus(q));@/
  12626.       link(q):=r; link(r):=p;
  12627.       if op_byte(cur_i)<qi(11) then math_type(nucleus(r)):=math_char
  12628.       else math_type(nucleus(r)):=math_text_char; {prevent combination}
  12629.       end;
  12630.     othercases begin link(q):=link(p);
  12631.       character(nucleus(q)):=rem_byte(cur_i); {\.{=:}}
  12632.       mem[subscr(q)]:=mem[subscr(p)]; mem[supscr(q)]:=mem[supscr(p)];@/
  12633.       free_node(p,noad_size);
  12634.       end
  12635.     endcases;
  12636.     if op_byte(cur_i)>qi(3) then return;
  12637.     math_type(nucleus(q)):=math_char; goto restart;
  12638.     end
  12639. @ When we get to the following part of the program, we have ``fallen through''
  12640. from cases that did not lead to |check_dimensions| or |done_with_noad| or
  12641. |done_with_node|. Thus, |q|~points to a noad whose nucleus may need to be
  12642. converted to an hlist, and whose subscripts and superscripts need to be
  12643. appended if they are present.
  12644. If |nucleus(q)| is not a |math_char|, the variable |delta| is the amount
  12645. by which a superscript should be moved right with respect to a subscript
  12646. when both are present.
  12647. @^subscripts@>
  12648. @^superscripts@>
  12649. @<Convert \(n)|nucleus(q)| to an hlist and attach the sub/superscripts@>=
  12650. case math_type(nucleus(q)) of
  12651. math_char, math_text_char:
  12652.   @<Create a character node |p| for |nucleus(q)|, possibly followed
  12653.   by a kern node for the italic correction, and set |delta| to the
  12654.   italic correction if a subscript is present@>;
  12655. empty: p:=null;
  12656. sub_box: p:=info(nucleus(q));
  12657. sub_mlist: begin cur_mlist:=info(nucleus(q)); save_style:=cur_style;
  12658.   mlist_penalties:=false; mlist_to_hlist; {recursive call}
  12659. @^recursion@>
  12660.   cur_style:=save_style; @<Set up the values...@>;
  12661.   p:=hpack(link(temp_head),natural);
  12662.   end;
  12663. othercases confusion("mlist2")
  12664. @:this can't happen mlist2}{\quad mlist2@>
  12665. endcases;@/
  12666. new_hlist(q):=p;
  12667. if (math_type(subscr(q))=empty)and(math_type(supscr(q))=empty) then
  12668.   goto check_dimensions;
  12669. make_scripts(q,delta)
  12670. @ @<Create a character node |p| for |nucleus(q)|...@>=
  12671. begin fetch(nucleus(q));
  12672. if char_exists(cur_i) then
  12673.   begin delta:=char_italic(cur_f)(cur_i); p:=new_character(cur_f,qo(cur_c));
  12674.   if (math_type(nucleus(q))=math_text_char)and(space(cur_f)<>0) then
  12675.     delta:=0; {no italic correction in mid-word of text font}
  12676.   if (math_type(subscr(q))=empty)and(delta<>0) then
  12677.     begin link(p):=new_kern(delta); delta:=0;
  12678.     end;
  12679.   end
  12680. else p:=null;
  12681. @ The purpose of |make_scripts(q,delta)| is to attach the subscript and/or
  12682. superscript of noad |q| to the list that starts at |new_hlist(q)|,
  12683. given that subscript and superscript aren't both empty. The superscript
  12684. will appear to the right of the subscript by a given distance |delta|.
  12685. We set |shift_down| and |shift_up| to the minimum amounts to shift the
  12686. baseline of subscripts and superscripts based on the given nucleus.
  12687. @<Declare math...@>=
  12688. procedure make_scripts(@!q:pointer;@!delta:scaled);
  12689. var p,@!x,@!y,@!z:pointer; {temporary registers for box construction}
  12690. @!shift_up,@!shift_down,@!clr:scaled; {dimensions in the calculation}
  12691. @!t:small_number; {subsidiary size code}
  12692. begin p:=new_hlist(q);
  12693. if is_char_node(p) then
  12694.   begin shift_up:=0; shift_down:=0;
  12695.   end
  12696. else  begin z:=hpack(p,natural);
  12697.   if cur_style<script_style then t:=script_size@+else t:=script_script_size;
  12698.   shift_up:=height(z)-sup_drop(t);
  12699.   shift_down:=depth(z)+sub_drop(t);
  12700.   free_node(z,box_node_size);
  12701.   end;
  12702. if math_type(supscr(q))=empty then
  12703.   @<Construct a subscript box |x| when there is no superscript@>
  12704. else  begin @<Construct a superscript box |x|@>;
  12705.   if math_type(subscr(q))=empty then shift_amount(x):=-shift_up
  12706.   else @<Construct a sub/superscript combination box |x|, with the
  12707.     superscript offset by |delta|@>;
  12708.   end;
  12709. if new_hlist(q)=null then new_hlist(q):=x
  12710. else  begin p:=new_hlist(q);
  12711.   while link(p)<>null do p:=link(p);
  12712.   link(p):=x;
  12713.   end;
  12714. @ When there is a subscript without a superscript, the top of the subscript
  12715. should not exceed the baseline plus four-fifths of the x-height.
  12716. @<Construct a subscript box |x| when there is no superscript@>=
  12717. begin x:=clean_box(subscr(q),sub_style(cur_style));
  12718. width(x):=width(x)+script_space;
  12719. if shift_down<sub1(cur_size) then shift_down:=sub1(cur_size);
  12720. clr:=height(x)-(abs(math_x_height(cur_size)*4) div 5);
  12721. if shift_down<clr then shift_down:=clr;
  12722. shift_amount(x):=shift_down;
  12723. @ The bottom of a superscript should never descend below the baseline plus
  12724. one-fourth of the x-height.
  12725. @<Construct a superscript box |x|@>=
  12726. begin x:=clean_box(supscr(q),sup_style(cur_style));
  12727. width(x):=width(x)+script_space;
  12728. if odd(cur_style) then clr:=sup3(cur_size)
  12729. else if cur_style<text_style then clr:=sup1(cur_size)
  12730. else clr:=sup2(cur_size);
  12731. if shift_up<clr then shift_up:=clr;
  12732. clr:=depth(x)+(abs(math_x_height(cur_size)) div 4);
  12733. if shift_up<clr then shift_up:=clr;
  12734. @ When both subscript and superscript are present, the subscript must be
  12735. separated from the superscript by at least four times |default_rule_thickness|.
  12736. If this condition would be violated, the subscript moves down, after which
  12737. both subscript and superscript move up so that the bottom of the superscript
  12738. is at least as high as the baseline plus four-fifths of the x-height.
  12739. @<Construct a sub/superscript combination box |x|...@>=
  12740. begin y:=clean_box(subscr(q),sub_style(cur_style));
  12741. width(y):=width(y)+script_space;
  12742. if shift_down<sub2(cur_size) then shift_down:=sub2(cur_size);
  12743. clr:=4*default_rule_thickness-
  12744.   ((shift_up-depth(x))-(height(y)-shift_down));
  12745. if clr>0 then
  12746.   begin shift_down:=shift_down+clr;
  12747.   clr:=(abs(math_x_height(cur_size)*4) div 5)-(shift_up-depth(x));
  12748.   if clr>0 then
  12749.     begin shift_up:=shift_up+clr;
  12750.     shift_down:=shift_down-clr;
  12751.     end;
  12752.   end;
  12753. shift_amount(x):=delta; {superscript is |delta| to the right of the subscript}
  12754. p:=new_kern((shift_up-depth(x))-(height(y)-shift_down)); link(x):=p; link(p):=y;
  12755. x:=vpack(x,natural); shift_amount(x):=shift_down;
  12756. @ We have now tied up all the loose ends of the first pass of |mlist_to_hlist|.
  12757. The second pass simply goes through and hooks everything together with the
  12758. proper glue and penalties. It also handles the |left_noad| and |right_noad| that
  12759. might be present, since |max_h| and |max_d| are now known. Variable |p| points
  12760. to a node at the current end of the final hlist.
  12761. @<Make a second pass over the mlist, ...@>=
  12762. p:=temp_head; link(p):=null; q:=mlist; r_type:=0; cur_style:=style;
  12763. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12764. while q<>null do
  12765.   begin @<If node |q| is a style node, change the style and |goto delete_q|;
  12766.     otherwise if it is not a noad, put it into the hlist,
  12767.     advance |q|, and |goto done|; otherwise set |s| to the size
  12768.     of noad |q|, set |t| to the associated type (|ord_noad..
  12769.     inner_noad|), and set |pen| to the associated penalty@>;
  12770.   @<Append inter-element spacing based on |r_type| and |t|@>;
  12771.   @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>;
  12772.   r_type:=t;
  12773.   delete_q: r:=q; q:=link(q); free_node(r,s);
  12774.   done: end
  12775. @ Just before doing the big |case| switch in the second pass, the program
  12776. sets up default values so that most of the branches are short.
  12777. @<If node |q| is a style node, change the style...@>=
  12778. t:=ord_noad; s:=noad_size; pen:=inf_penalty;
  12779. case type(q) of
  12780. op_noad,open_noad,close_noad,punct_noad,inner_noad: t:=type(q);
  12781. bin_noad: begin t:=bin_noad; pen:=bin_op_penalty;
  12782.   end;
  12783. rel_noad: begin t:=rel_noad; pen:=rel_penalty;
  12784.   end;
  12785. ord_noad,vcenter_noad,over_noad,under_noad: do_nothing;
  12786. radical_noad: s:=radical_noad_size;
  12787. accent_noad: s:=accent_noad_size;
  12788. fraction_noad: begin t:=inner_noad; s:=fraction_noad_size;
  12789.   end;
  12790. left_noad,right_noad: t:=make_left_right(q,style,max_d,max_h);
  12791. style_node: @<Change the current style and |goto delete_q|@>;
  12792. whatsit_node,penalty_node,rule_node,disc_node,adjust_node,ins_node,mark_node,
  12793.  glue_node,kern_node:@t@>@;@/
  12794.   begin link(p):=q; p:=q; q:=link(q); link(p):=null; goto done;
  12795.   end;
  12796. othercases confusion("mlist3")
  12797. @:this can't happen mlist3}{\quad mlist3@>
  12798. endcases
  12799. @ The |make_left_right| function constructs a left or right delimiter of
  12800. the required size and returns the value |open_noad| or |close_noad|. The
  12801. |right_noad| and |left_noad| will both be based on the original |style|,
  12802. so they will have consistent sizes.
  12803. We use the fact that |right_noad-left_noad=close_noad-open_noad|.
  12804. @<Declare math...@>=
  12805. function make_left_right(@!q:pointer;@!style:small_number;
  12806.   @!max_d,@!max_h:scaled):small_number;
  12807. var delta,@!delta1,@!delta2:scaled; {dimensions used in the calculation}
  12808. begin if style<script_style then cur_size:=text_size
  12809. else cur_size:=16*((style-text_style) div 2);
  12810. delta2:=max_d+axis_height(cur_size);
  12811. delta1:=max_h+max_d-delta2;
  12812. if delta2>delta1 then delta1:=delta2; {|delta1| is max distance from axis}
  12813. delta:=(delta1 div 500)*delimiter_factor;
  12814. delta2:=delta1+delta1-delimiter_shortfall;
  12815. if delta<delta2 then delta:=delta2;
  12816. new_hlist(q):=var_delimiter(delimiter(q),cur_size,delta);
  12817. make_left_right:=type(q)-(left_noad-open_noad); {|open_noad| or |close_noad|}
  12818. @ @<Change the current style and |goto delete_q|@>=
  12819. begin cur_style:=subtype(q); s:=style_node_size;
  12820. @<Set up the values of |cur_size| and |cur_mu|, based on |cur_style|@>;
  12821. goto delete_q;
  12822. @ The inter-element spacing in math formulas depends on a $8\times8$ table that
  12823. \TeX\ preloads as a 64-digit string. The elements of this string have the
  12824. following significance:
  12825. $$\vbox{\halign{#\hfil\cr
  12826. \.0 means no space;\cr
  12827. \.1 means a conditional thin space (\.{\\nonscript\\mskip\\thinmuskip});\cr
  12828. \.2 means a thin space (\.{\\mskip\\thinmuskip});\cr
  12829. \.3 means a conditional medium space
  12830.   (\.{\\nonscript\\mskip\\medmuskip});\cr
  12831. \.4 means a conditional thick space
  12832.   (\.{\\nonscript\\mskip\\thickmuskip});\cr
  12833. \.* means an impossible case.\cr}}$$
  12834. This is all pretty cryptic, but {\sl The \TeX book\/} explains what is
  12835. supposed to happen, and the string makes it happen.
  12836. @:TeXbook}{\sl The \TeX book@>
  12837. A global variable |magic_offset| is computed so that if |a| and |b| are
  12838. in the range |ord_noad..inner_noad|, then |str_pool[a*8+b+magic_offset]|
  12839. is the digit for spacing between noad types |a| and |b|.
  12840. If \PASCAL\ had provided a good way to preload constant arrays, this part of
  12841. the program would not have been so strange.
  12842. @:PASCAL}{\PASCAL@>
  12843. @d math_spacing=@;@/
  12844. @t\hskip-35pt@>
  12845. "0234000122*4000133**3**344*0400400*000000234000111*1111112341011"
  12846. @t$ \hskip-35pt$@>
  12847. @<Glob...@>=
  12848. @!magic_offset:integer; {used to find inter-element spacing}
  12849. @ @<Compute the magic offset@>=
  12850. magic_offset:=str_start[math_spacing]-9*ord_noad
  12851. @ @<Append inter-element spacing based on |r_type| and |t|@>=
  12852. if r_type>0 then {not the first noad}
  12853.   begin case so(str_pool[r_type*8+t+magic_offset]) of
  12854.   "0": x:=0;
  12855.   "1": if cur_style<script_style then x:=thin_mu_skip_code@+else x:=0;
  12856.   "2": x:=thin_mu_skip_code;
  12857.   "3": if cur_style<script_style then x:=med_mu_skip_code@+else x:=0;
  12858.   "4": if cur_style<script_style then x:=thick_mu_skip_code@+else x:=0;
  12859.   othercases confusion("mlist4")
  12860. @:this can't happen mlist4}{\quad mlist4@>
  12861.   endcases;
  12862.   if x<>0 then
  12863.     begin y:=math_glue(glue_par(x),cur_mu);
  12864.     z:=new_glue(y); glue_ref_count(y):=null; link(p):=z; p:=z;@/
  12865.     subtype(z):=x+1; {store a symbolic subtype}
  12866.     end;
  12867.   end
  12868. @ We insert a penalty node after the hlist entries of noad |q| if |pen|
  12869. is not an ``infinite'' penalty, and if the node immediately following |q|
  12870. is not a penalty node or a |rel_noad| or absent entirely.
  12871. @<Append any |new_hlist| entries for |q|, and any appropriate penalties@>=
  12872. if new_hlist(q)<>null then
  12873.   begin link(p):=new_hlist(q);
  12874.   repeat p:=link(p);
  12875.   until link(p)=null;
  12876.   end;
  12877. if penalties then if link(q)<>null then if pen<inf_penalty then
  12878.   begin r_type:=type(link(q));
  12879.   if r_type<>penalty_node then if r_type<>rel_noad then
  12880.     begin z:=new_penalty(pen); link(p):=z; p:=z;
  12881.     end;
  12882.   end
  12883. @* \[37] Alignment.
  12884. It's sort of a miracle whenever \.{\\halign} and \.{\\valign} work, because
  12885. they cut across so many of the control structures of \TeX.
  12886. Therefore the
  12887. present page is probably not the best place for a beginner to start reading
  12888. this program; it is better to master everything else first.
  12889. Let us focus our thoughts on an example of what the input might be, in order
  12890. to get some idea about how the alignment miracle happens. The example doesn't
  12891. do anything useful, but it is sufficiently general to indicate all of the
  12892. special cases that must be dealt with; please do not be disturbed by its
  12893. apparent complexity and meaninglessness.
  12894. $$\vbox{\halign{\.{#}\hfil\cr
  12895. {}\\tabskip 2pt plus 3pt\cr
  12896. {}\\halign to 300pt\{u1\#v1\&\cr
  12897. \hskip 50pt\\tabskip 1pt plus 1fil u2\#v2\&\cr
  12898. \hskip 50pt u3\#v3\\cr\cr
  12899. \hskip 25pt a1\&\\omit a2\&\\vrule\\cr\cr
  12900. \hskip 25pt \\noalign\{\\vskip 3pt\}\cr
  12901. \hskip 25pt b1\\span b2\\cr\cr
  12902. \hskip 25pt \\omit\&c2\\span\\omit\\cr\}\cr}}$$
  12903. Here's what happens:
  12904. \yskip
  12905. (0) When `\.{\\halign to 300pt\{}' is scanned, the |scan_spec| routine
  12906. places the 300pt dimension onto the |save_stack|, and an |align_group|
  12907. code is placed above it. This will make it possible to complete the alignment
  12908. when the matching `\.\}' is found.
  12909. (1) The preamble is scanned next. Macros in the preamble are not expanded,
  12910. @^preamble@>
  12911. except as part of a tabskip specification. For example, if \.{u2} had been
  12912. a macro in the preamble above, it would have been expanded, since \TeX\
  12913. must look for `\.{minus...}' as part of the tabskip glue. A ``preamble list''
  12914. is constructed based on the user's preamble; in our case it contains the
  12915. following seven items:
  12916. $$\vbox{\halign{\.{#}\hfil\qquad&(#)\hfil\cr
  12917. {}\\glue 2pt plus 3pt&the tabskip preceding column 1\cr
  12918. {}\\alignrecord, width $-\infty$&preamble info for column 1\cr
  12919. {}\\glue 2pt plus 3pt&the tabskip between columns 1 and 2\cr
  12920. {}\\alignrecord, width $-\infty$&preamble info for column 2\cr
  12921. {}\\glue 1pt plus 1fil&the tabskip between columns 2 and 3\cr
  12922. {}\\alignrecord, width $-\infty$&preamble info for column 3\cr
  12923. {}\\glue 1pt plus 1fil&the tabskip following column 3\cr}}$$
  12924. These ``alignrecord'' entries have the same size as an |unset_node|,
  12925. since they will later be converted into such nodes. However, at the
  12926. moment they have no |type| or |subtype| fields; they have |info| fields
  12927. instead, and these |info| fields are initially set to the value |end_span|,
  12928. for reasons explained below. Furthermore, the alignrecord nodes have no
  12929. |height| or |depth| fields; these are renamed |u_part| and |v_part|,
  12930. and they point to token lists for the templates of the alignment.
  12931. For example, the |u_part| field in the first alignrecord points to the
  12932. token list `\.{u1}', i.e., the template preceding the `\.\#' for column~1.
  12933. (2) \TeX\ now looks at what follows the \.{\\cr} that ended the preamble.
  12934. It is not `\.{\\noalign}' or `\.{\\omit}', so this input is put back to
  12935. be read again, and the template `\.{u1}' is fed to the scanner. Just
  12936. before reading `\.{u1}', \TeX\ goes into restricted horizontal mode.
  12937. Just after reading `\.{u1}', \TeX\ will see `\.{a1}', and then (when the
  12938. {\.\&} is sensed) \TeX\ will see `\.{v1}'. Then \TeX\ scans an |endv|
  12939. token, indicating the end of a column. At this point an |unset_node| is
  12940. created, containing the contents of the current hlist (i.e., `\.{u1a1v1}').
  12941. The natural width of this unset node replaces the |width| field of the
  12942. alignrecord for column~1; in general, the alignrecords will record the
  12943. maximum natural width that has occurred so far in a given column.
  12944. (3) Since `\.{\\omit}' follows the `\.\&', the templates for column~2
  12945. are now bypassed. Again \TeX\ goes into restricted horizontal mode and
  12946. makes an |unset_node| from the resulting hlist; but this time the
  12947. hlist contains simply `\.{a2}'. The natural width of the new unset box
  12948. is remembered in the |width| field of the alignrecord for column~2.
  12949. (4) A third |unset_node| is created for column 3, using essentially the
  12950. mechanism that worked for column~1; this unset box contains `\.{u3\\vrule
  12951. v3}'. The vertical rule in this case has running dimensions that will later
  12952. extend to the height and depth of the whole first row, since each |unset_node|
  12953. in a row will eventually inherit the height and depth of its enclosing box.
  12954. (5) The first row has now ended; it is made into a single unset box
  12955. comprising the following seven items:
  12956. $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
  12957. {}\\glue 2pt plus 3pt\cr
  12958. {}\\unsetbox for 1 column: u1a1v1\cr
  12959. {}\\glue 2pt plus 3pt\cr
  12960. {}\\unsetbox for 1 column: a2\cr
  12961. {}\\glue 1pt plus 1fil\cr
  12962. {}\\unsetbox for 1 column: u3\\vrule v3\cr
  12963. {}\\glue 1pt plus 1fil\cr}}$$
  12964. The width of this unset row is unimportant, but it has the correct height
  12965. and depth, so the correct baselineskip glue will be computed as the row
  12966. is inserted into a vertical list.
  12967. (6) Since `\.{\\noalign}' follows the current \.{\\cr}, \TeX\ appends
  12968. additional material (in this case \.{\\vskip 3pt}) to the vertical list.
  12969. While processing this material, \TeX\ will be in internal vertical
  12970. mode, and |no_align_group| will be on |save_stack|.
  12971. (7) The next row produces an unset box that looks like this:
  12972. $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
  12973. {}\\glue 2pt plus 3pt\cr
  12974. {}\\unsetbox for 2 columns: u1b1v1u2b2v2\cr
  12975. {}\\glue 1pt plus 1fil\cr
  12976. {}\\unsetbox for 1 column: {\rm(empty)}\cr
  12977. {}\\glue 1pt plus 1fil\cr}}$$
  12978. The natural width of the unset box that spans columns 1~and~2 is stored
  12979. in a ``span node,'' which we will explain later; the |info| field of the
  12980. alignrecord for column~1 now points to the new span node, and the |info|
  12981. of the span node points to |end_span|.
  12982. (8) The final row produces the unset box
  12983. $$\vbox{\halign{\hbox to 325pt{\qquad\.{#}\hfil}\cr
  12984. {}\\glue 2pt plus 3pt\cr
  12985. {}\\unsetbox for 1 column: {\rm(empty)}\cr
  12986. {}\\glue 2pt plus 3pt\cr
  12987. {}\\unsetbox for 2 columns: u2c2v2\cr
  12988. {}\\glue 1pt plus 1fil\cr}}$$
  12989. A new span node is attached to the alignrecord for column 2.
  12990. (9) The last step is to compute the true column widths and to change all the
  12991. unset boxes to hboxes, appending the whole works to the vertical list that
  12992. encloses the \.{\\halign}. The rules for deciding on the final widths of
  12993. each unset column box will be explained below.
  12994. \yskip\noindent
  12995. Note that as \.{\\halign} is being processed, we fearlessly give up control
  12996. to the rest of \TeX. At critical junctures, an alignment routine is
  12997. called upon to step in and do some little action, but most of the time
  12998. these routines just lurk in the background. It's something like
  12999. post-hypnotic suggestion.
  13000. @ We have mentioned that alignrecords contain no |height| or |depth| fields.
  13001. Their |glue_sign| and |glue_order| are pre-empted as well, since it
  13002. is necessary to store information about what to do when a template ends.
  13003. This information is called the |extra_info| field.
  13004. @d u_part(#)==mem[#+height_offset].int {pointer to \<u_j> token list}
  13005. @d v_part(#)==mem[#+depth_offset].int {pointer to \<v_j> token list}
  13006. @d extra_info(#)==info(#+list_offset) {info to remember during template}
  13007. @ Alignments can occur within alignments, so a small stack is used to access
  13008. the alignrecord information. At each level we have a |preamble| pointer,
  13009. indicating the beginning of the preamble list; a |cur_align| pointer,
  13010. indicating the current position in the preamble list; a |cur_span| pointer,
  13011. indicating the value of |cur_align| at the beginning of a sequence of
  13012. spanned columns; a |cur_loop| pointer, indicating the tabskip glue before
  13013. an alignrecord that should be copied next if the current list is extended;
  13014. and the |align_state| variable, which indicates the nesting of braces so
  13015. that \.{\\cr} and \.{\\span} and tab marks are properly intercepted.
  13016. There also are pointers |cur_head| and |cur_tail| to the head and tail
  13017. of a list of adjustments being moved out from horizontal mode to
  13018. vertical~mode.
  13019. The current values of these seven quantities appear in global variables;
  13020. when they have to be pushed down, they are stored in 5-word nodes, and
  13021. |align_ptr| points to the topmost such node.
  13022. @d preamble==link(align_head) {the current preamble list}
  13023. @d align_stack_node_size=5 {number of |mem| words to save alignment states}
  13024. @<Glob...@>=
  13025. @!cur_align:pointer; {current position in preamble list}
  13026. @!cur_span:pointer; {start of currently spanned columns in preamble list}
  13027. @!cur_loop:pointer; {place to copy when extending a periodic preamble}
  13028. @!align_ptr:pointer; {most recently pushed-down alignment stack node}
  13029. @!cur_head,@!cur_tail:pointer; {adjustment list pointers}
  13030. @ The |align_state| and |preamble| variables are initialized elsewhere.
  13031. @<Set init...@>=
  13032. align_ptr:=null; cur_align:=null; cur_span:=null; cur_loop:=null;
  13033. cur_head:=null; cur_tail:=null;
  13034. @ Alignment stack maintenance is handled by a pair of trivial routines
  13035. called |push_alignment| and |pop_alignment|.
  13036. @p procedure push_alignment;
  13037. var p:pointer; {the new alignment stack node}
  13038. begin p:=get_node(align_stack_node_size);
  13039. link(p):=align_ptr; info(p):=cur_align;
  13040. llink(p):=preamble; rlink(p):=cur_span;
  13041. mem[p+2].int:=cur_loop; mem[p+3].int:=align_state;
  13042. info(p+4):=cur_head; link(p+4):=cur_tail;
  13043. align_ptr:=p;
  13044. cur_head:=get_avail;
  13045. procedure pop_alignment;
  13046. var p:pointer; {the top alignment stack node}
  13047. begin free_avail(cur_head);
  13048. p:=align_ptr;
  13049. cur_tail:=link(p+4); cur_head:=info(p+4);
  13050. align_state:=mem[p+3].int; cur_loop:=mem[p+2].int;
  13051. cur_span:=rlink(p); preamble:=llink(p);
  13052. cur_align:=info(p); align_ptr:=link(p);
  13053. free_node(p,align_stack_node_size);
  13054. @ \TeX\ has eight procedures that govern alignments: |init_align| and
  13055. |fin_align| are used at the very beginning and the very end; |init_row| and
  13056. |fin_row| are used at the beginning and end of individual rows; |init_span|
  13057. is used at the beginning of a sequence of spanned columns (possibly involving
  13058. only one column); |init_col| and |fin_col| are used at the beginning and
  13059. end of individual columns; and |align_peek| is used after \.{\\cr} to see
  13060. whether the next item is \.{\\noalign}.
  13061. We shall consider these routines in the order they are first used during
  13062. the course of a complete \.{\\halign}, namely |init_align|, |align_peek|,
  13063. |init_row|, |init_span|, |init_col|, |fin_col|, |fin_row|, |fin_align|.
  13064. @ When \.{\\halign} or \.{\\valign} has been scanned in an appropriate
  13065. mode, \TeX\ calls |init_align|, whose task is to get everything off to a
  13066. good start. This mostly involves scanning the preamble and putting its
  13067. information into the preamble list.
  13068. @^preamble@>
  13069. @p @t\4@>@<Declare the procedure called |get_preamble_token|@>@t@>@/
  13070. procedure@?align_peek; forward;@t\2@>@/
  13071. procedure@?normal_paragraph; forward;@t\2@>@/
  13072. procedure init_align;
  13073. label done, done1, done2, continue;
  13074. var save_cs_ptr:pointer; {|warning_index| value for error messages}
  13075. @!p:pointer; {for short-term temporary use}
  13076. begin save_cs_ptr:=cur_cs; {\.{\\halign} or \.{\\valign}, usually}
  13077. push_alignment; align_state:=-1000000; {enter a new alignment level}
  13078. @<Check for improper alignment in displayed math@>;
  13079. push_nest; {enter a new semantic level}
  13080. @<Change current mode to |-vmode| for \.{\\halign}, |-hmode| for \.{\\valign}@>;
  13081. scan_spec(align_group,false);@/
  13082. @<Scan the preamble and record it in the |preamble| list@>;
  13083. new_save_level(align_group);
  13084. if every_cr<>null then begin_token_list(every_cr,every_cr_text);
  13085. align_peek; {look for \.{\\noalign} or \.{\\omit}}
  13086. @ In vertical modes, |prev_depth| already has the correct value. But
  13087. if we are in |mmode| (displayed formula mode), we reach out to the
  13088. enclosing vertical mode for the |prev_depth| value that produces the
  13089. correct baseline calculations.
  13090. @<Change current mode...@>=
  13091. if mode=mmode then
  13092.   begin mode:=-vmode; prev_depth:=nest[nest_ptr-2].aux_field.sc;
  13093.   end
  13094. else if mode>0 then negate(mode)
  13095. @ When \.{\\halign} is used as a displayed formula, there should be
  13096. no other pieces of mlists present.
  13097. @<Check for improper alignment in displayed math@>=
  13098. if (mode=mmode)and((tail<>head)or(incompleat_noad<>null)) then
  13099.   begin print_err("Improper "); print_esc("halign"); print(" inside $$'s");
  13100. @.Improper \\halign...@>
  13101.   help3("Displays can use special alignments (like \eqalignno)")@/
  13102.   ("only if nothing but the alignment itself is between $$'s.")@/
  13103.   ("So I've deleted the formulas that preceded this alignment.");
  13104.   error; flush_math;
  13105.   end
  13106. @ @<Scan the preamble and record it in the |preamble| list@>=
  13107. preamble:=null; cur_align:=align_head; cur_loop:=null; scanner_status:=aligning;
  13108. warning_index:=save_cs_ptr; align_state:=-1000000;
  13109.   {at this point, |cur_cmd=left_brace|}
  13110. loop@+  begin @<Append the current tabskip glue to the preamble list@>;
  13111.   if cur_cmd=car_ret then goto done; {\.{\\cr} ends the preamble}
  13112.   @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|,
  13113.     looking for changes in the tabskip glue; append an
  13114.     alignrecord to the preamble list@>;
  13115.   end;
  13116. done: scanner_status:=normal
  13117. @ @<Append the current tabskip glue to the preamble list@>=
  13118. link(cur_align):=new_param_glue(tab_skip_code);
  13119. cur_align:=link(cur_align)
  13120. @ @<Scan preamble text until |cur_cmd| is |tab_mark| or |car_ret|...@>=
  13121. @<Scan the template \<u_j>, putting the resulting token list in |hold_head|@>;
  13122. link(cur_align):=new_null_box; cur_align:=link(cur_align); {a new alignrecord}
  13123. info(cur_align):=end_span; width(cur_align):=null_flag;
  13124. u_part(cur_align):=link(hold_head);
  13125. @<Scan the template \<v_j>, putting the resulting token list in |hold_head|@>;
  13126. v_part(cur_align):=link(hold_head)
  13127. @ We enter `\.{\\span}' into |eqtb| with |tab_mark| as its command code,
  13128. and with |span_code| as the command modifier. This makes \TeX\ interpret it
  13129. essentially the same as an alignment delimiter like `\.\&', yet it is
  13130. recognizably different when we need to distinguish it from a normal delimiter.
  13131. It also turns out to be useful to give a special |cr_code| to `\.{\\cr}',
  13132. and an even larger |cr_cr_code| to `\.{\\crcr}'.
  13133. The end of a template is represented by two ``frozen'' control sequences
  13134. called \.{\\endtemplate}. The first has the command code |end_template|, which
  13135. is |>outer_call|, so it will not easily disappear in the presence of errors.
  13136. The |get_x_token| routine converts the first into the second, which has |endv|
  13137. as its command code.
  13138. @d span_code=256 {distinct from any character}
  13139. @d cr_code=257 {distinct from |span_code| and from any character}
  13140. @d cr_cr_code=cr_code+1 {this distinguishes \.{\\crcr} from \.{\\cr}}
  13141. @d end_template_token==cs_token_flag+frozen_end_template
  13142. @<Put each of \TeX's primitives into the hash table@>=
  13143. primitive("span",tab_mark,span_code);@/
  13144. @!@:span_}{\.{\\span} primitive@>
  13145. primitive("cr",car_ret,cr_code);
  13146. @!@:cr_}{\.{\\cr} primitive@>
  13147. text(frozen_cr):="cr"; eqtb[frozen_cr]:=eqtb[cur_val];@/
  13148. primitive("crcr",car_ret,cr_cr_code);
  13149. @!@:cr_cr_}{\.{\\crcr} primitive@>
  13150. text(frozen_end_template):="endtemplate"; text(frozen_endv):="endtemplate";
  13151. eq_type(frozen_endv):=endv; equiv(frozen_endv):=null_list;
  13152. eq_level(frozen_endv):=level_one;@/
  13153. eqtb[frozen_end_template]:=eqtb[frozen_endv];
  13154. eq_type(frozen_end_template):=end_template;
  13155. @ @<Cases of |print_cmd_chr|...@>=
  13156. tab_mark: if chr_code=span_code then print_esc("span")
  13157.   else chr_cmd("alignment tab character ");
  13158. car_ret: if chr_code=cr_code then print_esc("cr")
  13159.   else print_esc("crcr");
  13160. @ The preamble is copied directly, except that \.{\\tabskip} causes a change
  13161. to the tabskip glue, thereby possibly expanding macros that immediately
  13162. follow it. An appearance of \.{\\span} also causes such an expansion.
  13163. Note that if the preamble contains `\.{\\global\\tabskip}', the `\.{\\global}'
  13164. token survives in the preamble and the `\.{\\tabskip}' defines new
  13165. tabskip glue (locally).
  13166. @<Declare the procedure called |get_preamble_token|@>=
  13167. procedure get_preamble_token;
  13168. label restart;
  13169. begin restart: get_token;
  13170. while (cur_chr=span_code)and(cur_cmd=tab_mark) do
  13171.   begin get_token; {this token will be expanded once}
  13172.   if cur_cmd>max_command then
  13173.     begin expand; get_token;
  13174.     end;
  13175.   end;
  13176. if cur_cmd=endv then
  13177.   fatal_error("(interwoven alignment preambles are not allowed)");
  13178. @.interwoven alignment preambles...@>
  13179. if (cur_cmd=assign_glue)and(cur_chr=glue_base+tab_skip_code) then
  13180.   begin scan_optional_equals; scan_glue(glue_val);
  13181.   if global_defs>0 then geq_define(glue_base+tab_skip_code,glue_ref,cur_val)
  13182.   else eq_define(glue_base+tab_skip_code,glue_ref,cur_val);
  13183.   goto restart;
  13184.   end;
  13185. @ Spaces are eliminated from the beginning of a template.
  13186. @<Scan the template \<u_j>...@>=
  13187. p:=hold_head; link(p):=null;
  13188. loop@+  begin get_preamble_token;
  13189.   if cur_cmd=mac_param then goto done1;
  13190.   if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
  13191.    if (p=hold_head)and(cur_loop=null)and(cur_cmd=tab_mark)
  13192.     then cur_loop:=cur_align
  13193.    else  begin print_err("Missing # inserted in alignment preamble");
  13194. @.Missing \# inserted...@>
  13195.     help3("There should be exactly one # between &'s, when an")@/
  13196.     ("\halign or \valign is being set up. In this case you had")@/
  13197.     ("none, so I've put one in; maybe that will work.");
  13198.     back_error; goto done1;
  13199.     end
  13200.   else if (cur_cmd<>spacer)or(p<>hold_head) then
  13201.     begin link(p):=get_avail; p:=link(p); info(p):=cur_tok;
  13202.     end;
  13203.   end;
  13204. done1:
  13205. @ @<Scan the template \<v_j>...@>=
  13206. p:=hold_head; link(p):=null;
  13207. loop@+  begin continue: get_preamble_token;
  13208.   if (cur_cmd<=car_ret)and(cur_cmd>=tab_mark)and(align_state=-1000000) then
  13209.     goto done2;
  13210.   if cur_cmd=mac_param then
  13211.     begin print_err("Only one # is allowed per tab");
  13212. @.Only one \# is allowed...@>
  13213.     help3("There should be exactly one # between &'s, when an")@/
  13214.     ("\halign or \valign is being set up. In this case you had")@/
  13215.     ("more than one, so I'm ignoring all but the first.");
  13216.     error; goto continue;
  13217.     end;
  13218.   link(p):=get_avail; p:=link(p); info(p):=cur_tok;
  13219.   end;
  13220. done2: link(p):=get_avail; p:=link(p);
  13221. info(p):=end_template_token {put \.{\\endtemplate} at the end}
  13222. @ The tricky part about alignments is getting the templates into the
  13223. scanner at the right time, and recovering control when a row or column
  13224. is finished.
  13225. We usually begin a row after each \.{\\cr} has been sensed, unless that
  13226. \.{\\cr} is followed by \.{\\noalign} or by the right brace that terminates
  13227. the alignment. The |align_peek| routine is used to look ahead and do
  13228. the right thing; it either gets a new row started, or gets a \.{\\noalign}
  13229. started, or finishes off the alignment.
  13230. @<Declare the procedure called |align_peek|@>=
  13231. procedure align_peek;
  13232. label restart;
  13233. begin restart: align_state:=1000000; @<Get the next non-blank non-call token@>;
  13234. if cur_cmd=no_align then
  13235.   begin scan_left_brace; new_save_level(no_align_group);
  13236.   if mode=-vmode then normal_paragraph;
  13237.   end
  13238. else if cur_cmd=right_brace then fin_align
  13239. else if (cur_cmd=car_ret)and(cur_chr=cr_cr_code) then
  13240.   goto restart {ignore \.{\\crcr}}
  13241. else  begin init_row; {start a new row}
  13242.   init_col; {start a new column and replace what we peeked at}
  13243.   end;
  13244. @ To start a row (i.e., a `row' that rhymes with `dough' but not with `bough'),
  13245. we enter a new semantic level, copy the first tabskip glue, and change
  13246. from internal vertical mode to restricted horizontal mode or vice versa.
  13247. The |space_factor| and |prev_depth| are not used on this semantic level,
  13248. but we clear them to zero just to be tidy.
  13249. @p @t\4@>@<Declare the procedure called |init_span|@>@t@>@/
  13250. procedure init_row;
  13251. begin push_nest; mode:=(-hmode-vmode)-mode;
  13252. if mode=-hmode then space_factor:=0 @+else prev_depth:=0;
  13253. tail_append(new_glue(glue_ptr(preamble)));
  13254. subtype(tail):=tab_skip_code+1;@/
  13255. cur_align:=link(preamble); cur_tail:=cur_head; init_span(cur_align);
  13256. @ The parameter to |init_span| is a pointer to the alignrecord where the
  13257. next column or group of columns will begin. A new semantic level is
  13258. entered, so that the columns will generate a list for subsequent packaging.
  13259. @<Declare the procedure called |init_span|@>=
  13260. procedure init_span(@!p:pointer);
  13261. begin push_nest;
  13262. if mode=-hmode then space_factor:=1000
  13263. else  begin prev_depth:=ignore_depth; normal_paragraph;
  13264.   end;
  13265. cur_span:=p;
  13266. @ When a column begins, we assume that |cur_cmd| is either |omit| or else
  13267. the current token should be put back into the input until the \<u_j>
  13268. template has been scanned.  (Note that |cur_cmd| might be |tab_mark| or
  13269. |car_ret|.)  We also assume that |align_state| is approximately 1000000 at
  13270. this time.  We remain in the same mode, and start the template if it is
  13271. called for.
  13272. @p procedure init_col;
  13273. begin extra_info(cur_align):=cur_cmd;
  13274. if cur_cmd=omit then align_state:=0
  13275. else  begin back_input; begin_token_list(u_part(cur_align),u_template);
  13276.   end; {now |align_state=1000000|}
  13277. @ The scanner sets |align_state| to zero when the \<u_j> template ends. When
  13278. a subsequent \.{\\cr} or \.{\\span} or tab mark occurs with |align_state=0|,
  13279. the scanner activates the following code, which fires up the \<v_j> template.
  13280. We need to remember the |cur_chr|, which is either |cr_cr_code|, |cr_code|,
  13281. |span_code|, or a character code, depending on how the column text has ended.
  13282. This part of the program had better not be activated when the preamble
  13283. to another alignment is being scanned.
  13284. @<Insert the \(v)\<v_j>...@>=
  13285. begin if scanner_status=aligning then
  13286.   fatal_error("(interwoven alignment preambles are not allowed)");
  13287. @.interwoven alignment preambles...@>
  13288. cur_cmd:=extra_info(cur_align); extra_info(cur_align):=cur_chr;
  13289. if cur_cmd=omit then begin_token_list(omit_template,v_template)
  13290. else begin_token_list(v_part(cur_align),v_template);
  13291. align_state:=1000000; goto restart;
  13292. @ The token list |omit_template| just referred to is a constant token
  13293. list that contains the special control sequence \.{\\endtemplate} only.
  13294. @<Initialize the special...@>=
  13295. info(omit_template):=end_template_token; {|link(omit_template)=null|}
  13296. @ When the |endv| command at the end of a \<v_j> template comes through the
  13297. scanner, things really start to happen; and it is the |fin_col| routine
  13298. that makes them happen. This routine returns |true| if a row as well as a
  13299. column has been finished.
  13300. @p function fin_col:boolean;
  13301. label exit;
  13302. var p:pointer; {the alignrecord after the current one}
  13303. @!q,@!r:pointer; {temporary pointers for list manipulation}
  13304. @!s:pointer; {a new span node}
  13305. @!u:pointer; {a new unset box}
  13306. @!w:scaled; {natural width}
  13307. @!o:glue_ord; {order of infinity}
  13308. @!n:halfword; {span counter}
  13309. begin if cur_align=null then confusion("endv");
  13310. q:=link(cur_align);@+if q=null then confusion("endv");
  13311. @:this can't happen endv}{\quad endv@>
  13312. if align_state<500000 then
  13313.   fatal_error("(interwoven alignment preambles are not allowed)");
  13314. @.interwoven alignment preambles...@>
  13315. p:=link(q);
  13316. @<If the preamble list has been traversed, check that the row has ended@>;
  13317. if extra_info(cur_align)<>span_code then
  13318.   begin unsave; new_save_level(align_group);@/
  13319.   @<Package an unset box for the current column and record its width@>;
  13320.   @<Copy the tabskip glue between columns@>;
  13321.   if extra_info(cur_align)>=cr_code then
  13322.     begin fin_col:=true; return;
  13323.     end;
  13324.   init_span(p);
  13325.   end;
  13326. align_state:=1000000; @<Get the next non-blank non-call token@>;
  13327. cur_align:=p;
  13328. init_col; fin_col:=false;
  13329. exit: end;
  13330. @ @<If the preamble list has been traversed, check that the row has ended@>=
  13331. if (p=null)and(extra_info(cur_align)<cr_code) then
  13332.  if cur_loop<>null then @<Lengthen the preamble periodically@>
  13333.  else  begin print_err("Extra alignment tab has been changed to ");
  13334. @.Extra alignment tab...@>
  13335.   print_esc("cr");
  13336.   help3("You have given more \span or & marks than there were")@/
  13337.   ("in the preamble to the \halign or \valign now in progress.")@/
  13338.   ("So I'll assume that you meant to type \cr instead.");
  13339.   extra_info(cur_align):=cr_code; error;
  13340.   end
  13341. @ @<Lengthen the preamble...@>=
  13342. begin link(q):=new_null_box; p:=link(q); {a new alignrecord}
  13343. info(p):=end_span; width(p):=null_flag; cur_loop:=link(cur_loop);
  13344. @<Copy the templates from node |cur_loop| into node |p|@>;
  13345. cur_loop:=link(cur_loop);
  13346. link(p):=new_glue(glue_ptr(cur_loop));
  13347. @ @<Copy the templates from node |cur_loop| into node |p|@>=
  13348. q:=hold_head; r:=u_part(cur_loop);
  13349. while r<>null do
  13350.   begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
  13351.   end;
  13352. link(q):=null; u_part(p):=link(hold_head);
  13353. q:=hold_head; r:=v_part(cur_loop);
  13354. while r<>null do
  13355.   begin link(q):=get_avail; q:=link(q); info(q):=info(r); r:=link(r);
  13356.   end;
  13357. link(q):=null; v_part(p):=link(hold_head)
  13358. @ @<Copy the tabskip glue...@>=
  13359. tail_append(new_glue(glue_ptr(link(cur_align))));
  13360. subtype(tail):=tab_skip_code+1
  13361. @ @<Package an unset...@>=
  13362. begin if mode=-hmode then
  13363.   begin adjust_tail:=cur_tail; u:=hpack(link(head),natural); w:=width(u);
  13364.   cur_tail:=adjust_tail; adjust_tail:=null;
  13365.   end
  13366. else  begin u:=vpackage(link(head),natural,0); w:=height(u);
  13367.   end;
  13368. n:=min_quarterword; {this represents a span count of 1}
  13369. if cur_span<>cur_align then @<Update width entry for spanned columns@>
  13370. else if w>width(cur_align) then width(cur_align):=w;
  13371. type(u):=unset_node; span_count(u):=n;@/
  13372. @<Determine the stretch order@>;
  13373. glue_order(u):=o; glue_stretch(u):=total_stretch[o];@/
  13374. @<Determine the shrink order@>;
  13375. glue_sign(u):=o; glue_shrink(u):=total_shrink[o];@/
  13376. pop_nest; link(tail):=u; tail:=u;
  13377. @ A span node is a 2-word record containing |width|, |info|, and |link|
  13378. fields. The |link| field is not really a link, it indicates the number of
  13379. spanned columns; the |info| field points to a span node for the same
  13380. starting column, having a greater extent of spanning, or to |end_span|,
  13381. which has the largest possible |link| field; the |width| field holds the
  13382. largest natural width corresponding to a particular set of spanned columns.
  13383. A list of the maximum widths so far, for spanned columns starting at a
  13384. given column, begins with the |info| field of the alignrecord for that
  13385. column.
  13386. @d span_node_size=2 {number of |mem| words for a span node}
  13387. @<Initialize the special list heads...@>=
  13388. link(end_span):=max_quarterword+1; info(end_span):=null;
  13389. @ @<Update width entry for spanned columns@>=
  13390. begin q:=cur_span;
  13391. repeat incr(n); q:=link(link(q));
  13392. until q=cur_align;
  13393. if n>max_quarterword then confusion("256 spans"); {this can happen, but won't}
  13394. @^system dependencies@>
  13395. @:this can't happen 256 spans}{\quad 256 spans@>
  13396. q:=cur_span; while link(info(q))<n do q:=info(q);
  13397. if link(info(q))>n then
  13398.   begin s:=get_node(span_node_size); info(s):=info(q); link(s):=n;
  13399.   info(q):=s; width(s):=w;
  13400.   end
  13401. else if width(info(q))<w then width(info(q)):=w;
  13402. @ At the end of a row, we append an unset box to the current vlist (for
  13403. \.{\\halign}) or the current hlist (for \.{\\valign}). This unset box
  13404. contains the unset boxes for the columns, separated by the tabskip glue.
  13405. Everything will be set later.
  13406. @p procedure fin_row;
  13407. var p:pointer; {the new unset box}
  13408. begin if mode=-hmode then
  13409.   begin p:=hpack(link(head),natural);
  13410.   pop_nest; append_to_vlist(p);
  13411.   if cur_head<>cur_tail then
  13412.     begin link(tail):=link(cur_head); tail:=cur_tail;
  13413.     end;
  13414.   end
  13415. else  begin p:=vpack(link(head),natural); pop_nest;
  13416.   link(tail):=p; tail:=p; space_factor:=1000;
  13417.   end;
  13418. type(p):=unset_node; glue_stretch(p):=0;
  13419. if every_cr<>null then begin_token_list(every_cr,every_cr_text);
  13420. align_peek;
  13421. end; {note that |glue_shrink(p)=0| since |glue_shrink==shift_amount|}
  13422. @ Finally, we will reach the end of the alignment, and we can breathe a
  13423. sigh of relief that memory hasn't overflowed. All the unset boxes will now be
  13424. set so that the columns line up, taking due account of spanned columns.
  13425. @p procedure@?do_assignments; forward;@t\2@>@/
  13426. procedure@?resume_after_display; forward;@t\2@>@/
  13427. procedure@?build_page; forward;@t\2@>@/
  13428. procedure fin_align;
  13429. var @!p,@!q,@!r,@!s,@!u,@!v: pointer; {registers for the list operations}
  13430. @!t,@!w:scaled; {width of column}
  13431. @!o:scaled; {shift offset for unset boxes}
  13432. @!n:halfword; {matching span amount}
  13433. @!rule_save:scaled; {temporary storage for |overfull_rule|}
  13434. @!aux_save:memory_word; {temporary storage for |aux|}
  13435. begin if cur_group<>align_group then confusion("align1");
  13436. @:this can't happen align}{\quad align@>
  13437. unsave; {that |align_group| was for individual entries}
  13438. if cur_group<>align_group then confusion("align0");
  13439. unsave; {that |align_group| was for the whole alignment}
  13440. if nest[nest_ptr-1].mode_field=mmode then o:=display_indent
  13441.   else o:=0;
  13442. @<Go through the preamble list, determining the column widths and
  13443.   changing the alignrecords to dummy unset boxes@>;
  13444. @<Package the preamble list, to determine the actual tabskip glue amounts,
  13445.   and let |p| point to this prototype box@>;
  13446. @<Set the glue in all the unset boxes of the current list@>;
  13447. flush_node_list(p); pop_alignment;
  13448. @<Insert the \(c)current list into its environment@>;
  13449. end;@/
  13450. @t\4@>@<Declare the procedure called |align_peek|@>
  13451. @ It's time now to dismantle the preamble list and to compute the column
  13452. widths. Let $w_{ij}$ be the maximum of the natural widths of all entries
  13453. that span columns $i$ through $j$, inclusive. The alignrecord for column~$i$
  13454. contains $w_{ii}$ in its |width| field, and there is also a linked list of
  13455. the nonzero $w_{ij}$ for increasing $j$, accessible via the |info| field;
  13456. these span nodes contain the value $j-i-1+|min_quarterword|$ in their
  13457. |link| fields. The values of $w_{ii}$ were initialized to |null_flag|, which
  13458. we regard as $-\infty$.
  13459. The final column widths are defined by the formula
  13460. $$w_j=\max_{1\L i\L j}\biggl( w_{ij}-\sum_{i\L k<j}(t_k+w_k)\biggr),$$
  13461. where $t_k$ is the natural width of the tabskip glue between columns
  13462. $k$ and~$k+1$. However, if $w_{ij}=-\infty$ for all |i| in the range
  13463. |1<=i<=j| (i.e., if every entry that involved column~|j| also involved
  13464. column~|j+1|), we let $w_j=0$, and we zero out the tabskip glue after
  13465. column~|j|.
  13466. \TeX\ computes these values by using the following scheme: First $w_1=w_{11}$.
  13467. Then replace $w_{2j}$ by $\max(w_{2j},w_{1j}-t_1-w_1)$, for all $j>1$.
  13468. Then $w_2=w_{22}$. Then replace $w_{3j}$ by $\max(w_{3j},w_{2j}-t_2-w_2)$
  13469. for all $j>2$; and so on. If any $w_j$ turns out to be $-\infty$, its
  13470. value is changed to zero and so is the next tabskip.
  13471. @<Go through the preamble list,...@>=
  13472. q:=link(preamble);
  13473. repeat flush_list(u_part(q)); flush_list(v_part(q));
  13474. p:=link(link(q));
  13475. if width(q)=null_flag then
  13476.   @<Nullify |width(q)| and the tabskip glue following this column@>;
  13477. if info(q)<>end_span then
  13478.   @<Merge the widths in the span nodes of |q| with those of |p|,
  13479.     destroying the span nodes of |q|@>;
  13480. type(q):=unset_node; span_count(q):=min_quarterword; height(q):=0;
  13481. depth(q):=0; glue_order(q):=normal; glue_sign(q):=normal;
  13482. glue_stretch(q):=0; glue_shrink(q):=0; q:=p;
  13483. until q=null
  13484. @ @<Nullify |width(q)| and the tabskip glue following this column@>=
  13485. begin width(q):=0; r:=link(q); s:=glue_ptr(r);
  13486. if s<>zero_glue then
  13487.   begin add_glue_ref(zero_glue); delete_glue_ref(s);
  13488.   glue_ptr(r):=zero_glue;
  13489.   end;
  13490. @ Merging of two span-node lists is a typical exercise in the manipulation of
  13491. linearly linked data structures. The essential invariant in the following
  13492. |repeat| loop is that we want to dispense with node |r|, in |q|'s list,
  13493. and |u| is its successor; all nodes of |p|'s list up to and including |s|
  13494. have been processed, and the successor of |s| matches |r| or precedes |r|
  13495. or follows |r|, according as |link(r)=n| or |link(r)>n| or |link(r)<n|.
  13496. @<Merge the widths...@>=
  13497. begin t:=width(q)+width(glue_ptr(link(q)));
  13498. r:=info(q); s:=end_span; info(s):=p; n:=min_quarterword+1;
  13499. repeat width(r):=width(r)-t; u:=info(r);
  13500. while link(r)>n do
  13501.   begin s:=info(s); n:=link(info(s))+1;
  13502.   end;
  13503. if link(r)<n then
  13504.   begin info(r):=info(s); info(s):=r; decr(link(r)); s:=r;
  13505.   end
  13506. else  begin if width(r)>width(info(s)) then width(info(s)):=width(r);
  13507.   free_node(r,span_node_size);
  13508.   end;
  13509. r:=u;
  13510. until r=end_span;
  13511. @ Now the preamble list has been converted to a list of alternating unset
  13512. boxes and tabskip glue, where the box widths are equal to the final
  13513. column sizes. In case of \.{\\valign}, we change the widths to heights,
  13514. so that a correct error message will be produced if the alignment is
  13515. overfull or underfull.
  13516. @<Package the preamble list...@>=
  13517. save_ptr:=save_ptr-2; pack_begin_line:=-mode_line;
  13518. if mode=-vmode then
  13519.   begin rule_save:=overfull_rule;
  13520.   overfull_rule:=0; {prevent rule from being packaged}
  13521.   p:=hpack(preamble,saved(1),saved(0)); overfull_rule:=rule_save;
  13522.   end
  13523. else  begin q:=link(preamble);
  13524.   repeat height(q):=width(q); width(q):=0; q:=link(link(q));
  13525.   until q=null;
  13526.   p:=vpack(preamble,saved(1),saved(0));
  13527.   q:=link(preamble);
  13528.   repeat width(q):=height(q); height(q):=0; q:=link(link(q));
  13529.   until q=null;
  13530.   end;
  13531. pack_begin_line:=0
  13532. @ @<Set the glue in all the unset...@>=
  13533. q:=link(head); s:=head;
  13534. while q<>null do
  13535.   begin if not is_char_node(q) then
  13536.     if type(q)=unset_node then
  13537.       @<Set the unset box |q| and the unset boxes in it@>
  13538.     else if type(q)=rule_node then
  13539.       @<Make the running dimensions in rule |q| extend to the
  13540.         boundaries of the alignment@>;
  13541.   s:=q; q:=link(q);
  13542.   end
  13543. @ @<Make the running dimensions in rule |q| extend...@>=
  13544. begin if is_running(width(q)) then width(q):=width(p);
  13545. if is_running(height(q)) then height(q):=height(p);
  13546. if is_running(depth(q)) then depth(q):=depth(p);
  13547. if o<>0 then
  13548.   begin r:=link(q); link(q):=null; q:=hpack(q,natural);
  13549.   shift_amount(q):=o; link(q):=r; link(s):=q;
  13550.   end;
  13551. @ The unset box |q| represents a row that contains one or more unset boxes,
  13552. depending on how soon \.{\\cr} occurred in that row.
  13553. @<Set the unset box |q| and the unset boxes in it@>=
  13554. begin if mode=-vmode then
  13555.   begin type(q):=hlist_node; width(q):=width(p);
  13556.   end
  13557. else  begin type(q):=vlist_node; height(q):=height(p);
  13558.   end;
  13559. glue_order(q):=glue_order(p); glue_sign(q):=glue_sign(p);
  13560. glue_set(q):=glue_set(p); shift_amount(q):=o;
  13561. r:=link(list_ptr(q)); s:=link(list_ptr(p));
  13562. repeat @<Set the glue in node |r| and change it from an unset node@>;
  13563. r:=link(link(r)); s:=link(link(s));
  13564. until r=null;
  13565. @ A box made from spanned columns will be followed by tabskip glue nodes and
  13566. by empty boxes as if there were no spanning. This permits perfect alignment
  13567. of subsequent entries, and it prevents values that depend on floating point
  13568. arithmetic from entering into the dimensions of any boxes.
  13569. @<Set the glue in node |r|...@>=
  13570. n:=span_count(r); t:=width(s); w:=t; u:=hold_head;
  13571. while n>min_quarterword do
  13572.   begin decr(n);
  13573.   @<Append tabskip glue and an empty box to list |u|,
  13574.     and update |s| and |t| as the prototype nodes are passed@>;
  13575.   end;
  13576. if mode=-vmode then
  13577.   @<Make the unset node |r| into an |hlist_node| of width |w|,
  13578.     setting the glue as if the width were |t|@>
  13579. else @<Make the unset node |r| into a |vlist_node| of height |w|,
  13580.     setting the glue as if the height were |t|@>;
  13581. shift_amount(r):=0;
  13582. if u<>hold_head then {append blank boxes to account for spanned nodes}
  13583.   begin link(u):=link(r); link(r):=link(hold_head); r:=u;
  13584.   end
  13585. @ @<Append tabskip glue and an empty box to list |u|...@>=
  13586. s:=link(s); v:=glue_ptr(s); link(u):=new_glue(v); u:=link(u);
  13587. subtype(u):=tab_skip_code+1; t:=t+width(v);
  13588. if glue_sign(p)=stretching then
  13589.   begin if stretch_order(v)=glue_order(p) then
  13590.     t:=t+round(float(glue_set(p))*stretch(v));
  13591. @^real multiplication@>
  13592.   end
  13593. else if glue_sign(p)=shrinking then
  13594.   begin if shrink_order(v)=glue_order(p) then
  13595.     t:=t-round(float(glue_set(p))*shrink(v));
  13596.   end;
  13597. s:=link(s); link(u):=new_null_box; u:=link(u); t:=t+width(s);
  13598. if mode=-vmode then width(u):=width(s)@+else
  13599.   begin type(u):=vlist_node; height(u):=width(s);
  13600.   end
  13601. @ @<Make the unset node |r| into an |hlist_node| of width |w|...@>=
  13602. begin height(r):=height(q); depth(r):=depth(q);
  13603. if t=width(r) then
  13604.   begin glue_sign(r):=normal; glue_order(r):=normal;
  13605.   set_glue_ratio_zero(glue_set(r));
  13606.   end
  13607. else if t>width(r) then
  13608.   begin glue_sign(r):=stretching;
  13609.   if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
  13610.   else glue_set(r):=unfloat((t-width(r))/glue_stretch(r));
  13611. @^real division@>
  13612.   end
  13613. else  begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
  13614.   if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
  13615.   else if (glue_order(r)=normal)and(width(r)-t>glue_shrink(r)) then
  13616.     set_glue_ratio_one(glue_set(r))
  13617.   else glue_set(r):=unfloat((width(r)-t)/glue_shrink(r));
  13618.   end;
  13619. width(r):=w; type(r):=hlist_node;
  13620. @ @<Make the unset node |r| into a |vlist_node| of height |w|...@>=
  13621. begin width(r):=width(q);
  13622. if t=height(r) then
  13623.   begin glue_sign(r):=normal; glue_order(r):=normal;
  13624.   set_glue_ratio_zero(glue_set(r));
  13625.   end
  13626. else if t>height(r) then
  13627.   begin glue_sign(r):=stretching;
  13628.   if glue_stretch(r)=0 then set_glue_ratio_zero(glue_set(r))
  13629.   else glue_set(r):=unfloat((t-height(r))/glue_stretch(r));
  13630. @^real division@>
  13631.   end
  13632. else  begin glue_order(r):=glue_sign(r); glue_sign(r):=shrinking;
  13633.   if glue_shrink(r)=0 then set_glue_ratio_zero(glue_set(r))
  13634.   else if (glue_order(r)=normal)and(height(r)-t>glue_shrink(r)) then
  13635.     set_glue_ratio_one(glue_set(r))
  13636.   else glue_set(r):=unfloat((height(r)-t)/glue_shrink(r));
  13637.   end;
  13638. height(r):=w; type(r):=vlist_node;
  13639. @ We now have a completed alignment, in the list that starts at |head|
  13640. and ends at |tail|. This list will be merged with the one that encloses
  13641. it. (In case the enclosing mode is |mmode|, for displayed formulas,
  13642. we will need to insert glue before and after the display; that part of the
  13643. program will be deferred until we're more familiar with such operations.)
  13644. In horizontal mode, the |clang| part of |aux| is undefined; an over-cautious
  13645. \PASCAL\ runtime system may complain about this.
  13646. @^dirty Pascal@>
  13647. @<Insert the \(c)current list into its environment@>=
  13648. aux_save:=aux; p:=link(head); q:=tail; pop_nest;
  13649. if mode=mmode then @<Finish an alignment in a display@>
  13650. else  begin aux:=aux_save; link(tail):=p;
  13651.   if p<>null then tail:=q;
  13652.   if mode=vmode then build_page;
  13653.   end
  13654. @* \[38] Breaking paragraphs into lines.
  13655. We come now to what is probably the most interesting algorithm of \TeX:
  13656. the mechanism for choosing the ``best possible'' breakpoints that yield
  13657. the individual lines of a paragraph. \TeX's line-breaking algorithm takes
  13658. a given horizontal list and converts it to a sequence of boxes that are
  13659. appended to the current vertical list. In the course of doing this, it
  13660. creates a special data structure containing three kinds of records that are
  13661. not used elsewhere in \TeX. Such nodes are created while a paragraph is
  13662. being processed, and they are destroyed afterwards; thus, the other parts
  13663. of \TeX\ do not need to know anything about how line-breaking is done.
  13664. The method used here is based on an approach devised by Michael F. Plass and
  13665. @^Plass, Michael Frederick@>
  13666. @^Knuth, Donald Ervin@>
  13667. the author in 1977, subsequently generalized and improved by the same two
  13668. people in 1980. A detailed discussion appears in {\sl SOFTWARE---Practice
  13669. \AM\ Experience \bf11} (1981), 1119--1184, where it is shown that the
  13670. line-breaking problem can be regarded as a special case of the problem of
  13671. computing the shortest path in an acyclic network. The cited paper includes
  13672. numerous examples and describes the history of line breaking as it has been
  13673. practiced by printers through the ages. The present implementation adds two
  13674. new ideas to the algorithm of 1980: memory space requirements are considerably
  13675. reduced by using smaller records for inactive nodes than for active ones,
  13676. and arithmetic overflow is avoided by using ``delta distances'' instead of
  13677. keeping track of the total distance from the beginning of the paragraph to the
  13678. current point.
  13679. @ The |line_break| procedure should be invoked only in horizontal mode; it
  13680. leaves that mode and places its output into the current vlist of the
  13681. enclosing vertical mode (or internal vertical mode).
  13682. There is one explicit parameter:  |final_widow_penalty| is the amount of
  13683. additional penalty to be inserted before the final line of the paragraph.
  13684. There are also a number of implicit parameters: The hlist to be broken
  13685. starts at |link(head)|, and it is nonempty. The value of |prev_graf| in the
  13686. enclosing semantic level tells where the paragraph should begin in the
  13687. sequence of line numbers, in case hanging indentation or \.{\\parshape}
  13688. are in use; |prev_graf| is zero unless this paragraph is being continued
  13689. after a displayed formula.  Other implicit parameters, such as the
  13690. |par_shape_ptr| and various penalties to use for hyphenation, etc., appear
  13691. in |eqtb|.
  13692. After |line_break| has acted, it will have updated the current vlist and the
  13693. value of |prev_graf|. Furthermore, the global variable |just_box| will
  13694. point to the final box created by |line_break|, so that the width of this
  13695. line can be ascertained when it is necessary to decide whether to use
  13696. |above_display_skip| or |above_display_short_skip| before a displayed formula.
  13697. @<Glob...@>=
  13698. @!just_box:pointer; {the |hlist_node| for the last line of the new paragraph}
  13699. @ Since |line_break| is a rather lengthy procedure---sort of a small world unto
  13700. itself---we must build it up little by little, somewhat more cautiously
  13701. than we have done with the simpler procedures of \TeX. Here is the
  13702. general outline.
  13703. @p@t\4@>@<Declare subprocedures for |line_break|@>
  13704. procedure line_break(@!final_widow_penalty:integer);
  13705. label done,done1,done2,done3,done4,done5,continue;
  13706. var @<Local variables for line breaking@>@;
  13707. begin pack_begin_line:=mode_line; {this is for over/underfull box messages}
  13708. @<Get ready to start line breaking@>;
  13709. @<Find optimal breakpoints@>;
  13710. @<Break the paragraph at the chosen breakpoints, justify the resulting lines
  13711. to the correct widths, and append them to the current vertical list@>;
  13712. @<Clean up the memory by removing the break nodes@>;
  13713. pack_begin_line:=0;
  13714. @ The first task is to move the list from |head| to |temp_head| and go
  13715. into the enclosing semantic level. We also append the \.{\\parfillskip}
  13716. glue to the end of the paragraph, removing a space (or other glue node) if
  13717. it was there, since spaces usually precede blank lines and instances of
  13718. `\.{\$\$}'. The |par_fill_skip| is preceded by an infinite penalty, so
  13719. it will never be considered as a potential breakpoint.
  13720. This code assumes that a |glue_node| and a |penalty_node| occupy the
  13721. same number of |mem|~words.
  13722. @^data structure assumptions@>
  13723. @<Get ready to start...@>=
  13724. link(temp_head):=link(head);
  13725. if is_char_node(tail) then tail_append(new_penalty(inf_penalty))
  13726. else if type(tail)<>glue_node then tail_append(new_penalty(inf_penalty))
  13727. else  begin type(tail):=penalty_node; delete_glue_ref(glue_ptr(tail));
  13728.   flush_node_list(leader_ptr(tail)); penalty(tail):=inf_penalty;
  13729.   end;
  13730. link(tail):=new_param_glue(par_fill_skip_code);
  13731. init_cur_lang:=prev_graf mod @'200000;
  13732. init_l_hyf:=prev_graf div @'20000000;
  13733. init_r_hyf:=(prev_graf div @'200000) mod @'100;
  13734. pop_nest;
  13735. @ When looking for optimal line breaks, \TeX\ creates a ``break node'' for
  13736. each break that is {\sl feasible}, in the sense that there is a way to end
  13737. a line at the given place without requiring any line to stretch more than
  13738. a given tolerance. A break node is characterized by three things: the position
  13739. of the break (which is a pointer to a |glue_node|, |math_node|, |penalty_node|,
  13740. or |disc_node|); the ordinal number of the line that will follow this
  13741. breakpoint; and the fitness classification of the line that has just
  13742. ended, i.e., |tight_fit|, |decent_fit|, |loose_fit|, or |very_loose_fit|.
  13743. @d tight_fit=3 {fitness classification for lines shrinking 0.5 to 1.0 of their
  13744.   shrinkability}
  13745. @d loose_fit=1 {fitness classification for lines stretching 0.5 to 1.0 of their
  13746.   stretchability}
  13747. @d very_loose_fit=0 {fitness classification for lines stretching more than
  13748.   their stretchability}
  13749. @d decent_fit=2 {fitness classification for all other lines}
  13750. @ The algorithm essentially determines the best possible way to achieve
  13751. each feasible combination of position, line, and fitness. Thus, it answers
  13752. questions like, ``What is the best way to break the opening part of the
  13753. paragraph so that the fourth line is a tight line ending at such-and-such
  13754. a place?'' However, the fact that all lines are to be the same length
  13755. after a certain point makes it possible to regard all sufficiently large
  13756. line numbers as equivalent, when the looseness parameter is zero, and this
  13757. makes it possible for the algorithm to save space and time.
  13758. An ``active node'' and a ``passive node'' are created in |mem| for each
  13759. feasible breakpoint that needs to be considered. Active nodes are three
  13760. words long and passive nodes are two words long. We need active nodes only
  13761. for breakpoints near the place in the paragraph that is currently being
  13762. examined, so they are recycled within a comparatively short time after
  13763. they are created.
  13764. @ An active node for a given breakpoint contains six fields:
  13765. \yskip\hang|link| points to the next node in the list of active nodes; the
  13766. last active node has |link=last_active|.
  13767. \yskip\hang|break_node| points to the passive node associated with this
  13768. breakpoint.
  13769. \yskip\hang|line_number| is the number of the line that follows this
  13770. breakpoint.
  13771. \yskip\hang|fitness| is the fitness classification of the line ending at this
  13772. breakpoint.
  13773. \yskip\hang|type| is either |hyphenated| or |unhyphenated|, depending on
  13774. whether this breakpoint is a |disc_node|.
  13775. \yskip\hang|total_demerits| is the minimum possible sum of demerits over all
  13776. lines leading from the beginning of the paragraph to this breakpoint.
  13777. \yskip\noindent
  13778. The value of |link(active)| points to the first active node on a linked list
  13779. of all currently active nodes. This list is in order by |line_number|,
  13780. except that nodes with |line_number>easy_line| may be in any order relative
  13781. to each other.
  13782. @d active_node_size=3 {number of words in active nodes}
  13783. @d fitness==subtype {|very_loose_fit..tight_fit| on final line for this break}
  13784. @d break_node==rlink {pointer to the corresponding passive node}
  13785. @d line_number==llink {line that begins at this breakpoint}
  13786. @d total_demerits(#)==mem[#+2].int {the quantity that \TeX\ minimizes}
  13787. @d unhyphenated=0 {the |type| of a normal active break node}
  13788. @d hyphenated=1 {the |type| of an active node that breaks at a |disc_node|}
  13789. @d last_active==active {the active list ends where it begins}
  13790. @ @<Initialize the special list heads...@>=
  13791. type(last_active):=hyphenated; line_number(last_active):=max_halfword;
  13792. subtype(last_active):=0; {the |subtype| is never examined by the algorithm}
  13793. @ The passive node for a given breakpoint contains only four fields:
  13794. \yskip\hang|link| points to the passive node created just before this one,
  13795. if any, otherwise it is |null|.
  13796. \yskip\hang|cur_break| points to the position of this breakpoint in the
  13797. horizontal list for the paragraph being broken.
  13798. \yskip\hang|prev_break| points to the passive node that should precede this
  13799. one in an optimal path to this breakpoint.
  13800. \yskip\hang|serial| is equal to |n| if this passive node is the |n|th
  13801. one created during the current pass. (This field is used only when
  13802. printing out detailed statistics about the line-breaking calculations.)
  13803. \yskip\noindent
  13804. There is a global variable called |passive| that points to the most
  13805. recently created passive node. Another global variable, |printed_node|,
  13806. is used to help print out the paragraph when detailed information about
  13807. the line-breaking computation is being displayed.
  13808. @d passive_node_size=2 {number of words in passive nodes}
  13809. @d cur_break==rlink {in passive node, points to position of this breakpoint}
  13810. @d prev_break==llink {points to passive node that should precede this one}
  13811. @d serial==info {serial number for symbolic identification}
  13812. @<Glob...@>=
  13813. @!passive:pointer; {most recent node on passive list}
  13814. @!printed_node:pointer; {most recent node that has been printed}
  13815. @!pass_number:halfword; {the number of passive nodes allocated on this pass}
  13816. @ The active list also contains ``delta'' nodes that help the algorithm
  13817. compute the badness of individual lines. Such nodes appear only between two
  13818. active nodes, and they have |type=delta_node|. If |p| and |r| are active nodes
  13819. and if |q| is a delta node between them, so that |link(p)=q| and |link(q)=r|,
  13820. then |q| tells the space difference between lines in the horizontal list that
  13821. start after breakpoint |p| and lines that start after breakpoint |r|. In
  13822. other words, if we know the length of the line that starts after |p| and
  13823. ends at our current position, then the corresponding length of the line that
  13824. starts after |r| is obtained by adding the amounts in node~|q|. A delta node
  13825. contains six scaled numbers, since it must record the net change in glue
  13826. stretchability with respect to all orders of infinity. The natural width
  13827. difference appears in |mem[q+1].sc|; the stretch differences in units of
  13828. pt, fil, fill, and filll appear in |mem[q+2..q+5].sc|; and the shrink difference
  13829. appears in |mem[q+6].sc|. The |subtype| field of a delta node is not used.
  13830. @d delta_node_size=7 {number of words in a delta node}
  13831. @d delta_node=2 {|type| field in a delta node}
  13832. @ As the algorithm runs, it maintains a set of six delta-like registers
  13833. for the length of the line following the first active breakpoint to the
  13834. current position in the given hlist. When it makes a pass through the
  13835. active list, it also maintains a similar set of six registers for the
  13836. length following the active breakpoint of current interest. A third set
  13837. holds the length of an empty line (namely, the sum of \.{\\leftskip} and
  13838. \.{\\rightskip}); and a fourth set is used to create new delta nodes.
  13839. When we pass a delta node we want to do operations like
  13840. $$\hbox{\ignorespaces|for
  13841. k:=1 to 6 do cur_active_width[k]:=cur_active_width[k]+mem[q+k].sc|};$$ and we
  13842. want to do this without the overhead of |for| loops. The |do_all_six|
  13843. macro makes such six-tuples convenient.
  13844. @d do_all_six(#)==#(1);#(2);#(3);#(4);#(5);#(6)
  13845. @<Glo...@>=
  13846. @!active_width:array[1..6] of scaled;
  13847.   {distance from first active node to~|cur_p|}
  13848. @!cur_active_width:array[1..6] of scaled; {distance from current active node}
  13849. @!background:array[1..6] of scaled; {length of an ``empty'' line}
  13850. @!break_width:array[1..6] of scaled; {length being computed after current break}
  13851. @ Let's state the principles of the delta nodes more precisely and concisely,
  13852. so that the following programs will be less obscure. For each legal
  13853. breakpoint~|p| in the paragraph, we define two quantities $\alpha(p)$ and
  13854. $\beta(p)$ such that the length of material in a line from breakpoint~|p|
  13855. to breakpoint~|q| is $\gamma+\beta(q)-\alpha(p)$, for some fixed $\gamma$.
  13856. Intuitively, $\alpha(p)$ and $\beta(q)$ are the total length of material from
  13857. the beginning of the paragraph to a point ``after'' a break at |p| and to a
  13858. point ``before'' a break at |q|; and $\gamma$ is the width of an empty line,
  13859. namely the length contributed by \.{\\leftskip} and \.{\\rightskip}.
  13860. Suppose, for example, that the paragraph consists entirely of alternating
  13861. boxes and glue skips; let the boxes have widths $x_1\ldots x_n$ and
  13862. let the skips have widths $y_1\ldots y_n$, so that the paragraph can be
  13863. represented by $x_1y_1\ldots x_ny_n$. Let $p_i$ be the legal breakpoint
  13864. at $y_i$; then $\alpha(p_i)=x_1+y_1+\cdots+x_i+y_i$, and $\beta(p_i)=
  13865. x_1+y_1+\cdots+x_i$. To check this, note that the length of material from
  13866. $p_2$ to $p_5$, say, is $\gamma+x_3+y_3+x_4+y_4+x_5=\gamma+\beta(p_5)
  13867. -\alpha(p_2)$.
  13868. The quantities $\alpha$, $\beta$, $\gamma$ involve glue stretchability and
  13869. shrinkability as well as a natural width. If we were to compute $\alpha(p)$
  13870. and $\beta(p)$ for each |p|, we would need multiple precision arithmetic, and
  13871. the multiprecise numbers would have to be kept in the active nodes.
  13872. \TeX\ avoids this problem by working entirely with relative differences
  13873. or ``deltas.'' Suppose, for example, that the active list contains
  13874. $a_1\,\delta_1\,a_2\,\delta_2\,a_3$, where the |a|'s are active breakpoints
  13875. and the $\delta$'s are delta nodes. Then $\delta_1=\alpha(a_1)-\alpha(a_2)$
  13876. and $\delta_2=\alpha(a_2)-\alpha(a_3)$. If the line breaking algorithm is
  13877. currently positioned at some other breakpoint |p|, the |active_width| array
  13878. contains the value $\gamma+\beta(p)-\alpha(a_1)$. If we are scanning through
  13879. the list of active nodes and considering a tentative line that runs from
  13880. $a_2$ to~|p|, say, the |cur_active_width| array will contain the value
  13881. $\gamma+\beta(p)-\alpha(a_2)$. Thus, when we move from $a_2$ to $a_3$,
  13882. we want to add $\alpha(a_2)-\alpha(a_3)$ to |cur_active_width|; and this
  13883. is just $\delta_2$, which appears in the active list between $a_2$ and
  13884. $a_3$. The |background| array contains $\gamma$. The |break_width| array
  13885. will be used to calculate values of new delta nodes when the active
  13886. list is being updated.
  13887. @ Glue nodes in a horizontal list that is being paragraphed are not supposed to
  13888. include ``infinite'' shrinkability; that is why the algorithm maintains
  13889. four registers for stretching but only one for shrinking. If the user tries to
  13890. introduce infinite shrinkability, the shrinkability will be reset to finite
  13891. and an error message will be issued. A boolean variable |no_shrink_error_yet|
  13892. prevents this error message from appearing more than once per paragraph.
  13893. @d check_shrinkage(#)==if (shrink_order(#)<>normal)and(shrink(#)<>0) then
  13894.   begin #:=finite_shrink(#);
  13895.   end
  13896. @<Glob...@>=
  13897. @!no_shrink_error_yet:boolean; {have we complained about infinite shrinkage?}
  13898. @ @<Declare subprocedures for |line_break|@>=
  13899. function finite_shrink(@!p:pointer):pointer; {recovers from infinite shrinkage}
  13900. var q:pointer; {new glue specification}
  13901. begin if no_shrink_error_yet then
  13902.   begin no_shrink_error_yet:=false;
  13903.   print_err("Infinite glue shrinkage found in a paragraph");
  13904. @.Infinite glue shrinkage...@>
  13905.   help5("The paragraph just ended includes some glue that has")@/
  13906.   ("infinite shrinkability, e.g., `\hskip 0pt minus 1fil'.")@/
  13907.   ("Such glue doesn't belong there---it allows a paragraph")@/
  13908.   ("of any length to fit on one line. But it's safe to proceed,")@/
  13909.   ("since the offensive shrinkability has been made finite.");
  13910.   error;
  13911.   end;
  13912. q:=new_spec(p); shrink_order(q):=normal;
  13913. delete_glue_ref(p); finite_shrink:=q;
  13914. @ @<Get ready to start...@>=
  13915. no_shrink_error_yet:=true;@/
  13916. check_shrinkage(left_skip); check_shrinkage(right_skip);@/
  13917. q:=left_skip; r:=right_skip; background[1]:=width(q)+width(r);@/
  13918. background[2]:=0; background[3]:=0; background[4]:=0; background[5]:=0;@/
  13919. background[2+stretch_order(q)]:=stretch(q);@/
  13920. background[2+stretch_order(r)]:=@|background[2+stretch_order(r)]+stretch(r);@/
  13921. background[6]:=shrink(q)+shrink(r);
  13922. @ A pointer variable |cur_p| runs through the given horizontal list as we look
  13923. for breakpoints. This variable is global, since it is used both by |line_break|
  13924. and by its subprocedure |try_break|.
  13925. Another global variable called |threshold| is used to determine the feasibility
  13926. of individual lines: breakpoints are feasible if there is a way to reach
  13927. them without creating lines whose badness exceeds |threshold|.  (The
  13928. badness is compared to |threshold| before penalties are added, so that
  13929. penalty values do not affect the feasibility of breakpoints, except that
  13930. no break is allowed when the penalty is 10000 or more.) If |threshold|
  13931. is 10000 or more, all legal breaks are considered feasible, since the
  13932. |badness| function specified above never returns a value greater than~10000.
  13933. Up to three passes might be made through the paragraph in an attempt to find at
  13934. least one set of feasible breakpoints. On the first pass, we have
  13935. |threshold=pretolerance| and |second_pass=final_pass=false|.
  13936. If this pass fails to find a
  13937. feasible solution, |threshold| is set to |tolerance|, |second_pass| is set
  13938. |true|, and an attempt is made to hyphenate as many words as possible.
  13939. If that fails too, we add |emergency_stretch| to the background
  13940. stretchability and set |final_pass=true|.
  13941. @<Glob...@>=
  13942. @!cur_p:pointer; {the current breakpoint under consideration}
  13943. @!second_pass:boolean; {is this our second attempt to break this paragraph?}
  13944. @!final_pass:boolean; {is this our final attempt to break this paragraph?}
  13945. @!threshold:integer; {maximum badness on feasible lines}
  13946. @ The heart of the line-breaking procedure is `|try_break|', a subroutine
  13947. that tests if the current breakpoint |cur_p| is feasible, by running
  13948. through the active list to see what lines of text can be made from active
  13949. nodes to~|cur_p|.  If feasible breaks are possible, new break nodes are
  13950. created.  If |cur_p| is too far from an active node, that node is
  13951. deactivated.
  13952. The parameter |pi| to |try_break| is the penalty associated
  13953. with a break at |cur_p|; we have |pi=eject_penalty| if the break is forced,
  13954. and |pi=inf_penalty| if the break is illegal.
  13955. The other parameter, |break_type|, is set to |hyphenated| or |unhyphenated|,
  13956. depending on whether or not the current break is at a |disc_node|. The
  13957. end of a paragraph is also regarded as `|hyphenated|'; this case is
  13958. distinguishable by the condition |cur_p=null|.
  13959. @d copy_to_cur_active(#)==cur_active_width[#]:=active_width[#]
  13960. @d deactivate=60 {go here when node |r| should be deactivated}
  13961. @<Declare subprocedures for |line_break|@>=
  13962. procedure try_break(@!pi:integer;@!break_type:small_number);
  13963. label exit,done,done1,continue,deactivate;
  13964. var r:pointer; {runs through the active list}
  13965. @!prev_r:pointer; {stays a step behind |r|}
  13966. @!old_l:halfword; {maximum line number in current equivalence class of lines}
  13967. @!no_break_yet:boolean; {have we found a feasible break at |cur_p|?}
  13968. @<Other local variables for |try_break|@>@;
  13969. begin @<Make sure that |pi| is in the proper range@>;
  13970. no_break_yet:=true; prev_r:=active; old_l:=0;
  13971. do_all_six(copy_to_cur_active);
  13972. loop@+  begin continue: r:=link(prev_r);
  13973.   @<If node |r| is of type |delta_node|, update |cur_active_width|,
  13974.     set |prev_r| and |prev_prev_r|, then |goto continue|@>;
  13975.   @<If a line number class has ended, create new active nodes for
  13976.     the best feasible breaks in that class; then |return|
  13977.     if |r=last_active|, otherwise compute the new |line_width|@>;
  13978.   @<Consider the demerits for a line from |r| to |cur_p|;
  13979.     deactivate node |r| if it should no longer be active;
  13980.     then |goto continue| if a line from |r| to |cur_p| is infeasible,
  13981.     otherwise record a new feasible break@>;
  13982.   end;
  13983. exit: @!stat @<Update the value of |printed_node| for
  13984.   symbolic displays@>@+tats@;
  13985. @ @<Other local variables for |try_break|@>=
  13986. @!prev_prev_r:pointer; {a step behind |prev_r|, if |type(prev_r)=delta_node|}
  13987. @!s:pointer; {runs through nodes ahead of |cur_p|}
  13988. @!q:pointer; {points to a new node being created}
  13989. @!v:pointer; {points to a glue specification or a node ahead of |cur_p|}
  13990. @!t:integer; {node count, if |cur_p| is a discretionary node}
  13991. @!f:internal_font_number; {used in character width calculation}
  13992. @!l:halfword; {line number of current active node}
  13993. @!node_r_stays_active:boolean; {should node |r| remain in the active list?}
  13994. @!line_width:scaled; {the current line will be justified to this width}
  13995. @!fit_class:very_loose_fit..tight_fit; {possible fitness class of test line}
  13996. @!b:halfword; {badness of test line}
  13997. @!d:integer; {demerits of test line}
  13998. @!artificial_demerits:boolean; {has |d| been forced to zero?}
  13999. @!save_link:pointer; {temporarily holds value of |link(cur_p)|}
  14000. @!shortfall:scaled; {used in badness calculations}
  14001. @ @<Make sure that |pi| is in the proper range@>=
  14002. if abs(pi)>=inf_penalty then
  14003.   if pi>0 then return {this breakpoint is inhibited by infinite penalty}
  14004.   else pi:=eject_penalty {this breakpoint will be forced}
  14005. @ The following code uses the fact that |type(last_active)<>delta_node|.
  14006. @d update_width(#)==@|
  14007.   cur_active_width[#]:=cur_active_width[#]+mem[r+#].sc
  14008. @<If node |r|...@>=
  14009. @^inner loop@>
  14010. if type(r)=delta_node then
  14011.   begin do_all_six(update_width);
  14012.   prev_prev_r:=prev_r; prev_r:=r; goto continue;
  14013.   end
  14014. @ As we consider various ways to end a line at |cur_p|, in a given line number
  14015. class, we keep track of the best total demerits known, in an array with
  14016. one entry for each of the fitness classifications. For example,
  14017. |minimal_demerits[tight_fit]| contains the fewest total demerits of feasible
  14018. line breaks ending at |cur_p| with a |tight_fit| line; |best_place[tight_fit]|
  14019. points to the passive node for the break before~|cur_p| that achieves such
  14020. an optimum; and |best_pl_line[tight_fit]| is the |line_number| field in the
  14021. active node corresponding to |best_place[tight_fit]|. When no feasible break
  14022. sequence is known, the |minimal_demerits| entries will be equal to
  14023. |awful_bad|, which is $2^{30}-1$. Another variable, |minimum_demerits|,
  14024. keeps track of the smallest value in the |minimal_demerits| array.
  14025. @d awful_bad==@'7777777777 {more than a billion demerits}
  14026. @<Global...@>=
  14027. @!minimal_demerits:array[very_loose_fit..tight_fit] of integer; {best total
  14028.   demerits known for current line class and position, given the fitness}
  14029. @!minimum_demerits:integer; {best total demerits known for current line class
  14030.   and position}
  14031. @!best_place:array[very_loose_fit..tight_fit] of pointer; {how to achieve
  14032.   |minimal_demerits|}
  14033. @!best_pl_line:array[very_loose_fit..tight_fit] of halfword; {corresponding
  14034.   line number}
  14035. @ @<Get ready to start...@>=
  14036. minimum_demerits:=awful_bad;
  14037. minimal_demerits[tight_fit]:=awful_bad;
  14038. minimal_demerits[decent_fit]:=awful_bad;
  14039. minimal_demerits[loose_fit]:=awful_bad;
  14040. minimal_demerits[very_loose_fit]:=awful_bad;
  14041. @ The first part of the following code is part of \TeX's inner loop, so
  14042. we don't want to waste any time. The current active node, namely node |r|,
  14043. contains the line number that will be considered next. At the end of the
  14044. list we have arranged the data structure so that |r=last_active| and
  14045. |line_number(last_active)>old_l|.
  14046. @^inner loop@>
  14047. @<If a line number class...@>=
  14048. begin l:=line_number(r);
  14049. if l>old_l then
  14050.   begin {now we are no longer in the inner loop}
  14051.   if (minimum_demerits<awful_bad)and@|
  14052.       ((old_l<>easy_line)or(r=last_active)) then
  14053.     @<Create new active nodes for the best feasible breaks
  14054.       just found@>;
  14055.   if r=last_active then return;
  14056.   @<Compute the new line width@>;
  14057.   end;
  14058. @ It is not necessary to create new active nodes having |minimal_demerits|
  14059. greater than
  14060. |minimum_demerits+abs(adj_demerits)|, since such active nodes will never
  14061. be chosen in the final paragraph breaks. This observation allows us to
  14062. omit a substantial number of feasible breakpoints from further consideration.
  14063. @<Create new active nodes...@>=
  14064. begin if no_break_yet then @<Compute the values of |break_width|@>;
  14065. @<Insert a delta node to prepare for breaks at |cur_p|@>;
  14066. if abs(adj_demerits)>=awful_bad-minimum_demerits then
  14067.   minimum_demerits:=awful_bad-1
  14068. else minimum_demerits:=minimum_demerits+abs(adj_demerits);
  14069. for fit_class:=very_loose_fit to tight_fit do
  14070.   begin if minimal_demerits[fit_class]<=minimum_demerits then
  14071.     @<Insert a new active node
  14072.       from |best_place[fit_class]| to |cur_p|@>;
  14073.   minimal_demerits[fit_class]:=awful_bad;
  14074.   end;
  14075. minimum_demerits:=awful_bad;
  14076. @<Insert a delta node to prepare for the next active node@>;
  14077. @ When we insert a new active node for a break at |cur_p|, suppose this
  14078. new node is to be placed just before active node |a|; then we essentially
  14079. want to insert `$\delta\,|cur_p|\,\delta^\prime$' before |a|, where
  14080. $\delta=\alpha(a)-\alpha(|cur_p|)$ and $\delta^\prime=\alpha(|cur_p|)-\alpha(a)$
  14081. in the notation explained above.  The |cur_active_width| array now holds
  14082. $\gamma+\beta(|cur_p|)-\alpha(a)$; so $\delta$ can be obtained by
  14083. subtracting |cur_active_width| from the quantity $\gamma+\beta(|cur_p|)-
  14084. \alpha(|cur_p|)$. The latter quantity can be regarded as the length of a
  14085. line ``from |cur_p| to |cur_p|''; we call it the |break_width| at |cur_p|.
  14086. The |break_width| is usually negative, since it consists of the background
  14087. (which is normally zero) minus the width of nodes following~|cur_p| that are
  14088. eliminated after a break. If, for example, node |cur_p| is a glue node, the
  14089. width of this glue is subtracted from the background; and we also look
  14090. ahead to eliminate all subsequent glue and penalty and kern and math
  14091. nodes, subtracting their widths as well.
  14092. Kern nodes do not disappear at a line break unless they are |explicit|.
  14093. @d set_break_width_to_background(#)==break_width[#]:=background[#]
  14094. @<Compute the values of |break...@>=
  14095. begin no_break_yet:=false; do_all_six(set_break_width_to_background);
  14096. s:=cur_p;
  14097. if break_type>unhyphenated then if cur_p<>null then
  14098.   @<Compute the discretionary |break_width| values@>;
  14099. while s<>null do
  14100.   begin if is_char_node(s) then goto done;
  14101.   case type(s) of
  14102.   glue_node:@<Subtract glue from |break_width|@>;
  14103.   penalty_node: do_nothing;
  14104.   math_node: break_width[1]:=break_width[1]-width(s);
  14105.   kern_node: if subtype(s)<>explicit then goto done
  14106.     else break_width[1]:=break_width[1]-width(s);
  14107.   othercases goto done
  14108.   endcases;@/
  14109.   s:=link(s);
  14110.   end;
  14111. done: end
  14112. @ @<Subtract glue from |break...@>=
  14113. begin v:=glue_ptr(s); break_width[1]:=break_width[1]-width(v);
  14114. break_width[2+stretch_order(v)]:=break_width[2+stretch_order(v)]-stretch(v);
  14115. break_width[6]:=break_width[6]-shrink(v);
  14116. @ When |cur_p| is a discretionary break, the length of a line ``from |cur_p| to
  14117. |cur_p|'' has to be defined properly so that the other calculations work out.
  14118. Suppose that the pre-break text at |cur_p| has length $l_0$, the post-break
  14119. text has length $l_1$, and the replacement text has length |l|. Suppose
  14120. also that |q| is the node following the replacement text. Then length of a
  14121. line from |cur_p| to |q| will be computed as $\gamma+\beta(q)-\alpha(|cur_p|)$,
  14122. where $\beta(q)=\beta(|cur_p|)-l_0+l$. The actual length will be the background
  14123. plus $l_1$, so the length from |cur_p| to |cur_p| should be $\gamma+l_0+l_1-l$.
  14124. If the post-break text of the discretionary is empty, a break may also
  14125. discard~|q|; in that unusual case we subtract the length of~|q| and any
  14126. other nodes that will be discarded after the discretionary break.
  14127. The value of $l_0$ need not be computed, since |line_break| will put
  14128. it into the global variable |disc_width| before calling |try_break|.
  14129. @<Glob...@>=
  14130. @!disc_width:scaled; {the length of discretionary material preceding a break}
  14131. @ @<Compute the discretionary |break...@>=
  14132. begin t:=replace_count(cur_p); v:=cur_p; s:=post_break(cur_p);
  14133. while t>0 do
  14134.   begin decr(t); v:=link(v);
  14135.   @<Subtract the width of node |v| from |break_width|@>;
  14136.   end;
  14137. while s<>null do
  14138.   begin @<Add the width of node |s| to |break_width|@>;
  14139.   s:=link(s);
  14140.   end;
  14141. break_width[1]:=break_width[1]+disc_width;
  14142. if post_break(cur_p)=null then s:=link(v);
  14143.           {nodes may be discardable after the break}
  14144. @ Replacement texts and discretionary texts are supposed to contain
  14145. only character nodes, kern nodes, ligature nodes, and box or rule nodes.
  14146. @<Subtract the width of node |v|...@>=
  14147. if is_char_node(v) then
  14148.   begin f:=font(v);
  14149.   break_width[1]:=break_width[1]-char_width(f)(char_info(f)(character(v)));
  14150.   end
  14151. else  case type(v) of
  14152.   ligature_node: begin f:=font(lig_char(v));@/
  14153.     break_width[1]:=@|break_width[1]-
  14154.       char_width(f)(char_info(f)(character(lig_char(v))));
  14155.     end;
  14156.   hlist_node,vlist_node,rule_node,kern_node:
  14157.     break_width[1]:=break_width[1]-width(v);
  14158.   othercases confusion("disc1")
  14159. @:this can't happen disc1}{\quad disc1@>
  14160.   endcases
  14161. @ @<Add the width of node |s| to |b...@>=
  14162. if is_char_node(s) then
  14163.   begin f:=font(s);
  14164.   break_width[1]:=@|break_width[1]+char_width(f)(char_info(f)(character(s)));
  14165.   end
  14166. else  case type(s) of
  14167.   ligature_node: begin f:=font(lig_char(s));
  14168.     break_width[1]:=break_width[1]+
  14169.       char_width(f)(char_info(f)(character(lig_char(s))));
  14170.     end;
  14171.   hlist_node,vlist_node,rule_node,kern_node:
  14172.     break_width[1]:=break_width[1]+width(s);
  14173.   othercases confusion("disc2")
  14174. @:this can't happen disc2}{\quad disc2@>
  14175.   endcases
  14176. @ We use the fact that |type(active)<>delta_node|.
  14177. @d convert_to_break_width(#)==@|
  14178.   mem[prev_r+#].sc:=@|@t\hskip10pt@>mem[prev_r+#].sc
  14179.   -cur_active_width[#]+break_width[#]
  14180. @d store_break_width(#)==active_width[#]:=break_width[#]
  14181. @d new_delta_to_break_width(#)==@|
  14182.   mem[q+#].sc:=break_width[#]-cur_active_width[#]
  14183. @<Insert a delta node to prepare for breaks at |cur_p|@>=
  14184. if type(prev_r)=delta_node then {modify an existing delta node}
  14185.   begin do_all_six(convert_to_break_width);
  14186.   end
  14187. else if prev_r=active then {no delta node needed at the beginning}
  14188.   begin do_all_six(store_break_width);
  14189.   end
  14190. else  begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
  14191.   subtype(q):=0; {the |subtype| is not used}
  14192.   do_all_six(new_delta_to_break_width);
  14193.   link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
  14194.   end
  14195. @ When the following code is performed, we will have just inserted at
  14196. least one active node before |r|, so |type(prev_r)<>delta_node|.
  14197. @d new_delta_from_break_width(#)==@|mem[q+#].sc:=
  14198.     cur_active_width[#]-break_width[#]
  14199. @<Insert a delta node to prepare for the next active node@>=
  14200. if r<>last_active then
  14201.   begin q:=get_node(delta_node_size); link(q):=r; type(q):=delta_node;@/
  14202.   subtype(q):=0; {the |subtype| is not used}
  14203.   do_all_six(new_delta_from_break_width);
  14204.   link(prev_r):=q; prev_prev_r:=prev_r; prev_r:=q;
  14205.   end
  14206. @ When we create an active node, we also create the corresponding
  14207. passive node.
  14208. @<Insert a new active node from |best_place[fit_class]| to |cur_p|@>=
  14209. begin q:=get_node(passive_node_size);
  14210. link(q):=passive; passive:=q; cur_break(q):=cur_p;
  14211. @!stat incr(pass_number); serial(q):=pass_number;@+tats@;@/
  14212. prev_break(q):=best_place[fit_class];@/
  14213. q:=get_node(active_node_size); break_node(q):=passive;
  14214. line_number(q):=best_pl_line[fit_class]+1;
  14215. fitness(q):=fit_class; type(q):=break_type;
  14216. total_demerits(q):=minimal_demerits[fit_class];
  14217. link(q):=r; link(prev_r):=q; prev_r:=q;
  14218. @!stat if tracing_paragraphs>0 then
  14219.   @<Print a symbolic description of the new break node@>;
  14220. tats@;@/
  14221. @ @<Print a symbolic description of the new break node@>=
  14222. begin print_nl("@@@@"); print_int(serial(passive));
  14223. @.\AT!\AT!@>
  14224. print(": line "); print_int(line_number(q)-1);
  14225. print_char("."); print_int(fit_class);
  14226. if break_type=hyphenated then print_char("-");
  14227. print(" t="); print_int(total_demerits(q));
  14228. print(" -> @@@@");
  14229. if prev_break(passive)=null then print_char("0")
  14230. else print_int(serial(prev_break(passive)));
  14231. @ The length of lines depends on whether the user has specified
  14232. \.{\\parshape} or \.{\\hangindent}. If |par_shape_ptr| is not null, it
  14233. points to a $(2n+1)$-word record in |mem|, where the |info| in the first
  14234. word contains the value of |n|, and the other $2n$ words contain the left
  14235. margins and line lengths for the first |n| lines of the paragraph; the
  14236. specifications for line |n| apply to all subsequent lines. If
  14237. |par_shape_ptr=null|, the shape of the paragraph depends on the value of
  14238. |n=hang_after|; if |n>=0|, hanging indentation takes place on lines |n+1|,
  14239. |n+2|, \dots, otherwise it takes place on lines 1, \dots, $\vert
  14240. n\vert$. When hanging indentation is active, the left margin is
  14241. |hang_indent|, if |hang_indent>=0|, else it is 0; the line length is
  14242. $|hsize|-\vert|hang_indent|\vert$. The normal setting is
  14243. |par_shape_ptr=null|, |hang_after=0|, and |hang_indent=1|.
  14244. Note that if |hang_indent=0|, the value of |hang_after| is irrelevant.
  14245. @^length of lines@> @^hanging indentation@>
  14246. @<Glob...@>=
  14247. @!easy_line:halfword; {line numbers |>easy_line| are equivalent in break nodes}
  14248. @!last_special_line:halfword; {line numbers |>last_special_line| all have
  14249.   the same width}
  14250. @!first_width:scaled; {the width of all lines |<=last_special_line|, if
  14251.   no \.{\\parshape} has been specified}
  14252. @!second_width:scaled; {the width of all lines |>last_special_line|}
  14253. @!first_indent:scaled; {left margin to go with |first_width|}
  14254. @!second_indent:scaled; {left margin to go with |second_width|}
  14255. @ We compute the values of |easy_line| and the other local variables relating
  14256. to line length when the |line_break| procedure is initializing itself.
  14257. @<Get ready to start...@>=
  14258. if par_shape_ptr=null then
  14259.   if hang_indent=0 then
  14260.     begin last_special_line:=0; second_width:=hsize;
  14261.     second_indent:=0;
  14262.     end
  14263.   else @<Set line length parameters in preparation for hanging indentation@>
  14264. else  begin last_special_line:=info(par_shape_ptr)-1;
  14265.   second_width:=mem[par_shape_ptr+2*(last_special_line+1)].sc;
  14266.   second_indent:=mem[par_shape_ptr+2*last_special_line+1].sc;
  14267.   end;
  14268. if looseness=0 then easy_line:=last_special_line
  14269. else easy_line:=max_halfword
  14270. @ @<Set line length parameters in preparation for hanging indentation@>=
  14271. begin last_special_line:=abs(hang_after);
  14272. if hang_after<0 then
  14273.   begin first_width:=hsize-abs(hang_indent);
  14274.   if hang_indent>=0 then first_indent:=hang_indent
  14275.   else first_indent:=0;
  14276.   second_width:=hsize; second_indent:=0;
  14277.   end
  14278. else  begin first_width:=hsize; first_indent:=0;
  14279.   second_width:=hsize-abs(hang_indent);
  14280.   if hang_indent>=0 then second_indent:=hang_indent
  14281.   else second_indent:=0;
  14282.   end;
  14283. @ When we come to the following code, we have just encountered the first
  14284. active node~|r| whose |line_number| field contains |l|. Thus we want to
  14285. compute the length of the $l\,$th line of the current paragraph. Furthermore,
  14286. we want to set |old_l| to the last number in the class of line numbers
  14287. equivalent to~|l|.
  14288. @<Compute the new line width@>=
  14289. if l>easy_line then
  14290.   begin line_width:=second_width; old_l:=max_halfword-1;
  14291.   end
  14292. else  begin old_l:=l;
  14293.   if l>last_special_line then line_width:=second_width
  14294.   else if par_shape_ptr=null then line_width:=first_width
  14295.   else line_width:=mem[par_shape_ptr+2*l@,].sc;
  14296.   end
  14297. @ The remaining part of |try_break| deals with the calculation of
  14298. demerits for a break from |r| to |cur_p|.
  14299. The first thing to do is calculate the badness, |b|. This value will always
  14300. be between zero and |inf_bad+1|; the latter value occurs only in the
  14301. case of lines from |r| to |cur_p| that cannot shrink enough to fit the necessary
  14302. width. In such cases, node |r| will be deactivated.
  14303. We also deactivate node~|r| when a break at~|cur_p| is forced, since future
  14304. breaks must go through a forced break.
  14305. @<Consider the demerits for a line from |r| to |cur_p|...@>=
  14306. begin artificial_demerits:=false;@/
  14307. @^inner loop@>
  14308. shortfall:=line_width-cur_active_width[1]; {we're this much too short}
  14309. if shortfall>0 then
  14310.   @<Set the value of |b| to the badness for stretching the line,
  14311.     and compute the corresponding |fit_class|@>
  14312. else @<Set the value of |b| to the badness for shrinking the line,
  14313.     and compute the corresponding |fit_class|@>;
  14314. if (b>inf_bad)or(pi=eject_penalty) then
  14315.   @<Prepare to deactivate node~|r|, and |goto deactivate| unless
  14316.     there is a reason to consider lines of text from |r| to |cur_p|@>
  14317. else  begin prev_r:=r;
  14318.   if b>threshold then goto continue;
  14319.   node_r_stays_active:=true;
  14320.   end;
  14321. @<Record a new feasible break@>;
  14322. if node_r_stays_active then goto continue; {|prev_r| has been set to |r|}
  14323. deactivate: @<Deactivate node |r|@>;
  14324. @ When a line must stretch, the available stretchability can be found in the
  14325. subarray |cur_active_width[2..5]|, in units of points, fil, fill, and filll.
  14326. The present section is part of \TeX's inner loop, and it is most often performed
  14327. when the badness is infinite; therefore it is worth while to make a quick
  14328. test for large width excess and small stretchability, before calling the
  14329. |badness| subroutine.
  14330. @^inner loop@>
  14331. @<Set the value of |b| to the badness for stretching...@>=
  14332. if (cur_active_width[3]<>0)or(cur_active_width[4]<>0)or@|
  14333.   (cur_active_width[5]<>0) then
  14334.   begin b:=0; fit_class:=decent_fit; {infinite stretch}
  14335.   end
  14336. else  begin if shortfall>7230584 then if cur_active_width[2]<1663497 then
  14337.     begin b:=inf_bad; fit_class:=very_loose_fit; goto done1;
  14338.     end;
  14339.   b:=badness(shortfall,cur_active_width[2]);
  14340.   if b>12 then
  14341.     if b>99 then fit_class:=very_loose_fit
  14342.     else fit_class:=loose_fit
  14343.   else fit_class:=decent_fit;
  14344.   done1:
  14345.   end
  14346. @ Shrinkability is never infinite in a paragraph;
  14347. we can shrink the line from |r| to |cur_p| by at most |cur_active_width[6]|.
  14348. @<Set the value of |b| to the badness for shrinking...@>=
  14349. begin if -shortfall>cur_active_width[6] then b:=inf_bad+1
  14350. else b:=badness(-shortfall,cur_active_width[6]);
  14351. if b>12 then fit_class:=tight_fit@+else fit_class:=decent_fit;
  14352. @ During the final pass, we dare not lose all active nodes, lest we lose
  14353. touch with the line breaks already found. The code shown here makes sure
  14354. that such a catastrophe does not happen, by permitting overfull boxes as
  14355. a last resort. This particular part of \TeX\ was a source of several subtle
  14356. bugs before the correct program logic was finally discovered; readers
  14357. who seek to ``improve'' \TeX\ should therefore think thrice before daring
  14358. to make any changes here.
  14359. @^overfull boxes@>
  14360. @<Prepare to deactivate node~|r|, and |goto deactivate| unless...@>=
  14361. begin if final_pass and (minimum_demerits=awful_bad) and@|
  14362.    (link(r)=last_active) and
  14363.    (prev_r=active) then
  14364.   artificial_demerits:=true {set demerits zero, this break is forced}
  14365. else if b>threshold then goto deactivate;
  14366. node_r_stays_active:=false;
  14367. @ When we get to this part of the code, the line from |r| to |cur_p| is
  14368. feasible, its badness is~|b|, and its fitness classification is |fit_class|.
  14369. We don't want to make an active node for this break yet, but we will
  14370. compute the total demerits and record them in the |minimal_demerits| array,
  14371. if such a break is the current champion among all ways to get to |cur_p|
  14372. in a given line-number class and fitness class.
  14373. @<Record a new feasible break@>=
  14374. if artificial_demerits then d:=0
  14375. else @<Compute the demerits, |d|, from |r| to |cur_p|@>;
  14376. @!stat if tracing_paragraphs>0 then
  14377.   @<Print a symbolic description of this feasible break@>;
  14378. tats@;@/
  14379. d:=d+total_demerits(r); {this is the minimum total demerits
  14380.   from the beginning to |cur_p| via |r|}
  14381. if d<=minimal_demerits[fit_class] then
  14382.   begin minimal_demerits[fit_class]:=d;
  14383.   best_place[fit_class]:=break_node(r); best_pl_line[fit_class]:=l;
  14384.   if d<minimum_demerits then minimum_demerits:=d;
  14385.   end
  14386. @ @<Print a symbolic description of this feasible break@>=
  14387. begin if printed_node<>cur_p then
  14388.   @<Print the list between |printed_node| and |cur_p|,
  14389.     then set |printed_node:=cur_p|@>;
  14390. print_nl("@@");
  14391. @.\AT!@>
  14392. if cur_p=null then print_esc("par")
  14393. else if type(cur_p)<>glue_node then
  14394.   begin if type(cur_p)=penalty_node then print_esc("penalty")
  14395.   else if type(cur_p)=disc_node then print_esc("discretionary")
  14396.   else if type(cur_p)=kern_node then print_esc("kern")
  14397.   else print_esc("math");
  14398.   end;
  14399. print(" via @@@@");
  14400. if break_node(r)=null then print_char("0")
  14401. else print_int(serial(break_node(r)));
  14402. print(" b=");
  14403. if b>inf_bad then print_char("*")@+else print_int(b);
  14404. @.*\relax@>
  14405. print(" p="); print_int(pi); print(" d=");
  14406. if artificial_demerits then print_char("*")@+else print_int(d);
  14407. @ @<Print the list between |printed_node| and |cur_p|...@>=
  14408. begin print_nl("");
  14409. if cur_p=null then short_display(link(printed_node))
  14410. else  begin save_link:=link(cur_p);
  14411.   link(cur_p):=null; print_nl(""); short_display(link(printed_node));
  14412.   link(cur_p):=save_link;
  14413.   end;
  14414. printed_node:=cur_p;
  14415. @ When the data for a discretionary break is being displayed, we will have
  14416. printed the |pre_break| and |post_break| lists; we want to skip over the
  14417. third list, so that the discretionary data will not appear twice.  The
  14418. following code is performed at the very end of |try_break|.
  14419. @<Update the value of |printed_node|...@>=
  14420. if cur_p=printed_node then if cur_p<>null then if type(cur_p)=disc_node then
  14421.   begin t:=replace_count(cur_p);
  14422.   while t>0 do
  14423.     begin decr(t); printed_node:=link(printed_node);
  14424.     end;
  14425.   end
  14426. @ @<Compute the demerits, |d|, from |r| to |cur_p|@>=
  14427. begin d:=line_penalty+b;
  14428. if abs(d)>=10000 then d:=100000000@+else d:=d*d;
  14429. if pi<>0 then
  14430.   if pi>0 then d:=d+pi*pi
  14431.   else if pi>eject_penalty then d:=d-pi*pi;
  14432. if (break_type=hyphenated)and(type(r)=hyphenated) then
  14433.   if cur_p<>null then d:=d+double_hyphen_demerits
  14434.   else d:=d+final_hyphen_demerits;
  14435. if abs(fit_class-fitness(r))>1 then d:=d+adj_demerits;
  14436. @ When an active node disappears, we must delete an adjacent delta node if the
  14437. active node was at the beginning or the end of the active list, or if it
  14438. was surrounded by delta nodes. We also must preserve the property that
  14439. |cur_active_width| represents the length of material from |link(prev_r)|
  14440. to~|cur_p|.
  14441. @d combine_two_deltas(#)==@|mem[prev_r+#].sc:=mem[prev_r+#].sc+mem[r+#].sc
  14442. @d downdate_width(#)==@|cur_active_width[#]:=cur_active_width[#]-
  14443.   mem[prev_r+#].sc
  14444. @<Deactivate node |r|@>=
  14445. link(prev_r):=link(r); free_node(r,active_node_size);
  14446. if prev_r=active then @<Update the active widths, since the first active
  14447.   node has been deleted@>
  14448. else if type(prev_r)=delta_node then
  14449.   begin r:=link(prev_r);
  14450.   if r=last_active then
  14451.     begin do_all_six(downdate_width);
  14452.     link(prev_prev_r):=last_active;
  14453.     free_node(prev_r,delta_node_size); prev_r:=prev_prev_r;
  14454.     end
  14455.   else if type(r)=delta_node then
  14456.     begin do_all_six(update_width);
  14457.     do_all_six(combine_two_deltas);
  14458.     link(prev_r):=link(r); free_node(r,delta_node_size);
  14459.     end;
  14460.   end
  14461. @ The following code uses the fact that |type(last_active)<>delta_node|. If the
  14462. active list has just become empty, we do not need to update the
  14463. |active_width| array, since it will be initialized when an active
  14464. node is next inserted.
  14465. @d update_active(#)==active_width[#]:=active_width[#]+mem[r+#].sc
  14466. @<Update the active widths,...@>=
  14467. begin r:=link(active);
  14468. if type(r)=delta_node then
  14469.   begin do_all_six(update_active);
  14470.   do_all_six(copy_to_cur_active);
  14471.   link(active):=link(r); free_node(r,delta_node_size);
  14472.   end;
  14473. @* \[39] Breaking paragraphs into lines, continued.
  14474. So far we have gotten a little way into the |line_break| routine, having
  14475. covered its important |try_break| subroutine. Now let's consider the
  14476. rest of the process.
  14477. The main loop of |line_break| traverses the given hlist,
  14478. starting at |link(temp_head)|, and calls |try_break| at each legal
  14479. breakpoint. A variable called |auto_breaking| is set to true except
  14480. within math formulas, since glue nodes are not legal breakpoints when
  14481. they appear in formulas.
  14482. The current node of interest in the hlist is pointed to by |cur_p|. Another
  14483. variable, |prev_p|, is usually one step behind |cur_p|, but the real
  14484. meaning of |prev_p| is this: If |type(cur_p)=glue_node| then |cur_p| is a legal
  14485. breakpoint if and only if |auto_breaking| is true and |prev_p| does not
  14486. point to a glue node, penalty node, explicit kern node, or math node.
  14487. The following declarations provide for a few other local variables that are
  14488. used in special calculations.
  14489. @<Local variables for line breaking@>=
  14490. @!auto_breaking:boolean; {is node |cur_p| outside a formula?}
  14491. @!prev_p:pointer; {helps to determine when glue nodes are breakpoints}
  14492. @!q,@!r,@!s,@!prev_s:pointer; {miscellaneous nodes of temporary interest}
  14493. @!f:internal_font_number; {used when calculating character widths}
  14494. @ The `\ignorespaces|loop|\unskip' in the following code is performed at most
  14495. thrice per call of |line_break|, since it is actually a pass over the
  14496. entire paragraph.
  14497. @<Find optimal breakpoints@>=
  14498. threshold:=pretolerance;
  14499. if threshold>=0 then
  14500.   begin @!stat if tracing_paragraphs>0 then
  14501.     begin begin_diagnostic; print_nl("@@firstpass");@+end;@;@+tats@;@/
  14502.   second_pass:=false; final_pass:=false;
  14503.   end
  14504. else  begin threshold:=tolerance; second_pass:=true;
  14505.   final_pass:=(emergency_stretch<=0);
  14506.   @!stat if tracing_paragraphs>0 then begin_diagnostic;@+tats@;
  14507.   end;
  14508. loop@+  begin if threshold>inf_bad then threshold:=inf_bad;
  14509.   if second_pass then @<Initialize for hyphenating a paragraph@>;
  14510.   @<Create an active breakpoint representing the beginning of the paragraph@>;
  14511.   cur_p:=link(temp_head); auto_breaking:=true;@/
  14512.   prev_p:=cur_p; {glue at beginning is not a legal breakpoint}
  14513.   while (cur_p<>null)and(link(active)<>last_active) do
  14514.     @<Call |try_break| if |cur_p| is a legal breakpoint;
  14515.     on the second pass, also try to hyphenate the next
  14516.     word, if |cur_p| is a glue node;
  14517.     then advance |cur_p| to the next node of the paragraph
  14518.     that could possibly be a legal breakpoint@>;
  14519.   if cur_p=null then
  14520.     @<Try the final line break at the end of the paragraph,
  14521.     and |goto done| if the desired breakpoints have been found@>;
  14522.   @<Clean up the memory by removing the break nodes@>;
  14523.   if not second_pass then
  14524.     begin@!stat if tracing_paragraphs>0 then print_nl("@@secondpass");@;@+tats@/
  14525.     threshold:=tolerance; second_pass:=true; final_pass:=(emergency_stretch<=0);
  14526.     end {if at first you don't succeed, \dots}
  14527.   else begin @!stat if tracing_paragraphs>0 then
  14528.       print_nl("@@emergencypass");@;@+tats@/
  14529.     background[2]:=background[2]+emergency_stretch; final_pass:=true;
  14530.     end;
  14531.   end;
  14532. done: @!stat if tracing_paragraphs>0 then
  14533.   begin end_diagnostic(true); normalize_selector;
  14534.   end;@+tats@/
  14535. @ The active node that represents the starting point does not need a
  14536. corresponding passive node.
  14537. @d store_background(#)==active_width[#]:=background[#]
  14538. @<Create an active breakpoint representing the beginning of the paragraph@>=
  14539. q:=get_node(active_node_size);
  14540. type(q):=unhyphenated; fitness(q):=decent_fit;
  14541. link(q):=last_active; break_node(q):=null;
  14542. line_number(q):=prev_graf+1; total_demerits(q):=0; link(active):=q;
  14543. do_all_six(store_background);@/
  14544. passive:=null; printed_node:=temp_head; pass_number:=0;
  14545. font_in_short_display:=null_font
  14546. @ @<Clean...@>=
  14547. q:=link(active);
  14548. while q<>last_active do
  14549.   begin cur_p:=link(q);
  14550.   if type(q)=delta_node then free_node(q,delta_node_size)
  14551.   else free_node(q,active_node_size);
  14552.   q:=cur_p;
  14553.   end;
  14554. q:=passive;
  14555. while q<>null do
  14556.   begin cur_p:=link(q);
  14557.   free_node(q,passive_node_size);
  14558.   q:=cur_p;
  14559.   end
  14560. @ Here is the main switch in the |line_break| routine, where legal breaks
  14561. are determined. As we move through the hlist, we need to keep the |active_width|
  14562. array up to date, so that the badness of individual lines is readily calculated
  14563. by |try_break|. It is convenient to use the short name |act_width| for
  14564. the component of active width that represents real width as opposed to glue.
  14565. @d act_width==active_width[1] {length from first active node to current node}
  14566. @d kern_break==begin if not is_char_node(link(cur_p)) and auto_breaking then
  14567.     if type(link(cur_p))=glue_node then try_break(0,unhyphenated);
  14568.   act_width:=act_width+width(cur_p);
  14569.   end
  14570. @<Call |try_break| if |cur_p| is a legal breakpoint...@>=
  14571. begin if is_char_node(cur_p) then
  14572.   @<Advance \(c)|cur_p| to the node following the present
  14573.     string of characters@>;
  14574. case type(cur_p) of
  14575. hlist_node,vlist_node,rule_node: act_width:=act_width+width(cur_p);
  14576. whatsit_node: @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>;
  14577. glue_node: begin @<If node |cur_p| is a legal breakpoint, call |try_break|;
  14578.   then update the active widths by including the glue in |glue_ptr(cur_p)|@>;
  14579.   if second_pass and auto_breaking then
  14580.     @<Try to hyphenate the following word@>;
  14581.   end;
  14582. kern_node: if subtype(cur_p)=explicit then kern_break
  14583.   else act_width:=act_width+width(cur_p);
  14584. ligature_node: begin f:=font(lig_char(cur_p));
  14585.   act_width:=act_width+char_width(f)(char_info(f)(character(lig_char(cur_p))));
  14586.   end;
  14587. disc_node: @<Try to break after a discretionary fragment, then |goto done5|@>;
  14588. math_node: begin auto_breaking:=(subtype(cur_p)=after); kern_break;
  14589.   end;
  14590. penalty_node: try_break(penalty(cur_p),unhyphenated);
  14591. mark_node,ins_node,adjust_node: do_nothing;
  14592. othercases confusion("paragraph")
  14593. @:this can't happen paragraph}{\quad paragraph@>
  14594. endcases;@/
  14595. prev_p:=cur_p; cur_p:=link(cur_p);
  14596. done5:end
  14597. @ The code that passes over the characters of words in a paragraph is
  14598. part of \TeX's inner loop, so it has been streamlined for speed. We use
  14599. the fact that `\.{\\parfillskip}' glue appears at the end of each paragraph;
  14600. it is therefore unnecessary to check if |link(cur_p)=null| when |cur_p| is a
  14601. character node.
  14602. @^inner loop@>
  14603. @<Advance \(c)|cur_p| to the node following the present string...@>=
  14604. begin prev_p:=cur_p;
  14605. repeat f:=font(cur_p);
  14606. act_width:=act_width+char_width(f)(char_info(f)(character(cur_p)));
  14607. cur_p:=link(cur_p);
  14608. until not is_char_node(cur_p);
  14609. @ When node |cur_p| is a glue node, we look at |prev_p| to see whether or not
  14610. a breakpoint is legal at |cur_p|, as explained above.
  14611. @<If node |cur_p| is a legal breakpoint, call...@>=
  14612. if auto_breaking then
  14613.   begin if is_char_node(prev_p) then try_break(0,unhyphenated)
  14614.   else if precedes_break(prev_p) then try_break(0,unhyphenated)
  14615.   else if (type(prev_p)=kern_node)and(subtype(prev_p)<>explicit) then
  14616.     try_break(0,unhyphenated);
  14617.   end;
  14618. check_shrinkage(glue_ptr(cur_p)); q:=glue_ptr(cur_p);
  14619. act_width:=act_width+width(q);@|
  14620. active_width[2+stretch_order(q)]:=@|
  14621.   active_width[2+stretch_order(q)]+stretch(q);@/
  14622. active_width[6]:=active_width[6]+shrink(q)
  14623. @ The following code knows that discretionary texts contain
  14624. only character nodes, kern nodes, box nodes, rule nodes, and ligature nodes.
  14625. @<Try to break after a discretionary fragment...@>=
  14626. begin s:=pre_break(cur_p); disc_width:=0;
  14627. if s=null then try_break(ex_hyphen_penalty,hyphenated)
  14628. else  begin repeat @<Add the width of node |s| to |disc_width|@>;
  14629.     s:=link(s);
  14630.   until s=null;
  14631.   act_width:=act_width+disc_width;
  14632.   try_break(hyphen_penalty,hyphenated);
  14633.   act_width:=act_width-disc_width;
  14634.   end;
  14635. r:=replace_count(cur_p); s:=link(cur_p);
  14636. while r>0 do
  14637.   begin @<Add the width of node |s| to |act_width|@>;
  14638.   decr(r); s:=link(s);
  14639.   end;
  14640. prev_p:=cur_p; cur_p:=s; goto done5;
  14641. @ @<Add the width of node |s| to |disc_width|@>=
  14642. if is_char_node(s) then
  14643.   begin f:=font(s);
  14644.   disc_width:=disc_width+char_width(f)(char_info(f)(character(s)));
  14645.   end
  14646. else  case type(s) of
  14647.   ligature_node: begin f:=font(lig_char(s));
  14648.     disc_width:=disc_width+
  14649.       char_width(f)(char_info(f)(character(lig_char(s))));
  14650.     end;
  14651.   hlist_node,vlist_node,rule_node,kern_node:
  14652.     disc_width:=disc_width+width(s);
  14653.   othercases confusion("disc3")
  14654. @:this can't happen disc3}{\quad disc3@>
  14655.   endcases
  14656. @ @<Add the width of node |s| to |act_width|@>=
  14657. if is_char_node(s) then
  14658.   begin f:=font(s);
  14659.   act_width:=act_width+char_width(f)(char_info(f)(character(s)));
  14660.   end
  14661. else  case type(s) of
  14662.   ligature_node: begin f:=font(lig_char(s));
  14663.     act_width:=act_width+
  14664.       char_width(f)(char_info(f)(character(lig_char(s))));
  14665.     end;
  14666.   hlist_node,vlist_node,rule_node,kern_node:
  14667.     act_width:=act_width+width(s);
  14668.   othercases confusion("disc4")
  14669. @:this can't happen disc4}{\quad disc4@>
  14670.   endcases
  14671. @ The forced line break at the paragraph's end will reduce the list of
  14672. breakpoints so that all active nodes represent breaks at |cur_p=null|.
  14673. On the first pass, we insist on finding an active node that has the
  14674. correct ``looseness.'' On the final pass, there will be at least one active
  14675. node, and we will match the desired looseness as well as we can.
  14676. The global variable |best_bet| will be set to the active node for the best
  14677. way to break the paragraph, and a few other variables are used to
  14678. help determine what is best.
  14679. @<Glob...@>=
  14680. @!best_bet:pointer; {use this passive node and its predecessors}
  14681. @!fewest_demerits:integer; {the demerits associated with |best_bet|}
  14682. @!best_line:halfword; {line number following the last line of the new paragraph}
  14683. @!actual_looseness:integer; {the difference between |line_number(best_bet)|
  14684.   and the optimum |best_line|}
  14685. @!line_diff:integer; {the difference between the current line number and
  14686.   the optimum |best_line|}
  14687. @ @<Try the final line break at the end of the paragraph...@>=
  14688. begin try_break(eject_penalty,hyphenated);
  14689. if link(active)<>last_active then
  14690.   begin @<Find an active node with fewest demerits@>;
  14691.   if looseness=0 then goto done;
  14692.   @<Find the best active node for the desired looseness@>;
  14693.   if (actual_looseness=looseness)or final_pass then goto done;
  14694.   end;
  14695. @ @<Find an active node...@>=
  14696. r:=link(active); fewest_demerits:=awful_bad;
  14697. repeat if type(r)<>delta_node then if total_demerits(r)<fewest_demerits then
  14698.   begin fewest_demerits:=total_demerits(r); best_bet:=r;
  14699.   end;
  14700. r:=link(r);
  14701. until r=last_active;
  14702. best_line:=line_number(best_bet)
  14703. @ The adjustment for a desired looseness is a slightly more complicated
  14704. version of the loop just considered. Note that if a paragraph is broken
  14705. into segments by displayed equations, each segment will be subject to the
  14706. looseness calculation, independently of the other segments.
  14707. @<Find the best active node...@>=
  14708. begin r:=link(active); actual_looseness:=0;
  14709. repeat if type(r)<>delta_node then
  14710.   begin line_diff:=line_number(r)-best_line;
  14711.   if ((line_diff<actual_looseness)and(looseness<=line_diff))or@|
  14712.   ((line_diff>actual_looseness)and(looseness>=line_diff)) then
  14713.     begin best_bet:=r; actual_looseness:=line_diff;
  14714.     fewest_demerits:=total_demerits(r);
  14715.     end
  14716.   else if (line_diff=actual_looseness)and@|
  14717.     (total_demerits(r)<fewest_demerits) then
  14718.     begin best_bet:=r; fewest_demerits:=total_demerits(r);
  14719.     end;
  14720.   end;
  14721. r:=link(r);
  14722. until r=last_active;
  14723. best_line:=line_number(best_bet);
  14724. @ Once the best sequence of breakpoints has been found (hurray), we call on the
  14725. procedure |post_line_break| to finish the remainder of the work.
  14726. (By introducing this subprocedure, we are able to keep |line_break|
  14727. from getting extremely long.)
  14728. @<Break the paragraph at the chosen...@>=
  14729. post_line_break(final_widow_penalty)
  14730. @ The total number of lines that will be set by |post_line_break|
  14731. is |best_line-prev_graf-1|. The last breakpoint is specified by
  14732. |break_node(best_bet)|, and this passive node points to the other breakpoints
  14733. via the |prev_break| links. The finishing-up phase starts by linking the
  14734. relevant passive nodes in forward order, changing |prev_break| to
  14735. |next_break|. (The |next_break| fields actually reside in the same memory
  14736. space as the |prev_break| fields did, but we give them a new name because
  14737. of their new significance.) Then the lines are justified, one by one.
  14738. @d next_break==prev_break {new name for |prev_break| after links are reversed}
  14739. @<Declare subprocedures for |line_break|@>=
  14740. procedure post_line_break(@!final_widow_penalty:integer);
  14741. label done,done1;
  14742. var q,@!r,@!s:pointer; {temporary registers for list manipulation}
  14743. @!disc_break:boolean; {was the current break at a discretionary node?}
  14744. @!post_disc_break:boolean; {and did it have a nonempty post-break part?}
  14745. @!cur_width:scaled; {width of line number |cur_line|}
  14746. @!cur_indent:scaled; {left margin of line number |cur_line|}
  14747. @!t:quarterword; {used for replacement counts in discretionary nodes}
  14748. @!pen:integer; {use when calculating penalties between lines}
  14749. @!cur_line: halfword; {the current line number being justified}
  14750. begin @<Reverse the links of the relevant passive nodes, setting |cur_p| to the
  14751.   first breakpoint@>;
  14752. cur_line:=prev_graf+1;
  14753. repeat @<Justify the line ending at breakpoint |cur_p|, and append it to the
  14754.   current vertical list, together with associated penalties and other
  14755.   insertions@>;
  14756. incr(cur_line); cur_p:=next_break(cur_p);
  14757. if cur_p<>null then if not post_disc_break then
  14758.   @<Prune unwanted nodes at the beginning of the next line@>;
  14759. until cur_p=null;
  14760. if (cur_line<>best_line)or(link(temp_head)<>null) then
  14761.   confusion("line breaking");
  14762. @:this can't happen line breaking}{\quad line breaking@>
  14763. prev_graf:=best_line-1;
  14764. @ The job of reversing links in a list is conveniently regarded as the job
  14765. of taking items off one stack and putting them on another. In this case we
  14766. take them off a stack pointed to by |q| and having |prev_break| fields;
  14767. we put them on a stack pointed to by |cur_p| and having |next_break| fields.
  14768. Node |r| is the passive node being moved from stack to stack.
  14769. @<Reverse the links of the relevant passive nodes...@>=
  14770. q:=break_node(best_bet); cur_p:=null;
  14771. repeat r:=q; q:=prev_break(q); next_break(r):=cur_p; cur_p:=r;
  14772. until q=null
  14773. @ Glue and penalty and kern and math nodes are deleted at the beginning of
  14774. a line, except in the anomalous case that the node to be deleted is actually
  14775. one of the chosen breakpoints. Otherwise
  14776. the pruning done here is designed to match
  14777. the lookahead computation in |try_break|, where the |break_width| values
  14778. are computed for non-discretionary breakpoints.
  14779. @<Prune unwanted nodes at the beginning of the next line@>=
  14780. begin r:=temp_head;
  14781. loop@+  begin q:=link(r);
  14782.   if q=cur_break(cur_p) then goto done1;
  14783.     {|cur_break(cur_p)| is the next breakpoint}
  14784.   {now |q| cannot be |null|}
  14785.   if is_char_node(q) then goto done1;
  14786.   if non_discardable(q) then goto done1;
  14787.   if type(q)=kern_node then if subtype(q)<>explicit then goto done1;
  14788.   r:=q; {now |type(q)=glue_node|, |kern_node|, |math_node| or |penalty_node|}
  14789.   end;
  14790. done1: if r<>temp_head then
  14791.   begin link(r):=null; flush_node_list(link(temp_head));
  14792.   link(temp_head):=q;
  14793.   end;
  14794. @ The current line to be justified appears in a horizontal list starting
  14795. at |link(temp_head)| and ending at |cur_break(cur_p)|. If |cur_break(cur_p)| is
  14796. a glue node, we reset the glue to equal the |right_skip| glue; otherwise
  14797. we append the |right_skip| glue at the right. If |cur_break(cur_p)| is a
  14798. discretionary node, we modify the list so that the discretionary break
  14799. is compulsory, and we set |disc_break| to |true|. We also append
  14800. the |left_skip| glue at the left of the line, unless it is zero.
  14801. @<Justify the line ending at breakpoint |cur_p|, and append it...@>=
  14802. @<Modify the end of the line to reflect the nature of the break and to include
  14803.   \.{\\rightskip}; also set the proper value of |disc_break|@>;
  14804. @<Put the \(l)\.{\\leftskip} glue at the left and detach this line@>;
  14805. @<Call the packaging subroutine, setting |just_box| to the justified box@>;
  14806. @<Append the new box to the current vertical list, followed by the list of
  14807.   special nodes taken out of the box by the packager@>;
  14808. @<Append a penalty node, if a nonzero penalty is appropriate@>
  14809. @ At the end of the following code, |q| will point to the final node on the
  14810. list about to be justified.
  14811. @<Modify the end of the line...@>=
  14812. q:=cur_break(cur_p); disc_break:=false; post_disc_break:=false;
  14813. if q<>null then {|q| cannot be a |char_node|}
  14814.   if type(q)=glue_node then
  14815.     begin delete_glue_ref(glue_ptr(q));
  14816.     glue_ptr(q):=right_skip;
  14817.     subtype(q):=right_skip_code+1; add_glue_ref(right_skip);
  14818.     goto done;
  14819.     end
  14820.   else  begin if type(q)=disc_node then
  14821.       @<Change discretionary to compulsory and set
  14822.         |disc_break:=true|@>
  14823.     else if (type(q)=math_node)or(type(q)=kern_node) then width(q):=0;
  14824.     end
  14825. else  begin q:=temp_head;
  14826.   while link(q)<>null do q:=link(q);
  14827.   end;
  14828. @<Put the \(r)\.{\\rightskip} glue after node |q|@>;
  14829. done:
  14830. @ @<Change discretionary to compulsory...@>=
  14831. begin t:=replace_count(q);
  14832. @<Destroy the |t| nodes following |q|, and
  14833.    make |r| point to the following node@>;
  14834. if post_break(q)<>null then @<Transplant the post-break list@>;
  14835. if pre_break(q)<>null then @<Transplant the pre-break list@>;
  14836. link(q):=r; disc_break:=true;
  14837. @ @<Destroy the |t| nodes following |q|...@>=
  14838. if t=0 then r:=link(q)
  14839. else  begin r:=q;
  14840.   while t>1 do
  14841.     begin r:=link(r); decr(t);
  14842.     end;
  14843.   s:=link(r);
  14844.   r:=link(s); link(s):=null;
  14845.   flush_node_list(link(q)); replace_count(q):=0;
  14846.   end
  14847. @ We move the post-break list from inside node |q| to the main list by
  14848. re\-attaching it just before the present node |r|, then resetting |r|.
  14849. @<Transplant the post-break list@>=
  14850. begin s:=post_break(q);
  14851. while link(s)<>null do s:=link(s);
  14852. link(s):=r; r:=post_break(q); post_break(q):=null; post_disc_break:=true;
  14853. @ We move the pre-break list from inside node |q| to the main list by
  14854. re\-attaching it just after the present node |q|, then resetting |q|.
  14855. @<Transplant the pre-break list@>=
  14856. begin s:=pre_break(q); link(q):=s;
  14857. while link(s)<>null do s:=link(s);
  14858. pre_break(q):=null; q:=s;
  14859. @ @<Put the \(r)\.{\\rightskip} glue after node |q|@>=
  14860. r:=new_param_glue(right_skip_code); link(r):=link(q); link(q):=r; q:=r
  14861. @ The following code begins with |q| at the end of the list to be
  14862. justified. It ends with |q| at the beginning of that list, and with
  14863. |link(temp_head)| pointing to the remainder of the paragraph, if any.
  14864. @<Put the \(l)\.{\\leftskip} glue at the left...@>=
  14865. r:=link(q); link(q):=null; q:=link(temp_head); link(temp_head):=r;
  14866. if left_skip<>zero_glue then
  14867.   begin r:=new_param_glue(left_skip_code);
  14868.   link(r):=q; q:=r;
  14869.   end
  14870. @ @<Append the new box to the current vertical list...@>=
  14871. append_to_vlist(just_box);
  14872. if adjust_head<>adjust_tail then
  14873.   begin link(tail):=link(adjust_head); tail:=adjust_tail;
  14874.    end;
  14875. adjust_tail:=null
  14876. @ Now |q| points to the hlist that represents the current line of the
  14877. paragraph. We need to compute the appropriate line width, pack the
  14878. line into a box of this size, and shift the box by the appropriate
  14879. amount of indentation.
  14880. @<Call the packaging subroutine...@>=
  14881. if cur_line>last_special_line then
  14882.   begin cur_width:=second_width; cur_indent:=second_indent;
  14883.   end
  14884. else if par_shape_ptr=null then
  14885.   begin cur_width:=first_width; cur_indent:=first_indent;
  14886.   end
  14887. else  begin cur_width:=mem[par_shape_ptr+2*cur_line].sc;
  14888.   cur_indent:=mem[par_shape_ptr+2*cur_line-1].sc;
  14889.   end;
  14890. adjust_tail:=adjust_head; just_box:=hpack(q,cur_width,exactly);
  14891. shift_amount(just_box):=cur_indent
  14892. @ Penalties between the lines of a paragraph come from club and widow lines,
  14893. from the |inter_line_penalty| parameter, and from lines that end at
  14894. discretionary breaks.  Breaking between lines of a two-line paragraph gets
  14895. both club-line and widow-line penalties. The local variable |pen| will
  14896. be set to the sum of all relevant penalties for the current line, except
  14897. that the final line is never penalized.
  14898. @<Append a penalty node, if a nonzero penalty is appropriate@>=
  14899. if cur_line+1<>best_line then
  14900.   begin pen:=inter_line_penalty;
  14901.   if cur_line=prev_graf+1 then pen:=pen+club_penalty;
  14902.   if cur_line+2=best_line then pen:=pen+final_widow_penalty;
  14903.   if disc_break then pen:=pen+broken_penalty;
  14904.   if pen<>0 then
  14905.     begin r:=new_penalty(pen);
  14906.     link(tail):=r; tail:=r;
  14907.     end;
  14908.   end
  14909. @* \[40] Pre-hyphenation.
  14910. When the line-breaking routine is unable to find a feasible sequence of
  14911. breakpoints, it makes a second pass over the paragraph, attempting to
  14912. hyphenate the hyphenatable words. The goal of hyphenation is to insert
  14913. discretionary material into the paragraph so that there are more
  14914. potential places to break.
  14915. The general rules for hyphenation are somewhat complex and technical,
  14916. because we want to be able to hyphenate words that are preceded or
  14917. followed by punctuation marks, and because we want the rules to work
  14918. for languages other than English. We also must contend with the fact
  14919. that hyphens might radically alter the ligature and kerning structure
  14920. of a word.
  14921. A sequence of characters will be considered for hyphenation only if it
  14922. belongs to a ``potentially hyphenatable part'' of the current paragraph.
  14923. This is a sequence of nodes $p_0p_1\ldots p_m$ where $p_0$ is a glue node,
  14924. $p_1\ldots p_{m-1}$ are either character or ligature or whatsit or
  14925. implicit kern nodes, and $p_m$ is a glue or penalty or insertion or adjust
  14926. or mark or whatsit or explicit kern node.  (Therefore hyphenation is
  14927. disabled by boxes, math formulas, and discretionary nodes already inserted
  14928. by the user.) The ligature nodes among $p_1\ldots p_{m-1}$ are effectively
  14929. expanded into the original non-ligature characters; the kern nodes and
  14930. whatsits are ignored. Each character |c| is now classified as either a
  14931. nonletter (if |lc_code(c)=0|), a lowercase letter (if
  14932. |lc_code(c)=c|), or an uppercase letter (otherwise); an uppercase letter
  14933. is treated as if it were |lc_code(c)| for purposes of hyphenation. The
  14934. characters generated by $p_1\ldots p_{m-1}$ may begin with nonletters; let
  14935. $c_1$ be the first letter that is not in the middle of a ligature. Whatsit
  14936. nodes preceding $c_1$ are ignored; a whatsit found after $c_1$ will be the
  14937. terminating node $p_m$. All characters that do not have the same font as
  14938. $c_1$ will be treated as nonletters. The |hyphen_char| for that font
  14939. must be between 0 and 255, otherwise hyphenation will not be attempted.
  14940. \TeX\ looks ahead for as many consecutive letters $c_1\ldots c_n$ as
  14941. possible; however, |n| must be less than 64, so a character that would
  14942. otherwise be $c_{64}$ is effectively not a letter. Furthermore $c_n$ must
  14943. not be in the middle of a ligature.  In this way we obtain a string of
  14944. letters $c_1\ldots c_n$ that are generated by nodes $p_a\ldots p_b$, where
  14945. |1<=a<=b+1<=m|. If |n>=l_hyf+r_hyf|, this string qualifies for hyphenation;
  14946. however, |uc_hyph| must be positive, if $c_1$ is uppercase.
  14947. The hyphenation process takes place in three stages. First, the candidate
  14948. sequence $c_1\ldots c_n$ is found; then potential positions for hyphens
  14949. are determined by referring to hyphenation tables; and finally, the nodes
  14950. $p_a\ldots p_b$ are replaced by a new sequence of nodes that includes the
  14951. discretionary breaks found.
  14952. Fortunately, we do not have to do all this calculation very often, because
  14953. of the way it has been taken out of \TeX's inner loop. For example, when
  14954. the second edition of the author's 700-page book {\sl Seminumerical
  14955. Algorithms} was typeset by \TeX, only about 1.2 hyphenations needed to be
  14956. @^Knuth, Donald Ervin@>
  14957. tried per paragraph, since the line breaking algorithm needed to use two
  14958. passes on only about 5 per cent of the paragraphs.
  14959. @<Initialize for hyphenating...@>=
  14960. begin @!init if trie_not_ready then init_trie;@+tini@;@/
  14961. cur_lang:=init_cur_lang; l_hyf:=init_l_hyf; r_hyf:=init_r_hyf;
  14962. @ The letters $c_1\ldots c_n$ that are candidates for hyphenation are placed
  14963. into an array called |hc|; the number |n| is placed into |hn|; pointers to
  14964. nodes $p_{a-1}$ and~$p_b$ in the description above are placed into variables
  14965. |ha| and |hb|; and the font number is placed into |hf|.
  14966. @<Glob...@>=
  14967. @!hc:array[0..65] of 0..256; {word to be hyphenated}
  14968. @!hn:small_number; {the number of positions occupied in |hc|}
  14969. @!ha,@!hb:pointer; {nodes |ha..hb| should be replaced by the hyphenated result}
  14970. @!hf:internal_font_number; {font number of the letters in |hc|}
  14971. @!hu:array[0..63] of 0..256; {like |hc|, before conversion to lowercase}
  14972. @!hyf_char:integer; {hyphen character of the relevant font}
  14973. @!cur_lang,@!init_cur_lang:ASCII_code; {current hyphenation table of interest}
  14974. @!l_hyf,@!r_hyf,@!init_l_hyf,@!init_r_hyf:integer; {limits on fragment sizes}
  14975. @!hyf_bchar:halfword; {boundary character after $c_n$}
  14976. @ Hyphenation routines need a few more local variables.
  14977. @<Local variables for line...@>=
  14978. @!j:small_number; {an index into |hc| or |hu|}
  14979. @!c:0..255; {character being considered for hyphenation}
  14980. @ When the following code is activated, the |line_break| procedure is in its
  14981. second pass, and |cur_p| points to a glue node.
  14982. @<Try to hyphenate...@>=
  14983. begin prev_s:=cur_p; s:=link(prev_s);
  14984. if s<>null then
  14985.   begin @<Skip to node |ha|, or |goto done1| if no hyphenation
  14986.     should be attempted@>;
  14987.   if l_hyf+r_hyf>63 then goto done1;
  14988.   @<Skip to node |hb|, putting letters into |hu| and |hc|@>;
  14989.   @<Check that the nodes following |hb| permit hyphenation and that at least
  14990.     |l_hyf+r_hyf| letters have been found, otherwise |goto done1|@>;
  14991.   hyphenate;
  14992.   end;
  14993. done1: end
  14994. @ @<Declare subprocedures for |line_break|@>=
  14995. @t\4@>@<Declare the function called |reconstitute|@>
  14996. procedure hyphenate;
  14997. label common_ending,done,found,found1,found2,not_found,exit;
  14998. var @<Local variables for hyphenation@>@;
  14999. begin @<Find hyphen locations for the word in |hc|, or |return|@>;
  15000. @<If no hyphens were found, |return|@>;
  15001. @<Replace nodes |ha..hb| by a sequence of nodes that includes
  15002.   the discretionary hyphens@>;
  15003. exit:end;
  15004. @ The first thing we need to do is find the node |ha| just before the
  15005. first letter.
  15006. @<Skip to node |ha|, or |goto done1|...@>=
  15007. loop@+  begin if is_char_node(s) then
  15008.     begin c:=qo(character(s)); hf:=font(s);
  15009.     end
  15010.   else if type(s)=ligature_node then
  15011.     if lig_ptr(s)=null then goto continue
  15012.     else begin q:=lig_ptr(s); c:=qo(character(q)); hf:=font(q);
  15013.       end
  15014.   else if (type(s)=kern_node)and(subtype(s)=normal) then goto continue
  15015.   else if type(s)=whatsit_node then
  15016.     begin @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>;
  15017.     goto continue;
  15018.     end
  15019.   else goto done1;
  15020.   if lc_code(c)<>0 then
  15021.     if (lc_code(c)=c)or(uc_hyph>0) then goto done2
  15022.     else goto done1;
  15023. continue: prev_s:=s; s:=link(prev_s);
  15024.   end;
  15025. done2: hyf_char:=hyphen_char[hf];
  15026. if hyf_char<0 then goto done1;
  15027. if hyf_char>255 then goto done1;
  15028. ha:=prev_s
  15029. @ The word to be hyphenated is now moved to the |hu| and |hc| arrays.
  15030. @<Skip to node |hb|, putting letters...@>=
  15031. hn:=0;
  15032. loop@+  begin if is_char_node(s) then
  15033.     begin if font(s)<>hf then goto done3;
  15034.     hyf_bchar:=character(s); c:=qo(hyf_bchar);
  15035.     if lc_code(c)=0 then goto done3;
  15036.     if hn=63 then goto done3;
  15037.     hb:=s; incr(hn); hu[hn]:=c; hc[hn]:=lc_code(c); hyf_bchar:=non_char;
  15038.     end
  15039.   else if type(s)=ligature_node then
  15040.     @<Move the characters of a ligature node to |hu| and |hc|;
  15041.       but |goto done3| if they are not all letters@>
  15042.   else if (type(s)=kern_node)and(subtype(s)=normal) then
  15043.     begin hb:=s;
  15044.     hyf_bchar:=font_bchar[hf];
  15045.     end
  15046.   else goto done3;
  15047.   s:=link(s);
  15048.   end;
  15049. done3:
  15050. @ We let |j| be the index of the character being stored when a ligature node
  15051. is being expanded, since we do not want to advance |hn| until we are sure
  15052. that the entire ligature consists of letters. Note that it is possible
  15053. to get to |done3| with |hn=0| and |hb| not set to any value.
  15054. @<Move the characters of a ligature node to |hu| and |hc|...@>=
  15055. begin if font(lig_char(s))<>hf then goto done3;
  15056. j:=hn; q:=lig_ptr(s);@+if q>null then hyf_bchar:=character(q);
  15057. while q>null do
  15058.   begin c:=qo(character(q));
  15059.   if lc_code(c)=0 then goto done3;
  15060.   if j=63 then goto done3;
  15061.   incr(j); hu[j]:=c; hc[j]:=lc_code(c);@/
  15062.   q:=link(q);
  15063.   end;
  15064. hb:=s; hn:=j;
  15065. if odd(subtype(s)) then hyf_bchar:=font_bchar[hf]@+else hyf_bchar:=non_char;
  15066. @ @<Check that the nodes following |hb| permit hyphenation...@>=
  15067. if hn<l_hyf+r_hyf then goto done1; {|l_hyf| and |r_hyf| are |>=1|}
  15068. loop@+  begin if not(is_char_node(s)) then
  15069.     case type(s) of
  15070.     ligature_node: do_nothing;
  15071.     kern_node: if subtype(s)<>normal then goto done4;
  15072.     whatsit_node,glue_node,penalty_node,ins_node,adjust_node,mark_node:
  15073.       goto done4;
  15074.     othercases goto done1
  15075.     endcases;
  15076.   s:=link(s);
  15077.   end;
  15078. done4:
  15079. @* \[41] Post-hyphenation.
  15080. If a hyphen may be inserted between |hc[j]| and |hc[j+1]|, the hyphenation
  15081. procedure will set |hyf[j]| to some small odd number. But before we look
  15082. at \TeX's hyphenation procedure, which is independent of the rest of the
  15083. line-breaking algorithm, let us consider what we will do with the hyphens
  15084. it finds, since it is better to work on this part of the program before
  15085. forgetting what |ha| and |hb|, etc., are all about.
  15086. @<Glob...@>=
  15087. @!hyf:array [0..64] of 0..9; {odd values indicate discretionary hyphens}
  15088. @!init_list:pointer; {list of punctuation characters preceding the word}
  15089. @!init_lig:boolean; {does |init_list| represent a ligature?}
  15090. @!init_lft:boolean; {if so, did the ligature involve a left boundary?}
  15091. @ @<Local variables for hyphenation@>=
  15092. @!i,@!j,@!l:0..65; {indices into |hc| or |hu|}
  15093. @!q,@!r,@!s:pointer; {temporary registers for list manipulation}
  15094. @!bchar:halfword; {right boundary character of hyphenated word, or |non_char|}
  15095. @ \TeX\ will never insert a hyphen that has fewer than
  15096. \.{\\lefthyphenmin} letters before it or fewer than
  15097. \.{\\righthyphenmin} after it; hence, a short word has
  15098. comparatively little chance of being hyphenated. If no hyphens have
  15099. been found, we can save time by not having to make any changes to the
  15100. paragraph.
  15101. @<If no hyphens were found, |return|@>=
  15102. for j:=l_hyf to hn-r_hyf do if odd(hyf[j]) then goto found1;
  15103. return;
  15104. found1:
  15105. @ If hyphens are in fact going to be inserted, \TeX\ first deletes the
  15106. subsequence of nodes between |ha| and~|hb|. An attempt is made to
  15107. preserve the effect that implicit boundary characters and punctuation marks
  15108. had on ligatures inside the hyphenated word, by storing a left boundary or
  15109. preceding character in |hu[0]| and by storing a possible right boundary
  15110. in |bchar|. We set |j:=0| if |hu[0]| is to be part of the reconstruction;
  15111. otherwise |j:=1|.
  15112. The variable |s| will point to the tail of the current hlist, and
  15113. |q| will point to the node following |hb|, so that
  15114. things can be hooked up after we reconstitute the hyphenated word.
  15115. @<Replace nodes |ha..hb| by a sequence of nodes...@>=
  15116. q:=link(hb); link(hb):=null; r:=link(ha); link(ha):=null; bchar:=hyf_bchar;
  15117. if is_char_node(ha) then
  15118.   if font(ha)<>hf then goto found2
  15119.   else begin init_list:=ha; init_lig:=false; hu[0]:=qo(character(ha));
  15120.     end
  15121. else if type(ha)=ligature_node then
  15122.   if font(lig_char(ha))<>hf then goto found2
  15123.   else begin init_list:=lig_ptr(ha); init_lig:=true; init_lft:=(subtype(ha)>1);
  15124.     hu[0]:=qo(character(lig_char(ha)));
  15125.     if init_list=null then if init_lft then
  15126.       begin hu[0]:=256; init_lig:=false;
  15127.       end; {in this case a ligature will be reconstructed from scratch}
  15128.     free_node(ha,small_node_size);
  15129.     end
  15130. else begin {no punctuation found; look for left boundary}
  15131.   if not is_char_node(r) then if type(r)=ligature_node then
  15132.    if subtype(r)>1 then goto found2;
  15133.   j:=1; s:=ha; init_list:=null; goto common_ending;
  15134.   end;
  15135. s:=cur_p; {we have |cur_p<>ha| because |type(cur_p)=glue_node|}
  15136. while link(s)<>ha do s:=link(s);
  15137. j:=0; goto common_ending;
  15138. found2: s:=ha; j:=0; hu[0]:=256; init_lig:=false; init_list:=null;
  15139. common_ending: flush_node_list(r);
  15140. @<Reconstitute nodes for the hyphenated word, inserting discretionary hyphens@>;
  15141. flush_list(init_list)
  15142. @ We must now face the fact that the battle is not over, even though the
  15143. {\def\!{\kern-1pt}%
  15144. hyphens have been found: The process of reconstituting a word can be nontrivial
  15145. because ligatures might change when a hyphen is present. {\sl The \TeX book\/}
  15146. discusses the difficulties of the word ``difficult'', and
  15147. the discretionary material surrounding a
  15148. hyphen can be considerably more complex than that. Suppose
  15149. \.{abcdef} is a word in a font for which the only ligatures are \.{b\!c},
  15150. \.{c\!d}, \.{d\!e}, and \.{e\!f}. If this word permits hyphenation
  15151. between \.b and \.c, the two patterns with and without hyphenation are
  15152. $\.a\,\.b\,\.-\,\.{c\!d}\,\.{e\!f}$ and $\.a\,\.{b\!c}\,\.{d\!e}\,\.f$.
  15153. Thus the insertion of a hyphen might cause effects to ripple arbitrarily
  15154. far into the rest of the word. A further complication arises if additional
  15155. hyphens appear together with such rippling, e.g., if the word in the
  15156. example just given could also be hyphenated between \.c and \.d; \TeX\
  15157. avoids this by simply ignoring the additional hyphens in such weird cases.}
  15158. Still further complications arise in the presence of ligatures that do not
  15159. delete the original characters. When punctuation precedes the word being
  15160. hyphenated, \TeX's method is not perfect under all possible scenarios,
  15161. because punctuation marks and letters can propagate information back and forth.
  15162. For example, suppose the original pre-hyphenation pair
  15163. \.{*a} changes to \.{*y} via a \.{\?=:} ligature, which changes to \.{xy}
  15164. via a \.{=:\?} ligature; if $p_{a-1}=\.x$ and $p_a=\.y$, the reconstitution
  15165. procedure isn't smart enough to obtain \.{xy} again. In such cases the
  15166. font designer should include a ligature that goes from \.{xa} to \.{xy}.
  15167. @ The processing is facilitated by a subroutine called |reconstitute|. Given
  15168. a string of characters $x_j\ldots x_n$, there is a smallest index $m\ge j$
  15169. such that the ``translation'' of $x_j\ldots x_n$ by ligatures and kerning
  15170. has the form $y_1\ldots y_t$ followed by the translation of $x_{m+1}\ldots x_n$,
  15171. where $y_1\ldots y_t$ is some nonempty sequence of character, ligature, and
  15172. kern nodes. We call $x_j\ldots x_m$ a ``cut prefix'' of $x_j\ldots x_n$.
  15173. For example, if $x_1x_2x_3=\.{fly}$, and if the font contains `fl' as a
  15174. ligature and a kern between `fl' and `y', then $m=2$, $y=2$, and $y_1$ will
  15175. be a ligature node for `fl' followed by an appropriate kern node~$y_2$.
  15176. In the most common case, $x_j$~forms no ligature with $x_{j+1}$ and we
  15177. simply have $m=j$, $y_1=x_j$. If $m<n$ we can repeat the procedure on
  15178. $x_{m+1}\ldots x_n$ until the entire translation has been found.
  15179. The |reconstitute| function returns the integer $m$ and puts the nodes
  15180. $y_1\ldots y_t$ into a linked list starting at |link(hold_head)|,
  15181. getting the input $x_j\ldots x_n$ from the |hu| array. If $x_j=256$,
  15182. we consider $x_j$ to be an implicit left boundary character; in this
  15183. case |j| must be strictly less than~|n|. There is a
  15184. parameter |bchar|, which is either 256 or an implicit right boundary character
  15185. assumed to be present just following~$x_n$. (The value |hu[n+1]| is never
  15186. explicitly examined, but the algorithm imagines that |bchar| is there.)
  15187. If there exists an index |k| in the range $j\le k\le m$ such that |hyf[k]|
  15188. is odd and such that the result of |reconstitute| would have been different
  15189. if $x_{k+1}$ had been |hchar|, then |reconstitute| sets |hyphen_passed|
  15190. to the smallest such~|k|. Otherwise it sets |hyphen_passed| to zero.
  15191. A special convention is used in the case |j=0|: Then we assume that the
  15192. translation of |hu[0]| appears in a special list of charnodes starting at
  15193. |init_list|; moreover, if |init_lig| is |true|, then |hu[0]| will be
  15194. a ligature character, involving a left boundary if |init_lft| is |true|.
  15195. This facility is provided for cases when a hyphenated
  15196. word is preceded by punctuation (like single or double quotes) that might
  15197. affect the translation of the beginning of the word.
  15198. @<Glob...@>=
  15199. @!hyphen_passed:small_number; {first hyphen in a ligature, if any}
  15200. @ @<Declare the function called |reconstitute|@>=
  15201. function reconstitute(@!j,@!n:small_number;@!bchar,@!hchar:halfword):
  15202.   small_number;
  15203. label continue,done;
  15204. var @!p:pointer; {temporary register for list manipulation} 
  15205. @!t:pointer; {a node being appended to}
  15206. @!q:four_quarters; {character information or a lig/kern instruction}
  15207. @!cur_rh:halfword; {hyphen character for ligature testing}
  15208. @!test_char:halfword; {hyphen or other character for ligature testing}
  15209. @!w:scaled; {amount of kerning}
  15210. @!k:font_index; {position of current lig/kern instruction}
  15211. begin hyphen_passed:=0; t:=hold_head; w:=0; link(hold_head):=null;
  15212.  {at this point |ligature_present=lft_hit=rt_hit=false|}
  15213. @<Set up data structures with the cursor following position |j|@>;
  15214. continue:@<If there's a ligature or kern at the cursor position, update the data
  15215.   structures, possibly advancing~|j|; continue until the cursor moves@>;
  15216. @<Append a ligature and/or kern to the translation;
  15217.   |goto continue| if the stack of inserted ligatures is nonempty@>;
  15218. reconstitute:=j;
  15219. @ The reconstitution procedure shares many of the global data structures
  15220. by which \TeX\ has processed the words before they were hyphenated.
  15221. There is an implied ``cursor'' between characters |cur_l| and |cur_r|;
  15222. these characters will be tested for possible ligature activity. If
  15223. |ligature_present| then |cur_l| is a ligature character formed from the
  15224. original characters following |cur_q| in the current translation list.
  15225. There is a ``ligature stack'' between the cursor and character |j+1|,
  15226. consisting of pseudo-ligature nodes linked together by their |link| fields.
  15227. This stack is normally empty unless a ligature command has created a new
  15228. character that will need to be processed later. A pseudo-ligature is
  15229. a special node having a |character| field that represents a potential
  15230. ligature and a |lig_ptr| field that points to a |char_node| or is |null|.
  15231. We have
  15232. $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
  15233.   |qi(hu[j+1])|,&if |lig_stack=null| and |j<n|;\cr
  15234.   bchar,&if |lig_stack=null| and |j=n|.\cr}$$
  15235. @<Glob...@>=
  15236. @!cur_l,@!cur_r:halfword; {characters before and after the cursor}
  15237. @!cur_q:pointer; {where a ligature should be detached}
  15238. @!lig_stack:pointer; {unfinished business to the right of the cursor}
  15239. @!ligature_present:boolean; {should a ligature node be made for |cur_l|?}
  15240. @!lft_hit,@!rt_hit:boolean; {did we hit a ligature with a boundary character?}
  15241. @ @d append_charnode_to_t(#)== begin link(t):=get_avail; t:=link(t);
  15242.     font(t):=hf; character(t):=#;
  15243.     end
  15244. @d set_cur_r==begin if j<n then cur_r:=qi(hu[j+1])@+else cur_r:=bchar;
  15245.     if odd(hyf[j]) then cur_rh:=hchar@+else cur_rh:=non_char;
  15246.     end
  15247. @<Set up data structures with the cursor following position |j|@>=
  15248. cur_l:=qi(hu[j]); cur_q:=t;
  15249. if j=0 then
  15250.   begin ligature_present:=init_lig; p:=init_list;
  15251.   if ligature_present then lft_hit:=init_lft;
  15252.   while p>null do
  15253.     begin append_charnode_to_t(character(p)); p:=link(p);
  15254.     end;
  15255.   end
  15256. else if cur_l<non_char then append_charnode_to_t(cur_l);
  15257. lig_stack:=null; set_cur_r
  15258. @ We may want to look at the lig/kern program twice, once for a hyphen
  15259. and once for a normal letter. (The hyphen might appear after the letter
  15260. in the program, so we'd better not try to look for both at once.)
  15261. @<If there's a ligature or kern at the cursor position, update...@>=
  15262. if cur_l=non_char then
  15263.   begin k:=bchar_label[hf];
  15264.   if k=non_address then goto done@+else q:=font_info[k].qqqq;
  15265.   end
  15266. else begin q:=char_info(hf)(cur_l);
  15267.   if char_tag(q)<>lig_tag then goto done;
  15268.   k:=lig_kern_start(hf)(q); q:=font_info[k].qqqq;
  15269.   if skip_byte(q)>stop_flag then
  15270.     begin k:=lig_kern_restart(hf)(q); q:=font_info[k].qqqq;
  15271.     end;
  15272.   end; {now |k| is the starting address of the lig/kern program}
  15273. if cur_rh<non_char then test_char:=cur_rh@+else test_char:=cur_r;
  15274. loop@+begin if next_char(q)=test_char then if skip_byte(q)<=stop_flag then
  15275.     if cur_rh<non_char then
  15276.       begin hyphen_passed:=j; hchar:=non_char; cur_rh:=non_char;
  15277.       goto continue;
  15278.       end
  15279.     else begin if hchar<non_char then if odd(hyf[j]) then
  15280.         begin hyphen_passed:=j; hchar:=non_char;
  15281.         end;
  15282.       if op_byte(q)<kern_flag then
  15283.       @<Carry out a ligature replacement, updating the cursor structure
  15284.         and possibly advancing~|j|; |goto continue| if the cursor doesn't
  15285.         advance, otherwise |goto done|@>;
  15286.       w:=char_kern(hf)(q); goto done; {this kern will be inserted below}
  15287.      end;
  15288.   if skip_byte(q)>=stop_flag then
  15289.     if cur_rh=non_char then goto done
  15290.     else begin cur_rh:=non_char; goto continue;
  15291.       end;
  15292.   k:=k+qo(skip_byte(q))+1; q:=font_info[k].qqqq;
  15293.   end;
  15294. done:
  15295. @ @d wrap_lig(#)==if ligature_present then
  15296.     begin p:=new_ligature(hf,cur_l,link(cur_q));
  15297.     if lft_hit then
  15298.       begin subtype(p):=2; lft_hit:=false;
  15299.       end;
  15300.     if # then if lig_stack=null then
  15301.       begin incr(subtype(p)); rt_hit:=false;
  15302.       end;
  15303.     link(cur_q):=p; t:=p; ligature_present:=false;
  15304.     end
  15305. @d pop_lig_stack==begin if lig_ptr(lig_stack)>null then
  15306.     begin link(t):=lig_ptr(lig_stack); {this is a charnode for |hu[j+1]|}
  15307.     t:=link(t); incr(j);
  15308.     end;
  15309.   p:=lig_stack; lig_stack:=link(p); free_node(p,small_node_size);
  15310.   if lig_stack=null then set_cur_r@+else cur_r:=character(lig_stack);
  15311.   end {if |lig_stack| isn't |null| we have |cur_rh=non_char|}
  15312. @<Append a ligature and/or kern to the translation...@>=
  15313. wrap_lig(rt_hit);
  15314. if w<>0 then
  15315.   begin link(t):=new_kern(w); t:=link(t); w:=0;
  15316.   end;
  15317. if lig_stack>null then
  15318.   begin cur_q:=t; cur_l:=character(lig_stack); ligature_present:=true;
  15319.   pop_lig_stack; goto continue;
  15320.   end
  15321. @ @<Carry out a ligature replacement, updating the cursor structure...@>=
  15322. begin if cur_l=non_char then lft_hit:=true;
  15323. if j=n then if lig_stack=null then rt_hit:=true;
  15324. check_interrupt; {allow a way out in case there's an infinite ligature loop}
  15325. case op_byte(q) of
  15326. qi(1),qi(5):begin cur_l:=rem_byte(q); {\.{=:\?}, \.{=:\?>}}
  15327.   ligature_present:=true;
  15328.   end;
  15329. qi(2),qi(6):begin cur_r:=rem_byte(q); {\.{\?=:}. \.{\?=:>}}
  15330.   if lig_stack>null then character(lig_stack):=cur_r
  15331.   else begin lig_stack:=new_lig_item(cur_r);
  15332.     if j=n then bchar:=non_char
  15333.     else begin p:=get_avail; lig_ptr(lig_stack):=p;
  15334.       character(p):=qi(hu[j+1]); font(p):=hf;
  15335.       end;
  15336.     end;
  15337.   end;
  15338. qi(3):begin cur_r:=rem_byte(q); {\.{\?=:\?}}
  15339.   p:=lig_stack; lig_stack:=new_lig_item(cur_r); link(lig_stack):=p;
  15340.   end;
  15341. qi(7),qi(11):begin wrap_lig(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
  15342.   cur_q:=t; cur_l:=rem_byte(q); ligature_present:=true;
  15343.   end;
  15344. othercases begin cur_l:=rem_byte(q); ligature_present:=true; {\.{=:}}
  15345.   if lig_stack>null then pop_lig_stack
  15346.   else if j=n then goto done
  15347.   else begin append_charnode_to_t(cur_r); incr(j); set_cur_r;
  15348.     end;
  15349.   end
  15350. endcases;
  15351. if op_byte(q)>qi(4) then if op_byte(q)<>qi(7) then goto done;
  15352. goto continue;
  15353. @ Okay, we're ready to insert the potential hyphenations that were found.
  15354. When the following program is executed, we want to append the word
  15355. |hu[1..hn]| after node |ha|, and node |q| should be appended to the result.
  15356. During this process, the variable |i| will be a temporary
  15357. index into |hu|; the variable |j| will be an index to our current position
  15358. in |hu|; the variable |l| will be the counterpart of |j|, in a discretionary
  15359. branch; the variable |r| will point to new nodes being created; and
  15360. we need a few new local variables:
  15361. @<Local variables for hyph...@>=
  15362. @!major_tail,@!minor_tail:pointer; {the end of lists in the main and
  15363.   discretionary branches being reconstructed}
  15364. @!c:ASCII_code; {character temporarily replaced by a hyphen}
  15365. @!c_loc:0..63; {where that character came from}
  15366. @!r_count:integer; {replacement count for discretionary}
  15367. @!hyf_node:pointer; {the hyphen, if it exists}
  15368. @ When the following code is performed, |hyf[0]| and |hyf[hn]| will be zero.
  15369. @<Reconstitute nodes for the hyphenated word...@>=
  15370. repeat l:=j; j:=reconstitute(j,hn,bchar,qi(hyf_char))+1;
  15371. if hyphen_passed=0 then
  15372.   begin link(s):=link(hold_head);
  15373.   while link(s)>null do s:=link(s);
  15374.   if odd(hyf[j-1]) then
  15375.     begin l:=j; hyphen_passed:=j-1; link(hold_head):=null;
  15376.     end;
  15377.   end;
  15378. if hyphen_passed>0 then
  15379.   @<Create and append a discretionary node as an alternative to the
  15380.     unhyphenated word, and continue to develop both branches until they
  15381.     become equivalent@>;
  15382. until j>hn;
  15383. link(s):=q
  15384. @ In this repeat loop we will insert another discretionary if |hyf[j-1]| is
  15385. odd, when both branches of the previous discretionary end at position |j-1|.
  15386. Strictly speaking, we aren't justified in doing this, because we don't know
  15387. that a hyphen after |j-1| is truly independent of those branches. But in almost
  15388. all applications we would rather not lose a potentially valuable hyphenation
  15389. point. (Consider the word `difficult', where the letter `c' is in position |j|.)
  15390. @d advance_major_tail==begin major_tail:=link(major_tail); incr(r_count);
  15391.     end
  15392. @<Create and append a discretionary node as an alternative...@>=
  15393. repeat r:=get_node(small_node_size);
  15394. link(r):=link(hold_head); type(r):=disc_node;
  15395. major_tail:=r; r_count:=0;
  15396. while link(major_tail)>null do advance_major_tail;
  15397. i:=hyphen_passed; hyf[i]:=0;
  15398. @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>;
  15399. @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|, appending to this
  15400.   list and to |major_tail| until synchronization has been achieved@>;
  15401. @<Move pointer |s| to the end of the current list, and set |replace_count(r)|
  15402.   appropriately@>;
  15403. hyphen_passed:=j-1; link(hold_head):=null;
  15404. until not odd(hyf[j-1])
  15405. @ The new hyphen might combine with the previous character via ligature
  15406. or kern. At this point we have |l-1<=i<j| and |i<hn|.
  15407. @<Put the \(c)characters |hu[l..i]| and a hyphen into |pre_break(r)|@>=
  15408. minor_tail:=null; pre_break(r):=null; hyf_node:=new_character(hf,hyf_char);
  15409. if hyf_node<>null then
  15410.   begin incr(i); c:=hu[i]; hu[i]:=hyf_char; free_avail(hyf_node);
  15411.   end;
  15412. while l<=i do
  15413.   begin l:=reconstitute(l,i,font_bchar[hf],non_char)+1;
  15414.   if link(hold_head)>null then
  15415.     begin if minor_tail=null then pre_break(r):=link(hold_head)
  15416.     else link(minor_tail):=link(hold_head);
  15417.     minor_tail:=link(hold_head);
  15418.     while link(minor_tail)>null do minor_tail:=link(minor_tail);
  15419.     end;
  15420.   end;
  15421. if hyf_node<>null then
  15422.   begin hu[i]:=c; {restore the character in the hyphen position}
  15423.   l:=i; decr(i);
  15424.   end
  15425. @ The synchronization algorithm begins with |l=i+1<=j|.
  15426. @<Put the \(c)characters |hu[i+1..@,]| into |post_break(r)|...@>=
  15427. minor_tail:=null; post_break(r):=null; c_loc:=0;
  15428. if bchar_label[hf]<non_address then {put left boundary at beginning of new line}
  15429.   begin decr(l); c:=hu[l]; c_loc:=l; hu[l]:=256;
  15430.   end;
  15431. while l<j do
  15432.   begin repeat l:=reconstitute(l,hn,bchar,non_char)+1;
  15433.   if c_loc>0 then
  15434.     begin hu[c_loc]:=c; c_loc:=0;
  15435.     end;
  15436.   if link(hold_head)>null then
  15437.     begin if minor_tail=null then post_break(r):=link(hold_head)
  15438.     else link(minor_tail):=link(hold_head);
  15439.     minor_tail:=link(hold_head);
  15440.     while link(minor_tail)>null do minor_tail:=link(minor_tail);
  15441.     end;
  15442.   until l>=j;
  15443.   while l>j do
  15444.     @<Append characters of |hu[j..@,]| to |major_tail|, advancing~|j|@>;
  15445.   end
  15446. @ @<Append characters of |hu[j..@,]|...@>=
  15447. begin j:=reconstitute(j,hn,bchar,non_char)+1;
  15448. link(major_tail):=link(hold_head);
  15449. while link(major_tail)>null do advance_major_tail;
  15450. @ Ligature insertion can cause a word to grow exponentially in size. Therefore
  15451. we must test the size of |r_count| here, even though the hyphenated text
  15452. was at most 63 characters long.
  15453. @<Move pointer |s| to the end of the current list...@>=
  15454. if r_count>127 then {we have to forget the discretionary hyphen}
  15455.   begin link(s):=link(r); link(r):=null; flush_node_list(r);
  15456.   end
  15457. else begin link(s):=r; replace_count(r):=r_count;
  15458.   end;
  15459. s:=major_tail
  15460. @* \[42] Hyphenation.
  15461. When a word |hc[1..hn]| has been set up to contain a candidate for hyphenation,
  15462. \TeX\ first looks to see if it is in the user's exception dictionary. If not,
  15463. hyphens are inserted based on patterns that appear within the given word,
  15464. using an algorithm due to Frank~M. Liang.
  15465. @^Liang, Franklin Mark@>
  15466. Let's consider Liang's method first, since it is much more interesting than the
  15467. exception-lookup routine.  The algorithm begins by setting |hyf[j]| to zero
  15468. for all |j|, and invalid characters are inserted into |hc[0]|
  15469. and |hc[hn+1]| to serve as delimiters. Then a reasonably fast method is
  15470. used to see which of a given set of patterns occurs in the word
  15471. |hc[0..(hn+1)]|. Each pattern $p_1\ldots p_k$ of length |k| has an associated
  15472. sequence of |k+1| numbers $n_0\ldots n_k$; and if the pattern occurs in
  15473. |hc[(j+1)..(j+k)]|, \TeX\ will set |hyf[j+i]:=@tmax@>(hyf[j+i],@t$n_i$@>)| for
  15474. |0<=i<=k|. After this has been done for each pattern that occurs, a
  15475. discretionary hyphen will be inserted between |hc[j]| and |hc[j+1]| when
  15476. |hyf[j]| is odd, as we have already seen.
  15477. The set of patterns $p_1\ldots p_k$ and associated numbers $n_0\ldots n_k$
  15478. depends, of course, on the language whose words are being hyphenated, and
  15479. on the degree of hyphenation that is desired. A method for finding
  15480. appropriate |p|'s and |n|'s, from a given dictionary of words and acceptable
  15481. hyphenations, is discussed in Liang's Ph.D. thesis (Stanford University,
  15482. 1983); \TeX\ simply starts with the patterns and works from there.
  15483. @ The patterns are stored in a compact table that is also efficient for
  15484. retrieval, using a variant of ``trie memory'' [cf.\ {\sl The Art of
  15485. Computer Programming \bf3} (1973), 481--505]. We can find each pattern
  15486. $p_1\ldots p_k$ by letting $z_0$ be one greater than the relevant language
  15487. index and then, for |1<=i<=k|,
  15488. setting |@t$z_i$@>:=trie_link@t$(z_{i-1})+p_i$@>|; the pattern will be
  15489. identified by the number $z_k$. Since all the pattern information is
  15490. packed together into a single |trie_link| array, it is necessary to
  15491. prevent confusion between the data from inequivalent patterns, so another
  15492. table is provided such that |trie_char@t$(z_i)=p_i$@>| for all |i|. There
  15493. is also a table |trie_op|$(z_k)$ to identify the numbers $n_0\ldots n_k$
  15494. associated with $p_1\ldots p_k$.
  15495. Comparatively few different number sequences $n_0\ldots n_k$ actually occur,
  15496. since most of the |n|'s are generally zero. Therefore the number sequences
  15497. are encoded in such a way that |trie_op|$(z_k)$ is only one byte long.
  15498. If |trie_op(@t$z_k$@>)<>min_quarterword|, when $p_1\ldots p_k$ has matched
  15499. the letters in |hc[(l-k+1)..l@,]| of language |t|,
  15500. we perform all of the required operations
  15501. for this pattern by carrying out the following little program: Set
  15502. |v:=trie_op(@t$z_k$@>)|. Then set |v:=v+op_start[t]|,
  15503. |hyf[l-hyf_distance[v]]:=@tmax@>(hyf[l-hyf_distance[v]], hyf_num[v])|,
  15504. and |v:=hyf_next[v]|; repeat, if necessary, until |v=min_quarterword|.
  15505. @<Types...@>=
  15506. @!trie_pointer=0..trie_size; {an index into |trie|}
  15507. @ @d trie_link(#)==trie[#].rh {``downward'' link in a trie}
  15508. @d trie_char(#)==trie[#].b1 {character matched at this trie location}
  15509. @d trie_op(#)==trie[#].b0 {program for hyphenation at this trie location}
  15510. @<Glob...@>=
  15511. @!trie:array[trie_pointer] of two_halves; {|trie_link|, |trie_char|, |trie_op|}
  15512. @!hyf_distance:array[1..trie_op_size] of small_number; {position |k-j| of $n_j$}
  15513. @!hyf_num:array[1..trie_op_size] of small_number; {value of $n_j$}
  15514. @!hyf_next:array[1..trie_op_size] of quarterword; {continuation code}
  15515. @!op_start:array[ASCII_code] of 0..trie_op_size; {offset for current language}
  15516. @ @<Local variables for hyph...@>=
  15517. @!z:trie_pointer; {an index into |trie|}
  15518. @!v:integer; {an index into |hyf_distance|, etc.}
  15519. @ Assuming that these auxiliary tables have been set up properly, the
  15520. hyphenation algorithm is quite short. In the following code we set |hc[hn+2]|
  15521. to the impossible value 256, in order to guarantee that |hc[hn+3]| will
  15522. never be fetched.
  15523. @<Find hyphen locations for the word in |hc|...@>=
  15524. for j:=0 to hn do hyf[j]:=0;
  15525. @<Look for the word |hc[1..hn]| in the exception table, and |goto found| (with
  15526.   |hyf| containing the hyphens) if an entry is found@>;
  15527. if trie_char(cur_lang+1)<>qi(cur_lang) then return; {no patterns for |cur_lang|}
  15528. hc[0]:=0; hc[hn+1]:=0; hc[hn+2]:=256; {insert delimiters}
  15529. for j:=0 to hn-r_hyf+1 do
  15530.   begin z:=trie_link(cur_lang+1)+hc[j]; l:=j;
  15531.   while hc[l]=qo(trie_char(z)) do
  15532.     begin if trie_op(z)<>min_quarterword then
  15533.       @<Store \(m)maximum values in the |hyf| table@>;
  15534.     incr(l); z:=trie_link(z)+hc[l];
  15535.     end;
  15536.   end;
  15537. found: for j:=0 to l_hyf-1 do hyf[j]:=0;
  15538. for j:=0 to r_hyf-1 do hyf[hn-j]:=0
  15539. @ @<Store \(m)maximum values in the |hyf| table@>=
  15540. begin v:=trie_op(z);
  15541. repeat v:=v+op_start[cur_lang]; i:=l-hyf_distance[v];
  15542. if hyf_num[v]>hyf[i] then hyf[i]:=hyf_num[v];
  15543. v:=hyf_next[v];
  15544. until v=min_quarterword;
  15545. @ The exception table that is built by \TeX's \.{\\hyphenation} primitive is
  15546. organized as an ordered hash table [cf.\ Amble and Knuth, {\sl The Computer
  15547. @^Amble, Ole@> @^Knuth, Donald Ervin@>
  15548. Journal\/ \bf17} (1974), 135--142] using linear probing. If $\alpha$ and
  15549. $\beta$ are words, we will say that $\alpha<\beta$ if $\vert\alpha\vert<
  15550. \vert\beta\vert$ or if $\vert\alpha\vert=\vert\beta\vert$ and
  15551. $\alpha$ is lexicographically smaller than $\beta$. (The notation $\vert
  15552. \alpha\vert$ stands for the length of $\alpha$.) The idea of ordered hashing
  15553. is to arrange the table so that a given word $\alpha$ can be sought by computing
  15554. a hash address $h=h(\alpha)$ and then looking in table positions |h|, |h-1|,
  15555. \dots, until encountering the first word $\L\alpha$. If this word is
  15556. different from $\alpha$, we can conclude that $\alpha$ is not in the table.
  15557. The words in the table point to lists in |mem| that specify hyphen positions
  15558. in their |info| fields. The list for $c_1\ldots c_n$ contains the number |k| if
  15559. the word $c_1\ldots c_n$ has a discretionary hyphen between $c_k$ and
  15560. $c_{k+1}$.
  15561. @<Types...@>=
  15562. @!hyph_pointer=0..hyph_size; {an index into the ordered hash table}
  15563. @ @<Glob...@>=
  15564. @!hyph_word:array[hyph_pointer] of str_number; {exception words}
  15565. @!hyph_list:array[hyph_pointer] of pointer; {list of hyphen positions}
  15566. @!hyph_count:hyph_pointer; {the number of words in the exception dictionary}
  15567. @ @<Local variables for init...@>=
  15568. @!z:hyph_pointer; {runs through the exception dictionary}
  15569. @ @<Set init...@>=
  15570. for z:=0 to hyph_size do
  15571.   begin hyph_word[z]:=0; hyph_list[z]:=null;
  15572.   end;
  15573. hyph_count:=0;
  15574. @ The algorithm for exception lookup is quite simple, as soon as we have
  15575. a few more local variables to work with.
  15576. @<Local variables for hyph...@>=
  15577. @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
  15578. @!k:str_number; {an index into |str_start|}
  15579. @!u:pool_pointer; {an index into |str_pool|}
  15580. @ First we compute the hash code |h|, then we search until we either
  15581. find the word or we don't. Words from different languages are kept
  15582. separate by appending the language code to the string.
  15583. @<Look for the word |hc[1...@>=
  15584. h:=hc[1]; incr(hn); hc[hn]:=cur_lang;
  15585. for j:=2 to hn do h:=(h+h+hc[j]) mod hyph_size;
  15586. loop@+  begin @<If the string |hyph_word[h]| is less than \(hc)|hc[1..hn]|,
  15587.     |goto not_found|; but if the two strings are equal,
  15588.     set |hyf| to the hyphen positions and |goto found|@>;
  15589.   if h>0 then decr(h)@+else h:=hyph_size;
  15590.   end;
  15591. not_found: decr(hn)
  15592. @ @<If the string |hyph_word[h]| is less than \(hc)...@>=
  15593. k:=hyph_word[h]; if k=0 then goto not_found;
  15594. if length(k)<hn then goto not_found;
  15595. if length(k)=hn then
  15596.   begin j:=1; u:=str_start[k];
  15597.   repeat if so(str_pool[u])<hc[j] then goto not_found;
  15598.   if so(str_pool[u])>hc[j] then goto done;
  15599.   incr(j); incr(u);
  15600.   until j>hn;
  15601.   @<Insert hyphens as specified in |hyph_list[h]|@>;
  15602.   decr(hn); goto found;
  15603.   end;
  15604. done:
  15605. @ @<Insert hyphens as specified...@>=
  15606. s:=hyph_list[h];
  15607. while s<>null do
  15608.   begin hyf[info(s)]:=1; s:=link(s);
  15609.   end
  15610. @ @<Search |hyph_list| for pointers to |p|@>=
  15611. for q:=0 to hyph_size do
  15612.   begin if hyph_list[q]=p then
  15613.     begin print_nl("HYPH("); print_int(q); print_char(")");
  15614.     end;
  15615.   end
  15616. @ We have now completed the hyphenation routine, so the |line_break| procedure
  15617. is finished at last. Since the hyphenation exception table is fresh in our
  15618. minds, it's a good time to deal with the routine that adds new entries to it.
  15619. When \TeX\ has scanned `\.{\\hyphenation}', it calls on a procedure named
  15620. |new_hyph_exceptions| to do the right thing.
  15621. @d set_cur_lang==if language<=0 then cur_lang:=0
  15622.   else if language>255 then cur_lang:=0
  15623.   else cur_lang:=language
  15624. @p procedure new_hyph_exceptions; {enters new exceptions}
  15625. label reswitch, exit, found, not_found;
  15626. var n:0..64; {length of current word; not always a |small_number|}
  15627. @!j:0..64; {an index into |hc|}
  15628. @!h:hyph_pointer; {an index into |hyph_word| and |hyph_list|}
  15629. @!k:str_number; {an index into |str_start|}
  15630. @!p:pointer; {head of a list of hyphen positions}
  15631. @!q:pointer; {used when creating a new node for list |p|}
  15632. @!s,@!t:str_number; {strings being compared or stored}
  15633. @!u,@!v:pool_pointer; {indices into |str_pool|}
  15634. begin scan_left_brace; {a left brace must follow \.{\\hyphenation}}
  15635. set_cur_lang;
  15636. @<Enter as many hyphenation exceptions as are listed,
  15637. until coming to a right brace; then |return|@>;
  15638. exit:end;
  15639. @ @<Enter as many...@>=
  15640. n:=0; p:=null;
  15641. loop@+  begin get_x_token;
  15642.   reswitch: case cur_cmd of
  15643.   letter,other_char,char_given:@<Append a new letter or hyphen@>;
  15644.   char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
  15645.     goto reswitch;
  15646.     end;
  15647.   spacer,right_brace: begin if n>1 then @<Enter a hyphenation exception@>;
  15648.     if cur_cmd=right_brace then return;
  15649.     n:=0; p:=null;
  15650.     end;
  15651.   othercases @<Give improper \.{\\hyphenation} error@>
  15652.   endcases;
  15653.   end
  15654. @ @<Give improper \.{\\hyph...@>=
  15655. begin print_err("Improper "); print_esc("hyphenation");
  15656. @.Improper \\hyphenation...@>
  15657.   print(" will be flushed");
  15658. help2("Hyphenation exceptions must contain only letters")@/
  15659.   ("and hyphens. But continue; I'll forgive and forget.");
  15660. error;
  15661. @ @<Append a new letter or hyphen@>=
  15662. if cur_chr="-" then @<Append the value |n| to list |p|@>
  15663. else  begin if lc_code(cur_chr)=0 then
  15664.     begin print_err("Not a letter");
  15665. @.Not a letter@>
  15666.     help2("Letters in \hyphenation words must have \lccode>0.")@/
  15667.       ("Proceed; I'll ignore the character I just read.");
  15668.     error;
  15669.     end
  15670.   else if n<63 then
  15671.     begin incr(n); hc[n]:=lc_code(cur_chr);
  15672.     end;
  15673.   end
  15674. @ @<Append the value |n| to list |p|@>=
  15675. begin if n<63 then
  15676.   begin q:=get_avail; link(q):=p; info(q):=n; p:=q;
  15677.   end;
  15678. @ @<Enter a hyphenation exception@>=
  15679. begin incr(n); hc[n]:=cur_lang; str_room(n); h:=0;
  15680. for j:=1 to n do
  15681.   begin h:=(h+h+hc[j]) mod hyph_size;
  15682.   append_char(hc[j]);
  15683.   end;
  15684. s:=make_string;
  15685. @<Insert the \(p)pair |(s,p)| into the exception table@>;
  15686. @ @<Insert the \(p)pair |(s,p)|...@>=
  15687. if hyph_count=hyph_size then overflow("exception dictionary",hyph_size);
  15688. @:TeX capacity exceeded exception dictionary}{\quad exception dictionary@>
  15689. incr(hyph_count);
  15690. while hyph_word[h]<>0 do
  15691.   begin @<If the string |hyph_word[h]| is less than \(or)or equal to
  15692.   |s|, interchange |(hyph_word[h],hyph_list[h])| with |(s,p)|@>;
  15693.   if h>0 then decr(h)@+else h:=hyph_size;
  15694.   end;
  15695. hyph_word[h]:=s; hyph_list[h]:=p
  15696. @ @<If the string |hyph_word[h]| is less than \(or)...@>=
  15697. k:=hyph_word[h];
  15698. if length(k)<length(s) then goto found;
  15699. if length(k)>length(s) then goto not_found;
  15700. u:=str_start[k]; v:=str_start[s];
  15701. repeat if str_pool[u]<str_pool[v] then goto found;
  15702. if str_pool[u]>str_pool[v] then goto not_found;
  15703. incr(u); incr(v);
  15704. until u=str_start[k+1];
  15705. found:q:=hyph_list[h]; hyph_list[h]:=p; p:=q;@/
  15706. t:=hyph_word[h]; hyph_word[h]:=s; s:=t;
  15707. not_found:
  15708. @* \[43] Initializing the hyphenation tables.
  15709. The trie for \TeX's hyphenation algorithm is built from a sequence of
  15710. patterns following a \.{\\patterns} specification. Such a specification
  15711. is allowed only in \.{INITEX}, since the extra memory for auxiliary tables
  15712. and for the initialization program itself would only clutter up the
  15713. production version of \TeX\ with a lot of deadwood.
  15714. The first step is to build a trie that is linked, instead of packed
  15715. into sequential storage, so that insertions are readily made.
  15716. After all patterns have been processed, \.{INITEX}
  15717. compresses the linked trie by identifying common subtries. Finally the
  15718. trie is packed into the efficient sequential form that the hyphenation
  15719. algorithm actually uses.
  15720. @<Declare subprocedures for |line_break|@>=
  15721. @!init @<Declare procedures for preprocessing hyphenation patterns@>@;
  15722. @ Before we discuss trie building in detail, let's consider the simpler
  15723. problem of creating the |hyf_distance|, |hyf_num|, and |hyf_next| arrays.
  15724. Suppose, for example, that \TeX\ reads the pattern `\.{ab2cde1}'. This is
  15725. a pattern of length 5, with $n_0\ldots n_5=0\,0\,2\,0\,0\,1$ in the
  15726. notation above. We want the corresponding |trie_op| code |v| to have
  15727. |hyf_distance[v]=3|, |hyf_num[v]=2|, and |hyf_next[v]=@t$v^\prime$@>|,
  15728. where the auxiliary |trie_op| code $v^\prime$ has
  15729. |hyf_distance[@t$v^\prime$@>]=0|, |hyf_num[@t$v^\prime$@>]=1|, and
  15730. |hyf_next[@t$v^\prime$@>]=min_quarterword|.
  15731. \TeX\ computes an appropriate value |v| with the |new_trie_op| subroutine
  15732. below, by setting
  15733. $$\hbox{|@t$v^\prime$@>:=new_trie_op(0,1,min_quarterword)|,\qquad
  15734. |v:=new_trie_op(3,2,@t$v^\prime$@>)|.}$$
  15735. This subroutine looks up its three
  15736. parameters in a special hash table, assigning a new value only if these
  15737. three have not appeared before for the current language.
  15738. The hash table is called |trie_op_hash|, and the number of entries it contains
  15739. is |trie_op_ptr|.
  15740. @<Glob...@>=
  15741. @!init@! trie_op_hash:array[-trie_op_size..trie_op_size] of 0..trie_op_size;
  15742.   {trie op codes for quadruples}
  15743. @!trie_used:array[ASCII_code] of quarterword;
  15744.   {largest opcode used so far for this language}
  15745. @!trie_op_lang:array[1..trie_op_size] of ASCII_code;
  15746.   {language part of a hashed quadruple}
  15747. @!trie_op_val:array[1..trie_op_size] of quarterword;
  15748.   {opcode corresponding to a hashed quadruple}
  15749. @!trie_op_ptr:0..trie_op_size; {number of stored ops so far}
  15750. @ It's tempting to remove the |overflow| stops in the following procedure;
  15751. |new_trie_op| could return |min_quarterword| (thereby simply ignoring
  15752. part of a hyphenation pattern) instead of aborting the job. However, that would
  15753. lead to different hyphenation results on different installations of \TeX\
  15754. using the same patterns. The |overflow| stops are necessary for portability
  15755. of patterns.
  15756. @<Declare procedures for preprocessing hyph...@>=
  15757. function new_trie_op(@!d,@!n:small_number;@!v:quarterword):quarterword;
  15758. label exit;
  15759. var h:-trie_op_size..trie_op_size; {trial hash location}
  15760. @!u:quarterword; {trial op code}
  15761. @!l:0..trie_op_size; {pointer to stored data}
  15762. begin h:=abs(n+313*d+361*v+1009*cur_lang) mod (trie_op_size+trie_op_size)
  15763.   - trie_op_size;
  15764. loop@+  begin l:=trie_op_hash[h];
  15765.   if l=0 then {empty position found for a new op}
  15766.     begin if trie_op_ptr=trie_op_size then
  15767.       overflow("pattern memory ops",trie_op_size);
  15768.     u:=trie_used[cur_lang];
  15769.     if u=max_quarterword then
  15770.       overflow("pattern memory ops per language",
  15771.         max_quarterword-min_quarterword);
  15772.     incr(trie_op_ptr); incr(u); trie_used[cur_lang]:=u;
  15773.     hyf_distance[trie_op_ptr]:=d;
  15774.     hyf_num[trie_op_ptr]:=n; hyf_next[trie_op_ptr]:=v;
  15775.     trie_op_lang[trie_op_ptr]:=cur_lang; trie_op_hash[h]:=trie_op_ptr;
  15776.     trie_op_val[trie_op_ptr]:=u; new_trie_op:=u; return;
  15777.     end;
  15778.   if (hyf_distance[l]=d)and(hyf_num[l]=n)and(hyf_next[l]=v)
  15779.    and(trie_op_lang[l]=cur_lang) then
  15780.     begin new_trie_op:=trie_op_val[l]; return;
  15781.     end;
  15782.   if h>-trie_op_size then decr(h)@+else h:=trie_op_size;
  15783.   end;
  15784. exit:end;
  15785. @ After |new_trie_op| has compressed the necessary opcode information,
  15786. plenty of information is available to unscramble the data into the
  15787. final form needed by our hyphenation algorithm.
  15788. @<Sort \(t)the hyphenation op tables into proper order@>=
  15789. op_start[0]:=-min_quarterword;
  15790. for j:=1 to 255 do op_start[j]:=op_start[j-1]+qo(trie_used[j-1]);
  15791. for j:=1 to trie_op_ptr do
  15792.   trie_op_hash[j]:=op_start[trie_op_lang[j]]+trie_op_val[j]; {destination}
  15793. for j:=1 to trie_op_ptr do while trie_op_hash[j]>j do
  15794.   begin k:=trie_op_hash[j];@/
  15795.   t:=hyf_distance[k]; hyf_distance[k]:=hyf_distance[j]; hyf_distance[j]:=t;@/
  15796.   t:=hyf_num[k]; hyf_num[k]:=hyf_num[j]; hyf_num[j]:=t;@/
  15797.   t:=hyf_next[k]; hyf_next[k]:=hyf_next[j]; hyf_next[j]:=t;@/
  15798.   trie_op_hash[j]:=trie_op_hash[k]; trie_op_hash[k]:=k;
  15799.   end
  15800. @ Before we forget how to initialize the data structures that have been
  15801. mentioned so far, let's write down the code that gets them started.
  15802. @<Initialize table entries...@>=
  15803. for k:=-trie_op_size to trie_op_size do trie_op_hash[k]:=0;
  15804. for k:=0 to 255 do trie_used[k]:=min_quarterword;
  15805. trie_op_ptr:=0;
  15806. @ The linked trie that is used to preprocess hyphenation patterns appears
  15807. in several global arrays. Each node represents an instruction of the form
  15808. ``if you see character |c|, then perform operation |o|, move to the
  15809. next character, and go to node |l|; otherwise go to node |r|.''
  15810. The four quantities |c|, |o|, |l|, and |r| are stored in four arrays
  15811. |trie_c|, |trie_o|, |trie_l|, and |trie_r|. The root of the trie
  15812. is |trie_l[0]|, and the number of nodes is |trie_ptr|. Null trie
  15813. pointers are represented by zero. To initialize the trie, we simply
  15814. set |trie_l[0]| and |trie_ptr| to zero. We also set |trie_c[0]| to some
  15815. arbitrary value, since the algorithm may access it.
  15816. The algorithms maintain the condition
  15817. $$\hbox{|trie_c[trie_r[z]]>trie_c[z]|\qquad
  15818. whenever |z<>0| and |trie_r[z]<>0|};$$ in other words, sibling nodes are
  15819. ordered by their |c| fields.
  15820. @d trie_root==trie_l[0] {root of the linked trie}
  15821. @<Glob...@>=
  15822. @!init @!trie_c:packed array[trie_pointer] of packed_ASCII_code;
  15823.   {characters to match}
  15824. @t\hskip10pt@>@!trie_o:packed array[trie_pointer] of quarterword;
  15825.   {operations to perform}
  15826. @t\hskip10pt@>@!trie_l:packed array[trie_pointer] of trie_pointer;
  15827.   {left subtrie links}
  15828. @t\hskip10pt@>@!trie_r:packed array[trie_pointer] of trie_pointer;
  15829.   {right subtrie links}
  15830. @t\hskip10pt@>@!trie_ptr:trie_pointer; {the number of nodes in the trie}
  15831. @t\hskip10pt@>@!trie_hash:packed array[trie_pointer] of trie_pointer;
  15832.   {used to identify equivalent subtries}
  15833. @ Let us suppose that a linked trie has already been constructed.
  15834. Experience shows that we can often reduce its size by recognizing common
  15835. subtries; therefore another hash table is introduced for this purpose,
  15836. somewhat similar to |trie_op_hash|. The new hash table will be
  15837. initialized to zero.
  15838. The function |trie_node(p)| returns |p| if |p| is distinct from other nodes
  15839. that it has seen, otherwise it returns the number of the first equivalent
  15840. node that it has seen.
  15841. Notice that we might make subtries equivalent even if they correspond to
  15842. patterns for different languages, in which the trie ops might mean quite
  15843. different things. That's perfectly all right.
  15844. @<Declare procedures for preprocessing hyph...@>=
  15845. function trie_node(@!p:trie_pointer):trie_pointer; {converts
  15846.   to a canonical form}
  15847. label exit;
  15848. var h:trie_pointer; {trial hash location}
  15849. @!q:trie_pointer; {trial trie node}
  15850. begin h:=abs(trie_c[p]+1009*trie_o[p]+@|
  15851.     2718*trie_l[p]+3142*trie_r[p]) mod trie_size;
  15852. loop@+  begin q:=trie_hash[h];
  15853.   if q=0 then
  15854.     begin trie_hash[h]:=p; trie_node:=p; return;
  15855.     end;
  15856.   if (trie_c[q]=trie_c[p])and(trie_o[q]=trie_o[p])and@|
  15857.     (trie_l[q]=trie_l[p])and(trie_r[q]=trie_r[p]) then
  15858.     begin trie_node:=q; return;
  15859.     end;
  15860.   if h>0 then decr(h)@+else h:=trie_size;
  15861.   end;
  15862. exit:end;
  15863. @ A neat recursive procedure is now able to compress a trie by
  15864. traversing it and applying |trie_node| to its nodes in ``bottom up''
  15865. fashion. We will compress the entire trie by clearing |trie_hash| to
  15866. zero and then saying `|trie_root:=compress_trie(trie_root)|'.
  15867. @^recursion@>
  15868. @<Declare procedures for preprocessing hyph...@>=
  15869. function compress_trie(@!p:trie_pointer):trie_pointer;
  15870. begin if p=0 then compress_trie:=0
  15871. else  begin trie_l[p]:=compress_trie(trie_l[p]);
  15872.   trie_r[p]:=compress_trie(trie_r[p]);
  15873.   compress_trie:=trie_node(p);
  15874.   end;
  15875. @ The compressed trie will be packed into the |trie| array using a
  15876. ``top-down first-fit'' procedure. This is a little tricky, so the reader
  15877. should pay close attention: The |trie_hash| array is cleared to zero
  15878. again and renamed |trie_ref| for this phase of the operation; later on,
  15879. |trie_ref[p]| will be nonzero only if the linked trie node |p| is the
  15880. smallest character
  15881. in a family and if the characters |c| of that family have been allocated to
  15882. locations |trie_ref[p]+c| in the |trie| array. Locations of |trie| that
  15883. are in use will have |trie_link=0|, while the unused holes in |trie|
  15884. will be doubly linked with |trie_link| pointing to the next larger vacant
  15885. location and |trie_back| pointing to the next smaller one. This double
  15886. linking will have been carried out only as far as |trie_max|, where
  15887. |trie_max| is the largest index of |trie| that will be needed.
  15888. To save time at the low end of the trie, we maintain array entries
  15889. |trie_min[c]| pointing to the smallest hole that is greater than~|c|.
  15890. Another array |trie_taken| tells whether or not a given location is
  15891. equal to |trie_ref[p]| for some |p|; this array is used to ensure that
  15892. distinct nodes in the compressed trie will have distinct |trie_ref|
  15893. entries.
  15894. @d trie_ref==trie_hash {where linked trie families go into |trie|}
  15895. @d trie_back(#)==trie[#].lh {backward links in |trie| holes}
  15896. @<Glob...@>=
  15897. @!init@!trie_taken:packed array[1..trie_size] of boolean;
  15898.   {does a family start here?}
  15899. @t\hskip10pt@>@!trie_min:array[ASCII_code] of trie_pointer;
  15900.   {the first possible slot for each character}
  15901. @t\hskip10pt@>@!trie_max:trie_pointer; {largest location used in |trie|}
  15902. @t\hskip10pt@>@!trie_not_ready:boolean; {is the trie still in linked form?}
  15903. @ Each time \.{\\patterns} appears, it contributes further patterns to
  15904. the future trie, which will be built only when hyphenation is attempted or
  15905. when a format file is dumped. The boolean variable |trie_not_ready|
  15906. will change to |false| when the trie is compressed; this will disable
  15907. further patterns.
  15908. @<Initialize table entries...@>=
  15909. trie_not_ready:=true; trie_root:=0; trie_c[0]:=si(0); trie_ptr:=0;
  15910. @ Here is how the trie-compression data structures are initialized.
  15911. If storage is tight, it would be possible to overlap |trie_op_hash|,
  15912. |trie_op_lang|, and |trie_op_val| with |trie|, |trie_hash|, and |trie_taken|,
  15913. because we finish with the former just before we need the latter.
  15914. @<Get ready to compress the trie@>=
  15915. @<Sort \(t)the hyphenation...@>;
  15916. for p:=0 to trie_size do trie_hash[p]:=0;
  15917. trie_root:=compress_trie(trie_root); {identify equivalent subtries}
  15918. for p:=0 to trie_ptr do trie_ref[p]:=0;
  15919. for p:=0 to 255 do trie_min[p]:=p+1;
  15920. trie_link(0):=1; trie_max:=0
  15921. @ The |first_fit| procedure finds the smallest hole |z| in |trie| such that
  15922. a trie family starting at a given node |p| will fit into vacant positions
  15923. starting at |z|. If |c=trie_c[p]|, this means that location |z-c| must
  15924. not already be taken by some other family, and that |z-c+@t$c^\prime$@>|
  15925. must be vacant for all characters $c^\prime$ in the family. The procedure
  15926. sets |trie_ref[p]| to |z-c| when the first fit has been found.
  15927. @<Declare procedures for preprocessing hyph...@>=
  15928. procedure first_fit(@!p:trie_pointer); {packs a family into |trie|}
  15929. label not_found,found;
  15930. var h:trie_pointer; {candidate for |trie_ref[p]|}
  15931. @!z:trie_pointer; {runs through holes}
  15932. @!q:trie_pointer; {runs through the family starting at |p|}
  15933. @!c:ASCII_code; {smallest character in the family}
  15934. @!l,@!r:trie_pointer; {left and right neighbors}
  15935. @!ll:1..256; {upper limit of |trie_min| updating}
  15936. begin c:=so(trie_c[p]);
  15937. z:=trie_min[c]; {get the first conceivably good hole}
  15938. loop@+  begin h:=z-c;@/
  15939.   @<Ensure that |trie_max>=h+256|@>;
  15940.   if trie_taken[h] then goto not_found;
  15941.   @<If all characters of the family fit relative to |h|, then
  15942.     |goto found|,\30\ otherwise |goto not_found|@>;
  15943.   not_found: z:=trie_link(z); {move to the next hole}
  15944.   end;
  15945. found: @<Pack the family into |trie| relative to |h|@>;
  15946. @ By making sure that |trie_max| is at least |h+256|, we can be sure that
  15947. |trie_max>z|, since |h=z-c|. It follows that location |trie_max| will
  15948. never be occupied in |trie|, and we will have |trie_max>=trie_link(z)|.
  15949. @<Ensure that |trie_max>=h+256|@>=
  15950. if trie_max<h+256 then
  15951.   begin if trie_size<=h+256 then overflow("pattern memory",trie_size);
  15952. @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
  15953.   repeat incr(trie_max); trie_taken[trie_max]:=false;
  15954.   trie_link(trie_max):=trie_max+1; trie_back(trie_max):=trie_max-1;
  15955.   until trie_max=h+256;
  15956.   end
  15957. @ @<If all characters of the family fit relative to |h|...@>=
  15958. q:=trie_r[p];
  15959. while q>0 do
  15960.   begin if trie_link(h+so(trie_c[q]))=0 then goto not_found;
  15961.   q:=trie_r[q];
  15962.   end;
  15963. goto found
  15964. @ @<Pack the family into |trie| relative to |h|@>=
  15965. trie_taken[h]:=true; trie_ref[p]:=h; q:=p;
  15966. repeat z:=h+so(trie_c[q]); l:=trie_back(z); r:=trie_link(z);
  15967. trie_back(r):=l; trie_link(l):=r; trie_link(z):=0;
  15968. if l<256 then
  15969.   begin if z<256 then ll:=z @+else ll:=256;
  15970.   repeat trie_min[l]:=r; incr(l);
  15971.   until l=ll;
  15972.   end;
  15973. q:=trie_r[q];
  15974. until q=0
  15975. @ To pack the entire linked trie, we use the following recursive procedure.
  15976. @^recursion@>
  15977. @<Declare procedures for preprocessing hyph...@>=
  15978. procedure trie_pack(@!p:trie_pointer); {pack subtries of a family}
  15979. var q:trie_pointer; {a local variable that need not be saved on recursive calls}
  15980. begin repeat q:=trie_l[p];
  15981. if (q>0)and(trie_ref[q]=0) then
  15982.   begin first_fit(q); trie_pack(q);
  15983.   end;
  15984. p:=trie_r[p];
  15985. until p=0;
  15986. @ When the whole trie has been allocated into the sequential table, we
  15987. must go through it once again so that |trie| contains the correct
  15988. information. Null pointers in the linked trie will be represented by the
  15989. value~0, which properly implements an ``empty'' family.
  15990. @<Move the data into |trie|@>=
  15991. h.rh:=0; h.b0:=min_quarterword; h.b1:=min_quarterword; {|trie_link:=0|,
  15992.   |trie_op:=min_quarterword|, |trie_char:=qi(0)|}
  15993. if trie_root=0 then {no patterns were given}
  15994.   begin for r:=0 to 256 do trie[r]:=h;
  15995.   trie_max:=256;
  15996.   end
  15997. else begin trie_fix(trie_root); {this fixes the non-holes in |trie|}
  15998.   r:=0; {now we will zero out all the holes}
  15999.   repeat s:=trie_link(r); trie[r]:=h; r:=s;
  16000.   until r>trie_max;
  16001.   end;
  16002. trie_char(0):=qi("?"); {make |trie_char(c)<>c| for all |c|}
  16003. @ The fixing-up procedure is, of course, recursive. Since the linked trie
  16004. usually has overlapping subtries, the same data may be moved several
  16005. times; but that causes no harm, and at most as much work is done as it
  16006. took to build the uncompressed trie.
  16007. @^recursion@>
  16008. @<Declare procedures for preprocessing hyph...@>=
  16009. procedure trie_fix(@!p:trie_pointer); {moves |p| and its siblings into |trie|}
  16010. var q:trie_pointer; {a local variable that need not be saved on recursive calls}
  16011. @!c:ASCII_code; {another one that need not be saved}
  16012. @!z:trie_pointer; {|trie| reference; this local variable must be saved}
  16013. begin z:=trie_ref[p];
  16014. repeat q:=trie_l[p]; c:=so(trie_c[p]);
  16015. trie_link(z+c):=trie_ref[q]; trie_char(z+c):=qi(c); trie_op(z+c):=trie_o[p];
  16016. if q>0 then trie_fix(q);
  16017. p:=trie_r[p];
  16018. until p=0;
  16019. @ Now let's go back to the easier problem, of building the linked
  16020. trie.  When \.{INITEX} has scanned the `\.{\\patterns}' control
  16021. sequence, it calls on |new_patterns| to do the right thing.
  16022. @<Declare procedures for preprocessing hyph...@>=
  16023. procedure new_patterns; {initializes the hyphenation pattern data}
  16024. label done, done1;
  16025. var k,@!l:0..64; {indices into |hc| and |hyf|;
  16026.                   not always in |small_number| range}
  16027. @!digit_sensed:boolean; {should the next digit be treated as a letter?}
  16028. @!v:quarterword; {trie op code}
  16029. @!p,@!q:trie_pointer; {nodes of trie traversed during insertion}
  16030. @!first_child:boolean; {is |p=trie_l[q]|?}
  16031. @!c:ASCII_code; {character being inserted}
  16032. begin if trie_not_ready then
  16033.   begin set_cur_lang; scan_left_brace; {a left brace must follow \.{\\patterns}}
  16034.   @<Enter all of the patterns into a linked trie, until coming to a right
  16035.   brace@>;
  16036.   end
  16037. else begin print_err("Too late for "); print_esc("patterns");
  16038.   help1("All patterns must be given before typesetting begins.");
  16039.   error; link(garbage):=scan_toks(false,false); flush_list(def_ref);
  16040.   end;
  16041. @ Novices are not supposed to be using \.{\\patterns}, so the error
  16042. messages are terse. (Note that all error messages appear in \TeX's string
  16043. pool, even if they are used only by \.{INITEX}.)
  16044. @<Enter all of the patterns into a linked trie...@>=
  16045. k:=0; hyf[0]:=0; digit_sensed:=false;
  16046. loop@+  begin get_x_token;
  16047.   case cur_cmd of
  16048.   letter,other_char:@<Append a new letter or a hyphen level@>;
  16049.   spacer,right_brace: begin if k>0 then
  16050.       @<Insert a new pattern into the linked trie@>;
  16051.     if cur_cmd=right_brace then goto done;
  16052.     k:=0; hyf[0]:=0; digit_sensed:=false;
  16053.     end;
  16054.   othercases begin print_err("Bad "); print_esc("patterns");
  16055. @.Bad \\patterns@>
  16056.     help1("(See Appendix H.)"); error;
  16057.     end
  16058.   endcases;
  16059.   end;
  16060. done:
  16061. @ @<Append a new letter or a hyphen level@>=
  16062. if digit_sensed or(cur_chr<"0")or(cur_chr>"9") then
  16063.   begin if cur_chr="." then cur_chr:=0 {edge-of-word delimiter}
  16064.   else  begin cur_chr:=lc_code(cur_chr);
  16065.     if cur_chr=0 then
  16066.       begin print_err("Nonletter");
  16067. @.Nonletter@>
  16068.       help1("(See Appendix H.)"); error;
  16069.       end;
  16070.     end;
  16071.   if k<63 then
  16072.     begin incr(k); hc[k]:=cur_chr; hyf[k]:=0; digit_sensed:=false;
  16073.     end;
  16074.   end
  16075. else if k<63 then
  16076.   begin hyf[k]:=cur_chr-"0"; digit_sensed:=true;
  16077.   end
  16078. @ When the following code comes into play, the pattern $p_1\ldots p_k$
  16079. appears in |hc[1..k]|, and the corresponding sequence of numbers $n_0\ldots
  16080. n_k$ appears in |hyf[0..k]|.
  16081. @<Insert a new pattern into the linked trie@>=
  16082. begin @<Compute the trie op code, |v|, and set |l:=0|@>;
  16083. q:=0; hc[0]:=cur_lang;
  16084. while l<=k do
  16085.   begin c:=hc[l]; incr(l); p:=trie_l[q]; first_child:=true;
  16086.   while (p>0)and(c>so(trie_c[p])) do
  16087.     begin q:=p; p:=trie_r[q]; first_child:=false;
  16088.     end;
  16089.   if (p=0)or(c<so(trie_c[p])) then
  16090.     @<Insert a new trie node between |q| and |p|, and
  16091.       make |p| point to it@>;
  16092.   q:=p; {now node |q| represents $p_1\ldots p_l$}
  16093.   end;
  16094. if trie_o[q]<>min_quarterword then
  16095.   begin print_err("Duplicate pattern");
  16096. @.Duplicate pattern@>
  16097.   help1("(See Appendix H.)"); error;
  16098.   end;
  16099. trie_o[q]:=v;
  16100. @ @<Insert a new trie node between |q| and |p|...@>=
  16101. begin if trie_ptr=trie_size then overflow("pattern memory",trie_size);
  16102. @:TeX capacity exceeded pattern memory}{\quad pattern memory@>
  16103. incr(trie_ptr); trie_r[trie_ptr]:=p; p:=trie_ptr; trie_l[p]:=0;
  16104. if first_child then trie_l[q]:=p@+else trie_r[q]:=p;
  16105. trie_c[p]:=si(c); trie_o[p]:=min_quarterword;
  16106. @ @<Compute the trie op code, |v|...@>=
  16107. if hc[1]=0 then hyf[0]:=0;
  16108. if hc[k]=0 then hyf[k]:=0;
  16109. l:=k; v:=min_quarterword;
  16110. loop@+  begin if hyf[l]<>0 then v:=new_trie_op(k-l,hyf[l],v);
  16111.   if l>0 then decr(l)@+else goto done1;
  16112.   end;
  16113. done1:
  16114. @ Finally we put everything together: Here is how the trie gets to its
  16115. final, efficient form.
  16116. The following packing routine is rigged so that the root of the linked
  16117. tree gets mapped into location 1 of |trie|, as required by the hyphenation
  16118. algorithm. This happens because the first call of |first_fit| will
  16119. ``take'' location~1.
  16120. @<Declare procedures for preprocessing hyphenation patterns@>=
  16121. procedure init_trie;
  16122. var @!p:trie_pointer; {pointer for initialization}
  16123. @!j,@!k,@!t:integer; {all-purpose registers for initialization}
  16124. @!r,@!s:trie_pointer; {used to clean up the packed |trie|}
  16125. @!h:two_halves; {template used to zero out |trie|'s holes}
  16126. begin @<Get ready to compress the trie@>;
  16127. if trie_root<>0 then
  16128.   begin first_fit(trie_root); trie_pack(trie_root);
  16129.   end;
  16130. @<Move the data into |trie|@>;
  16131. trie_not_ready:=false;
  16132. @* \[44] Breaking vertical lists into pages.
  16133. The |vsplit| procedure, which implements \TeX's \.{\\vsplit} operation,
  16134. is considerably simpler than |line_break| because it doesn't have to
  16135. worry about hyphenation, and because its mission is to discover a single
  16136. break instead of an optimum sequence of breakpoints.  But before we get
  16137. into the details of |vsplit|, we need to consider a few more basic things.
  16138. @ A subroutine called |prune_page_top| takes a pointer to a vlist and
  16139. returns a pointer to a modified vlist in which all glue, kern, and penalty nodes
  16140. have been deleted before the first box or rule node. However, the first
  16141. box or rule is actually preceded by a newly created glue node designed so that
  16142. the topmost baseline will be at distance |split_top_skip| from the top,
  16143. whenever this is possible without backspacing.
  16144. In this routine and those that follow, we make use of the fact that a
  16145. vertical list contains no character nodes, hence the |type| field exists
  16146. for each node in the list.
  16147. @^data structure assumptions@>
  16148. @p function prune_page_top(@!p:pointer):pointer; {adjust top after page break}
  16149. var prev_p:pointer; {lags one step behind |p|}
  16150. @!q:pointer; {temporary variable for list manipulation}
  16151. begin prev_p:=temp_head; link(temp_head):=p;
  16152. while p<>null do
  16153.   case type(p) of
  16154.   hlist_node,vlist_node,rule_node:@<Insert glue for |split_top_skip|
  16155.     and set~|p:=null|@>;
  16156.   whatsit_node,mark_node,ins_node: begin prev_p:=p; p:=link(prev_p);
  16157.     end;
  16158.   glue_node,kern_node,penalty_node: begin q:=p; p:=link(q); link(q):=null;
  16159.     link(prev_p):=p; flush_node_list(q);
  16160.     end;
  16161.   othercases confusion("pruning")
  16162. @:this can't happen pruning}{\quad pruning@>
  16163.   endcases;
  16164. prune_page_top:=link(temp_head);
  16165. @ @<Insert glue for |split_top_skip|...@>=
  16166. begin q:=new_skip_param(split_top_skip_code); link(prev_p):=q; link(q):=p;
  16167.   {now |temp_ptr=glue_ptr(q)|}
  16168. if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
  16169. else width(temp_ptr):=0;
  16170. p:=null;
  16171. @ The next subroutine finds the best place to break a given vertical list
  16172. so as to obtain a box of height~|h|, with maximum depth~|d|.
  16173. A pointer to the beginning of the vertical list is given,
  16174. and a pointer to the optimum breakpoint is returned. The list is effectively
  16175. followed by a forced break, i.e., a penalty node with the |eject_penalty|;
  16176. if the best break occurs at this artificial node, the value |null| is returned.
  16177. An array of six |scaled| distances is used to keep track of the height
  16178. from the beginning of the list to the current place, just as in |line_break|.
  16179. In fact, we use one of the same arrays, only changing its name to reflect
  16180. its new significance.
  16181. @d active_height==active_width {new name for the six distance variables}
  16182. @d cur_height==active_height[1] {the natural height}
  16183. @d set_height_zero(#)==active_height[#]:=0 {initialize the height to zero}
  16184. @d update_heights=90 {go here to record glue in the |active_height| table}
  16185. @p function vert_break(@!p:pointer; @!h,@!d:scaled):pointer;
  16186.   {finds optimum page break}
  16187. label done,not_found,update_heights;
  16188. var prev_p:pointer; {if |p| is a glue node, |type(prev_p)| determines
  16189.   whether |p| is a legal breakpoint}
  16190. @!q,@!r:pointer; {glue specifications}
  16191. @!pi:integer; {penalty value}
  16192. @!b:integer; {badness at a trial breakpoint}
  16193. @!least_cost:integer; {the smallest badness plus penalties found so far}
  16194. @!best_place:pointer; {the most recent break that leads to |least_cost|}
  16195. @!prev_dp:scaled; {depth of previous box in the list}
  16196. @!t:small_number; {|type| of the node following a kern}
  16197. begin prev_p:=p; {an initial glue node is not a legal breakpoint}
  16198. least_cost:=awful_bad; do_all_six(set_height_zero); prev_dp:=0;
  16199. loop@+  begin @<If node |p| is a legal breakpoint, check if this break is
  16200.     the best known, and |goto done| if |p| is null or
  16201.     if the page-so-far is already too full to accept more stuff@>;
  16202.   prev_p:=p; p:=link(prev_p);
  16203.   end;
  16204. done: vert_break:=best_place;
  16205. @ A global variable |best_height_plus_depth| will be set to the natural size
  16206. of the box that corresponds to the optimum breakpoint found by |vert_break|.
  16207. (This value is used by the insertion-splitting algorithm of the page builder.)
  16208. @<Glob...@>=
  16209. @!best_height_plus_depth:scaled; {height of the best box, without stretching or
  16210.   shrinking}
  16211. @ A subtle point to be noted here is that the maximum depth~|d| might be
  16212. negative, so |cur_height| and |prev_dp| might need to be corrected even
  16213. after a glue or kern node.
  16214. @<If node |p| is a legal breakpoint, check...@>=
  16215. if p=null then pi:=eject_penalty
  16216. else  @<Use node |p| to update the current height and depth measurements;
  16217.     if this node is not a legal breakpoint, |goto not_found|
  16218.     or |update_heights|,
  16219.     otherwise set |pi| to the associated penalty at the break@>;
  16220. @<Check if node |p| is a new champion breakpoint; then \(go)|goto done|
  16221.   if |p| is a forced break or if the page-so-far is already too full@>;
  16222. if (type(p)<glue_node)or(type(p)>kern_node) then goto not_found;
  16223. update_heights: @<Update the current height and depth measurements with
  16224.   respect to a glue or kern node~|p|@>;
  16225. not_found: if prev_dp>d then
  16226.     begin cur_height:=cur_height+prev_dp-d;
  16227.     prev_dp:=d;
  16228.     end;
  16229. @ @<Use node |p| to update the current height and depth measurements...@>=
  16230. case type(p) of
  16231. hlist_node,vlist_node,rule_node: begin@t@>@;@/
  16232.   cur_height:=cur_height+prev_dp+height(p); prev_dp:=depth(p);
  16233.   goto not_found;
  16234.   end;
  16235. whatsit_node:@<Process whatsit |p| in |vert_break| loop, |goto not_found|@>;
  16236. glue_node: if precedes_break(prev_p) then pi:=0
  16237.   else goto update_heights;
  16238. kern_node: begin if link(p)=null then t:=penalty_node
  16239.   else t:=type(link(p));
  16240.   if t=glue_node then pi:=0@+else goto update_heights;
  16241.   end;
  16242. penalty_node: pi:=penalty(p);
  16243. mark_node,ins_node: goto not_found;
  16244. othercases confusion("vertbreak")
  16245. @:this can't happen vertbreak}{\quad vertbreak@>
  16246. endcases
  16247. @ @d deplorable==100000 {more than |inf_bad|, but less than |awful_bad|}
  16248. @<Check if node |p| is a new champion breakpoint; then \(go)...@>=
  16249. if pi<inf_penalty then
  16250.   begin @<Compute the badness, |b|, using |awful_bad|
  16251.     if the box is too full@>;
  16252.   if b<awful_bad then
  16253.     if pi<=eject_penalty then b:=pi
  16254.     else if b<inf_bad then b:=b+pi
  16255.       else b:=deplorable;
  16256.   if b<=least_cost then
  16257.     begin best_place:=p; least_cost:=b;
  16258.     best_height_plus_depth:=cur_height+prev_dp;
  16259.     end;
  16260.   if (b=awful_bad)or(pi<=eject_penalty) then goto done;
  16261.   end
  16262. @ @<Compute the badness, |b|, using |awful_bad| if the box is too full@>=
  16263. if cur_height<h then
  16264.   if (active_height[3]<>0) or (active_height[4]<>0) or
  16265.     (active_height[5]<>0) then b:=0
  16266.   else b:=badness(h-cur_height,active_height[2])
  16267. else if cur_height-h>active_height[6] then b:=awful_bad
  16268. else b:=badness(cur_height-h,active_height[6])
  16269. @ Vertical lists that are subject to the |vert_break| procedure should not
  16270. contain infinite shrinkability, since that would permit any amount of
  16271. information to ``fit'' on one page.
  16272. @<Update the current height and depth measurements with...@>=
  16273. if type(p)=kern_node then q:=p
  16274. else  begin q:=glue_ptr(p);
  16275.   active_height[2+stretch_order(q)]:=@|
  16276.     active_height[2+stretch_order(q)]+stretch(q);@/
  16277.   active_height[6]:=active_height[6]+shrink(q);
  16278.   if (shrink_order(q)<>normal)and(shrink(q)<>0) then
  16279.     begin@t@>@;@/
  16280.     print_err("Infinite glue shrinkage found in box being split");@/
  16281. @.Infinite glue shrinkage...@>
  16282.     help4("The box you are \vsplitting contains some infinitely")@/
  16283.       ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
  16284.       ("Such glue doesn't belong there; but you can safely proceed,")@/
  16285.       ("since the offensive shrinkability has been made finite.");
  16286.     error; r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
  16287.     glue_ptr(p):=r; q:=r;
  16288.     end;
  16289.   end;
  16290. cur_height:=cur_height+prev_dp+width(q); prev_dp:=0
  16291. @ Now we are ready to consider |vsplit| itself. Most of
  16292. its work is accomplished by the two subroutines that we have just considered.
  16293. Given the number of a vlist box |n|, and given a desired page height |h|,
  16294. the |vsplit| function finds the best initial segment of the vlist and
  16295. returns a box for a page of height~|h|. The remainder of the vlist, if
  16296. any, replaces the original box, after removing glue and penalties and
  16297. adjusting for |split_top_skip|. Mark nodes in the split-off box are used to
  16298. set the values of |split_first_mark| and |split_bot_mark|; we use the
  16299. fact that |split_first_mark=null| if and only if |split_bot_mark=null|.
  16300. The original box becomes ``void'' if and only if it has been entirely
  16301. extracted.  The extracted box is ``void'' if and only if the original
  16302. box was void (or if it was, erroneously, an hlist box).
  16303. @p function vsplit(@!n:eight_bits; @!h:scaled):pointer;
  16304.   {extracts a page of height |h| from box |n|}
  16305. label exit,done;
  16306. var v:pointer; {the box to be split}
  16307. p:pointer; {runs through the vlist}
  16308. q:pointer; {points to where the break occurs}
  16309. begin v:=box(n);
  16310. if split_first_mark<>null then
  16311.   begin delete_token_ref(split_first_mark); split_first_mark:=null;
  16312.   delete_token_ref(split_bot_mark); split_bot_mark:=null;
  16313.   end;
  16314. @<Dispense with trivial cases of void or bad boxes@>;
  16315. q:=vert_break(list_ptr(v),h,split_max_depth);
  16316. @<Look at all the marks in nodes before the break, and set the final
  16317.   link to |null| at the break@>;
  16318. q:=prune_page_top(q); p:=list_ptr(v); free_node(v,box_node_size);
  16319. if q=null then box(n):=null {the |eq_level| of the box stays the same}
  16320. else box(n):=vpack(q,natural);
  16321. vsplit:=vpackage(p,h,exactly,split_max_depth);
  16322. exit: end;
  16323. @ @<Dispense with trivial cases of void or bad boxes@>=
  16324. if v=null then
  16325.   begin vsplit:=null; return;
  16326.   end;
  16327. if type(v)<>vlist_node then
  16328.   begin print_err(""); print_esc("vsplit"); print(" needs a ");
  16329.   print_esc("vbox");
  16330. @:vsplit_}{\.{\\vsplit needs a \\vbox}@>
  16331.   help2("The box you are trying to split is an \hbox.")@/
  16332.   ("I can't split such a box, so I'll leave it alone.");
  16333.   error; vsplit:=null; return;
  16334.   end
  16335. @ It's possible that the box begins with a penalty node that is the
  16336. ``best'' break, so we must be careful to handle this special case correctly.
  16337. @<Look at all the marks...@>=
  16338. p:=list_ptr(v);
  16339. if p=q then list_ptr(v):=null
  16340. else loop@+begin if type(p)=mark_node then
  16341.     if split_first_mark=null then
  16342.       begin split_first_mark:=mark_ptr(p);
  16343.       split_bot_mark:=split_first_mark;
  16344.       token_ref_count(split_first_mark):=@|
  16345.         token_ref_count(split_first_mark)+2;
  16346.       end
  16347.     else  begin delete_token_ref(split_bot_mark);
  16348.       split_bot_mark:=mark_ptr(p);
  16349.       add_token_ref(split_bot_mark);
  16350.       end;
  16351.   if link(p)=q then
  16352.     begin link(p):=null; goto done;
  16353.     end;
  16354.   p:=link(p);
  16355.   end;
  16356. done:
  16357. @* \[45] The page builder.
  16358. When \TeX\ appends new material to its main vlist in vertical mode, it uses
  16359. a method something like |vsplit| to decide where a page ends, except that
  16360. the calculations are done ``on line'' as new items come in.
  16361. The main complication in this process is that insertions must be put
  16362. into their boxes and removed from the vlist, in a more-or-less optimum manner.
  16363. We shall use the term ``current page'' for that part of the main vlist that
  16364. is being considered as a candidate for being broken off and sent to the
  16365. user's output routine. The current page starts at |link(page_head)|, and
  16366. it ends at |page_tail|.  We have |page_head=page_tail| if this list is empty.
  16367. @^current page@>
  16368. Utter chaos would reign if the user kept changing page specifications
  16369. while a page is being constructed, so the page builder keeps the pertinent
  16370. specifications frozen as soon as the page receives its first box or
  16371. insertion.  The global variable |page_contents| is |empty| when the
  16372. current page contains only mark nodes and content-less whatsit nodes; it
  16373. is |inserts_only| if the page contains only insertion nodes in addition to
  16374. marks and whatsits.  Glue nodes, kern nodes, and penalty nodes are
  16375. discarded until a box or rule node appears, at which time |page_contents|
  16376. changes to |box_there|.  As soon as |page_contents| becomes non-|empty|,
  16377. the current |vsize| and |max_depth| are squirreled away into |page_goal|
  16378. and |page_max_depth|; the latter values will be used until the page has
  16379. been forwarded to the user's output routine. The \.{\\topskip} adjustment
  16380. is made when |page_contents| changes to |box_there|.
  16381. Although |page_goal| starts out equal to |vsize|, it is decreased by the
  16382. scaled natural height-plus-depth of the insertions considered so far, and by
  16383. the \.{\\skip} corrections for those insertions. Therefore it represents
  16384. the size into which the non-inserted material should fit, assuming that
  16385. all insertions in the current page have been made.
  16386. The global variables |best_page_break| and |least_page_cost| correspond
  16387. respectively to the local variables |best_place| and |least_cost| in the
  16388. |vert_break| routine that we have already studied; i.e., they record the
  16389. location and value of the best place currently known for breaking the
  16390. current page. The value of |page_goal| at the time of the best break is
  16391. stored in |best_size|.
  16392. @d inserts_only=1
  16393.   {|page_contents| when an insert node has been contributed, but no boxes}
  16394. @d box_there=2 {|page_contents| when a box or rule has been contributed}
  16395. @<Glob...@>=
  16396. @!page_tail:pointer; {the final node on the current page}
  16397. @!page_contents:empty..box_there; {what is on the current page so far?}
  16398. @!page_max_depth:scaled; {maximum box depth on page being built}
  16399. @!best_page_break:pointer; {break here to get the best page known so far}
  16400. @!least_page_cost:integer; {the score for this currently best page}
  16401. @!best_size:scaled; {its |page_goal|}
  16402. @ The page builder has another data structure to keep track of insertions.
  16403. This is a list of four-word nodes, starting and ending at |page_ins_head|.
  16404. That is, the first element of the list is node |r@t$_1$@>=link(page_ins_head)|;
  16405. node $r_j$ is followed by |r@t$_{j+1}$@>=link(r@t$_j$@>)|; and if there are
  16406. |n| items we have |r@t$_{n+1}$@>=page_ins_head|. The |subtype| field of
  16407. each node in this list refers to an insertion number; for example, `\.{\\insert
  16408. 250}' would correspond to a node whose |subtype| is |qi(250)|
  16409. (the same as the |subtype| field of the relevant |ins_node|). These |subtype|
  16410. fields are in increasing order, and |subtype(page_ins_head)=
  16411. qi(255)|, so |page_ins_head| serves as a convenient sentinel
  16412. at the end of the list. A record is present for each insertion number that
  16413. appears in the current page.
  16414. The |type| field in these nodes distinguishes two possibilities that
  16415. might occur as we look ahead before deciding on the optimum page break.
  16416. If |type(r)=inserting|, then |height(r)| contains the total of the
  16417. height-plus-depth dimensions of the box and all its inserts seen so far.
  16418. If |type(r)=split_up|, then no more insertions will be made into this box,
  16419. because at least one previous insertion was too big to fit on the current
  16420. page; |broken_ptr(r)| points to the node where that insertion will be
  16421. split, if \TeX\ decides to split it, |broken_ins(r)| points to the
  16422. insertion node that was tentatively split, and |height(r)| includes also the
  16423. natural height plus depth of the part that would be split off.
  16424. In both cases, |last_ins_ptr(r)| points to the last |ins_node|
  16425. encountered for box |qo(subtype(r))| that would be at least partially
  16426. inserted on the next page; and |best_ins_ptr(r)| points to the last
  16427. such |ins_node| that should actually be inserted, to get the page with
  16428. minimum badness among all page breaks considered so far. We have
  16429. |best_ins_ptr(r)=null| if and only if no insertion for this box should
  16430. be made to produce this optimum page.
  16431. The data structure definitions here use the fact that the |@!height| field
  16432. appears in the fourth word of a box node.
  16433. @^data structure assumptions@>
  16434. @d page_ins_node_size=4 {number of words for a page insertion node}
  16435. @d inserting=0 {an insertion class that has not yet overflowed}
  16436. @d split_up=1 {an overflowed insertion class}
  16437. @d broken_ptr(#)==link(#+1)
  16438.   {an insertion for this class will break here if anywhere}
  16439. @d broken_ins(#)==info(#+1) {this insertion might break at |broken_ptr|}
  16440. @d last_ins_ptr(#)==link(#+2) {the most recent insertion for this |subtype|}
  16441. @d best_ins_ptr(#)==info(#+2) {the optimum most recent insertion}
  16442. @<Initialize the special list heads...@>=
  16443. subtype(page_ins_head):=qi(255);
  16444. type(page_ins_head):=split_up; link(page_ins_head):=page_ins_head;
  16445. @ An array |page_so_far| records the heights and depths of everything
  16446. on the current page. This array contains six |scaled| numbers, like the
  16447. similar arrays already considered in |line_break| and |vert_break|; and it
  16448. also contains |page_goal| and |page_depth|, since these values are
  16449. all accessible to the user via |set_page_dimen| commands. The
  16450. value of |page_so_far[1]| is also called |page_total|.  The stretch
  16451. and shrink components of the \.{\\skip} corrections for each insertion are
  16452. included in |page_so_far|, but the natural space components of these
  16453. corrections are not, since they have been subtracted from |page_goal|.
  16454. The variable |page_depth| records the depth of the current page; it has been
  16455. adjusted so that it is at most |page_max_depth|. The variable
  16456. |last_glue| points to the glue specification of the most recent node
  16457. contributed from the contribution list, if this was a glue node; otherwise
  16458. |last_glue=max_halfword|. (If the contribution list is nonempty,
  16459. however, the value of |last_glue| is not necessarily accurate.)
  16460. The variables |last_penalty| and |last_kern| are similar.  And
  16461. finally, |insert_penalties| holds the sum of the penalties associated with
  16462. all split and floating insertions.
  16463. @d page_goal==page_so_far[0] {desired height of information on page being built}
  16464. @d page_total==page_so_far[1] {height of the current page}
  16465. @d page_shrink==page_so_far[6] {shrinkability of the current page}
  16466. @d page_depth==page_so_far[7] {depth of the current page}
  16467. @<Glob...@>=
  16468. @!page_so_far:array [0..7] of scaled; {height and glue of the current page}
  16469. @!last_glue:pointer; {used to implement \.{\\lastskip}}
  16470. @!last_penalty:integer; {used to implement \.{\\lastpenalty}}
  16471. @!last_kern:scaled; {used to implement \.{\\lastkern}}
  16472. @!insert_penalties:integer; {sum of the penalties for held-over insertions}
  16473. @ @<Put each...@>=
  16474. primitive("pagegoal",set_page_dimen,0);
  16475. @!@:page_goal_}{\.{\\pagegoal} primitive@>
  16476. primitive("pagetotal",set_page_dimen,1);
  16477. @!@:page_total_}{\.{\\pagetotal} primitive@>
  16478. primitive("pagestretch",set_page_dimen,2);
  16479. @!@:page_stretch_}{\.{\\pagestretch} primitive@>
  16480. primitive("pagefilstretch",set_page_dimen,3);
  16481. @!@:page_fil_stretch_}{\.{\\pagefilstretch} primitive@>
  16482. primitive("pagefillstretch",set_page_dimen,4);
  16483. @!@:page_fill_stretch_}{\.{\\pagefillstretch} primitive@>
  16484. primitive("pagefilllstretch",set_page_dimen,5);
  16485. @!@:page_filll_stretch_}{\.{\\pagefilllstretch} primitive@>
  16486. primitive("pageshrink",set_page_dimen,6);
  16487. @!@:page_shrink_}{\.{\\pageshrink} primitive@>
  16488. primitive("pagedepth",set_page_dimen,7);
  16489. @!@:page_depth_}{\.{\\pagedepth} primitive@>
  16490. @ @<Cases of |print_cmd_chr|...@>=
  16491. set_page_dimen: case chr_code of
  16492. 0: print_esc("pagegoal");
  16493. 1: print_esc("pagetotal");
  16494. 2: print_esc("pagestretch");
  16495. 3: print_esc("pagefilstretch");
  16496. 4: print_esc("pagefillstretch");
  16497. 5: print_esc("pagefilllstretch");
  16498. 6: print_esc("pageshrink");
  16499. othercases print_esc("pagedepth")
  16500. endcases;
  16501. @ @d print_plus_end(#)==print(#);@+end
  16502. @d print_plus(#)==if page_so_far[#]<>0 then
  16503.   begin print(" plus "); print_scaled(page_so_far[#]); print_plus_end
  16504. @p procedure print_totals;
  16505. begin print_scaled(page_total);
  16506. print_plus(2)("");
  16507. print_plus(3)("fil");
  16508. print_plus(4)("fill");
  16509. print_plus(5)("filll");
  16510. if page_shrink<>0 then
  16511.   begin print(" minus "); print_scaled(page_shrink);
  16512.   end;
  16513. @ @<Show the status of the current page@>=
  16514. if page_head<>page_tail then
  16515.   begin print_nl("### current page:");
  16516.   if output_active then print(" (held over for next output)");
  16517. @.held over for next output@>
  16518.   show_box(link(page_head));
  16519.   if page_contents>empty then
  16520.     begin print_nl("total height "); print_totals;
  16521. @:total_height}{\.{total height}@>
  16522.     print_nl(" goal height "); print_scaled(page_goal);
  16523. @.goal height@>
  16524.     r:=link(page_ins_head);
  16525.     while r<>page_ins_head do
  16526.       begin print_ln; print_esc("insert"); t:=qo(subtype(r));
  16527.       print_int(t); print(" adds ");
  16528.       t:=x_over_n(height(r),1000)*count(t); print_scaled(t);
  16529.       if type(r)=split_up then
  16530.         begin q:=page_head; t:=0;
  16531.         repeat q:=link(q);
  16532.         if (type(q)=ins_node)and(subtype(q)=subtype(r)) then incr(t);
  16533.         until q=broken_ins(r);
  16534.         print(", #"); print_int(t); print(" might split");
  16535.         end;
  16536.       r:=link(r);
  16537.       end;
  16538.     end;
  16539.   end
  16540. @ Here is a procedure that is called when the |page_contents| is changing
  16541. from |empty| to |inserts_only| or |box_there|.
  16542. @d set_page_so_far_zero(#)==page_so_far[#]:=0
  16543. @p procedure freeze_page_specs(@!s:small_number);
  16544. begin page_contents:=s;
  16545. page_goal:=vsize; page_max_depth:=max_depth;
  16546. page_depth:=0; do_all_six(set_page_so_far_zero);
  16547. least_page_cost:=awful_bad;
  16548. @!stat if tracing_pages>0 then
  16549.   begin begin_diagnostic;
  16550.   print_nl("%% goal height="); print_scaled(page_goal);
  16551. @.goal height@>
  16552.   print(", max depth="); print_scaled(page_max_depth);
  16553.   end_diagnostic(false);
  16554.   end;@;@+tats@;@/
  16555. @ Pages are built by appending nodes to the current list in \TeX's
  16556. vertical mode, which is at the outermost level of the semantic nest. This
  16557. vlist is split into two parts; the ``current page'' that we have been
  16558. talking so much about already, and the ``contribution list'' that receives
  16559. new nodes as they are created.  The current page contains everything that
  16560. the page builder has accounted for in its data structures, as described
  16561. above, while the contribution list contains other things that have been
  16562. generated by other parts of \TeX\ but have not yet been
  16563. seen by the page builder.
  16564. The contribution list starts at |link(contrib_head)|, and it ends at the
  16565. current node in \TeX's vertical mode.
  16566. When \TeX\ has appended new material in vertical mode, it calls the procedure
  16567. |build_page|, which tries to catch up by moving nodes from the contribution
  16568. list to the current page. This procedure will succeed in its goal of
  16569. emptying the contribution list, unless a page break is discovered, i.e.,
  16570. unless the current page has grown to the point where the optimum next
  16571. page break has been determined. In the latter case, the nodes after the
  16572. optimum break will go back onto the contribution list, and control will
  16573. effectively pass to the user's output routine.
  16574. We make |type(page_head)=glue_node|, so that an initial glue node on
  16575. the current page will not be considered a valid breakpoint.
  16576. @<Initialize the special list...@>=
  16577. type(page_head):=glue_node; subtype(page_head):=normal;
  16578. @ The global variable |output_active| is true during the time the
  16579. user's output routine is driving \TeX.
  16580. @<Glob...@>=
  16581. @!output_active:boolean; {are we in the midst of an output routine?}
  16582. @ @<Set init...@>=
  16583. output_active:=false; insert_penalties:=0;
  16584. @ The page builder is ready to start a fresh page if we initialize
  16585. the following state variables. (However, the page insertion list is initialized
  16586. elsewhere.)
  16587. @<Start a new current page@>=
  16588. page_contents:=empty; page_tail:=page_head; link(page_head):=null;@/
  16589. last_glue:=max_halfword; last_penalty:=0; last_kern:=0;
  16590. page_depth:=0; page_max_depth:=0
  16591. @ At certain times box 255 is supposed to be void (i.e., |null|),
  16592. or an insertion box is supposed to be ready to accept a vertical list.
  16593. If not, an error message is printed, and the following subroutine
  16594. flushes the unwanted contents, reporting them to the user.
  16595. @p procedure box_error(@!n:eight_bits);
  16596. begin error; begin_diagnostic;
  16597. print_nl("The following box has been deleted:");
  16598. @.The following...deleted@>
  16599. show_box(box(n)); end_diagnostic(true);
  16600. flush_node_list(box(n)); box(n):=null;
  16601. @ The following procedure guarantees that a given box register
  16602. does not contain an \.{\\hbox}.
  16603. @p procedure ensure_vbox(@!n:eight_bits);
  16604. var p:pointer; {the box register contents}
  16605. begin p:=box(n);
  16606. if p<>null then if type(p)=hlist_node then
  16607.   begin print_err("Insertions can only be added to a vbox");
  16608. @.Insertions can only...@>
  16609.   help3("Tut tut: You're trying to \insert into a")@/
  16610.     ("\box register that now contains an \hbox.")@/
  16611.     ("Proceed, and I'll discard its present contents.");
  16612.   box_error(n);
  16613.   end;
  16614. @ \TeX\ is not always in vertical mode at the time |build_page|
  16615. is called; the current mode reflects what \TeX\ should return to, after
  16616. the contribution list has been emptied. A call on |build_page| should
  16617. be immediately followed by `|goto big_switch|', which is \TeX's central
  16618. control point.
  16619. @d contribute=80 {go here to link a node into the current page}
  16620. @p @t\4@>@<Declare the procedure called |fire_up|@>@;@/
  16621. procedure build_page; {append contributions to the current page}
  16622. label exit,done,done1,continue,contribute,update_heights;
  16623. var p:pointer; {the node being appended}
  16624. @!q,@!r:pointer; {nodes being examined}
  16625. @!b,@!c:integer; {badness and cost of current page}
  16626. @!pi:integer; {penalty to be added to the badness}
  16627. @!n:min_quarterword..255; {insertion box number}
  16628. @!delta,@!h,@!w:scaled; {sizes used for insertion calculations}
  16629. begin if (link(contrib_head)=null)or output_active then return;
  16630. repeat continue: p:=link(contrib_head);@/
  16631. @<Update the values of |last_glue|, |last_penalty|, and |last_kern|@>;
  16632. @<Move node |p| to the current page; if it is time for a page break,
  16633.   put the nodes following the break back onto the contribution list,
  16634.   and |return| to the user's output routine if there is one@>;
  16635. until link(contrib_head)=null;
  16636. @<Make the contribution list empty by setting its tail to |contrib_head|@>;
  16637. exit:end;
  16638. @ @d contrib_tail==nest[0].tail_field {tail of the contribution list}
  16639. @<Make the contribution list empty...@>=
  16640. if nest_ptr=0 then tail:=contrib_head {vertical mode}
  16641. else contrib_tail:=contrib_head {other modes}
  16642. @ @<Update the values of |last_glue|...@>=
  16643. if last_glue<>max_halfword then delete_glue_ref(last_glue);
  16644. last_penalty:=0; last_kern:=0;
  16645. if type(p)=glue_node then
  16646.   begin last_glue:=glue_ptr(p); add_glue_ref(last_glue);
  16647.   end
  16648. else  begin last_glue:=max_halfword;
  16649.   if type(p)=penalty_node then last_penalty:=penalty(p)
  16650.   else if type(p)=kern_node then last_kern:=width(p);
  16651.   end
  16652. @ The code here is an example of a many-way switch into routines that
  16653. merge together in different places. Some people call this unstructured
  16654. programming, but the author doesn't see much wrong with it, as long as
  16655. @^Knuth, Donald Ervin@>
  16656. the various labels have a well-understood meaning.
  16657. @<Move node |p| to the current page; ...@>=
  16658. @<If the current page is empty and node |p| is to be deleted, |goto done1|;
  16659.   otherwise use node |p| to update the state of the current page;
  16660.   if this node is an insertion, |goto contribute|; otherwise if this node
  16661.   is not a legal breakpoint, |goto contribute| or |update_heights|;
  16662.   otherwise set |pi| to the penalty associated with this breakpoint@>;
  16663. @<Check if node |p| is a new champion breakpoint; then \(if)if it is time for
  16664.   a page break, prepare for output, and either fire up the user's
  16665.   output routine and |return| or ship out the page and |goto done|@>;
  16666. if (type(p)<glue_node)or(type(p)>kern_node) then goto contribute;
  16667. update_heights:@<Update the current page measurements with respect to the
  16668.   glue or kern specified by node~|p|@>;
  16669. contribute: @<Make sure that |page_max_depth| is not exceeded@>;
  16670. @<Link node |p| into the current page and |goto done|@>;
  16671. done1:@<Recycle node |p|@>;
  16672. done:
  16673. @ @<Link node |p| into the current page and |goto done|@>=
  16674. link(page_tail):=p; page_tail:=p;
  16675. link(contrib_head):=link(p); link(p):=null; goto done
  16676. @ @<Recycle node |p|@>=
  16677. link(contrib_head):=link(p); link(p):=null; flush_node_list(p)
  16678. @ The title of this section is already so long, it seems best to avoid
  16679. making it more accurate but still longer, by mentioning the fact that a
  16680. kern node at the end of the contribution list will not be contributed until
  16681. we know its successor.
  16682. @<If the current page is empty...@>=
  16683. case type(p) of
  16684. hlist_node,vlist_node,rule_node: if page_contents<box_there then
  16685.     @<Initialize the current page, insert the \.{\\topskip} glue
  16686.       ahead of |p|, and |goto continue|@>
  16687.   else @<Prepare to move a box or rule node to the current page,
  16688.     then |goto contribute|@>;
  16689. whatsit_node: @<Prepare to move whatsit |p| to the current page,
  16690.   then |goto contribute|@>;
  16691. glue_node: if page_contents<box_there then goto done1
  16692.   else if precedes_break(page_tail) then pi:=0
  16693.   else goto update_heights;
  16694. kern_node: if page_contents<box_there then goto done1
  16695.   else if link(p)=null then return
  16696.   else if type(link(p))=glue_node then pi:=0
  16697.   else goto update_heights;
  16698. penalty_node: if page_contents<box_there then goto done1@+else pi:=penalty(p);
  16699. mark_node: goto contribute;
  16700. ins_node: @<Append an insertion to the current page and |goto contribute|@>;
  16701. othercases confusion("page")
  16702. @:this can't happen page}{\quad page@>
  16703. endcases
  16704. @ @<Initialize the current page, insert the \.{\\topskip} glue...@>=
  16705. begin if page_contents=empty then freeze_page_specs(box_there)
  16706. else page_contents:=box_there;
  16707. q:=new_skip_param(top_skip_code); {now |temp_ptr=glue_ptr(q)|}
  16708. if width(temp_ptr)>height(p) then width(temp_ptr):=width(temp_ptr)-height(p)
  16709. else width(temp_ptr):=0;
  16710. link(q):=p; link(contrib_head):=q; goto continue;
  16711. @ @<Prepare to move a box or rule node to the current page...@>=
  16712. begin page_total:=page_total+page_depth+height(p);
  16713. page_depth:=depth(p);
  16714. goto contribute;
  16715. @ @<Make sure that |page_max_depth| is not exceeded@>=
  16716. if page_depth>page_max_depth then
  16717.   begin page_total:=@|
  16718.     page_total+page_depth-page_max_depth;@/
  16719.   page_depth:=page_max_depth;
  16720.   end;
  16721. @ @<Update the current page measurements with respect to the glue...@>=
  16722. if type(p)=kern_node then q:=p
  16723. else begin q:=glue_ptr(p);
  16724.   page_so_far[2+stretch_order(q)]:=@|
  16725.     page_so_far[2+stretch_order(q)]+stretch(q);@/
  16726.   page_shrink:=page_shrink+shrink(q);
  16727.   if (shrink_order(q)<>normal)and(shrink(q)<>0) then
  16728.     begin@t@>@;@/
  16729.     print_err("Infinite glue shrinkage found on current page");@/
  16730. @.Infinite glue shrinkage...@>
  16731.     help4("The page about to be output contains some infinitely")@/
  16732.       ("shrinkable glue, e.g., `\vss' or `\vskip 0pt minus 1fil'.")@/
  16733.       ("Such glue doesn't belong there; but you can safely proceed,")@/
  16734.       ("since the offensive shrinkability has been made finite.");
  16735.     error;
  16736.     r:=new_spec(q); shrink_order(r):=normal; delete_glue_ref(q);
  16737.     glue_ptr(p):=r; q:=r;
  16738.     end;
  16739.   end;
  16740. page_total:=page_total+page_depth+width(q); page_depth:=0
  16741. @ @<Check if node |p| is a new champion breakpoint; then \(if)...@>=
  16742. if pi<inf_penalty then
  16743.   begin @<Compute the badness, |b|, of the current page,
  16744.     using |awful_bad| if the box is too full@>;
  16745.   if b<awful_bad then
  16746.     if pi<=eject_penalty then c:=pi
  16747.     else  if b<inf_bad then c:=b+pi+insert_penalties
  16748.       else c:=deplorable
  16749.   else c:=b;
  16750.   if insert_penalties>=10000 then c:=awful_bad;
  16751.   @!stat if tracing_pages>0 then @<Display the page break cost@>;@+tats@;@/
  16752.   if c<=least_page_cost then
  16753.     begin best_page_break:=p; best_size:=page_goal;
  16754.     least_page_cost:=c;
  16755.     r:=link(page_ins_head);
  16756.     while r<>page_ins_head do
  16757.       begin best_ins_ptr(r):=last_ins_ptr(r);
  16758.       r:=link(r);
  16759.       end;
  16760.     end;
  16761.   if (c=awful_bad)or(pi<=eject_penalty) then
  16762.     begin fire_up(p); {output the current page at the best place}
  16763.     if output_active then return; {user's output routine will act}
  16764.     goto done; {the page has been shipped out by default output routine}
  16765.     end;
  16766.   end
  16767. @ @<Display the page break cost@>=
  16768. begin begin_diagnostic; print_nl("%");
  16769. print(" t="); print_totals;@/
  16770. print(" g="); print_scaled(page_goal);@/
  16771. print(" b=");
  16772. if b=awful_bad then print_char("*")@+else print_int(b);
  16773. @.*\relax@>
  16774. print(" p="); print_int(pi);
  16775. print(" c=");
  16776. if c=awful_bad then print_char("*")@+else print_int(c);
  16777. if c<=least_page_cost then print_char("#");
  16778. end_diagnostic(false);
  16779. @ @<Compute the badness, |b|, of the current page...@>=
  16780. if page_total<page_goal then
  16781.   if (page_so_far[3]<>0) or (page_so_far[4]<>0) or@|
  16782.     (page_so_far[5]<>0) then b:=0
  16783.   else b:=badness(page_goal-page_total,page_so_far[2])
  16784. else if page_total-page_goal>page_shrink then b:=awful_bad
  16785. else b:=badness(page_total-page_goal,page_shrink)
  16786. @ @<Append an insertion to the current page and |goto contribute|@>=
  16787. begin if page_contents=empty then freeze_page_specs(inserts_only);
  16788. n:=subtype(p); r:=page_ins_head;
  16789. while n>=subtype(link(r)) do r:=link(r);
  16790. n:=qo(n);
  16791. if subtype(r)<>qi(n) then
  16792.   @<Create a page insertion node with |subtype(r)=qi(n)|, and
  16793.     include the glue correction for box |n| in the
  16794.     current page state@>;
  16795. if type(r)=split_up then insert_penalties:=insert_penalties+float_cost(p)
  16796. else  begin last_ins_ptr(r):=p;
  16797.   delta:=page_goal-page_total-page_depth+page_shrink;
  16798.     {this much room is left if we shrink the maximum}
  16799.   if count(n)=1000 then h:=height(p)
  16800.   else h:=x_over_n(height(p),1000)*count(n); {this much room is needed}
  16801.   if ((h<=0)or(h<=delta))and(height(p)+height(r)<=dimen(n)) then
  16802.     begin page_goal:=page_goal-h; height(r):=height(r)+height(p);
  16803.     end
  16804.   else @<Find the best way to split the insertion, and change
  16805.     |type(r)| to |split_up|@>;
  16806.   end;
  16807. goto contribute;
  16808. @ We take note of the value of \.{\\skip} |n| and the height plus depth
  16809. of \.{\\box}~|n| only when the first \.{\\insert}~|n| node is
  16810. encountered for a new page. A user who changes the contents of \.{\\box}~|n|
  16811. after that first \.{\\insert}~|n| had better be either extremely careful
  16812. or extremely lucky, or both.
  16813. @<Create a page insertion node...@>=
  16814. begin q:=get_node(page_ins_node_size); link(q):=link(r); link(r):=q; r:=q;
  16815. subtype(r):=qi(n); type(r):=inserting; ensure_vbox(n);
  16816. if box(n)=null then height(r):=0
  16817. else height(r):=height(box(n))+depth(box(n));
  16818. best_ins_ptr(r):=null;@/
  16819. q:=skip(n);
  16820. if count(n)=1000 then h:=height(r)
  16821. else h:=x_over_n(height(r),1000)*count(n);
  16822. page_goal:=page_goal-h-width(q);@/
  16823. page_so_far[2+stretch_order(q)]:=@|page_so_far[2+stretch_order(q)]+stretch(q);@/
  16824. page_shrink:=page_shrink+shrink(q);
  16825. if (shrink_order(q)<>normal)and(shrink(q)<>0) then
  16826.   begin print_err("Infinite glue shrinkage inserted from "); print_esc("skip");
  16827. @.Infinite glue shrinkage...@>
  16828.   print_int(n);
  16829.   help3("The correction glue for page breaking with insertions")@/
  16830.     ("must have finite shrinkability. But you may proceed,")@/
  16831.     ("since the offensive shrinkability has been made finite.");
  16832.   error;
  16833.   end;
  16834. @ Here is the code that will split a long footnote between pages, in an
  16835. emergency. The current situation deserves to be recapitulated: Node |p|
  16836. is an insertion into box |n|; the insertion will not fit, in its entirety,
  16837. either because it would make the total contents of box |n| greater than
  16838. \.{\\dimen} |n|, or because it would make the incremental amount of growth
  16839. |h| greater than the available space |delta|, or both. (This amount |h| has
  16840. been weighted by the insertion scaling factor, i.e., by \.{\\count} |n|
  16841. over 1000.) Now we will choose the best way to break the vlist of the
  16842. insertion, using the same criteria as in the \.{\\vsplit} operation.
  16843. @<Find the best way to split the insertion...@>=
  16844. begin if count(n)<=0 then w:=max_dimen
  16845. else  begin w:=page_goal-page_total-page_depth;
  16846.   if count(n)<>1000 then w:=x_over_n(w,count(n))*1000;
  16847.   end;
  16848. if w>dimen(n)-height(r) then w:=dimen(n)-height(r);
  16849. q:=vert_break(ins_ptr(p),w,depth(p));
  16850. height(r):=height(r)+best_height_plus_depth;
  16851. @!stat if tracing_pages>0 then @<Display the insertion split cost@>;@+tats@;@/
  16852. if count(n)<>1000 then
  16853.   best_height_plus_depth:=x_over_n(best_height_plus_depth,1000)*count(n);
  16854. page_goal:=page_goal-best_height_plus_depth;
  16855. type(r):=split_up; broken_ptr(r):=q; broken_ins(r):=p;
  16856. if q=null then insert_penalties:=insert_penalties+eject_penalty
  16857. else if type(q)=penalty_node then insert_penalties:=insert_penalties+penalty(q);
  16858. @ @<Display the insertion split cost@>=
  16859. begin begin_diagnostic; print_nl("% split"); print_int(n);
  16860. @.split@>
  16861. print(" to "); print_scaled(w);
  16862. print_char(","); print_scaled(best_height_plus_depth);@/
  16863. print(" p=");
  16864. if q=null then print_int(eject_penalty)
  16865. else if type(q)=penalty_node then print_int(penalty(q))
  16866. else print_char("0");
  16867. end_diagnostic(false);
  16868. @ When the page builder has looked at as much material as could appear before
  16869. the next page break, it makes its decision. The break that gave minimum
  16870. badness will be used to put a completed ``page'' into box 255, with insertions
  16871. appended to their other boxes.
  16872. We also set the values of |top_mark|, |first_mark|, and |bot_mark|. The
  16873. program uses the fact that |bot_mark<>null| implies |first_mark<>null|;
  16874. it also knows that |bot_mark=null| implies |top_mark=first_mark=null|.
  16875. The |fire_up| subroutine prepares to output the current page at the best
  16876. place; then it fires up the user's output routine, if there is one,
  16877. or it simply ships out the page. There is one parameter, |c|, which represents
  16878. the node that was being contributed to the page when the decision to
  16879. force an output was made.
  16880. @<Declare the procedure called |fire_up|@>=
  16881. procedure fire_up(@!c:pointer);
  16882. label exit;
  16883. var p,@!q,@!r,@!s:pointer; {nodes being examined and/or changed}
  16884. @!prev_p:pointer; {predecessor of |p|}
  16885. @!n:min_quarterword..255; {insertion box number}
  16886. @!wait:boolean; {should the present insertion be held over?}
  16887. @!save_vbadness:integer; {saved value of |vbadness|}
  16888. @!save_vfuzz: scaled; {saved value of |vfuzz|}
  16889. @!save_split_top_skip: pointer; {saved value of |split_top_skip|}
  16890. begin @<Set the value of |output_penalty|@>;
  16891. if bot_mark<>null then
  16892.   begin if top_mark<>null then delete_token_ref(top_mark);
  16893.   top_mark:=bot_mark; add_token_ref(top_mark);
  16894.   delete_token_ref(first_mark); first_mark:=null;
  16895.   end;
  16896. @<Put the \(o)optimal current page into box 255, update |first_mark| and
  16897.   |bot_mark|, append insertions to their boxes, and put the
  16898.   remaining nodes back on the contribution list@>;
  16899. if (top_mark<>null)and(first_mark=null) then
  16900.   begin first_mark:=top_mark; add_token_ref(top_mark);
  16901.   end;
  16902. if output_routine<>null then
  16903.   if dead_cycles>=max_dead_cycles then
  16904.     @<Explain that too many dead cycles have occurred in a row@>
  16905.   else @<Fire up the user's output routine and |return|@>;
  16906. @<Perform the default output routine@>;
  16907. exit:end;
  16908. @ @<Set the value of |output_penalty|@>=
  16909. if type(best_page_break)=penalty_node then
  16910.   begin geq_word_define(int_base+output_penalty_code,penalty(best_page_break));
  16911.   penalty(best_page_break):=inf_penalty;
  16912.   end
  16913. else geq_word_define(int_base+output_penalty_code,inf_penalty)
  16914. @ As the page is finally being prepared for output,
  16915. pointer |p| runs through the vlist, with |prev_p| trailing behind;
  16916. pointer |q| is the tail of a list of insertions that
  16917. are being held over for a subsequent page.
  16918. @<Put the \(o)optimal current page into box 255...@>=
  16919. if c=best_page_break then best_page_break:=null; {|c| not yet linked in}
  16920. @<Ensure that box 255 is empty before output@>;
  16921. insert_penalties:=0; {this will count the number of insertions held over}
  16922. save_split_top_skip:=split_top_skip;
  16923. if holding_inserts<=0 then
  16924.   @<Prepare all the boxes involved in insertions to act as queues@>;
  16925. q:=hold_head; link(q):=null; prev_p:=page_head; p:=link(prev_p);
  16926. while p<>best_page_break do
  16927.   begin if type(p)=ins_node then
  16928.     begin if holding_inserts<=0 then
  16929.        @<Either insert the material specified by node |p| into the
  16930.          appropriate box, or hold it for the next page;
  16931.          also delete node |p| from the current page@>;
  16932.     end
  16933.   else if type(p)=mark_node then @<Update the values of
  16934.     |first_mark| and |bot_mark|@>;
  16935.   prev_p:=p; p:=link(prev_p);
  16936.   end;
  16937. split_top_skip:=save_split_top_skip;
  16938. @<Break the current page at node |p|, put it in box~255,
  16939.   and put the remaining nodes on the contribution list@>;
  16940. @<Delete \(t)the page-insertion nodes@>
  16941. @ @<Ensure that box 255 is empty before output@>=
  16942. if box(255)<>null then
  16943.   begin print_err(""); print_esc("box"); print("255 is not void");
  16944. @:box255}{\.{\\box255 is not void}@>
  16945.   help2("You shouldn't use \box255 except in \output routines.")@/
  16946.     ("Proceed, and I'll discard its present contents.");
  16947.   box_error(255);
  16948.   end
  16949. @ @<Update the values of |first_mark| and |bot_mark|@>=
  16950. begin if first_mark=null then
  16951.   begin first_mark:=mark_ptr(p);
  16952.   add_token_ref(first_mark);
  16953.   end;
  16954. if bot_mark<>null then delete_token_ref(bot_mark);
  16955. bot_mark:=mark_ptr(p); add_token_ref(bot_mark);
  16956. @ When the following code is executed, the current page runs from node
  16957. |link(page_head)| to node |prev_p|, and the nodes from |p| to |page_tail|
  16958. are to be placed back at the front of the contribution list. Furthermore
  16959. the heldover insertions appear in a list from |link(hold_head)| to |q|; we
  16960. will put them into the current page list for safekeeping while the user's
  16961. output routine is active.  We might have |q=hold_head|; and |p=null| if
  16962. and only if |prev_p=page_tail|. Error messages are suppressed within
  16963. |vpackage|, since the box might appear to be overfull or underfull simply
  16964. because the stretch and shrink from the \.{\\skip} registers for inserts
  16965. are not actually present in the box.
  16966. @<Break the current page at node |p|, put it...@>=
  16967. if p<>null then
  16968.   begin if link(contrib_head)=null then
  16969.     if nest_ptr=0 then tail:=page_tail
  16970.     else contrib_tail:=page_tail;
  16971.   link(page_tail):=link(contrib_head);
  16972.   link(contrib_head):=p;
  16973.   link(prev_p):=null;
  16974.   end;
  16975. save_vbadness:=vbadness; vbadness:=inf_bad;
  16976. save_vfuzz:=vfuzz; vfuzz:=max_dimen; {inhibit error messages}
  16977. box(255):=vpackage(link(page_head),best_size,exactly,page_max_depth);
  16978. vbadness:=save_vbadness; vfuzz:=save_vfuzz;
  16979. if last_glue<>max_halfword then delete_glue_ref(last_glue);
  16980. @<Start a new current page@>; {this sets |last_glue:=max_halfword|}
  16981. if q<>hold_head then
  16982.   begin link(page_head):=link(hold_head); page_tail:=q;
  16983.   end
  16984. @ If many insertions are supposed to go into the same box, we want to know
  16985. the position of the last node in that box, so that we don't need to waste time
  16986. when linking further information into it. The |last_ins_ptr| fields of the
  16987. page insertion nodes are therefore used for this purpose during the
  16988. packaging phase.
  16989. @<Prepare all the boxes involved in insertions to act as queues@>=
  16990. begin r:=link(page_ins_head);
  16991. while r<>page_ins_head do
  16992.   begin if best_ins_ptr(r)<>null then
  16993.     begin n:=qo(subtype(r)); ensure_vbox(n);
  16994.     if box(n)=null then box(n):=new_null_box;
  16995.     p:=box(n)+list_offset;
  16996.     while link(p)<>null do p:=link(p);
  16997.     last_ins_ptr(r):=p;
  16998.     end;
  16999.   r:=link(r);
  17000.   end;
  17001. @ @<Delete \(t)the page-insertion nodes@>=
  17002. r:=link(page_ins_head);
  17003. while r<>page_ins_head do
  17004.   begin q:=link(r); free_node(r,page_ins_node_size); r:=q;
  17005.   end;
  17006. link(page_ins_head):=page_ins_head
  17007. @ We will set |best_ins_ptr:=null| and package the box corresponding to
  17008. insertion node~|r|, just after making the final insertion into that box.
  17009. If this final insertion is `|split_up|', the remainder after splitting
  17010. and pruning (if any) will be carried over to the next page.
  17011. @<Either insert the material specified by node |p| into...@>=
  17012. begin r:=link(page_ins_head);
  17013. while subtype(r)<>subtype(p) do r:=link(r);
  17014. if best_ins_ptr(r)=null then wait:=true
  17015. else  begin wait:=false; s:=last_ins_ptr(r); link(s):=ins_ptr(p);
  17016.   if best_ins_ptr(r)=p then
  17017.     @<Wrap up the box specified by node |r|, splitting node |p| if
  17018.     called for; set |wait:=true| if node |p| holds a remainder after
  17019.     splitting@>
  17020.   else  begin while link(s)<>null do s:=link(s);
  17021.     last_ins_ptr(r):=s;
  17022.     end;
  17023.   end;
  17024. @<Either append the insertion node |p| after node |q|, and remove it
  17025.   from the current page, or delete |node(p)|@>;
  17026. @ @<Wrap up the box specified by node |r|, splitting node |p| if...@>=
  17027. begin if type(r)=split_up then
  17028.   if (broken_ins(r)=p)and(broken_ptr(r)<>null) then
  17029.     begin while link(s)<>broken_ptr(r) do s:=link(s);
  17030.     link(s):=null;
  17031.     split_top_skip:=split_top_ptr(p);
  17032.     ins_ptr(p):=prune_page_top(broken_ptr(r));
  17033.     if ins_ptr(p)<>null then
  17034.       begin temp_ptr:=vpack(ins_ptr(p),natural);
  17035.       height(p):=height(temp_ptr)+depth(temp_ptr);
  17036.       free_node(temp_ptr,box_node_size); wait:=true;
  17037.       end;
  17038.     end;
  17039. best_ins_ptr(r):=null;
  17040. n:=qo(subtype(r));
  17041. temp_ptr:=list_ptr(box(n));
  17042. free_node(box(n),box_node_size);
  17043. box(n):=vpack(temp_ptr,natural);
  17044. @ @<Either append the insertion node |p|...@>=
  17045. link(prev_p):=link(p); link(p):=null;
  17046. if wait then
  17047.   begin link(q):=p; q:=p; incr(insert_penalties);
  17048.   end
  17049. else  begin delete_glue_ref(split_top_ptr(p));
  17050.   free_node(p,ins_node_size);
  17051.   end;
  17052. p:=prev_p
  17053. @ The list of heldover insertions, running from |link(page_head)| to
  17054. |page_tail|, must be moved to the contribution list when the user has
  17055. specified no output routine.
  17056. @<Perform the default output routine@>=
  17057. begin if link(page_head)<>null then
  17058.   begin if link(contrib_head)=null then
  17059.     if nest_ptr=0 then tail:=page_tail@+else contrib_tail:=page_tail
  17060.   else link(page_tail):=link(contrib_head);
  17061.   link(contrib_head):=link(page_head);
  17062.   link(page_head):=null; page_tail:=page_head;
  17063.   end;
  17064. ship_out(box(255)); box(255):=null;
  17065. @ @<Explain that too many dead cycles have occurred in a row@>=
  17066. begin print_err("Output loop---"); print_int(dead_cycles);
  17067. @.Output loop...@>
  17068. print(" consecutive dead cycles");
  17069. help3("I've concluded that your \output is awry; it never does a")@/
  17070. ("\shipout, so I'm shipping \box255 out myself. Next time")@/
  17071. ("increase \maxdeadcycles if you want me to be more patient!"); error;
  17072. @ @<Fire up the user's output routine and |return|@>=
  17073. begin output_active:=true;
  17074. incr(dead_cycles);
  17075. push_nest; mode:=-vmode; prev_depth:=ignore_depth; mode_line:=-line;
  17076. begin_token_list(output_routine,output_text);
  17077. new_save_level(output_group); normal_paragraph;
  17078. scan_left_brace;
  17079. return;
  17080. @ When the user's output routine finishes, it has constructed a vlist
  17081. in internal vertical mode, and \TeX\ will do the following:
  17082. @<Resume the page builder after an output routine has come to an end@>=
  17083. begin if (loc<>null) or 
  17084.  ((token_type<>output_text)and(token_type<>backed_up)) then
  17085.   @<Recover from an unbalanced output routine@>;
  17086. end_token_list; {conserve stack space in case more outputs are triggered}
  17087. end_graf; unsave; output_active:=false; insert_penalties:=0;@/
  17088. @<Ensure that box 255 is empty after output@>;
  17089. if tail<>head then {current list goes after heldover insertions}
  17090.   begin link(page_tail):=link(head);
  17091.   page_tail:=tail;
  17092.   end;
  17093. if link(page_head)<>null then {and both go before heldover contributions}
  17094.   begin if link(contrib_head)=null then contrib_tail:=page_tail;
  17095.   link(page_tail):=link(contrib_head);
  17096.   link(contrib_head):=link(page_head);
  17097.   link(page_head):=null; page_tail:=page_head;
  17098.   end;
  17099. pop_nest; build_page;
  17100. @ @<Recover from an unbalanced output routine@>=
  17101. begin print_err("Unbalanced output routine");
  17102. @.Unbalanced output routine@>
  17103. help2("Your sneaky output routine has problematic {'s and/or }'s.")@/
  17104. ("I can't handle that very well; good luck."); error;
  17105. repeat get_token;
  17106. until loc=null;
  17107. end {loops forever if reading from a file, since |null=min_halfword<=0|}
  17108. @ @<Ensure that box 255 is empty after output@>=
  17109. if box(255)<>null then
  17110.   begin print_err("Output routine didn't use all of ");
  17111.   print_esc("box"); print_int(255);
  17112. @.Output routine didn't use...@>
  17113.   help3("Your \output commands should empty \box255,")@/
  17114.     ("e.g., by saying `\shipout\box255'.")@/
  17115.     ("Proceed; I'll discard its present contents.");
  17116.   box_error(255);
  17117.   end
  17118. @* \[46] The chief executive.
  17119. We come now to the |main_control| routine, which contains the master
  17120. switch that causes all the various pieces of \TeX\ to do their things,
  17121. in the right order.
  17122. In a sense, this is the grand climax of the program: It applies all the
  17123. tools that we have worked so hard to construct. In another sense, this is
  17124. the messiest part of the program: It necessarily refers to other pieces
  17125. of code all over the place, so that a person can't fully understand what is
  17126. going on without paging back and forth to be reminded of conventions that
  17127. are defined elsewhere. We are now at the hub of the web, the central nervous
  17128. system that touches most of the other parts and ties them together.
  17129. @^brain@>
  17130. The structure of |main_control| itself is quite simple. There's a label
  17131. called |big_switch|, at which point the next token of input is fetched
  17132. using |get_x_token|. Then the program branches at high speed into one of
  17133. about 100 possible directions, based on the value of the current
  17134. mode and the newly fetched command code; the sum |abs(mode)+cur_cmd|
  17135. indicates what to do next. For example, the case `|vmode+letter|' arises
  17136. when a letter occurs in vertical mode (or internal vertical mode); this
  17137. case leads to instructions that initialize a new paragraph and enter
  17138. horizontal mode.
  17139. The big |case| statement that contains this multiway switch has been labeled
  17140. |reswitch|, so that the program can |goto reswitch| when the next token
  17141. has already been fetched. Most of the cases are quite short; they call
  17142. an ``action procedure'' that does the work for that case, and then they
  17143. either |goto reswitch| or they ``fall through'' to the end of the |case|
  17144. statement, which returns control back to |big_switch|. Thus, |main_control|
  17145. is not an extremely large procedure, in spite of the multiplicity of things
  17146. it must do; it is small enough to be handled by \PASCAL\ compilers that put
  17147. severe restrictions on procedure size.
  17148. @!@^action procedure@>
  17149. One case is singled out for special treatment, because it accounts for most
  17150. of \TeX's activities in typical applications. The process of reading simple
  17151. text and converting it into |char_node| records, while looking for ligatures
  17152. and kerns, is part of \TeX's ``inner loop''; the whole program runs
  17153. efficiently when its inner loop is fast, so this part has been written
  17154. with particular care.
  17155. @ We shall concentrate first on the inner loop of |main_control|, deferring
  17156. consideration of the other cases until later.
  17157. @d big_switch=60 {go here to branch on the next token of input}
  17158. @d main_loop=70 {go here to typeset a string of consecutive characters}
  17159. @d main_loop_wrapup=80 {go here to finish a character or ligature}
  17160. @d main_loop_move=90 {go here to advance the ligature cursor}
  17161. @d main_loop_move_lig=95 {same, when advancing past a generated ligature}
  17162. @d main_loop_lookahead=100 {go here to bring in another character, if any}
  17163. @d main_lig_loop=110 {go here to check for ligatures or kerning}
  17164. @d append_normal_space=120 {go here to append a normal space between words}
  17165. @p @t\4@>@<Declare action procedures for use by |main_control|@>@;
  17166. @t\4@>@<Declare the procedure called |handle_right_brace|@>@;
  17167. procedure main_control; {governs \TeX's activities}
  17168. label big_switch,reswitch,main_loop,main_loop_wrapup,
  17169.   main_loop_move,main_loop_move+1,main_loop_move+2,main_loop_move_lig,
  17170.   main_loop_lookahead,main_loop_lookahead+1,
  17171.   main_lig_loop,main_lig_loop+1,main_lig_loop+2,
  17172.   append_normal_space,exit;
  17173. var@!t:integer; {general-purpose temporary variable}
  17174. begin if every_job<>null then begin_token_list(every_job,every_job_text);
  17175. big_switch: get_x_token;@/
  17176. reswitch: @<Give diagnostic information, if requested@>;
  17177. case abs(mode)+cur_cmd of
  17178. hmode+letter,hmode+other_char,hmode+char_given: goto main_loop;
  17179. hmode+char_num: begin scan_char_num; cur_chr:=cur_val; goto main_loop;@+end;
  17180. hmode+no_boundary: begin get_x_token;
  17181.   if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given)or
  17182.    (cur_cmd=char_num) then cancel_boundary:=true;
  17183.   goto reswitch;
  17184.   end;
  17185. hmode+spacer: if space_factor=1000 then goto append_normal_space
  17186.   else app_space;
  17187. hmode+ex_space,mmode+ex_space: goto append_normal_space;
  17188. @t\4@>@<Cases of |main_control| that are not part of the inner loop@>@;
  17189. end; {of the big |case| statement}
  17190. goto big_switch;
  17191. main_loop:@<Append character |cur_chr| and the following characters (if~any)
  17192.   to the current hlist in the current font; |goto reswitch| when
  17193.   a non-character has been fetched@>;
  17194. append_normal_space:@<Append a normal inter-word space to the current list,
  17195.   then |goto big_switch|@>;
  17196. exit:end;
  17197. @ When a new token has just been fetched at |big_switch|, we have an
  17198. ideal place to monitor \TeX's activity.
  17199. @^debugging@>
  17200. @<Give diagnostic information, if requested@>=
  17201. if interrupt<>0 then if OK_to_interrupt then
  17202.   begin back_input; check_interrupt; goto big_switch;
  17203.   end;
  17204. @!debug if panicking then check_mem(false);@+@;@+gubed
  17205. if tracing_commands>0 then show_cur_cmd_chr
  17206. @ The following part of the program was first written in a structured
  17207. manner, according to the philosophy that ``premature optimization is
  17208. the root of all evil.'' Then it was rearranged into pieces of
  17209. spaghetti so that the most common actions could proceed with little or
  17210. no redundancy.
  17211. The original unoptimized form of this algorithm resembles the
  17212. |reconstitute| procedure, which was described earlier in connection with
  17213. hyphenation. Again we have an implied ``cursor'' between characters
  17214. |cur_l| and |cur_r|. The main difference is that the |lig_stack| can now
  17215. contain a charnode as well as pseudo-ligatures; that stack is now
  17216. usually nonempty, because the next character of input (if any) has been
  17217. appended to it. In |main_control| we have
  17218. $$|cur_r|=\cases{|character(lig_stack)|,&if |lig_stack>null|;\cr
  17219.   |font_bchar[cur_font]|,&otherwise;\cr}$$
  17220. except when |character(lig_stack)=font_false_bchar[cur_font]|.
  17221. Several additional global variables are needed.
  17222. @<Glob...@>=
  17223. @!main_f:internal_font_number; {the current font}
  17224. @!main_i:four_quarters; {character information bytes for |cur_l|}
  17225. @!main_j:four_quarters; {ligature/kern command}
  17226. @!main_k:font_index; {index into |font_info|}
  17227. @!main_p:pointer; {temporary register for list manipulation}
  17228. @!main_s:integer; {space factor value}
  17229. @!bchar:halfword; {right boundary character of current font, or |non_char|}
  17230. @!false_bchar:halfword; {nonexistent character matching |bchar|, or |non_char|}
  17231. @!cancel_boundary:boolean; {should the left boundary be ignored?}
  17232. @!ins_disc:boolean; {should we insert a discretionary node?}
  17233. @ The boolean variables of the main loop are normally false, and always reset
  17234. to false before the loop is left. That saves us the extra work of initializing
  17235. each time.
  17236. @<Set init...@>=
  17237. ligature_present:=false; cancel_boundary:=false; lft_hit:=false; rt_hit:=false;
  17238. ins_disc:=false;
  17239. @ We leave the |space_factor| unchanged if |sf_code(cur_chr)=0|; otherwise we
  17240. set it equal to |sf_code(cur_chr)|, except that it should never change
  17241. from a value less than 1000 to a value exceeding 1000. The most common
  17242. case is |sf_code(cur_chr)=1000|, so we want that case to be fast.
  17243. The overall structure of the main loop is presented here. Some program labels
  17244. are inside the individual sections.
  17245. @d adjust_space_factor==@t@>@;@/
  17246.   main_s:=sf_code(cur_chr);
  17247.   if main_s=1000 then space_factor:=1000
  17248.   else if main_s<1000 then
  17249.     begin if main_s>0 then space_factor:=main_s;
  17250.     end
  17251.   else if space_factor<1000 then space_factor:=1000
  17252.   else space_factor:=main_s
  17253. @<Append character |cur_chr|...@>=
  17254. adjust_space_factor;@/
  17255. main_f:=cur_font;
  17256. bchar:=font_bchar[main_f]; false_bchar:=font_false_bchar[main_f];
  17257. if mode>0 then if language<>clang then fix_language;
  17258. fast_get_avail(lig_stack); font(lig_stack):=main_f; cur_l:=qi(cur_chr);
  17259. character(lig_stack):=cur_l;@/
  17260. cur_q:=tail;
  17261. if cancel_boundary then
  17262.   begin cancel_boundary:=false; main_k:=non_address;
  17263.   end
  17264. else main_k:=bchar_label[main_f];
  17265. if main_k=non_address then goto main_loop_move+2; {no left boundary processing}
  17266. cur_r:=cur_l; cur_l:=non_char;
  17267. goto main_lig_loop+1; {begin with cursor after left boundary}
  17268. main_loop_wrapup:@<Make a ligature node, if |ligature_present|;
  17269.   insert a null discretionary, if appropriate@>;
  17270. main_loop_move:@<If the cursor is immediately followed by the right boundary,
  17271.   |goto reswitch|; if it's followed by an invalid character, |goto big_switch|;
  17272.   otherwise move the cursor one step to the right and |goto main_lig_loop|@>;
  17273. main_loop_lookahead:@<Look ahead for another character, or leave |lig_stack|
  17274.   empty if there's none there@>;
  17275. main_lig_loop:@<If there's a ligature/kern command relevant to |cur_l| and
  17276.   |cur_r|, adjust the text appropriately; exit to |main_loop_wrapup|@>;
  17277. main_loop_move_lig:@<Move the cursor past a pseudo-ligature, then
  17278.   |goto main_loop_lookahead| or |main_lig_loop|@>
  17279. @ If the current horizontal list is empty, the reference to |character(tail)|
  17280. here is not strictly legal, since |tail| will be a node freshly returned by
  17281. |get_avail|. But this should cause no problem on most implementations, and we
  17282. do want the inner loop to be fast.
  17283. @^dirty Pascal@>
  17284. A discretionary break is not inserted for an explicit hyphen when we are in
  17285. restricted horizontal mode. In particular, this avoids putting discretionary
  17286. nodes inside of other discretionaries.
  17287. @d pack_lig(#)== {the parameter is either |rt_hit| or |false|}
  17288.   begin main_p:=new_ligature(main_f,cur_l,link(cur_q));
  17289.   if lft_hit then
  17290.     begin subtype(main_p):=2; lft_hit:=false;
  17291.     end;
  17292.   if # then if lig_stack=null then
  17293.     begin incr(subtype(main_p)); rt_hit:=false;
  17294.     end;
  17295.   link(cur_q):=main_p; tail:=main_p; ligature_present:=false;
  17296.   end
  17297. @d wrapup(#)==if cur_l<non_char then
  17298.   begin if character(tail)=qi(hyphen_char[main_f]) then if link(cur_q)>null then
  17299.     ins_disc:=true;
  17300.   if ligature_present then pack_lig(#);
  17301.   if ins_disc then
  17302.     begin ins_disc:=false;
  17303.     if mode>0 then tail_append(new_disc);
  17304.     end;
  17305.   end
  17306. @<Make a ligature node, if |ligature_present|;...@>=
  17307. wrapup(rt_hit)
  17308. @ @<If the cursor is immediately followed by the right boundary...@>=
  17309. if lig_stack=null then goto reswitch;
  17310. cur_q:=tail; cur_l:=character(lig_stack);
  17311. main_loop_move+1:if not is_char_node(lig_stack) then goto main_loop_move_lig;
  17312. main_loop_move+2:if(cur_chr<font_bc[main_f])or(cur_chr>font_ec[main_f]) then
  17313.   begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
  17314.   end;
  17315. main_i:=char_info(main_f)(cur_l);
  17316. if not char_exists(main_i) then
  17317.   begin char_warning(main_f,cur_chr); free_avail(lig_stack); goto big_switch;
  17318.   end;
  17319. tail_append(lig_stack) {|main_loop_lookahead| is next}
  17320. @ Here we are at |main_loop_move_lig|.
  17321. When we begin this code we have |cur_q=tail| and |cur_l=character(lig_stack)|.
  17322. @<Move the cursor past a pseudo-ligature...@>=
  17323. main_p:=lig_ptr(lig_stack);
  17324. if main_p>null then tail_append(main_p);
  17325. temp_ptr:=lig_stack; lig_stack:=link(temp_ptr);
  17326. free_node(temp_ptr,small_node_size);
  17327. main_i:=char_info(main_f)(cur_l); ligature_present:=true;
  17328. if lig_stack=null then
  17329.   if main_p>null then goto main_loop_lookahead
  17330.   else cur_r:=bchar
  17331. else cur_r:=character(lig_stack);
  17332. goto main_lig_loop
  17333. @ The result of \.{\\char} can participate in a ligature or kern, so we must
  17334. look ahead for it.
  17335. @<Look ahead for another character...@>=
  17336. get_next; {set only |cur_cmd| and |cur_chr|, for speed}
  17337. if cur_cmd=letter then goto main_loop_lookahead+1;
  17338. if cur_cmd=other_char then goto main_loop_lookahead+1;
  17339. if cur_cmd=char_given then goto main_loop_lookahead+1;
  17340. x_token; {now expand and set |cur_cmd|, |cur_chr|, |cur_tok|}
  17341. if cur_cmd=letter then goto main_loop_lookahead+1;
  17342. if cur_cmd=other_char then goto main_loop_lookahead+1;
  17343. if cur_cmd=char_given then goto main_loop_lookahead+1;
  17344. if cur_cmd=char_num then
  17345.   begin scan_char_num; cur_chr:=cur_val; goto main_loop_lookahead+1;
  17346.   end;
  17347. if cur_cmd=no_boundary then bchar:=non_char;
  17348. cur_r:=bchar; lig_stack:=null; goto main_lig_loop;
  17349. main_loop_lookahead+1: adjust_space_factor;
  17350. fast_get_avail(lig_stack); font(lig_stack):=main_f;
  17351. cur_r:=qi(cur_chr); character(lig_stack):=cur_r;
  17352. if cur_r=false_bchar then cur_r:=non_char {this prevents spurious ligatures}
  17353. @ Even though comparatively few characters have a lig/kern program, several
  17354. of the instructions here count as part of \TeX's inner loop, since a
  17355. potentially long sequential search must be performed. For example, tests with
  17356. Computer Modern Roman showed that about 40 per cent of all characters
  17357. actually encountered in practice had a lig/kern program, and that about four
  17358. lig/kern commands were investigated for every such character.
  17359. At the beginning of this code we have |main_i=char_info(main_f)(cur_l)|.
  17360. @<If there's a ligature/kern command...@>=
  17361. if char_tag(main_i)<>lig_tag then goto main_loop_wrapup;
  17362. main_k:=lig_kern_start(main_f)(main_i); main_j:=font_info[main_k].qqqq;
  17363. if skip_byte(main_j)<=stop_flag then goto main_lig_loop+2;
  17364. main_k:=lig_kern_restart(main_f)(main_j);
  17365. main_lig_loop+1:main_j:=font_info[main_k].qqqq;
  17366. main_lig_loop+2:if next_char(main_j)=cur_r then
  17367.  if skip_byte(main_j)<=stop_flag then
  17368.   @<Do ligature or kern command, returning to |main_lig_loop|
  17369.   or |main_loop_wrapup| or |main_loop_move|@>;
  17370. if skip_byte(main_j)=qi(0) then incr(main_k)
  17371. else begin if skip_byte(main_j)>=stop_flag then goto main_loop_wrapup;
  17372.   main_k:=main_k+qo(skip_byte(main_j))+1;
  17373.   end;
  17374. goto main_lig_loop+1
  17375. @ When a ligature or kern instruction matches a character, we know from
  17376. |read_font_info| that the character exists in the font, even though we
  17377. haven't verified its existence in the normal way.
  17378. This section could be made into a subroutine, if the code inside
  17379. |main_control| needs to be shortened.
  17380. \chardef\?='174 % vertical line to indicate character retention
  17381. @<Do ligature or kern command...@>=
  17382. begin if op_byte(main_j)>=kern_flag then
  17383.   begin wrapup(rt_hit);
  17384.   tail_append(new_kern(char_kern(main_f)(main_j))); goto main_loop_move;
  17385.   end;
  17386. if cur_l=non_char then lft_hit:=true
  17387. else if lig_stack=null then rt_hit:=true;
  17388. check_interrupt; {allow a way out in case there's an infinite ligature loop}
  17389. case op_byte(main_j) of
  17390. qi(1),qi(5):begin cur_l:=rem_byte(main_j); {\.{=:\?}, \.{=:\?>}}
  17391.   main_i:=char_info(main_f)(cur_l); ligature_present:=true;
  17392.   end;
  17393. qi(2),qi(6):begin cur_r:=rem_byte(main_j); {\.{\?=:}, \.{\?=:>}}
  17394.   if lig_stack=null then {right boundary character is being consumed}
  17395.     begin lig_stack:=new_lig_item(cur_r); bchar:=non_char;
  17396.     end
  17397.   else if is_char_node(lig_stack) then {|link(lig_stack)=null|}
  17398.     begin main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
  17399.     lig_ptr(lig_stack):=main_p;
  17400.     end
  17401.   else character(lig_stack):=cur_r;
  17402.   end;
  17403. qi(3):begin cur_r:=rem_byte(main_j); {\.{\?=:\?}}
  17404.   main_p:=lig_stack; lig_stack:=new_lig_item(cur_r);
  17405.   link(lig_stack):=main_p;
  17406.   end;
  17407. qi(7),qi(11):begin wrapup(false); {\.{\?=:\?>}, \.{\?=:\?>>}}
  17408.   cur_q:=tail; cur_l:=rem_byte(main_j);
  17409.   main_i:=char_info(main_f)(cur_l); ligature_present:=true;
  17410.   end;
  17411. othercases begin cur_l:=rem_byte(main_j); ligature_present:=true; {\.{=:}}
  17412.   if lig_stack=null then goto main_loop_wrapup
  17413.   else goto main_loop_move+1;
  17414.   end
  17415. endcases;
  17416. if op_byte(main_j)>qi(4) then
  17417.   if op_byte(main_j)<>qi(7) then goto main_loop_wrapup;
  17418. if cur_l<non_char then goto main_lig_loop;
  17419. main_k:=bchar_label[main_f]; goto main_lig_loop+1;
  17420. @ The occurrence of blank spaces is almost part of \TeX's inner loop,
  17421. since we usually encounter about one space for every five non-blank characters.
  17422. Therefore |main_control| gives second-highest priority to ordinary spaces.
  17423. When a glue parameter like \.{\\spaceskip} is set to `\.{0pt}', we will
  17424. see to it later that the corresponding glue specification is precisely
  17425. |zero_glue|, not merely a pointer to some specification that happens
  17426. to be full of zeroes. Therefore it is simple to test whether a glue parameter
  17427. is zero or~not.
  17428. @<Append a normal inter-word space...@>=
  17429. if space_skip=zero_glue then
  17430.   begin @<Find the glue specification, |main_p|, for
  17431.     text spaces in the current font@>;
  17432.   temp_ptr:=new_glue(main_p);
  17433.   end
  17434. else temp_ptr:=new_param_glue(space_skip_code);
  17435. link(tail):=temp_ptr; tail:=temp_ptr;
  17436. goto big_switch
  17437. @ Having |font_glue| allocated for each text font saves both time and memory.
  17438. If any of the three spacing parameters are subsequently changed by the
  17439. use of \.{\\fontdimen}, the |find_font_dimen| procedure deallocates the
  17440. |font_glue| specification allocated here.
  17441. @<Find the glue specification...@>=
  17442. begin main_p:=font_glue[cur_font];
  17443. if main_p=null then
  17444.   begin main_p:=new_spec(zero_glue); main_k:=param_base[cur_font]+space_code;
  17445.   width(main_p):=font_info[main_k].sc; {that's |space(cur_font)|}
  17446.   stretch(main_p):=font_info[main_k+1].sc; {and |space_stretch(cur_font)|}
  17447.   shrink(main_p):=font_info[main_k+2].sc; {and |space_shrink(cur_font)|}
  17448.   font_glue[cur_font]:=main_p;
  17449.   end;
  17450. @ @<Declare act...@>=
  17451. procedure app_space; {handle spaces when |space_factor<>1000|}
  17452. var@!q:pointer; {glue node}
  17453. begin if (space_factor>=2000)and(xspace_skip<>zero_glue) then
  17454.   q:=new_param_glue(xspace_skip_code)
  17455. else  begin if space_skip<>zero_glue then main_p:=space_skip
  17456.   else @<Find the glue specification...@>;
  17457.   main_p:=new_spec(main_p);
  17458.   @<Modify the glue specification in |main_p| according to the space factor@>;
  17459.   q:=new_glue(main_p); glue_ref_count(main_p):=null;
  17460.   end;
  17461. link(tail):=q; tail:=q;
  17462. @ @<Modify the glue specification in |main_p| according to the space factor@>=
  17463. if space_factor>=2000 then width(main_p):=width(main_p)+extra_space(cur_font);
  17464. stretch(main_p):=xn_over_d(stretch(main_p),space_factor,1000);
  17465. shrink(main_p):=xn_over_d(shrink(main_p),1000,space_factor)
  17466. @ Whew---that covers the main loop. We can now proceed at a leisurely
  17467. pace through the other combinations of possibilities.
  17468. @d any_mode(#)==vmode+#,hmode+#,mmode+# {for mode-independent commands}
  17469. @<Cases of |main_control| that are not part of the inner loop@>=
  17470. any_mode(relax),vmode+spacer,mmode+spacer,mmode+no_boundary:do_nothing;
  17471. any_mode(ignore_spaces): begin @<Get the next non-blank non-call...@>;
  17472.   goto reswitch;
  17473.   end;
  17474. vmode+stop: if its_all_over then return; {this is the only way out}
  17475. @t\4@>@<Forbidden cases detected in |main_control|@>@+@,any_mode(mac_param):
  17476.   report_illegal_case;
  17477. @<Math-only cases in non-math modes, or vice versa@>: insert_dollar_sign;
  17478. @t\4@>@<Cases of |main_control| that build boxes and lists@>@;
  17479. @t\4@>@<Cases of |main_control| that don't depend on |mode|@>@;
  17480. @t\4@>@<Cases of |main_control| that are for extensions to \TeX@>@;
  17481. @ Here is a list of cases where the user has probably gotten into or out of math
  17482. mode by mistake. \TeX\ will insert a dollar sign and rescan the current token.
  17483. @d non_math(#)==vmode+#,hmode+#
  17484. @<Math-only cases in non-math modes...@>=
  17485. non_math(sup_mark), non_math(sub_mark), non_math(math_char_num),
  17486. non_math(math_given), non_math(math_comp), non_math(delim_num),
  17487. non_math(left_right), non_math(above), non_math(radical),
  17488. non_math(math_style), non_math(math_choice), non_math(vcenter),
  17489. non_math(non_script), non_math(mkern), non_math(limit_switch),
  17490. non_math(mskip), non_math(math_accent),
  17491. mmode+endv, mmode+par_end, mmode+stop, mmode+vskip, mmode+un_vbox,
  17492. mmode+valign, mmode+hrule
  17493. @ @<Declare action...@>=
  17494. procedure insert_dollar_sign;
  17495. begin back_input; cur_tok:=math_shift_token+"$";
  17496. print_err("Missing $ inserted");
  17497. @.Missing \$ inserted@>
  17498. help2("I've inserted a begin-math/end-math symbol since I think")@/
  17499. ("you left one out. Proceed, with fingers crossed."); ins_error;
  17500. @ When erroneous situations arise, \TeX\ usually issues an error message
  17501. specific to the particular error. For example, `\.{\\noalign}' should
  17502. not appear in any mode, since it is recognized by the |align_peek| routine
  17503. in all of its legitimate appearances; a special error message is given
  17504. when `\.{\\noalign}' occurs elsewhere. But sometimes the most appropriate
  17505. error message is simply that the user is not allowed to do what he or she
  17506. has attempted. For example, `\.{\\moveleft}' is allowed only in vertical mode,
  17507. and `\.{\\lower}' only in non-vertical modes.  Such cases are enumerated
  17508. here and in the other sections referred to under `See also \dots.'
  17509. @<Forbidden cases...@>=
  17510. vmode+vmove,hmode+hmove,mmode+hmove,any_mode(last_item),
  17511. @ The `|you_cant|' procedure prints a line saying that the current command
  17512. is illegal in the current mode; it identifies these things symbolically.
  17513. @<Declare action...@>=
  17514. procedure you_cant;
  17515. begin print_err("You can't use `");
  17516. @.You can't use x in y mode@>
  17517. print_cmd_chr(cur_cmd,cur_chr);
  17518. print("' in "); print_mode(mode);
  17519. @ @<Declare act...@>=
  17520. procedure report_illegal_case;
  17521. begin you_cant;
  17522. help4("Sorry, but I'm not programmed to handle this case;")@/
  17523. ("I'll just pretend that you didn't ask for it.")@/
  17524. ("If you're in the wrong mode, you might be able to")@/
  17525. ("return to the right one by typing `I}' or `I$' or `I\par'.");@/
  17526. error;
  17527. @ Some operations are allowed only in privileged modes, i.e., in cases
  17528. that |mode>0|. The |privileged| function is used to detect violations
  17529. of this rule; it issues an error message and returns |false| if the
  17530. current |mode| is negative.
  17531. @<Declare act...@>=
  17532. function privileged:boolean;
  17533. begin if mode>0 then privileged:=true
  17534. else  begin report_illegal_case; privileged:=false;
  17535.   end;
  17536. @ Either \.{\\dump} or \.{\\end} will cause |main_control| to enter the
  17537. endgame, since both of them have `|stop|' as their command code.
  17538. @<Put each...@>=
  17539. primitive("end",stop,0);@/
  17540. @!@:end_}{\.{\\end} primitive@>
  17541. primitive("dump",stop,1);@/
  17542. @!@:dump_}{\.{\\dump} primitive@>
  17543. @ @<Cases of |print_cmd_chr|...@>=
  17544. stop:if chr_code=1 then print_esc("dump")@+else print_esc("end");
  17545. @ We don't want to leave |main_control| immediately when a |stop| command
  17546. is sensed, because it may be necessary to invoke an \.{\\output} routine
  17547. several times before things really grind to a halt. (The output routine
  17548. might even say `\.{\\gdef\\end\{...\}}', to prolong the life of the job.)
  17549. Therefore |its_all_over| is |true| only when the current page
  17550. and contribution list are empty, and when the last output was not a
  17551. ``dead cycle.''
  17552. @<Declare act...@>=
  17553. function its_all_over:boolean; {do this when \.{\\end} or \.{\\dump} occurs}
  17554. label exit;
  17555. begin if privileged then
  17556.   begin if (page_head=page_tail)and(head=tail)and(dead_cycles=0) then
  17557.     begin its_all_over:=true; return;
  17558.     end;
  17559.   back_input; {we will try to end again after ejecting residual material}
  17560.   tail_append(new_null_box);
  17561.   width(tail):=hsize;
  17562.   tail_append(new_glue(fill_glue));
  17563.   tail_append(new_penalty(-@'10000000000));@/
  17564.   build_page; {append \.{\\hbox to \\hsize\{\}\\vfill\\penalty-'10000000000}}
  17565.   end;
  17566. its_all_over:=false;
  17567. exit:end;
  17568. @* \[47] Building boxes and lists.
  17569. The most important parts of |main_control| are concerned with \TeX's
  17570. chief mission of box-making. We need to control the activities that put
  17571. entries on vlists and hlists, as well as the activities that convert
  17572. those lists into boxes. All of the necessary machinery has already been
  17573. developed; it remains for us to ``push the buttons'' at the right times.
  17574. @ As an introduction to these routines, let's consider one of the simplest
  17575. cases: What happens when `\.{\\hrule}' occurs in vertical mode, or
  17576. `\.{\\vrule}' in horizontal mode or math mode? The code in |main_control|
  17577. is short, since the |scan_rule_spec| routine already does most of what is
  17578. required; thus, there is no need for a special action procedure.
  17579. Note that baselineskip calculations are disabled after a rule in vertical
  17580. mode, by setting |prev_depth:=ignore_depth|.
  17581. @<Cases of |main_control| that build...@>=
  17582. vmode+hrule,hmode+vrule,mmode+vrule: begin tail_append(scan_rule_spec);
  17583.   if abs(mode)=vmode then prev_depth:=ignore_depth
  17584.   else if abs(mode)=hmode then space_factor:=1000;
  17585.   end;
  17586. @ The processing of things like \.{\\hskip} and \.{\\vskip} is slightly
  17587. more complicated. But the code in |main_control| is very short, since
  17588. it simply calls on the action routine |append_glue|. Similarly, \.{\\kern}
  17589. activates |append_kern|.
  17590. @<Cases of |main_control| that build...@>=
  17591. vmode+vskip,hmode+hskip,mmode+hskip,mmode+mskip: append_glue;
  17592. any_mode(kern),mmode+mkern: append_kern;
  17593. @ The |hskip| and |vskip| command codes are used for control sequences
  17594. like \.{\\hss} and \.{\\vfil} as well as for \.{\\hskip} and \.{\\vskip}.
  17595. The difference is in the value of |cur_chr|.
  17596. @d fil_code=0 {identifies \.{\\hfil} and \.{\\vfil}}
  17597. @d fill_code=1 {identifies \.{\\hfill} and \.{\\vfill}}
  17598. @d ss_code=2 {identifies \.{\\hss} and \.{\\vss}}
  17599. @d fil_neg_code=3 {identifies \.{\\hfilneg} and \.{\\vfilneg}}
  17600. @d skip_code=4 {identifies \.{\\hskip} and \.{\\vskip}}
  17601. @d mskip_code=5 {identifies \.{\\mskip}}
  17602. @<Put each...@>=
  17603. primitive("hskip",hskip,skip_code);@/
  17604. @!@:hskip_}{\.{\\hskip} primitive@>
  17605. primitive("hfil",hskip,fil_code);
  17606. @!@:hfil_}{\.{\\hfil} primitive@>
  17607. primitive("hfill",hskip,fill_code);@/
  17608. @!@:hfill_}{\.{\\hfill} primitive@>
  17609. primitive("hss",hskip,ss_code);
  17610. @!@:hss_}{\.{\\hss} primitive@>
  17611. primitive("hfilneg",hskip,fil_neg_code);@/
  17612. @!@:hfil_neg_}{\.{\\hfilneg} primitive@>
  17613. primitive("vskip",vskip,skip_code);@/
  17614. @!@:vskip_}{\.{\\vskip} primitive@>
  17615. primitive("vfil",vskip,fil_code);
  17616. @!@:vfil_}{\.{\\vfil} primitive@>
  17617. primitive("vfill",vskip,fill_code);@/
  17618. @!@:vfill_}{\.{\\vfill} primitive@>
  17619. primitive("vss",vskip,ss_code);
  17620. @!@:vss_}{\.{\\vss} primitive@>
  17621. primitive("vfilneg",vskip,fil_neg_code);@/
  17622. @!@:vfil_neg_}{\.{\\vfilneg} primitive@>
  17623. primitive("mskip",mskip,mskip_code);@/
  17624. @!@:mskip_}{\.{\\mskip} primitive@>
  17625. primitive("kern",kern,explicit);
  17626. @!@:kern_}{\.{\\kern} primitive@>
  17627. primitive("mkern",mkern,mu_glue);@/
  17628. @!@:mkern_}{\.{\\mkern} primitive@>
  17629. @ @<Cases of |print_cmd_chr|...@>=
  17630. hskip: case chr_code of
  17631.   skip_code:print_esc("hskip");
  17632.   fil_code:print_esc("hfil");
  17633.   fill_code:print_esc("hfill");
  17634.   ss_code:print_esc("hss");
  17635.   othercases print_esc("hfilneg")
  17636.   endcases;
  17637. vskip: case chr_code of
  17638.   skip_code:print_esc("vskip");
  17639.   fil_code:print_esc("vfil");
  17640.   fill_code:print_esc("vfill");
  17641.   ss_code:print_esc("vss");
  17642.   othercases print_esc("vfilneg")
  17643.   endcases;
  17644. mskip: print_esc("mskip");
  17645. kern: print_esc("kern");
  17646. mkern: print_esc("mkern");
  17647. @ All the work relating to glue creation has been relegated to the
  17648. following subroutine. It does not call |build_page|, because it is
  17649. used in at least one place where that would be a mistake.
  17650. @<Declare action...@>=
  17651. procedure append_glue;
  17652. var s:small_number; {modifier of skip command}
  17653. begin s:=cur_chr;
  17654. case s of
  17655. fil_code: cur_val:=fil_glue;
  17656. fill_code: cur_val:=fill_glue;
  17657. ss_code: cur_val:=ss_glue;
  17658. fil_neg_code: cur_val:=fil_neg_glue;
  17659. skip_code: scan_glue(glue_val);
  17660. mskip_code: scan_glue(mu_val);
  17661. end; {now |cur_val| points to the glue specification}
  17662. tail_append(new_glue(cur_val));
  17663. if s>=skip_code then
  17664.   begin decr(glue_ref_count(cur_val));
  17665.   if s>skip_code then subtype(tail):=mu_glue;
  17666.   end;
  17667. @ @<Declare act...@>=
  17668. procedure append_kern;
  17669. var s:quarterword; {|subtype| of the kern node}
  17670. begin s:=cur_chr; scan_dimen(s=mu_glue,false,false);
  17671. tail_append(new_kern(cur_val)); subtype(tail):=s;
  17672. @ Many of the actions related to box-making are triggered by the appearance
  17673. of braces in the input. For example, when the user says `\.{\\hbox}
  17674. \.{to} \.{100pt\{$\langle\,\hbox{hlist}\,\rangle$\}}' in vertical mode,
  17675. the information about the box size (100pt, |exactly|) is put onto |save_stack|
  17676. with a level boundary word just above it, and |cur_group:=adjusted_hbox_group|;
  17677. \TeX\ enters restricted horizontal mode to process the hlist. The right
  17678. brace eventually causes |save_stack| to be restored to its former state,
  17679. at which time the information about the box size (100pt, |exactly|) is
  17680. available once again; a box is packaged and we leave restricted horizontal
  17681. mode, appending the new box to the current list of the enclosing mode
  17682. (in this case to the current list of vertical mode), followed by any
  17683. vertical adjustments that were removed from the box by |hpack|.
  17684. The next few sections of the program are therefore concerned with the
  17685. treatment of left and right curly braces.
  17686. @ If a left brace occurs in the middle of a page or paragraph, it simply
  17687. introduces a new level of grouping, and the matching right brace will not have
  17688. such a drastic effect. Such grouping affects neither the mode nor the
  17689. current list.
  17690. @<Cases of |main_control| that build...@>=
  17691. non_math(left_brace): new_save_level(simple_group);
  17692. any_mode(begin_group): new_save_level(semi_simple_group);
  17693. any_mode(end_group): if cur_group=semi_simple_group then unsave
  17694.   else off_save;
  17695. @ We have to deal with errors in which braces and such things are not
  17696. properly nested. Sometimes the user makes an error of commission by
  17697. inserting an extra symbol, but sometimes the user makes an error of omission.
  17698. \TeX\ can't always tell one from the other, so it makes a guess and tries
  17699. to avoid getting into a loop.
  17700. The |off_save| routine is called when the current group code is wrong. It tries
  17701. to insert something into the user's input that will help clean off
  17702. the top level.
  17703. @<Declare act...@>=
  17704. procedure off_save;
  17705. var p:pointer; {inserted token}
  17706. begin if cur_group=bottom_level then
  17707.   @<Drop current token and complain that it was unmatched@>
  17708. else  begin back_input; p:=get_avail; link(temp_head):=p;
  17709.   print_err("Missing ");
  17710.   @<Prepare to insert a token that matches |cur_group|,
  17711.     and print what it is@>;
  17712.   print(" inserted"); ins_list(link(temp_head));
  17713.   help5("I've inserted something that you may have forgotten.")@/
  17714.   ("(See the <inserted text> above.)")@/
  17715.   ("With luck, this will get me unwedged. But if you")@/
  17716.   ("really didn't forget anything, try typing `2' now; then")@/
  17717.   ("my insertion and my current dilemma will both disappear.");
  17718.   error;
  17719.   end;
  17720. @ At this point, |link(temp_head)=p|, a pointer to an empty one-word node.
  17721. @<Prepare to insert a token that matches |cur_group|...@>=
  17722. case cur_group of
  17723. semi_simple_group: begin info(p):=cs_token_flag+frozen_end_group;
  17724.   print_esc("endgroup");
  17725. @.Missing \\endgroup inserted@>
  17726.   end;
  17727. math_shift_group: begin info(p):=math_shift_token+"$"; print_char("$");
  17728. @.Missing \$ inserted@>
  17729.   end;
  17730. math_left_group: begin info(p):=cs_token_flag+frozen_right; link(p):=get_avail;
  17731.   p:=link(p); info(p):=other_token+"."; print_esc("right.");
  17732. @.Missing \\right\hbox{.} inserted@>
  17733. @^null delimiter@>
  17734.   end;
  17735. othercases begin info(p):=right_brace_token+"}"; print_char("}");
  17736. @.Missing \} inserted@>
  17737.   end
  17738. endcases
  17739. @ @<Drop current token and complain that it was unmatched@>=
  17740. begin print_err("Extra "); print_cmd_chr(cur_cmd,cur_chr);
  17741. @.Extra x@>
  17742. help1("Things are pretty mixed up, but I think the worst is over.");@/
  17743. error;
  17744. @ The routine for a |right_brace| character branches into many subcases,
  17745. since a variety of things may happen, depending on |cur_group|. Some
  17746. types of groups are not supposed to be ended by a right brace; error
  17747. messages are given in hopes of pinpointing the problem. Most branches
  17748. of this routine will be filled in later, when we are ready to understand
  17749. them; meanwhile, we must prepare ourselves to deal with such errors.
  17750. @<Cases of |main_control| that build...@>=
  17751. any_mode(right_brace): handle_right_brace;
  17752. @ @<Declare the procedure called |handle_right_brace|@>=
  17753. procedure handle_right_brace;
  17754. var p,@!q:pointer; {for short-term use}
  17755. @!d:scaled; {holds |split_max_depth| in |insert_group|}
  17756. @!f:integer; {holds |floating_penalty| in |insert_group|}
  17757. begin case cur_group of
  17758. simple_group: unsave;
  17759. bottom_level: begin print_err("Too many }'s");
  17760. @.Too many \}'s@>
  17761.   help2("You've closed more groups than you opened.")@/
  17762.   ("Such booboos are generally harmless, so keep going."); error;
  17763.   end;
  17764. semi_simple_group,math_shift_group,math_left_group: extra_right_brace;
  17765. @t\4@>@<Cases of |handle_right_brace| where a |right_brace| triggers
  17766.   a delayed action@>@;
  17767. othercases confusion("rightbrace")
  17768. @:this can't happen rightbrace}{\quad rightbrace@>
  17769. endcases;
  17770. @ @<Declare act...@>=
  17771. procedure extra_right_brace;
  17772. begin print_err("Extra }, or forgotten ");
  17773. @.Extra \}, or forgotten x@>
  17774. case cur_group of
  17775. semi_simple_group: print_esc("endgroup");
  17776. math_shift_group: print_char("$");
  17777. math_left_group: print_esc("right");
  17778. end;@/
  17779. help5("I've deleted a group-closing symbol because it seems to be")@/
  17780. ("spurious, as in `$x}$'. But perhaps the } is legitimate and")@/
  17781. ("you forgot something else, as in `\hbox{$x}'. In such cases")@/
  17782. ("the way to recover is to insert both the forgotten and the")@/
  17783. ("deleted material, e.g., by typing `I$}'."); error;
  17784. incr(align_state);
  17785. @ Here is where we clear the parameters that are supposed to revert to their
  17786. default values after every paragraph and when internal vertical mode is entered.
  17787. @<Declare act...@>=
  17788. procedure normal_paragraph;
  17789. begin if looseness<>0 then eq_word_define(int_base+looseness_code,0);
  17790. if hang_indent<>0 then eq_word_define(dimen_base+hang_indent_code,0);
  17791. if hang_after<>1 then eq_word_define(int_base+hang_after_code,1);
  17792. if par_shape_ptr<>null then eq_define(par_shape_loc,shape_ref,null);
  17793. @ Now let's turn to the question of how \.{\\hbox} is treated. We actually
  17794. need to consider also a slightly larger context, since constructions like
  17795. `\.{\\setbox3=}\penalty0\.{\\hbox...}' and
  17796. `\.{\\leaders}\penalty0\.{\\hbox...}' and
  17797. `\.{\\lower3.8pt\\hbox...}'
  17798. are supposed to invoke quite
  17799. different actions after the box has been packaged. Conversely,
  17800. constructions like `\.{\\setbox3=}' can be followed by a variety of
  17801. different kinds of boxes, and we would like to encode such things in an
  17802. efficient way.
  17803. In other words, there are two problems: To represent the context of a box,
  17804. and to represent its type.
  17805. The first problem is solved by putting a ``context code'' on the |save_stack|,
  17806. just below the two entries that give the dimensions produced by |scan_spec|.
  17807. The context code is either a (signed) shift amount, or it is a large
  17808. integer |>=box_flag|, where |box_flag=@t$2^{30}$@>|. Codes |box_flag| through
  17809. |box_flag+255| represent `\.{\\setbox0}' through `\.{\\setbox255}';
  17810. codes |box_flag+256| through |box_flag+511| represent `\.{\\global\\setbox0}'
  17811. through `\.{\\global\\setbox255}';
  17812. code |box_flag+512| represents `\.{\\shipout}'; and codes |box_flag+513|
  17813. through |box_flag+515| represent `\.{\\leaders}', `\.{\\cleaders}',
  17814. and `\.{\\xleaders}'.
  17815. The second problem is solved by giving the command code |make_box| to all
  17816. control sequences that produce a box, and by using the following |chr_code|
  17817. values to distinguish between them: |box_code|, |copy_code|, |last_box_code|,
  17818. |vsplit_code|, |vtop_code|, |vtop_code+vmode|, and |vtop_code+hmode|,
  17819. where the latter two are used denote \.{\\vbox} and \.{\\hbox}, respectively.
  17820. @d box_flag==@'10000000000 {context code for `\.{\\setbox0}'}
  17821. @d ship_out_flag==box_flag+512 {context code for `\.{\\shipout}'}
  17822. @d leader_flag==box_flag+513 {context code for `\.{\\leaders}'}
  17823. @d box_code=0 {|chr_code| for `\.{\\box}'}
  17824. @d copy_code=1 {|chr_code| for `\.{\\copy}'}
  17825. @d last_box_code=2 {|chr_code| for `\.{\\lastbox}'}
  17826. @d vsplit_code=3 {|chr_code| for `\.{\\vsplit}'}
  17827. @d vtop_code=4 {|chr_code| for `\.{\\vtop}'}
  17828. @<Put each...@>=
  17829. primitive("moveleft",hmove,1);
  17830. @!@:move_left_}{\.{\\moveleft} primitive@>
  17831. primitive("moveright",hmove,0);@/
  17832. @!@:move_right_}{\.{\\moveright} primitive@>
  17833. primitive("raise",vmove,1);
  17834. @!@:raise_}{\.{\\raise} primitive@>
  17835. primitive("lower",vmove,0);
  17836. @!@:lower_}{\.{\\lower} primitive@>
  17837. primitive("box",make_box,box_code);
  17838. @!@:box_}{\.{\\box} primitive@>
  17839. primitive("copy",make_box,copy_code);
  17840. @!@:copy_}{\.{\\copy} primitive@>
  17841. primitive("lastbox",make_box,last_box_code);
  17842. @!@:last_box_}{\.{\\lastbox} primitive@>
  17843. primitive("vsplit",make_box,vsplit_code);
  17844. @!@:vsplit_}{\.{\\vsplit} primitive@>
  17845. primitive("vtop",make_box,vtop_code);@/
  17846. @!@:vtop_}{\.{\\vtop} primitive@>
  17847. primitive("vbox",make_box,vtop_code+vmode);
  17848. @!@:vbox_}{\.{\\vbox} primitive@>
  17849. primitive("hbox",make_box,vtop_code+hmode);@/
  17850. @!@:hbox_}{\.{\\hbox} primitive@>
  17851. primitive("shipout",leader_ship,a_leaders-1); {|ship_out_flag=leader_flag-1|}
  17852. @!@:ship_out_}{\.{\\shipout} primitive@>
  17853. primitive("leaders",leader_ship,a_leaders);
  17854. @!@:leaders_}{\.{\\leaders} primitive@>
  17855. primitive("cleaders",leader_ship,c_leaders);
  17856. @!@:c_leaders_}{\.{\\cleaders} primitive@>
  17857. primitive("xleaders",leader_ship,x_leaders);
  17858. @!@:x_leaders_}{\.{\\xleaders} primitive@>
  17859. @ @<Cases of |print_cmd_chr|...@>=
  17860. hmove: if chr_code=1 then print_esc("moveleft")@+else print_esc("moveright");
  17861. vmove: if chr_code=1 then print_esc("raise")@+else print_esc("lower");
  17862. make_box: case chr_code of
  17863.   box_code: print_esc("box");
  17864.   copy_code: print_esc("copy");
  17865.   last_box_code: print_esc("lastbox");
  17866.   vsplit_code: print_esc("vsplit");
  17867.   vtop_code: print_esc("vtop");
  17868.   vtop_code+vmode: print_esc("vbox");
  17869.   othercases print_esc("hbox")
  17870.   endcases;
  17871. leader_ship: if chr_code=a_leaders then print_esc("leaders")
  17872.   else if chr_code=c_leaders then print_esc("cleaders")
  17873.   else if chr_code=x_leaders then print_esc("xleaders")
  17874.   else print_esc("shipout");
  17875. @ Constructions that require a box are started by calling |scan_box| with
  17876. a specified context code. The |scan_box| routine verifies
  17877. that a |make_box| command comes next and then it calls |begin_box|.
  17878. @<Cases of |main_control| that build...@>=
  17879. vmode+hmove,hmode+vmove,mmode+vmove: begin t:=cur_chr;
  17880.   scan_normal_dimen;
  17881.   if t=0 then scan_box(cur_val)@+else scan_box(-cur_val);
  17882.   end;
  17883. any_mode(leader_ship): scan_box(leader_flag-a_leaders+cur_chr);
  17884. any_mode(make_box): begin_box(0);
  17885. @ The global variable |cur_box| will point to a newly-made box. If the box
  17886. is void, we will have |cur_box=null|. Otherwise we will have
  17887. |type(cur_box)=hlist_node| or |vlist_node| or |rule_node|; the |rule_node|
  17888. case can occur only with leaders.
  17889. @<Glob...@>=
  17890. @!cur_box:pointer; {box to be placed into its context}
  17891. @ The |box_end| procedure does the right thing with |cur_box|, if
  17892. |box_context| represents the context as explained above.
  17893. @<Declare act...@>=
  17894. procedure box_end(@!box_context:integer);
  17895. var p:pointer; {|ord_noad| for new box in math mode}
  17896. begin if box_context<box_flag then @<Append box |cur_box| to the current list,
  17897.     shifted by |box_context|@>
  17898. else if box_context<ship_out_flag then @<Store \(c)|cur_box| in a box register@>
  17899. else if cur_box<>null then
  17900.   if box_context>ship_out_flag then @<Append a new leader node that
  17901.       uses |cur_box|@>
  17902.   else ship_out(cur_box);
  17903. @ The global variable |adjust_tail| will be non-null if and only if the
  17904. current box might include adjustments that should be appended to the
  17905. current vertical list.
  17906. @<Append box |cur_box| to the current...@>=
  17907. begin if cur_box<>null then
  17908.   begin shift_amount(cur_box):=box_context;
  17909.   if abs(mode)=vmode then
  17910.     begin append_to_vlist(cur_box);
  17911.     if adjust_tail<>null then
  17912.       begin if adjust_head<>adjust_tail then
  17913.         begin link(tail):=link(adjust_head); tail:=adjust_tail;
  17914.         end;
  17915.       adjust_tail:=null;
  17916.       end;
  17917.     if mode>0 then build_page;
  17918.     end
  17919.   else  begin if abs(mode)=hmode then space_factor:=1000
  17920.     else  begin p:=new_noad;
  17921.       math_type(nucleus(p)):=sub_box;
  17922.       info(nucleus(p)):=cur_box; cur_box:=p;
  17923.       end;
  17924.     link(tail):=cur_box; tail:=cur_box;
  17925.     end;
  17926.   end;
  17927. @ @<Store \(c)|cur_box| in a box register@>=
  17928. if box_context<box_flag+256 then
  17929.   eq_define(box_base-box_flag+box_context,box_ref,cur_box)
  17930. else geq_define(box_base-box_flag-256+box_context,box_ref,cur_box)
  17931. @ @<Append a new leader node ...@>=
  17932. begin @<Get the next non-blank non-relax...@>;
  17933. if ((cur_cmd=hskip)and(abs(mode)<>vmode))or@|
  17934.    ((cur_cmd=vskip)and(abs(mode)=vmode))or@|
  17935.    ((cur_cmd=mskip)and(abs(mode)=mmode)) then
  17936.   begin append_glue; subtype(tail):=box_context-(leader_flag-a_leaders);
  17937.   leader_ptr(tail):=cur_box;
  17938.   end
  17939. else  begin print_err("Leaders not followed by proper glue");
  17940. @.Leaders not followed by...@>
  17941.   help3("You should say `\leaders <box or rule><hskip or vskip>'.")@/
  17942.   ("I found the <box or rule>, but there's no suitable")@/
  17943.   ("<hskip or vskip>, so I'm ignoring these leaders."); back_error;
  17944.   flush_node_list(cur_box);
  17945.   end;
  17946. @ Now that we can see what eventually happens to boxes, we can consider
  17947. the first steps in their creation. The |begin_box| routine is called when
  17948. |box_context| is a context specification, |cur_chr| specifies the type of
  17949. box desired, and |cur_cmd=make_box|.
  17950. @<Declare act...@>=
  17951. procedure begin_box(@!box_context:integer);
  17952. label exit, done;
  17953. var @!p,@!q:pointer; {run through the current list}
  17954. @!m:quarterword; {the length of a replacement list}
  17955. @!k:halfword; {0 or |vmode| or |hmode|}
  17956. @!n:eight_bits; {a box number}
  17957. begin case cur_chr of
  17958. box_code: begin scan_eight_bit_int; cur_box:=box(cur_val);
  17959.   box(cur_val):=null; {the box becomes void, at the same level}
  17960.   end;
  17961. copy_code: begin scan_eight_bit_int; cur_box:=copy_node_list(box(cur_val));
  17962.   end;
  17963. last_box_code: @<If the current list ends with a box node, delete it from
  17964.   the list and make |cur_box| point to it; otherwise set |cur_box:=null|@>;
  17965. vsplit_code: @<Split off part of a vertical box, make |cur_box| point to it@>;
  17966. othercases @<Initiate the construction of an hbox or vbox, then |return|@>
  17967. endcases;@/
  17968. box_end(box_context); {in simple cases, we use the box immediately}
  17969. exit:end;
  17970. @ Note that the condition |not is_char_node(tail)| implies that |head<>tail|,
  17971. since |head| is a one-word node.
  17972. @<If the current list ends with a box node, delete it...@>=
  17973. begin cur_box:=null;
  17974. if abs(mode)=mmode then
  17975.   begin you_cant; help1("Sorry; this \lastbox will be void."); error;
  17976.   end
  17977. else if (mode=vmode)and(head=tail) then
  17978.   begin you_cant;
  17979.   help2("Sorry...I usually can't take things from the current page.")@/
  17980.     ("This \lastbox will therefore be void."); error;
  17981.   end
  17982. else  begin if not is_char_node(tail) then
  17983.     if (type(tail)=hlist_node)or(type(tail)=vlist_node) then
  17984.       @<Remove the last box, unless it's part of a discretionary@>;
  17985.   end;
  17986. @ @<Remove the last box...@>=
  17987. begin q:=head;
  17988. repeat p:=q;
  17989. if not is_char_node(q) then if type(q)=disc_node then
  17990.   begin for m:=1 to replace_count(q) do p:=link(p);
  17991.   if p=tail then goto done;
  17992.   end;
  17993. q:=link(p);
  17994. until q=tail;
  17995. cur_box:=tail; shift_amount(cur_box):=0;
  17996. tail:=p; link(p):=null;
  17997. done:end
  17998. @ Here we deal with things like `\.{\\vsplit 13 to 100pt}'.
  17999. @<Split off part of a vertical box, make |cur_box| point to it@>=
  18000. begin scan_eight_bit_int; n:=cur_val;
  18001. if not scan_keyword("to") then
  18002. @.to@>
  18003.   begin print_err("Missing `to' inserted");
  18004. @.Missing `to' inserted@>
  18005.   help2("I'm working on `\vsplit<box number> to <dimen>';")@/
  18006.   ("will look for the <dimen> next."); error;
  18007.   end;
  18008. scan_normal_dimen;
  18009. cur_box:=vsplit(n,cur_val);
  18010. @ Here is where we enter restricted horizontal mode or internal vertical
  18011. mode, in order to make a box.
  18012. @<Initiate the construction of an hbox or vbox, then |return|@>=
  18013. begin k:=cur_chr-vtop_code; saved(0):=box_context;
  18014. if k=hmode then
  18015.   if (box_context<box_flag)and(abs(mode)=vmode) then
  18016.     scan_spec(adjusted_hbox_group,true)
  18017.   else scan_spec(hbox_group,true)
  18018. else  begin if k=vmode then scan_spec(vbox_group,true)
  18019.   else  begin scan_spec(vtop_group,true); k:=vmode;
  18020.     end;
  18021.   normal_paragraph;
  18022.   end;
  18023. push_nest; mode:=-k;
  18024. if k=vmode then
  18025.   begin prev_depth:=ignore_depth;
  18026.   if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
  18027.   end
  18028. else  begin space_factor:=1000;
  18029.   if every_hbox<>null then begin_token_list(every_hbox,every_hbox_text);
  18030.   end;
  18031. return;
  18032. @ @<Declare act...@>=
  18033. procedure scan_box(@!box_context:integer);
  18034.   {the next input should specify a box or perhaps a rule}
  18035. begin @<Get the next non-blank non-relax...@>;
  18036. if cur_cmd=make_box then begin_box(box_context)
  18037. else if (box_context>=leader_flag)and((cur_cmd=hrule)or(cur_cmd=vrule)) then
  18038.   begin cur_box:=scan_rule_spec; box_end(box_context);
  18039.   end
  18040. else  begin@t@>@;@/
  18041.   print_err("A <box> was supposed to be here");@/
  18042. @.A <box> was supposed to...@>
  18043.   help3("I was expecting to see \hbox or \vbox or \copy or \box or")@/
  18044.   ("something like that. So you might find something missing in")@/
  18045.   ("your output. But keep trying; you can fix this later."); back_error;
  18046.   end;
  18047. @ When the right brace occurs at the end of an \.{\\hbox} or \.{\\vbox} or
  18048. \.{\\vtop} construction, the |package| routine comes into action. We might
  18049. also have to finish a paragraph that hasn't ended.
  18050. @<Cases of |handle...@>=
  18051. hbox_group: package(0);
  18052. adjusted_hbox_group: begin adjust_tail:=adjust_head; package(0);
  18053.   end;
  18054. vbox_group: begin end_graf; package(0);
  18055.   end;
  18056. vtop_group: begin end_graf; package(vtop_code);
  18057.   end;
  18058. @ @<Declare action...@>=
  18059. procedure package(@!c:small_number);
  18060. var h:scaled; {height of box}
  18061. @!p:pointer; {first node in a box}
  18062. @!d:scaled; {max depth}
  18063. begin d:=box_max_depth; unsave; save_ptr:=save_ptr-3;
  18064. if mode=-hmode then cur_box:=hpack(link(head),saved(2),saved(1))
  18065. else  begin cur_box:=vpackage(link(head),saved(2),saved(1),d);
  18066.   if c=vtop_code then @<Readjust the height and depth of |cur_box|,
  18067.     for \.{\\vtop}@>;
  18068.   end;
  18069. pop_nest; box_end(saved(0));
  18070. @ The height of a `\.{\\vtop}' box is inherited from the first item on its list,
  18071. if that item is an |hlist_node|, |vlist_node|, or |rule_node|; otherwise
  18072. the \.{\\vtop} height is zero.
  18073. @<Readjust the height...@>=
  18074. begin h:=0; p:=list_ptr(cur_box);
  18075. if p<>null then if type(p)<=rule_node then h:=height(p);
  18076. depth(cur_box):=depth(cur_box)-h+height(cur_box); height(cur_box):=h;
  18077. @ A paragraph begins when horizontal-mode material occurs in vertical mode,
  18078. or when the paragraph is explicitly started by `\.{\\indent}' or
  18079. `\.{\\noindent}'.
  18080. @<Put each...@>=
  18081. primitive("indent",start_par,1);
  18082. @!@:indent_}{\.{\\indent} primitive@>
  18083. primitive("noindent",start_par,0);
  18084. @!@:no_indent_}{\.{\\noindent} primitive@>
  18085. @ @<Cases of |print_cmd_chr|...@>=
  18086. start_par: if chr_code=0 then print_esc("noindent")@+ else print_esc("indent");
  18087. @ @<Cases of |main_control| that build...@>=
  18088. vmode+start_par: new_graf(cur_chr>0);
  18089. vmode+letter,vmode+other_char,vmode+char_num,vmode+char_given,
  18090.    vmode+math_shift,vmode+un_hbox,vmode+vrule,
  18091.    vmode+accent,vmode+discretionary,vmode+hskip,vmode+valign,
  18092.    vmode+ex_space,vmode+no_boundary:@t@>@;@/
  18093.   begin back_input; new_graf(true);
  18094.   end;
  18095. @ @<Declare act...@>=
  18096. function norm_min(@!h:integer):small_number;
  18097. begin if h<=0 then norm_min:=1@+else if h>=63 then norm_min:=63@+
  18098. else norm_min:=h;
  18099. procedure new_graf(@!indented:boolean);
  18100. begin prev_graf:=0;
  18101. if (mode=vmode)or(head<>tail) then
  18102.   tail_append(new_param_glue(par_skip_code));
  18103. push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
  18104. prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
  18105.              *@'200000+cur_lang;
  18106. if indented then
  18107.   begin tail:=new_null_box; link(head):=tail; width(tail):=par_indent;@+
  18108.   end;
  18109. if every_par<>null then begin_token_list(every_par,every_par_text);
  18110. if nest_ptr=1 then build_page; {put |par_skip| glue on current page}
  18111. @ @<Cases of |main_control| that build...@>=
  18112. hmode+start_par,mmode+start_par: indent_in_hmode;
  18113. @ @<Declare act...@>=
  18114. procedure indent_in_hmode;
  18115. var p,@!q:pointer;
  18116. begin if cur_chr>0 then {\.{\\indent}}
  18117.   begin p:=new_null_box; width(p):=par_indent;
  18118.   if abs(mode)=hmode then space_factor:=1000
  18119.   else  begin q:=new_noad; math_type(nucleus(q)):=sub_box;
  18120.     info(nucleus(q)):=p; p:=q;
  18121.     end;
  18122.   tail_append(p);
  18123.   end;
  18124. @ A paragraph ends when a |par_end| command is sensed, or when we are in
  18125. horizontal mode when reaching the right brace of vertical-mode routines
  18126. like \.{\\vbox}, \.{\\insert}, or \.{\\output}.
  18127. @<Cases of |main_control| that build...@>=
  18128. vmode+par_end: begin normal_paragraph;
  18129.   if mode>0 then build_page;
  18130.   end;
  18131. hmode+par_end: begin if align_state<0 then off_save; {this tries to
  18132.     recover from an alignment that didn't end properly}
  18133.   end_graf; {this takes us to the enclosing mode, if |mode>0|}
  18134.   if mode=vmode then build_page;
  18135.   end;
  18136. hmode+stop,hmode+vskip,hmode+hrule,hmode+un_vbox,hmode+halign: head_for_vmode;
  18137. @ @<Declare act...@>=
  18138. procedure head_for_vmode;
  18139. begin if mode<0 then
  18140.   if cur_cmd<>hrule then off_save
  18141.   else  begin print_err("You can't use `");
  18142.     print_esc("hrule"); print("' here except with leaders");
  18143. @.You can't use \\hrule...@>
  18144.     help2("To put a horizontal rule in an hbox or an alignment,")@/
  18145.       ("you should use \leaders or \hrulefill (see The TeXbook).");
  18146.     error;
  18147.     end
  18148. else  begin back_input; cur_tok:=par_token; back_input; token_type:=inserted;
  18149.   end;
  18150. @ @<Declare act...@>=
  18151. procedure end_graf;
  18152. begin if mode=hmode then
  18153.   begin if head=tail then pop_nest {null paragraphs are ignored}
  18154.   else line_break(widow_penalty);
  18155.   normal_paragraph;
  18156.   error_count:=0;
  18157.   end;
  18158. @ Insertion and adjustment and mark nodes are constructed by the following
  18159. pieces of the program.
  18160. @<Cases of |main_control| that build...@>=
  18161. any_mode(insert),hmode+vadjust,mmode+vadjust: begin_insert_or_adjust;
  18162. any_mode(mark): make_mark;
  18163. @ @<Forbidden...@>=
  18164. vmode+vadjust,
  18165. @ @<Declare act...@>=
  18166. procedure begin_insert_or_adjust;
  18167. begin if cur_cmd=vadjust then cur_val:=255
  18168. else  begin scan_eight_bit_int;
  18169.   if cur_val=255 then
  18170.     begin print_err("You can't "); print_esc("insert"); print_int(255);
  18171. @.You can't \\insert255@>
  18172.     help1("I'm changing to \insert0; box 255 is special.");
  18173.     error; cur_val:=0;
  18174.     end;
  18175.   end;
  18176. saved(0):=cur_val; incr(save_ptr);
  18177. new_save_level(insert_group); scan_left_brace; normal_paragraph;
  18178. push_nest; mode:=-vmode; prev_depth:=ignore_depth;
  18179. @ @<Cases of |handle...@>=
  18180. insert_group: begin end_graf; q:=split_top_skip; add_glue_ref(q);
  18181.   d:=split_max_depth; f:=floating_penalty; unsave; decr(save_ptr);
  18182.   {now |saved(0)| is the insertion number, or 255 for |vadjust|}
  18183.   p:=vpack(link(head),natural); pop_nest;
  18184.   if saved(0)<255 then
  18185.     begin tail_append(get_node(ins_node_size));
  18186.     type(tail):=ins_node; subtype(tail):=qi(saved(0));
  18187.     height(tail):=height(p)+depth(p); ins_ptr(tail):=list_ptr(p);
  18188.     split_top_ptr(tail):=q; depth(tail):=d; float_cost(tail):=f;
  18189.     end
  18190.   else  begin tail_append(get_node(small_node_size));
  18191.     type(tail):=adjust_node;@/
  18192.     subtype(tail):=0; {the |subtype| is not used}
  18193.     adjust_ptr(tail):=list_ptr(p); delete_glue_ref(q);
  18194.     end;
  18195.   free_node(p,box_node_size);
  18196.   if nest_ptr=0 then build_page;
  18197.   end;
  18198. output_group: @<Resume the page builder...@>;
  18199. @ @<Declare act...@>=
  18200. procedure make_mark;
  18201. var p:pointer; {new node}
  18202. begin p:=scan_toks(false,true); p:=get_node(small_node_size);
  18203. type(p):=mark_node; subtype(p):=0; {the |subtype| is not used}
  18204. mark_ptr(p):=def_ref; link(tail):=p; tail:=p;
  18205. @ Penalty nodes get into a list via the |break_penalty| command.
  18206. @^penalties@>
  18207. @<Cases of |main_control| that build...@>=
  18208. any_mode(break_penalty): append_penalty;
  18209. @ @<Declare action...@>=
  18210. procedure append_penalty;
  18211. begin scan_int; tail_append(new_penalty(cur_val));
  18212. if mode=vmode then build_page;
  18213. @ The |remove_item| command removes a penalty, kern, or glue node if it
  18214. appears at the tail of the current list, using a brute-force linear scan.
  18215. Like \.{\\lastbox}, this command is not allowed in vertical mode (except
  18216. internal vertical mode), since the current list in vertical mode is sent
  18217. to the page builder.  But if we happen to be able to implement it in
  18218. vertical mode, we do.
  18219. @<Cases of |main_control| that build...@>=
  18220. any_mode(remove_item): delete_last;
  18221. @ When |delete_last| is called, |cur_chr| is the |type| of node that
  18222. will be deleted, if present.
  18223. @<Declare action...@>=
  18224. procedure delete_last;
  18225. label exit;
  18226. var @!p,@!q:pointer; {run through the current list}
  18227. @!m:quarterword; {the length of a replacement list}
  18228. begin if (mode=vmode)and(tail=head) then
  18229.   @<Apologize for inability to do the operation now,
  18230.     unless \.{\\unskip} follows non-glue@>
  18231. else  begin if not is_char_node(tail) then if type(tail)=cur_chr then
  18232.     begin q:=head;
  18233.     repeat p:=q;
  18234.     if not is_char_node(q) then if type(q)=disc_node then
  18235.       begin for m:=1 to replace_count(q) do p:=link(p);
  18236.       if p=tail then return;
  18237.       end;
  18238.     q:=link(p);
  18239.     until q=tail;
  18240.     link(p):=null; flush_node_list(tail); tail:=p;
  18241.     end;
  18242.   end;
  18243. exit:end;
  18244. @ @<Apologize for inability to do the operation...@>=
  18245. begin if (cur_chr<>glue_node)or(last_glue<>max_halfword) then
  18246.   begin you_cant;
  18247.   help2("Sorry...I usually can't take things from the current page.")@/
  18248.     ("Try `I\vskip-\lastskip' instead.");
  18249.   if cur_chr=kern_node then help_line[0]:=
  18250.     ("Try `I\kern-\lastkern' instead.")
  18251.   else if cur_chr<>glue_node then help_line[0]:=@|
  18252.     ("Perhaps you can make the output routine do it.");
  18253.   error;
  18254.   end;
  18255. @ @<Put each...@>=
  18256. primitive("unpenalty",remove_item,penalty_node);@/
  18257. @!@:un_penalty_}{\.{\\unpenalty} primitive@>
  18258. primitive("unkern",remove_item,kern_node);@/
  18259. @!@:un_kern_}{\.{\\unkern} primitive@>
  18260. primitive("unskip",remove_item,glue_node);@/
  18261. @!@:un_skip_}{\.{\\unskip} primitive@>
  18262. primitive("unhbox",un_hbox,box_code);@/
  18263. @!@:un_hbox_}{\.{\\unhbox} primitive@>
  18264. primitive("unhcopy",un_hbox,copy_code);@/
  18265. @!@:un_hcopy_}{\.{\\unhcopy} primitive@>
  18266. primitive("unvbox",un_vbox,box_code);@/
  18267. @!@:un_vbox_}{\.{\\unvbox} primitive@>
  18268. primitive("unvcopy",un_vbox,copy_code);@/
  18269. @!@:un_vcopy_}{\.{\\unvcopy} primitive@>
  18270. @ @<Cases of |print_cmd_chr|...@>=
  18271. remove_item: if chr_code=glue_node then print_esc("unskip")
  18272.   else if chr_code=kern_node then print_esc("unkern")
  18273.   else print_esc("unpenalty");
  18274. un_hbox: if chr_code=copy_code then print_esc("unhcopy")
  18275.   else print_esc("unhbox");
  18276. un_vbox: if chr_code=copy_code then print_esc("unvcopy")
  18277.   else print_esc("unvbox");
  18278. @ The |un_hbox| and |un_vbox| commands unwrap one of the 256 current boxes.
  18279. @<Cases of |main_control| that build...@>=
  18280. vmode+un_vbox,hmode+un_hbox,mmode+un_hbox: unpackage;
  18281. @ @<Declare act...@>=
  18282. procedure unpackage;
  18283. label exit;
  18284. var p:pointer; {the box}
  18285. @!c:box_code..copy_code; {should we copy?}
  18286. begin c:=cur_chr; scan_eight_bit_int; p:=box(cur_val);
  18287. if p=null then return;
  18288. if (abs(mode)=mmode)or((abs(mode)=vmode)and(type(p)<>vlist_node))or@|
  18289.    ((abs(mode)=hmode)and(type(p)<>hlist_node)) then
  18290.   begin print_err("Incompatible list can't be unboxed");
  18291. @.Incompatible list...@>
  18292.   help3("Sorry, Pandora. (You sneaky devil.)")@/
  18293.   ("I refuse to unbox an \hbox in vertical mode or vice versa.")@/
  18294.   ("And I can't open any boxes in math mode.");@/
  18295.   error; return;
  18296.   end;
  18297. if c=copy_code then link(tail):=copy_node_list(list_ptr(p))
  18298. else  begin link(tail):=list_ptr(p); box(cur_val):=null;
  18299.   free_node(p,box_node_size);
  18300.   end;
  18301. while link(tail)<>null do tail:=link(tail);
  18302. exit:end;
  18303. @ @<Forbidden...@>=vmode+ital_corr,
  18304. @ Italic corrections are converted to kern nodes when the |ital_corr| command
  18305. follows a character. In math mode the same effect is achieved by appending
  18306. a kern of zero here, since italic corrections are supplied later.
  18307. @<Cases of |main_control| that build...@>=
  18308. hmode+ital_corr: append_italic_correction;
  18309. mmode+ital_corr: tail_append(new_kern(0));
  18310. @ @<Declare act...@>=
  18311. procedure append_italic_correction;
  18312. label exit;
  18313. var p:pointer; {|char_node| at the tail of the current list}
  18314. @!f:internal_font_number; {the font in the |char_node|}
  18315. begin if tail<>head then
  18316.   begin if is_char_node(tail) then p:=tail
  18317.   else if type(tail)=ligature_node then p:=lig_char(tail)
  18318.   else return;
  18319.   f:=font(p);
  18320.   tail_append(new_kern(char_italic(f)(char_info(f)(character(p)))));
  18321.   subtype(tail):=explicit;
  18322.   end;
  18323. exit:end;
  18324. @ Discretionary nodes are easy in the common case `\.{\\-}', but in the
  18325. general case we must process three braces full of items.
  18326. @<Put each...@>=
  18327. primitive("-",discretionary,1);
  18328. @!@:Single-character primitives -}{\quad\.{\\-}@>
  18329. primitive("discretionary",discretionary,0);
  18330. @!@:discretionary_}{\.{\\discretionary} primitive@>
  18331. @ @<Cases of |print_cmd_chr|...@>=
  18332. discretionary: if chr_code=1 then
  18333.   print_esc("-")@+else print_esc("discretionary");
  18334. @ @<Cases of |main_control| that build...@>=
  18335. hmode+discretionary,mmode+discretionary: append_discretionary;
  18336. @ The space factor does not change when we append a discretionary node,
  18337. but it starts out as 1000 in the subsidiary lists.
  18338. @<Declare act...@>=
  18339. procedure append_discretionary;
  18340. var c:integer; {hyphen character}
  18341. begin tail_append(new_disc);
  18342. if cur_chr=1 then
  18343.   begin c:=hyphen_char[cur_font];
  18344.   if c>=0 then if c<256 then pre_break(tail):=new_character(cur_font,c);
  18345.   end
  18346. else  begin incr(save_ptr); saved(-1):=0; new_save_level(disc_group);
  18347.   scan_left_brace; push_nest; mode:=-hmode; space_factor:=1000;
  18348.   end;
  18349. @ The three discretionary lists are constructed somewhat as if they were
  18350. hboxes. A~subroutine called |build_discretionary| handles the transitions.
  18351. (This is sort of fun.)
  18352. @<Cases of |handle...@>=
  18353. disc_group: build_discretionary;
  18354. @ @<Declare act...@>=
  18355. procedure build_discretionary;
  18356. label done,exit;
  18357. var p,@!q:pointer; {for link manipulation}
  18358. @!n:integer; {length of discretionary list}
  18359. begin unsave;
  18360. @<Prune the current list, if necessary, until it contains only
  18361.   |char_node|, |kern_node|, |hlist_node|, |vlist_node|, |rule_node|,
  18362.   and |ligature_node| items; set |n| to the length of the list,
  18363.   and set |q| to the list's tail@>;
  18364. p:=link(head); pop_nest;
  18365. case saved(-1) of
  18366. 0:pre_break(tail):=p;
  18367. 1:post_break(tail):=p;
  18368. 2:@<Attach list |p| to the current list, and record its length;
  18369.   then finish up and |return|@>;
  18370. end; {there are no other cases}
  18371. incr(saved(-1)); new_save_level(disc_group); scan_left_brace;
  18372. push_nest; mode:=-hmode; space_factor:=1000;
  18373. exit:end;
  18374. @ @<Attach list |p| to the current...@>=
  18375. begin if (n>0)and(abs(mode)=mmode) then
  18376.   begin print_err("Illegal math "); print_esc("discretionary");
  18377. @.Illegal math \\disc...@>
  18378.   help2("Sorry: The third part of a discretionary break must be")@/
  18379.   ("empty, in math formulas. I had to delete your third part.");
  18380.   flush_node_list(p); n:=0; error;
  18381.   end
  18382. else link(tail):=p;
  18383. if n<=max_quarterword then replace_count(tail):=n
  18384. else  begin print_err("Discretionary list is too long");
  18385. @.Discretionary list is too long@>
  18386.   help2("Wow---I never thought anybody would tweak me here.")@/
  18387.   ("You can't seriously need such a huge discretionary list?");
  18388.   error;
  18389.   end;
  18390. if n>0 then tail:=q;
  18391. decr(save_ptr); return;
  18392. @ During this loop, |p=link(q)| and there are |n| items preceding |p|.
  18393. @<Prune the current list, if necessary...@>=
  18394. q:=head; p:=link(q); n:=0;
  18395. while p<>null do
  18396.   begin if not is_char_node(p) then if type(p)>rule_node then
  18397.     if type(p)<>kern_node then if type(p)<>ligature_node then
  18398.       begin print_err("Improper discretionary list");
  18399. @.Improper discretionary list@>
  18400.       help1("Discretionary lists must contain only boxes and kerns.");@/
  18401.       error;
  18402.       begin_diagnostic;
  18403.       print_nl("The following discretionary sublist has been deleted:");
  18404. @.The following...deleted@>
  18405.       show_box(p);
  18406.       end_diagnostic(true);
  18407.       flush_node_list(p); link(q):=null; goto done;
  18408.       end;
  18409.   q:=p; p:=link(q); incr(n);
  18410.   end;
  18411. done:
  18412. @ We need only one more thing to complete the horizontal mode routines, namely
  18413. the \.{\\accent} primitive.
  18414. @<Cases of |main_control| that build...@>=
  18415. hmode+accent: make_accent;
  18416. @ The positioning of accents is straightforward but tedious. Given an accent
  18417. of width |a|, designed for characters of height |x| and slant |s|;
  18418. and given a character of width |w|, height |h|, and slant |t|: We will shift
  18419. the accent down by |x-h|, and we will insert kern nodes that have the effect of
  18420. centering the accent over the character and shifting the accent to the
  18421. right by $\delta={1\over2}(w-a)+h\cdot t-x\cdot s$.  If either character is
  18422. absent from the font, we will simply use the other, without shifting.
  18423. @<Declare act...@>=
  18424. procedure make_accent;
  18425. var s,@!t: real; {amount of slant}
  18426. @!p,@!q,@!r:pointer; {character, box, and kern nodes}
  18427. @!f:internal_font_number; {relevant font}
  18428. @!a,@!h,@!x,@!w,@!delta:scaled; {heights and widths, as explained above}
  18429. @!i:four_quarters; {character information}
  18430. begin scan_char_num; f:=cur_font; p:=new_character(f,cur_val);
  18431. if p<>null then
  18432.   begin x:=x_height(f); s:=slant(f)/float_constant(65536);
  18433. @^real division@>
  18434.   a:=char_width(f)(char_info(f)(character(p)));@/
  18435.   do_assignments;@/
  18436.   @<Create a character node |q| for the next character,
  18437.     but set |q:=null| if problems arise@>;
  18438.   if q<>null then @<Append the accent with appropriate kerns,
  18439.       then set |p:=q|@>;
  18440.   link(tail):=p; tail:=p; space_factor:=1000;
  18441.   end;
  18442. @ @<Create a character node |q| for the next...@>=
  18443. q:=null; f:=cur_font;
  18444. if (cur_cmd=letter)or(cur_cmd=other_char)or(cur_cmd=char_given) then
  18445.   q:=new_character(f,cur_chr)
  18446. else if cur_cmd=char_num then
  18447.   begin scan_char_num; q:=new_character(f,cur_val);
  18448.   end
  18449. else back_input
  18450. @ The kern nodes appended here must be distinguished from other kerns, lest
  18451. they be wiped away by the hyphenation algorithm or by a previous line break.
  18452. The two kerns are computed with (machine-dependent) |real| arithmetic, but
  18453. their sum is machine-independent; the net effect is machine-independent,
  18454. because the user cannot remove these nodes nor access them via \.{\\lastkern}.
  18455. @<Append the accent with appropriate kerns...@>=
  18456. begin t:=slant(f)/float_constant(65536);
  18457. @^real division@>
  18458. i:=char_info(f)(character(q));
  18459. w:=char_width(f)(i); h:=char_height(f)(height_depth(i));
  18460. if h<>x then {the accent must be shifted up or down}
  18461.   begin p:=hpack(p,natural); shift_amount(p):=x-h;
  18462.   end;
  18463. delta:=round((w-a)/float_constant(2)+h*t-x*s);
  18464. @^real multiplication@>
  18465. @^real addition@>
  18466. r:=new_kern(delta); subtype(r):=acc_kern; link(tail):=r; link(r):=p;
  18467. tail:=new_kern(-a-delta); subtype(tail):=acc_kern; link(p):=tail; p:=q;
  18468. @ When `\.{\\cr}' or `\.{\\span}' or a tab mark comes through the scanner
  18469. into |main_control|, it might be that the user has foolishly inserted
  18470. one of them into something that has nothing to do with alignment. But it is
  18471. far more likely that a left brace or right brace has been omitted, since
  18472. |get_next| takes actions appropriate to alignment only when `\.{\\cr}'
  18473. or `\.{\\span}' or tab marks occur with |align_state=0|. The following
  18474. program attempts to make an appropriate recovery.
  18475. @<Cases of |main_control| that build...@>=
  18476. any_mode(car_ret), any_mode(tab_mark): align_error;
  18477. any_mode(no_align): no_align_error;
  18478. any_mode(omit): omit_error;
  18479. @ @<Declare act...@>=
  18480. procedure align_error;
  18481. begin if abs(align_state)>2 then
  18482.   @<Express consternation over the fact that no alignment is in progress@>
  18483. else  begin back_input;
  18484.   if align_state<0 then
  18485.     begin print_err("Missing { inserted");
  18486. @.Missing \{ inserted@>
  18487.     incr(align_state); cur_tok:=left_brace_token+"{";
  18488.     end
  18489.   else  begin print_err("Missing } inserted");
  18490. @.Missing \} inserted@>
  18491.     decr(align_state); cur_tok:=right_brace_token+"}";
  18492.     end;
  18493.   help3("I've put in what seems to be necessary to fix")@/
  18494.     ("the current column of the current alignment.")@/
  18495.     ("Try to go on, since this might almost work."); ins_error;
  18496.   end;
  18497. @ @<Express consternation...@>=
  18498. begin print_err("Misplaced "); print_cmd_chr(cur_cmd,cur_chr);
  18499. @.Misplaced \&@>
  18500. @.Misplaced \\span@>
  18501. @.Misplaced \\cr@>
  18502. if cur_tok=tab_token+"&" then
  18503.   begin help6("I can't figure out why you would want to use a tab mark")@/
  18504.   ("here. If you just want an ampersand, the remedy is")@/
  18505.   ("simple: Just type `I\&' now. But if some right brace")@/
  18506.   ("up above has ended a previous alignment prematurely,")@/
  18507.   ("you're probably due for more error messages, and you")@/
  18508.   ("might try typing `S' now just to see what is salvageable.");
  18509.   end
  18510. else  begin help5("I can't figure out why you would want to use a tab mark")@/
  18511.   ("or \cr or \span just now. If something like a right brace")@/
  18512.   ("up above has ended a previous alignment prematurely,")@/
  18513.   ("you're probably due for more error messages, and you")@/
  18514.   ("might try typing `S' now just to see what is salvageable.");
  18515.   end;
  18516. error;
  18517. @ The help messages here contain a little white lie, since \.{\\noalign}
  18518. and \.{\\omit} are allowed also after `\.{\\noalign\{...\}}'.
  18519. @<Declare act...@>=
  18520. procedure no_align_error;
  18521. begin print_err("Misplaced "); print_esc("noalign");
  18522. @.Misplaced \\noalign@>
  18523. help2("I expect to see \noalign only after the \cr of")@/
  18524.   ("an alignment. Proceed, and I'll ignore this case."); error;
  18525. procedure omit_error;
  18526. begin print_err("Misplaced "); print_esc("omit");
  18527. @.Misplaced \\omit@>
  18528. help2("I expect to see \omit only after tab marks or the \cr of")@/
  18529.   ("an alignment. Proceed, and I'll ignore this case."); error;
  18530. @ We've now covered most of the abuses of \.{\\halign} and \.{\\valign}.
  18531. Let's take a look at what happens when they are used correctly.
  18532. @<Cases of |main_control| that build...@>=
  18533. vmode+halign,hmode+valign:init_align;
  18534. mmode+halign: if privileged then
  18535.   if cur_group=math_shift_group then init_align
  18536.   else off_save;
  18537. vmode+endv,hmode+endv: do_endv;
  18538. @ An |align_group| code is supposed to remain on the |save_stack|
  18539. during an entire alignment, until |fin_align| removes it.
  18540. @<Declare act...@>=
  18541. procedure do_endv;
  18542. begin if cur_group=align_group then
  18543.   begin end_graf;
  18544.   if fin_col then fin_row;
  18545.   end
  18546. else off_save;
  18547. @ @<Cases of |handle_right_brace|...@>=
  18548. align_group: begin back_input; cur_tok:=cs_token_flag+frozen_cr;
  18549.   print_err("Missing "); print_esc("cr"); print(" inserted");
  18550. @.Missing \\cr inserted@>
  18551.   help1("I'm guessing that you meant to end an alignment here.");
  18552.   ins_error;
  18553.   end;
  18554. @ @<Cases of |handle_right_brace|...@>=
  18555. no_align_group: begin end_graf; unsave; align_peek;
  18556.   end;
  18557. @ Finally, \.{\\endcsname} is not supposed to get through to |main_control|.
  18558. @<Cases of |main_control| that build...@>=
  18559. any_mode(end_cs_name): cs_error;
  18560. @ @<Declare act...@>=
  18561. procedure cs_error;
  18562. begin print_err("Extra "); print_esc("endcsname");
  18563. @.Extra \\endcsname@>
  18564. help1("I'm ignoring this, since I wasn't doing a \csname.");
  18565. error;
  18566. @* \[48] Building math lists.
  18567. The routines that \TeX\ uses to create mlists are similar to those we have
  18568. just seen for the generation of hlists and vlists. But it is necessary to
  18569. make ``noads'' as well as nodes, so the reader should review the
  18570. discussion of math mode data structures before trying to make sense out of
  18571. the following program.
  18572. Here is a little routine that needs to be done whenever a subformula
  18573. is about to be processed. The parameter is a code like |math_group|.
  18574. @<Declare act...@>=
  18575. procedure push_math(@!c:group_code);
  18576. begin push_nest; mode:=-mmode; incompleat_noad:=null; new_save_level(c);
  18577. @ We get into math mode from horizontal mode when a `\.\$' (i.e., a
  18578. |math_shift| character) is scanned. We must check to see whether this
  18579. `\.\$' is immediately followed by another, in case display math mode is
  18580. called for.
  18581. @<Cases of |main_control| that build...@>=
  18582. hmode+math_shift:init_math;
  18583. @ @<Declare act...@>=
  18584. procedure init_math;
  18585. label reswitch,found,not_found,done;
  18586. var w:scaled; {new or partial |pre_display_size|}
  18587. @!l:scaled; {new |display_width|}
  18588. @!s:scaled; {new |display_indent|}
  18589. @!p:pointer; {current node when calculating |pre_display_size|}
  18590. @!q:pointer; {glue specification when calculating |pre_display_size|}
  18591. @!f:internal_font_number; {font in current |char_node|}
  18592. @!n:integer; {scope of paragraph shape specification}
  18593. @!v:scaled; {|w| plus possible glue amount}
  18594. @!d:scaled; {increment to |v|}
  18595. begin get_token; {|get_x_token| would fail on \.{\\ifmmode}\thinspace!}
  18596. if (cur_cmd=math_shift)and(mode>0) then @<Go into display math mode@>
  18597. else  begin back_input; @<Go into ordinary math mode@>;
  18598.   end;
  18599. @ @<Go into ordinary math mode@>=
  18600. begin push_math(math_shift_group); eq_word_define(int_base+cur_fam_code,-1);
  18601. if every_math<>null then begin_token_list(every_math,every_math_text);
  18602. @ We get into ordinary math mode from display math mode when `\.{\\eqno}' or
  18603. `\.{\\leqno}' appears. In such cases |cur_chr| will be 0 or~1, respectively;
  18604. the value of |cur_chr| is placed onto |save_stack| for safe keeping.
  18605. @<Cases of |main_control| that build...@>=
  18606. mmode+eq_no: if privileged then
  18607.   if cur_group=math_shift_group then start_eq_no
  18608.   else off_save;
  18609. @ @<Put each...@>=
  18610. primitive("eqno",eq_no,0);
  18611. @!@:eq_no_}{\.{\\eqno} primitive@>
  18612. primitive("leqno",eq_no,1);
  18613. @!@:leq_no_}{\.{\\leqno} primitive@>
  18614. @ When \TeX\ is in display math mode, |cur_group=math_shift_group|,
  18615. so it is not necessary for the |start_eq_no| procedure to test for
  18616. this condition.
  18617. @<Declare act...@>=
  18618. procedure start_eq_no;
  18619. begin saved(0):=cur_chr; incr(save_ptr);
  18620. @<Go into ordinary math mode@>;
  18621. @ @<Cases of |print_cmd_chr|...@>=
  18622. eq_no:if chr_code=1 then print_esc("leqno")@+else print_esc("eqno");
  18623. @ @<Forbidden...@>=non_math(eq_no),
  18624. @ When we enter display math mode, we need to call |line_break| to
  18625. process the partial paragraph that has just been interrupted by the
  18626. display. Then we can set the proper values of |display_width| and
  18627. |display_indent| and |pre_display_size|.
  18628. @<Go into display math mode@>=
  18629. begin if head=tail then {`\.{\\noindent\$\$}' or `\.{\$\${ }\$\$}'}
  18630.   begin pop_nest; w:=-max_dimen;
  18631.   end
  18632. else  begin line_break(display_widow_penalty);@/
  18633.   @<Calculate the natural width, |w|, by which the characters of the
  18634.     final line extend to the right of the reference point,
  18635.     plus two ems; or set |w:=max_dimen| if the non-blank information
  18636.     on that line is affected by stretching or shrinking@>;
  18637.   end;
  18638. {Now we are in vertical mode, working on the list that will contain the display}
  18639. @<Calculate the length, |l|, and the shift amount, |s|, of the display lines@>;
  18640. push_math(math_shift_group); mode:=mmode;
  18641. eq_word_define(int_base+cur_fam_code,-1);@/
  18642. eq_word_define(dimen_base+pre_display_size_code,w);
  18643. eq_word_define(dimen_base+display_width_code,l);
  18644. eq_word_define(dimen_base+display_indent_code,s);
  18645. if every_display<>null then begin_token_list(every_display,every_display_text);
  18646. if nest_ptr=1 then build_page;
  18647. @ @<Calculate the natural width, |w|, by which...@>=
  18648. v:=shift_amount(just_box)+2*quad(cur_font); w:=-max_dimen;
  18649. p:=list_ptr(just_box);
  18650. while p<>null do
  18651.   begin @<Let |d| be the natural width of node |p|;
  18652.     if the node is ``visible,'' |goto found|;
  18653.     if the node is glue that stretches or shrinks, set |v:=max_dimen|@>;
  18654.   if v<max_dimen then v:=v+d;
  18655.   goto not_found;
  18656.   found: if v<max_dimen then
  18657.     begin v:=v+d; w:=v;
  18658.     end
  18659.   else  begin w:=max_dimen; goto done;
  18660.     end;
  18661.   not_found: p:=link(p);
  18662.   end;
  18663. done:
  18664. @ @<Let |d| be the natural width of node |p|...@>=
  18665. reswitch: if is_char_node(p) then
  18666.   begin f:=font(p); d:=char_width(f)(char_info(f)(character(p)));
  18667.   goto found;
  18668.   end;
  18669. case type(p) of
  18670. hlist_node,vlist_node,rule_node: begin d:=width(p); goto found;
  18671.   end;
  18672. ligature_node:@<Make node |p| look like a |char_node|...@>;
  18673. kern_node,math_node: d:=width(p);
  18674. glue_node:@<Let |d| be the natural width of this glue; if stretching
  18675.   or shrinking, set |v:=max_dimen|; |goto found| in the case of leaders@>;
  18676. whatsit_node: @<Let |d| be the width of the whatsit |p|@>;
  18677. othercases d:=0
  18678. endcases
  18679. @ We need to be careful that |w|, |v|, and |d| do not depend on any |glue_set|
  18680. values, since such values are subject to system-dependent rounding.
  18681. System-dependent numbers are not allowed to infiltrate parameters like
  18682. |pre_display_size|, since \TeX82 is supposed to make the same decisions on all
  18683. machines.
  18684. @<Let |d| be the natural width of this glue...@>=
  18685. begin q:=glue_ptr(p); d:=width(q);
  18686. if glue_sign(just_box)=stretching then
  18687.   begin if (glue_order(just_box)=stretch_order(q))and@|
  18688.      (stretch(q)<>0) then
  18689.     v:=max_dimen;
  18690.   end
  18691. else if glue_sign(just_box)=shrinking then
  18692.   begin if (glue_order(just_box)=shrink_order(q))and@|
  18693.      (shrink(q)<>0) then
  18694.     v:=max_dimen;
  18695.   end;
  18696. if subtype(p)>=a_leaders then goto found;
  18697. @ A displayed equation is considered to be three lines long, so we
  18698. calculate the length and offset of line number |prev_graf+2|.
  18699. @<Calculate the length, |l|, ...@>=
  18700. if par_shape_ptr=null then
  18701.   if (hang_indent<>0)and@|
  18702.    (((hang_after>=0)and(prev_graf+2>hang_after))or@|
  18703.     (prev_graf+1<-hang_after)) then
  18704.     begin l:=hsize-abs(hang_indent);
  18705.     if hang_indent>0 then s:=hang_indent@+else s:=0;
  18706.     end
  18707.   else  begin l:=hsize; s:=0;
  18708.     end
  18709. else  begin n:=info(par_shape_ptr);
  18710.   if prev_graf+2>=n then p:=par_shape_ptr+2*n
  18711.   else p:=par_shape_ptr+2*(prev_graf+2);
  18712.   s:=mem[p-1].sc; l:=mem[p].sc;
  18713.   end
  18714. @ Subformulas of math formulas cause a new level of math mode to be entered,
  18715. on the semantic nest as well as the save stack. These subformulas arise in
  18716. several ways: (1)~A left brace by itself indicates the beginning of a
  18717. subformula that will be put into a box, thereby freezing its glue and
  18718. preventing line breaks. (2)~A subscript or superscript is treated as a
  18719. subformula if it is not a single character; the same applies to
  18720. the nucleus of things like \.{\\underline}. (3)~The \.{\\left} primitive
  18721. initiates a subformula that will be terminated by a matching \.{\\right}.
  18722. The group codes placed on |save_stack| in these three cases are
  18723. |math_group|, |math_group|, and |math_left_group|, respectively.
  18724. Here is the code that handles case (1); the other cases are not quite as
  18725. trivial, so we shall consider them later.
  18726. @<Cases of |main_control| that build...@>=
  18727. mmode+left_brace: begin tail_append(new_noad);
  18728.   back_input; scan_math(nucleus(tail));
  18729.   end;
  18730. @ Recall that the |nucleus|, |subscr|, and |supscr| fields in a noad are
  18731. broken down into subfields called |math_type| and either |info| or
  18732. |(fam,character)|. The job of |scan_math| is to figure out what to place
  18733. in one of these principal fields; it looks at the subformula that
  18734. comes next in the input, and places an encoding of that subformula
  18735. into a given word of |mem|.
  18736. @d fam_in_range==((cur_fam>=0)and(cur_fam<16))
  18737. @<Declare act...@>=
  18738. procedure scan_math(@!p:pointer);
  18739. label restart,reswitch,exit;
  18740. var c:integer; {math character code}
  18741. begin restart:@<Get the next non-blank non-relax...@>;
  18742. reswitch:case cur_cmd of
  18743. letter,other_char,char_given: begin c:=ho(math_code(cur_chr));
  18744.     if c=@'100000 then
  18745.       begin @<Treat |cur_chr| as an active character@>;
  18746.       goto restart;
  18747.       end;
  18748.     end;
  18749. char_num: begin scan_char_num; cur_chr:=cur_val; cur_cmd:=char_given;
  18750.   goto reswitch;
  18751.   end;
  18752. math_char_num: begin scan_fifteen_bit_int; c:=cur_val;
  18753.   end;
  18754. math_given: c:=cur_chr;
  18755. delim_num: begin scan_twenty_seven_bit_int; c:=cur_val div @'10000;
  18756.   end;
  18757. othercases @<Scan a subformula enclosed in braces and |return|@>
  18758. endcases;@/
  18759. math_type(p):=math_char; character(p):=qi(c mod 256);
  18760. if (c>=var_code)and fam_in_range then fam(p):=cur_fam
  18761. else fam(p):=(c div 256) mod 16;
  18762. exit:end;
  18763. @ An active character that is an |outer_call| is allowed here.
  18764. @<Treat |cur_chr|...@>=
  18765. begin cur_cs:=cur_chr+active_base;
  18766. cur_cmd:=eq_type(cur_cs); cur_chr:=equiv(cur_cs);
  18767. x_token; back_input;
  18768. @ The pointer |p| is placed on |save_stack| while a complex subformula
  18769. is being scanned.
  18770. @<Scan a subformula...@>=
  18771. begin back_input; scan_left_brace;@/
  18772. saved(0):=p; incr(save_ptr); push_math(math_group); return;
  18773. @ The simplest math formula is, of course, `\.{\${ }\$}', when no noads are
  18774. generated. The next simplest cases involve a single character, e.g.,
  18775. `\.{\$x\$}'. Even though such cases may not seem to be very interesting,
  18776. the reader can perhaps understand how happy the author was when `\.{\$x\$}'
  18777. was first properly typeset by \TeX. The code in this section was used.
  18778. @^Knuth, Donald Ervin@>
  18779. @<Cases of |main_control| that build...@>=
  18780. mmode+letter,mmode+other_char,mmode+char_given:
  18781.   set_math_char(ho(math_code(cur_chr)));
  18782. mmode+char_num: begin scan_char_num; cur_chr:=cur_val;
  18783.   set_math_char(ho(math_code(cur_chr)));
  18784.   end;
  18785. mmode+math_char_num: begin scan_fifteen_bit_int; set_math_char(cur_val);
  18786.   end;
  18787. mmode+math_given: set_math_char(cur_chr);
  18788. mmode+delim_num: begin scan_twenty_seven_bit_int;
  18789.   set_math_char(cur_val div @'10000);
  18790.   end;
  18791. @ The |set_math_char| procedure creates a new noad appropriate to a given
  18792. math code, and appends it to the current mlist. However, if the math code
  18793. is sufficiently large, the |cur_chr| is treated as an active character and
  18794. nothing is appended.
  18795. @<Declare act...@>=
  18796. procedure set_math_char(@!c:integer);
  18797. var p:pointer; {the new noad}
  18798. begin if c>=@'100000 then
  18799.   @<Treat |cur_chr|...@>
  18800. else  begin p:=new_noad; math_type(nucleus(p)):=math_char;
  18801.   character(nucleus(p)):=qi(c mod 256);
  18802.   fam(nucleus(p)):=(c div 256) mod 16;
  18803.   if c>=var_code then
  18804.     begin if fam_in_range then fam(nucleus(p)):=cur_fam;
  18805.     type(p):=ord_noad;
  18806.     end
  18807.   else  type(p):=ord_noad+(c div @'10000);
  18808.   link(tail):=p; tail:=p;
  18809.   end;
  18810. @ Primitive math operators like \.{\\mathop} and \.{\\underline} are given
  18811. the command code |math_comp|, supplemented by the noad type that they
  18812. generate.
  18813. @<Put each...@>=
  18814. primitive("mathord",math_comp,ord_noad);
  18815. @!@:math_ord_}{\.{\\mathord} primitive@>
  18816. primitive("mathop",math_comp,op_noad);
  18817. @!@:math_op_}{\.{\\mathop} primitive@>
  18818. primitive("mathbin",math_comp,bin_noad);
  18819. @!@:math_bin_}{\.{\\mathbin} primitive@>
  18820. primitive("mathrel",math_comp,rel_noad);
  18821. @!@:math_rel_}{\.{\\mathrel} primitive@>
  18822. primitive("mathopen",math_comp,open_noad);
  18823. @!@:math_open_}{\.{\\mathopen} primitive@>
  18824. primitive("mathclose",math_comp,close_noad);
  18825. @!@:math_close_}{\.{\\mathclose} primitive@>
  18826. primitive("mathpunct",math_comp,punct_noad);
  18827. @!@:math_punct_}{\.{\\mathpunct} primitive@>
  18828. primitive("mathinner",math_comp,inner_noad);
  18829. @!@:math_inner_}{\.{\\mathinner} primitive@>
  18830. primitive("underline",math_comp,under_noad);
  18831. @!@:underline_}{\.{\\underline} primitive@>
  18832. primitive("overline",math_comp,over_noad);@/
  18833. @!@:overline_}{\.{\\overline} primitive@>
  18834. primitive("displaylimits",limit_switch,normal);
  18835. @!@:display_limits_}{\.{\\displaylimits} primitive@>
  18836. primitive("limits",limit_switch,limits);
  18837. @!@:limits_}{\.{\\limits} primitive@>
  18838. primitive("nolimits",limit_switch,no_limits);
  18839. @!@:no_limits_}{\.{\\nolimits} primitive@>
  18840. @ @<Cases of |print_cmd_chr|...@>=
  18841. math_comp: case chr_code of
  18842.   ord_noad: print_esc("mathord");
  18843.   op_noad: print_esc("mathop");
  18844.   bin_noad: print_esc("mathbin");
  18845.   rel_noad: print_esc("mathrel");
  18846.   open_noad: print_esc("mathopen");
  18847.   close_noad: print_esc("mathclose");
  18848.   punct_noad: print_esc("mathpunct");
  18849.   inner_noad: print_esc("mathinner");
  18850.   under_noad: print_esc("underline");
  18851.   othercases print_esc("overline")
  18852.   endcases;
  18853. limit_switch: if chr_code=limits then print_esc("limits")
  18854.   else if chr_code=no_limits then print_esc("nolimits")
  18855.   else print_esc("displaylimits");
  18856. @ @<Cases of |main_control| that build...@>=
  18857. mmode+math_comp: begin tail_append(new_noad);
  18858.   type(tail):=cur_chr; scan_math(nucleus(tail));
  18859.   end;
  18860. mmode+limit_switch: math_limit_switch;
  18861. @ @<Declare act...@>=
  18862. procedure math_limit_switch;
  18863. label exit;
  18864. begin if head<>tail then if type(tail)=op_noad then
  18865.   begin subtype(tail):=cur_chr; return;
  18866.   end;
  18867. print_err("Limit controls must follow a math operator");
  18868. @.Limit controls must follow...@>
  18869. help1("I'm ignoring this misplaced \limits or \nolimits command."); error;
  18870. exit:end;
  18871. @ Delimiter fields of noads are filled in by the |scan_delimiter| routine.
  18872. The first parameter of this procedure is the |mem| address where the
  18873. delimiter is to be placed; the second tells if this delimiter follows
  18874. \.{\\radical} or not.
  18875. @<Declare act...@>=
  18876. procedure scan_delimiter(@!p:pointer;@!r:boolean);
  18877. begin if r then scan_twenty_seven_bit_int
  18878. else  begin @<Get the next non-blank non-relax...@>;
  18879.   case cur_cmd of
  18880.   letter,other_char: cur_val:=del_code(cur_chr);
  18881.   delim_num: scan_twenty_seven_bit_int;
  18882.   othercases cur_val:=-1
  18883.   endcases;
  18884.   end;
  18885. if cur_val<0 then @<Report that an invalid delimiter code is being changed
  18886.    to null; set~|cur_val:=0|@>;
  18887. small_fam(p):=(cur_val div @'4000000) mod 16;
  18888. small_char(p):=qi((cur_val div @'10000) mod 256);
  18889. large_fam(p):=(cur_val div 256) mod 16;
  18890. large_char(p):=qi(cur_val mod 256);
  18891. @ @<Report that an invalid delimiter...@>=
  18892. begin print_err("Missing delimiter (. inserted)");
  18893. @.Missing delimiter...@>
  18894. help6("I was expecting to see something like `(' or `\{' or")@/
  18895.   ("`\}' here. If you typed, e.g., `{' instead of `\{', you")@/
  18896.   ("should probably delete the `{' by typing `1' now, so that")@/
  18897.   ("braces don't get unbalanced. Otherwise just proceed.")@/
  18898.   ("Acceptable delimiters are characters whose \delcode is")@/
  18899.   ("nonnegative, or you can use `\delimiter <delimiter code>'.");
  18900. back_error; cur_val:=0;
  18901. @ @<Cases of |main_control| that build...@>=
  18902. mmode+radical:math_radical;
  18903. @ @<Declare act...@>=
  18904. procedure math_radical;
  18905. begin tail_append(get_node(radical_noad_size));
  18906. type(tail):=radical_noad; subtype(tail):=normal;
  18907. mem[nucleus(tail)].hh:=empty_field;
  18908. mem[subscr(tail)].hh:=empty_field;
  18909. mem[supscr(tail)].hh:=empty_field;
  18910. scan_delimiter(left_delimiter(tail),true); scan_math(nucleus(tail));
  18911. @ @<Cases of |main_control| that build...@>=
  18912. mmode+accent,mmode+math_accent:math_ac;
  18913. @ @<Declare act...@>=
  18914. procedure math_ac;
  18915. begin if cur_cmd=accent then
  18916.   @<Complain that the user should have said \.{\\mathaccent}@>;
  18917. tail_append(get_node(accent_noad_size));
  18918. type(tail):=accent_noad; subtype(tail):=normal;
  18919. mem[nucleus(tail)].hh:=empty_field;
  18920. mem[subscr(tail)].hh:=empty_field;
  18921. mem[supscr(tail)].hh:=empty_field;
  18922. math_type(accent_chr(tail)):=math_char;
  18923. scan_fifteen_bit_int;
  18924. character(accent_chr(tail)):=qi(cur_val mod 256);
  18925. if (cur_val>=var_code)and fam_in_range then fam(accent_chr(tail)):=cur_fam
  18926. else fam(accent_chr(tail)):=(cur_val div 256) mod 16;
  18927. scan_math(nucleus(tail));
  18928. @ @<Complain that the user should have said \.{\\mathaccent}@>=
  18929. begin print_err("Please use "); print_esc("mathaccent");
  18930. print(" for accents in math mode");
  18931. @.Please use \\mathaccent...@>
  18932. help2("I'm changing \accent to \mathaccent here; wish me luck.")@/
  18933.   ("(Accents are not the same in formulas as they are in text.)");
  18934. error;
  18935. @ @<Cases of |main_control| that build...@>=
  18936. mmode+vcenter: begin scan_spec(vcenter_group,false); normal_paragraph;
  18937.   push_nest; mode:=-vmode; prev_depth:=ignore_depth;
  18938.   if every_vbox<>null then begin_token_list(every_vbox,every_vbox_text);
  18939.   end;
  18940. @ @<Cases of |handle...@>=
  18941. vcenter_group: begin end_graf; unsave; save_ptr:=save_ptr-2;
  18942.   p:=vpack(link(head),saved(1),saved(0)); pop_nest;
  18943.   tail_append(new_noad); type(tail):=vcenter_noad;
  18944.   math_type(nucleus(tail)):=sub_box; info(nucleus(tail)):=p;
  18945.   end;
  18946. @ The routine that inserts a |style_node| holds no surprises.
  18947. @<Put each...@>=
  18948. primitive("displaystyle",math_style,display_style);
  18949. @!@:display_style_}{\.{\\displaystyle} primitive@>
  18950. primitive("textstyle",math_style,text_style);
  18951. @!@:text_style_}{\.{\\textstyle} primitive@>
  18952. primitive("scriptstyle",math_style,script_style);
  18953. @!@:script_style_}{\.{\\scriptstyle} primitive@>
  18954. primitive("scriptscriptstyle",math_style,script_script_style);
  18955. @!@:script_script_style_}{\.{\\scriptscriptstyle} primitive@>
  18956. @ @<Cases of |print_cmd_chr|...@>=
  18957. math_style: print_style(chr_code);
  18958. @ @<Cases of |main_control| that build...@>=
  18959. mmode+math_style: tail_append(new_style(cur_chr));
  18960. mmode+non_script: begin tail_append(new_glue(zero_glue));
  18961.   subtype(tail):=cond_math_glue;
  18962.   end;
  18963. mmode+math_choice: append_choices;
  18964. @ The routine that scans the four mlists of a \.{\\mathchoice} is very
  18965. much like the routine that builds discretionary nodes.
  18966. @<Declare act...@>=
  18967. procedure append_choices;
  18968. begin tail_append(new_choice); incr(save_ptr); saved(-1):=0;
  18969. push_math(math_choice_group); scan_left_brace;
  18970. @ @<Cases of |handle_right_brace|...@>=
  18971. math_choice_group: build_choices;
  18972. @ @<Declare act...@>=
  18973. @t\4@>@<Declare the function called |fin_mlist|@>@t@>@;@/
  18974. procedure build_choices;
  18975. label exit;
  18976. var p:pointer; {the current mlist}
  18977. begin unsave; p:=fin_mlist(null);
  18978. case saved(-1) of
  18979. 0:display_mlist(tail):=p;
  18980. 1:text_mlist(tail):=p;
  18981. 2:script_mlist(tail):=p;
  18982. 3:begin script_script_mlist(tail):=p; decr(save_ptr); return;
  18983.   end;
  18984. end; {there are no other cases}
  18985. incr(saved(-1)); push_math(math_choice_group); scan_left_brace;
  18986. exit:end;
  18987. @ Subscripts and superscripts are attached to the previous nucleus by the
  18988. @^superscripts@>@^subscripts@>
  18989. action procedure called |sub_sup|. We use the facts that |sub_mark=sup_mark+1|
  18990. and |subscr(p)=supscr(p)+1|.
  18991. @<Cases of |main_control| that build...@>=
  18992. mmode+sub_mark,mmode+sup_mark: sub_sup;
  18993. @ @<Declare act...@>=
  18994. procedure sub_sup;
  18995. var t:small_number; {type of previous sub/superscript}
  18996. @!p:pointer; {field to be filled by |scan_math|}
  18997. begin t:=empty; p:=null;
  18998. if tail<>head then if scripts_allowed(tail) then
  18999.   begin p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
  19000.   t:=math_type(p);
  19001.   end;
  19002. if (p=null)or(t<>empty) then @<Insert a dummy noad to be sub/superscripted@>;
  19003. scan_math(p);
  19004. @ @<Insert a dummy...@>=
  19005. begin tail_append(new_noad);
  19006. p:=supscr(tail)+cur_cmd-sup_mark; {|supscr| or |subscr|}
  19007. if t<>empty then
  19008.   begin if cur_cmd=sup_mark then
  19009.     begin print_err("Double superscript");
  19010. @.Double superscript@>
  19011.     help1("I treat `x^1^2' essentially like `x^1{}^2'.");
  19012.     end
  19013.   else  begin print_err("Double subscript");
  19014. @.Double subscript@>
  19015.     help1("I treat `x_1_2' essentially like `x_1{}_2'.");
  19016.     end;
  19017.   error;
  19018.   end;
  19019. @ An operation like `\.{\\over}' causes the current mlist to go into a
  19020. state of suspended animation: |incompleat_noad| points to a |fraction_noad|
  19021. that contains the mlist-so-far as its numerator, while the denominator
  19022. is yet to come. Finally when the mlist is finished, the denominator will
  19023. go into the incompleat fraction noad, and that noad will become the
  19024. whole formula, unless it is surrounded by `\.{\\left}' and `\.{\\right}'
  19025. delimiters.
  19026. @d above_code=0 { `\.{\\above}' }
  19027. @d over_code=1 { `\.{\\over}' }
  19028. @d atop_code=2 { `\.{\\atop}' }
  19029. @d delimited_code=3 { `\.{\\abovewithdelims}', etc.}
  19030. @<Put each...@>=
  19031. primitive("above",above,above_code);@/
  19032. @!@:above_}{\.{\\above} primitive@>
  19033. primitive("over",above,over_code);@/
  19034. @!@:over_}{\.{\\over} primitive@>
  19035. primitive("atop",above,atop_code);@/
  19036. @!@:atop_}{\.{\\atop} primitive@>
  19037. primitive("abovewithdelims",above,delimited_code+above_code);@/
  19038. @!@:above_with_delims_}{\.{\\abovewithdelims} primitive@>
  19039. primitive("overwithdelims",above,delimited_code+over_code);@/
  19040. @!@:over_with_delims_}{\.{\\overwithdelims} primitive@>
  19041. primitive("atopwithdelims",above,delimited_code+atop_code);
  19042. @!@:atop_with_delims_}{\.{\\atopwithdelims} primitive@>
  19043. @ @<Cases of |print_cmd_chr|...@>=
  19044. above: case chr_code of
  19045.   over_code:print_esc("over");
  19046.   atop_code:print_esc("atop");
  19047.   delimited_code+above_code:print_esc("abovewithdelims");
  19048.   delimited_code+over_code:print_esc("overwithdelims");
  19049.   delimited_code+atop_code:print_esc("atopwithdelims");
  19050.   othercases print_esc("above")
  19051.   endcases;
  19052. @ @<Cases of |main_control| that build...@>=
  19053. mmode+above: math_fraction;
  19054. @ @<Declare act...@>=
  19055. procedure math_fraction;
  19056. var c:small_number; {the type of generalized fraction we are scanning}
  19057. begin c:=cur_chr;
  19058. if incompleat_noad<>null then
  19059.   @<Ignore the fraction operation and complain about this ambiguous case@>
  19060. else  begin incompleat_noad:=get_node(fraction_noad_size);
  19061.   type(incompleat_noad):=fraction_noad;
  19062.   subtype(incompleat_noad):=normal;
  19063.   math_type(numerator(incompleat_noad)):=sub_mlist;
  19064.   info(numerator(incompleat_noad)):=link(head);
  19065.   mem[denominator(incompleat_noad)].hh:=empty_field;
  19066.   mem[left_delimiter(incompleat_noad)].qqqq:=null_delimiter;
  19067.   mem[right_delimiter(incompleat_noad)].qqqq:=null_delimiter;@/
  19068.   link(head):=null; tail:=head;
  19069.   @<Use code |c| to distinguish between generalized fractions@>;
  19070.   end;
  19071. @ @<Use code |c|...@>=
  19072. if c>=delimited_code then
  19073.   begin scan_delimiter(left_delimiter(incompleat_noad),false);
  19074.   scan_delimiter(right_delimiter(incompleat_noad),false);
  19075.   end;
  19076. case c mod delimited_code of
  19077. above_code: begin scan_normal_dimen;
  19078.   thickness(incompleat_noad):=cur_val;
  19079.   end;
  19080. over_code: thickness(incompleat_noad):=default_code;
  19081. atop_code: thickness(incompleat_noad):=0;
  19082. end {there are no other cases}
  19083. @ @<Ignore the fraction...@>=
  19084. begin if c>=delimited_code then
  19085.   begin scan_delimiter(garbage,false); scan_delimiter(garbage,false);
  19086.   end;
  19087. if c mod delimited_code=above_code then scan_normal_dimen;
  19088. print_err("Ambiguous; you need another { and }");
  19089. @.Ambiguous...@>
  19090. help3("I'm ignoring this fraction specification, since I don't")@/
  19091.   ("know whether a construction like `x \over y \over z'")@/
  19092.   ("means `{x \over y} \over z' or `x \over {y \over z}'.");
  19093. error;
  19094. @ At the end of a math formula or subformula, the |fin_mlist| routine is
  19095. called upon to return a pointer to the newly completed mlist, and to
  19096. pop the nest back to the enclosing semantic level. The parameter to
  19097. |fin_mlist|, if not null, points to a |right_noad| that ends the
  19098. current mlist; this |right_noad| has not yet been appended.
  19099. @<Declare the function called |fin_mlist|@>=
  19100. function fin_mlist(@!p:pointer):pointer;
  19101. var q:pointer; {the mlist to return}
  19102. begin if incompleat_noad<>null then @<Compleat the incompleat noad@>
  19103. else  begin link(tail):=p; q:=link(head);
  19104.   end;
  19105. pop_nest; fin_mlist:=q;
  19106. @ @<Compleat...@>=
  19107. begin math_type(denominator(incompleat_noad)):=sub_mlist;
  19108. info(denominator(incompleat_noad)):=link(head);
  19109. if p=null then q:=incompleat_noad
  19110. else  begin q:=info(numerator(incompleat_noad));
  19111.   if type(q)<>left_noad then confusion("right");
  19112. @:this can't happen right}{\quad right@>
  19113.   info(numerator(incompleat_noad)):=link(q);
  19114.   link(q):=incompleat_noad; link(incompleat_noad):=p;
  19115.   end;
  19116. @ Now at last we're ready to see what happens when a right brace occurs
  19117. in a math formula. Two special cases are simplified here: Braces are effectively
  19118. removed when they surround a single Ord without sub/superscripts, or when they
  19119. surround an accent that is the nucleus of an Ord atom.
  19120. @<Cases of |handle...@>=
  19121. math_group: begin unsave; decr(save_ptr);@/
  19122.   math_type(saved(0)):=sub_mlist; p:=fin_mlist(null); info(saved(0)):=p;
  19123.   if p<>null then if link(p)=null then
  19124.    if type(p)=ord_noad then
  19125.     begin if math_type(subscr(p))=empty then
  19126.      if math_type(supscr(p))=empty then
  19127.       begin mem[saved(0)].hh:=mem[nucleus(p)].hh;
  19128.       free_node(p,noad_size);
  19129.       end;
  19130.     end
  19131.   else if type(p)=accent_noad then if saved(0)=nucleus(tail) then
  19132.    if type(tail)=ord_noad then @<Replace the tail of the list by |p|@>;
  19133.   end;
  19134. @ @<Replace the tail...@>=
  19135. begin q:=head; while link(q)<>tail do q:=link(q);
  19136. link(q):=p; free_node(tail,noad_size); tail:=p;
  19137. @ We have dealt with all constructions of math mode except `\.{\\left}' and
  19138. `\.{\\right}', so the picture is completed by the following sections of
  19139. the program.
  19140. @<Put each...@>=
  19141. primitive("left",left_right,left_noad);
  19142. @!@:left_}{\.{\\left} primitive@>
  19143. primitive("right",left_right,right_noad);
  19144. @!@:right_}{\.{\\right} primitive@>
  19145. text(frozen_right):="right"; eqtb[frozen_right]:=eqtb[cur_val];
  19146. @ @<Cases of |print_cmd_chr|...@>=
  19147. left_right: if chr_code=left_noad then print_esc("left")
  19148. else print_esc("right");
  19149. @ @<Cases of |main_control| that build...@>=
  19150. mmode+left_right: math_left_right;
  19151. @ @<Declare act...@>=
  19152. procedure math_left_right;
  19153. var t:small_number; {|left_noad| or |right_noad|}
  19154. @!p:pointer; {new noad}
  19155. begin t:=cur_chr;
  19156. if (t=right_noad)and(cur_group<>math_left_group) then
  19157.   @<Try to recover from mismatched \.{\\right}@>
  19158. else  begin p:=new_noad; type(p):=t;
  19159.   scan_delimiter(delimiter(p),false);
  19160.   if t=left_noad then
  19161.     begin push_math(math_left_group); link(head):=p; tail:=p;
  19162.     end
  19163.   else  begin p:=fin_mlist(p); unsave; {end of |math_left_group|}
  19164.     tail_append(new_noad); type(tail):=inner_noad;
  19165.     math_type(nucleus(tail)):=sub_mlist;
  19166.     info(nucleus(tail)):=p;
  19167.     end;
  19168.   end;
  19169. @ @<Try to recover from mismatch...@>=
  19170. begin if cur_group=math_shift_group then
  19171.   begin scan_delimiter(garbage,false);
  19172.   print_err("Extra "); print_esc("right");
  19173. @.Extra \\right.@>
  19174.   help1("I'm ignoring a \right that had no matching \left.");
  19175.   error;
  19176.   end
  19177. else off_save;
  19178. @ Here is the only way out of math mode.
  19179. @<Cases of |main_control| that build...@>=
  19180. mmode+math_shift: if cur_group=math_shift_group then after_math
  19181.   else off_save;
  19182. @ @<Declare act...@>=
  19183. procedure after_math;
  19184. var l:boolean; {`\.{\\leqno}' instead of `\.{\\eqno}'}
  19185. @!danger:boolean; {not enough symbol fonts are present}
  19186. @!m:integer; {|mmode| or |-mmode|}
  19187. @!p:pointer; {the formula}
  19188. @!a:pointer; {box containing equation number}
  19189. @<Local variables for finishing a displayed formula@>@;
  19190. begin danger:=false;
  19191. @<Check that the necessary fonts for math symbols are present;
  19192.   if not, flush the current math lists and set |danger:=true|@>;
  19193. m:=mode; l:=false; p:=fin_mlist(null); {this pops the nest}
  19194. if mode=-m then {end of equation number}
  19195.   begin @<Check that another \.\$ follows@>;
  19196.   cur_mlist:=p; cur_style:=text_style; mlist_penalties:=false;
  19197.   mlist_to_hlist; a:=hpack(link(temp_head),natural);
  19198.   unsave; decr(save_ptr); {now |cur_group=math_shift_group|}
  19199.   if saved(0)=1 then l:=true;
  19200.   danger:=false;
  19201.   @<Check that the necessary fonts for math symbols are present;
  19202.     if not, flush the current math lists and set |danger:=true|@>;
  19203.   m:=mode; p:=fin_mlist(null);
  19204.   end
  19205. else a:=null;
  19206. if m<0 then @<Finish math in text@>
  19207. else  begin if a=null then @<Check that another \.\$ follows@>;
  19208.   @<Finish displayed math@>;
  19209.   end;
  19210. @ @<Check that the necessary fonts...@>=
  19211. if (font_params[fam_fnt(2+text_size)]<total_mathsy_params)or@|
  19212.    (font_params[fam_fnt(2+script_size)]<total_mathsy_params)or@|
  19213.    (font_params[fam_fnt(2+script_script_size)]<total_mathsy_params) then
  19214.   begin print_err("Math formula deleted: Insufficient symbol fonts");@/
  19215. @.Math formula deleted...@>
  19216.   help3("Sorry, but I can't typeset math unless \textfont 2")@/
  19217.     ("and \scriptfont 2 and \scriptscriptfont 2 have all")@/
  19218.     ("the \fontdimen values needed in math symbol fonts.");
  19219.   error; flush_math; danger:=true;
  19220.   end
  19221. else if (font_params[fam_fnt(3+text_size)]<total_mathex_params)or@|
  19222.    (font_params[fam_fnt(3+script_size)]<total_mathex_params)or@|
  19223.    (font_params[fam_fnt(3+script_script_size)]<total_mathex_params) then
  19224.   begin print_err("Math formula deleted: Insufficient extension fonts");@/
  19225.   help3("Sorry, but I can't typeset math unless \textfont 3")@/
  19226.     ("and \scriptfont 3 and \scriptscriptfont 3 have all")@/
  19227.     ("the \fontdimen values needed in math extension fonts.");
  19228.   error; flush_math; danger:=true;
  19229.   end
  19230. @ The |unsave| is done after everything else here; hence an appearance of
  19231. `\.{\\mathsurround}' inside of `\.{\$...\$}' affects the spacing at these
  19232. particular \.\$'s. This is consistent with the conventions of
  19233. `\.{\$\$...\$\$}', since `\.{\\abovedisplayskip}' inside a display affects the
  19234. space above that display.
  19235. @<Finish math in text@>=
  19236. begin tail_append(new_math(math_surround,before));
  19237. cur_mlist:=p; cur_style:=text_style; mlist_penalties:=(mode>0); mlist_to_hlist;
  19238. link(tail):=link(temp_head);
  19239. while link(tail)<>null do tail:=link(tail);
  19240. tail_append(new_math(math_surround,after));
  19241. space_factor:=1000; unsave;
  19242. @ \TeX\ gets to the following part of the program when the first `\.\$' ending
  19243. a display has been scanned.
  19244. @<Check that another \.\$ follows@>=
  19245. begin get_x_token;
  19246. if cur_cmd<>math_shift then
  19247.   begin print_err("Display math should end with $$");
  19248. @.Display math...with \$\$@>
  19249.   help2("The `$' that I just saw supposedly matches a previous `$$'.")@/
  19250.     ("So I shall assume that you typed `$$' both times.");
  19251.   back_error;
  19252.   end;
  19253. @ We have saved the worst for last: The fussiest part of math mode processing
  19254. occurs when a displayed formula is being centered and placed with an optional
  19255. equation number.
  19256. @<Local variables for finishing...@>=
  19257. @!b:pointer; {box containing the equation}
  19258. @!w:scaled; {width of the equation}
  19259. @!z:scaled; {width of the line}
  19260. @!e:scaled; {width of equation number}
  19261. @!q:scaled; {width of equation number plus space to separate from equation}
  19262. @!d:scaled; {displacement of equation in the line}
  19263. @!s:scaled; {move the line right this much}
  19264. @!g1,@!g2:small_number; {glue parameter codes for before and after}
  19265. @!r:pointer; {kern node used to position the display}
  19266. @!t:pointer; {tail of adjustment list}
  19267. @ At this time |p| points to the mlist for the formula; |a| is either
  19268. |null| or it points to a box containing the equation number; and we are in
  19269. vertical mode (or internal vertical mode).
  19270. @<Finish displayed math@>=
  19271. cur_mlist:=p; cur_style:=display_style; mlist_penalties:=false;
  19272. mlist_to_hlist; p:=link(temp_head);@/
  19273. adjust_tail:=adjust_head; b:=hpack(p,natural); p:=list_ptr(b);
  19274. t:=adjust_tail; adjust_tail:=null;@/
  19275. w:=width(b); z:=display_width; s:=display_indent;
  19276. if (a=null)or danger then
  19277.   begin e:=0; q:=0;
  19278.   end
  19279. else  begin e:=width(a); q:=e+math_quad(text_size);
  19280.   end;
  19281. if w+q>z then
  19282.   @<Squeeze the equation as much as possible; if there is an equation
  19283.     number that should go on a separate line by itself,
  19284.     set~|e:=0|@>;
  19285. @<Determine the displacement, |d|, of the left edge of the equation, with
  19286.   respect to the line size |z|, assuming that |l=false|@>;
  19287. @<Append the glue or equation number preceding the display@>;
  19288. @<Append the display and perhaps also the equation number@>;
  19289. @<Append the glue or equation number following the display@>;
  19290. resume_after_display
  19291. @ @<Declare act...@>=
  19292. procedure resume_after_display;
  19293. begin if cur_group<>math_shift_group then confusion("display");
  19294. @:this can't happen display}{\quad display@>
  19295. unsave; prev_graf:=prev_graf+3;
  19296. push_nest; mode:=hmode; space_factor:=1000; set_cur_lang; clang:=cur_lang;
  19297. prev_graf:=(norm_min(left_hyphen_min)*@'100+norm_min(right_hyphen_min))
  19298.              *@'200000+cur_lang;
  19299. @<Scan an optional space@>;
  19300. if nest_ptr=1 then build_page;
  19301. @ The user can force the equation number to go on a separate line
  19302. by causing its width to be zero.
  19303. @<Squeeze the equation as much as possible...@>=
  19304. begin if (e<>0)and((w-total_shrink[normal]+q<=z)or@|
  19305.    (total_shrink[fil]<>0)or(total_shrink[fill]<>0)or
  19306.    (total_shrink[filll]<>0)) then
  19307.   begin free_node(b,box_node_size);
  19308.   b:=hpack(p,z-q,exactly);
  19309.   end
  19310. else  begin e:=0;
  19311.   if w>z then
  19312.     begin free_node(b,box_node_size);
  19313.     b:=hpack(p,z,exactly);
  19314.     end;
  19315.   end;
  19316. w:=width(b);
  19317. @ We try first to center the display without regard to the existence of
  19318. the equation number. If that would make it too close (where ``too close''
  19319. means that the space between display and equation number is less than the
  19320. width of the equation number), we either center it in the remaining space
  19321. or move it as far from the equation number as possible. The latter alternative
  19322. is taken only if the display begins with glue, since we assume that the
  19323. user put glue there to control the spacing precisely.
  19324. @<Determine the displacement, |d|, of the left edge of the equation...@>=
  19325. d:=half(z-w);
  19326. if (e>0)and(d<2*e) then {too close}
  19327.   begin d:=half(z-w-e);
  19328.   if p<>null then if not is_char_node(p) then if type(p)=glue_node then d:=0;
  19329.   end
  19330. @ If the equation number is set on a line by itself, either before or
  19331. after the formula, we append an infinite penalty so that no page break will
  19332. separate the display from its number; and we use the same size and
  19333. displacement for all three potential lines of the display, even though
  19334. `\.{\\parshape}' may specify them differently.
  19335. @<Append the glue or equation number preceding the display@>=
  19336. tail_append(new_penalty(pre_display_penalty));@/
  19337. if (d+s<=pre_display_size)or l then {not enough clearance}
  19338.   begin g1:=above_display_skip_code; g2:=below_display_skip_code;
  19339.   end
  19340. else  begin g1:=above_display_short_skip_code;
  19341.   g2:=below_display_short_skip_code;
  19342.   end;
  19343. if l and(e=0) then {it follows that |type(a)=hlist_node|}
  19344.   begin shift_amount(a):=s; append_to_vlist(a);
  19345.   tail_append(new_penalty(inf_penalty));
  19346.   end
  19347. else tail_append(new_param_glue(g1))
  19348. @ @<Append the display and perhaps also the equation number@>=
  19349. if e<>0 then
  19350.   begin r:=new_kern(z-w-e-d);
  19351.   if l then
  19352.     begin link(a):=r; link(r):=b; b:=a; d:=0;
  19353.     end
  19354.   else  begin link(b):=r; link(r):=a;
  19355.     end;
  19356.   b:=hpack(b,natural);
  19357.   end;
  19358. shift_amount(b):=s+d; append_to_vlist(b)
  19359. @ @<Append the glue or equation number following the display@>=
  19360. if (a<>null)and(e=0)and not l then
  19361.   begin tail_append(new_penalty(inf_penalty));
  19362.   shift_amount(a):=s+z-width(a);
  19363.   append_to_vlist(a);
  19364.   g2:=0;
  19365.   end;
  19366. if t<>adjust_head then {migrating material comes after equation number}
  19367.   begin link(tail):=link(adjust_head); tail:=t;
  19368.   end;
  19369. tail_append(new_penalty(post_display_penalty));
  19370. if g2>0 then tail_append(new_param_glue(g2))
  19371. @ When \.{\\halign} appears in a display, the alignment routines operate
  19372. essentially as they do in vertical mode. Then the following program is
  19373. activated, with |p| and |q| pointing to the beginning and end of the
  19374. resulting list, and with |aux_save| holding the |prev_depth| value.
  19375. @<Finish an alignment in a display@>=
  19376. begin do_assignments;
  19377. if cur_cmd<>math_shift then @<Pontificate about improper alignment in display@>
  19378. else @<Check that another \.\$ follows@>;
  19379. pop_nest;
  19380. tail_append(new_penalty(pre_display_penalty));
  19381. tail_append(new_param_glue(above_display_skip_code));
  19382. link(tail):=p;
  19383. if p<>null then tail:=q;
  19384. tail_append(new_penalty(post_display_penalty));
  19385. tail_append(new_param_glue(below_display_skip_code));
  19386. prev_depth:=aux_save.sc; resume_after_display;
  19387. @ @<Pontificate...@>=
  19388. begin print_err("Missing $$ inserted");
  19389. @.Missing {\$\$} inserted@>
  19390. help2("Displays can use special alignments (like \eqalignno)")@/
  19391.   ("only if nothing but the alignment itself is between $$'s.");
  19392. back_error;
  19393. @* \[49] Mode-independent processing.
  19394. The long |main_control| procedure has now been fully specified, except for
  19395. certain activities that are independent of the current mode. These activities
  19396. do not change the current vlist or hlist or mlist; if they change anything,
  19397. it is the value of a parameter or the meaning of a control sequence.
  19398. Assignments to values in |eqtb| can be global or local. Furthermore, a
  19399. control sequence can be defined to be `\.{\\long}' or `\.{\\outer}', and
  19400. it might or might not be expanded. The prefixes `\.{\\global}', `\.{\\long}',
  19401. and `\.{\\outer}' can occur in any order. Therefore we assign binary numeric
  19402. codes, making it possible to accumulate the union of all specified prefixes
  19403. by adding the corresponding codes.  (\PASCAL's |set| operations could also
  19404. have been used.)
  19405. @<Put each...@>=
  19406. primitive("long",prefix,1);
  19407. @!@:long_}{\.{\\long} primitive@>
  19408. primitive("outer",prefix,2);
  19409. @!@:outer_}{\.{\\outer} primitive@>
  19410. primitive("global",prefix,4);
  19411. @!@:global_}{\.{\\global} primitive@>
  19412. primitive("def",def,0);
  19413. @!@:def_}{\.{\\def} primitive@>
  19414. primitive("gdef",def,1);
  19415. @!@:gdef_}{\.{\\gdef} primitive@>
  19416. primitive("edef",def,2);
  19417. @!@:edef_}{\.{\\edef} primitive@>
  19418. primitive("xdef",def,3);
  19419. @!@:xdef_}{\.{\\xdef} primitive@>
  19420. @ @<Cases of |print_cmd_chr|...@>=
  19421. prefix: if chr_code=1 then print_esc("long")
  19422.   else if chr_code=2 then print_esc("outer")
  19423.   else print_esc("global");
  19424. def: if chr_code=0 then print_esc("def")
  19425.   else if chr_code=1 then print_esc("gdef")
  19426.   else if chr_code=2 then print_esc("edef")
  19427.   else print_esc("xdef");
  19428. @ Every prefix, and every command code that might or might not be prefixed,
  19429. calls the action procedure |prefixed_command|. This routine accumulates
  19430. a sequence of prefixes until coming to a non-prefix, then it carries out
  19431. the command.
  19432. @<Cases of |main_control| that don't...@>=
  19433. any_mode(toks_register),
  19434. any_mode(assign_toks),
  19435. any_mode(assign_int),
  19436. any_mode(assign_dimen),
  19437. any_mode(assign_glue),
  19438. any_mode(assign_mu_glue),
  19439. any_mode(assign_font_dimen),
  19440. any_mode(assign_font_int),
  19441. any_mode(set_aux),
  19442. any_mode(set_prev_graf),
  19443. any_mode(set_page_dimen),
  19444. any_mode(set_page_int),
  19445. any_mode(set_box_dimen),
  19446. any_mode(set_shape),
  19447. any_mode(def_code),
  19448. any_mode(def_family),
  19449. any_mode(set_font),
  19450. any_mode(def_font),
  19451. any_mode(register),
  19452. any_mode(advance),
  19453. any_mode(multiply),
  19454. any_mode(divide),
  19455. any_mode(prefix),
  19456. any_mode(let),
  19457. any_mode(shorthand_def),
  19458. any_mode(read_to_cs),
  19459. any_mode(def),
  19460. any_mode(set_box),
  19461. any_mode(hyph_data),
  19462. any_mode(set_interaction):prefixed_command;
  19463. @ If the user says, e.g., `\.{\\global\\global}', the redundancy is
  19464. silently accepted.
  19465. @<Declare act...@>=
  19466. @t\4@>@<Declare subprocedures for |prefixed_command|@>@t@>@;@/
  19467. procedure prefixed_command;
  19468. label done,exit;
  19469. var a:small_number; {accumulated prefix codes so far}
  19470. @!f:internal_font_number; {identifies a font}
  19471. @!j:halfword; {index into a \.{\\parshape} specification}
  19472. @!k:font_index; {index into |font_info|}
  19473. @!p,@!q:pointer; {for temporary short-term use}
  19474. @!n:integer; {ditto}
  19475. @!e:boolean; {should a definition be expanded? or was \.{\\let} not done?}
  19476. begin a:=0;
  19477. while cur_cmd=prefix do
  19478.   begin if not odd(a div cur_chr) then a:=a+cur_chr;
  19479.   @<Get the next non-blank non-relax...@>;
  19480.   if cur_cmd<=max_non_prefixed_command then
  19481.     @<Discard erroneous prefixes and |return|@>;
  19482.   end;
  19483. @<Discard the prefixes \.{\\long} and \.{\\outer} if they are irrelevant@>;
  19484. @<Adjust \(f)for the setting of \.{\\globaldefs}@>;
  19485. case cur_cmd of
  19486. @t\4@>@<Assignments@>@;
  19487. othercases confusion("prefix")
  19488. @:this can't happen prefix}{\quad prefix@>
  19489. endcases;
  19490. done: @<Insert a token saved by \.{\\afterassignment}, if any@>;
  19491. exit:end;
  19492. @ @<Discard erroneous...@>=
  19493. begin print_err("You can't use a prefix with `");
  19494. @.You can't use a prefix with x@>
  19495. print_cmd_chr(cur_cmd,cur_chr); print_char("'");
  19496. help1("I'll pretend you didn't say \long or \outer or \global.");
  19497. back_error; return;
  19498. @ @<Discard the prefixes...@>=
  19499. if (cur_cmd<>def)and(a mod 4<>0) then
  19500.   begin print_err("You can't use `"); print_esc("long"); print("' or `");
  19501.   print_esc("outer"); print("' with `");
  19502. @.You can't use \\long...@>
  19503.   print_cmd_chr(cur_cmd,cur_chr); print_char("'");
  19504.   help1("I'll pretend you didn't say \long or \outer here.");
  19505.   error;
  19506.   end
  19507. @ The previous routine does not have to adjust |a| so that |a mod 4=0|,
  19508. since the following routines test for the \.{\\global} prefix as follows.
  19509. @d global==(a>=4)
  19510. @d define(#)==if global then geq_define(#)@+else eq_define(#)
  19511. @d word_define(#)==if global then geq_word_define(#)@+else eq_word_define(#)
  19512. @<Adjust \(f)for the setting of \.{\\globaldefs}@>=
  19513. if global_defs<>0 then
  19514.   if global_defs<0 then
  19515.     begin if global then a:=a-4;
  19516.     end
  19517.   else  begin if not global then a:=a+4;
  19518.     end
  19519. @ When a control sequence is to be defined, by \.{\\def} or \.{\\let} or
  19520. something similar, the |get_r_token| routine will substitute a special
  19521. control sequence for a token that is not redefinable.
  19522. @<Declare subprocedures for |prefixed_command|@>=
  19523. procedure get_r_token;
  19524. label restart;
  19525. begin restart: repeat get_token;
  19526. until cur_tok<>space_token;
  19527. if (cur_cs=0)or(cur_cs>frozen_control_sequence) then
  19528.   begin print_err("Missing control sequence inserted");
  19529. @.Missing control...@>
  19530.   help5("Please don't say `\def cs{...}', say `\def\cs{...}'.")@/
  19531.   ("I've inserted an inaccessible control sequence so that your")@/
  19532.   ("definition will be completed without mixing me up too badly.")@/
  19533.   ("You can recover graciously from this error, if you're")@/
  19534.   ("careful; see exercise 27.2 in The TeXbook.");
  19535. @:TeXbook}{\sl The \TeX book@>
  19536.   if cur_cs=0 then back_input;
  19537.   cur_tok:=cs_token_flag+frozen_protection; ins_error; goto restart;
  19538.   end;
  19539. @ @<Initialize table entries...@>=
  19540. text(frozen_protection):="inaccessible";
  19541. @ Here's an example of the way many of the following routines operate.
  19542. (Unfortunately, they aren't all as simple as this.)
  19543. @<Assignments@>=
  19544. set_font: define(cur_font_loc,data,cur_chr);
  19545. @ When a |def| command has been scanned,
  19546. |cur_chr| is odd if the definition is supposed to be global, and
  19547. |cur_chr>=2| if the definition is supposed to be expanded.
  19548. @<Assignments@>=
  19549. def: begin if odd(cur_chr)and not global and(global_defs>=0) then a:=a+4;
  19550.   e:=(cur_chr>=2); get_r_token; p:=cur_cs;
  19551.   q:=scan_toks(true,e); define(p,call+(a mod 4),def_ref);
  19552.   end;
  19553. @ Both \.{\\let} and \.{\\futurelet} share the command code |let|.
  19554. @<Put each...@>=
  19555. primitive("let",let,normal);@/
  19556. @!@:let_}{\.{\\let} primitive@>
  19557. primitive("futurelet",let,normal+1);@/
  19558. @!@:future_let_}{\.{\\futurelet} primitive@>
  19559. @ @<Cases of |print_cmd_chr|...@>=
  19560. let: if chr_code<>normal then print_esc("futurelet")@+else print_esc("let");
  19561. @ @<Assignments@>=
  19562. let:  begin n:=cur_chr;
  19563.   get_r_token; p:=cur_cs;
  19564.   if n=normal then
  19565.     begin repeat get_token;
  19566.     until cur_cmd<>spacer;
  19567.     if cur_tok=other_token+"=" then
  19568.       begin get_token;
  19569.       if cur_cmd=spacer then get_token;
  19570.       end;
  19571.     end
  19572.   else  begin get_token; q:=cur_tok; get_token; back_input;
  19573.     cur_tok:=q; back_input; {look ahead, then back up}
  19574.     end; {note that |back_input| doesn't affect |cur_cmd|, |cur_chr|}
  19575.   if cur_cmd>=call then add_token_ref(cur_chr);
  19576.   define(p,cur_cmd,cur_chr);
  19577.   end;
  19578. @ A \.{\\chardef} creates a control sequence whose |cmd| is |char_given|;
  19579. a \.{\\mathchardef} creates a control sequence whose |cmd| is |math_given|;
  19580. and the corresponding |chr| is the character code or math code. A \.{\\countdef}
  19581. or \.{\\dimendef} or \.{\\skipdef} or \.{\\muskipdef} creates a control
  19582. sequence whose |cmd| is |assign_int| or \dots\ or |assign_mu_glue|, and the
  19583. corresponding |chr| is the |eqtb| location of the internal register in question.
  19584. @d char_def_code=0 {|shorthand_def| for \.{\\chardef}}
  19585. @d math_char_def_code=1 {|shorthand_def| for \.{\\mathchardef}}
  19586. @d count_def_code=2 {|shorthand_def| for \.{\\countdef}}
  19587. @d dimen_def_code=3 {|shorthand_def| for \.{\\dimendef}}
  19588. @d skip_def_code=4 {|shorthand_def| for \.{\\skipdef}}
  19589. @d mu_skip_def_code=5 {|shorthand_def| for \.{\\muskipdef}}
  19590. @d toks_def_code=6 {|shorthand_def| for \.{\\toksdef}}
  19591. @<Put each...@>=
  19592. primitive("chardef",shorthand_def,char_def_code);@/
  19593. @!@:char_def_}{\.{\\chardef} primitive@>
  19594. primitive("mathchardef",shorthand_def,math_char_def_code);@/
  19595. @!@:math_char_def_}{\.{\\mathchardef} primitive@>
  19596. primitive("countdef",shorthand_def,count_def_code);@/
  19597. @!@:count_def_}{\.{\\countdef} primitive@>
  19598. primitive("dimendef",shorthand_def,dimen_def_code);@/
  19599. @!@:dimen_def_}{\.{\\dimendef} primitive@>
  19600. primitive("skipdef",shorthand_def,skip_def_code);@/
  19601. @!@:skip_def_}{\.{\\skipdef} primitive@>
  19602. primitive("muskipdef",shorthand_def,mu_skip_def_code);@/
  19603. @!@:mu_skip_def_}{\.{\\muskipdef} primitive@>
  19604. primitive("toksdef",shorthand_def,toks_def_code);@/
  19605. @!@:toks_def_}{\.{\\toksdef} primitive@>
  19606. @ @<Cases of |print_cmd_chr|...@>=
  19607. shorthand_def: case chr_code of
  19608.   char_def_code: print_esc("chardef");
  19609.   math_char_def_code: print_esc("mathchardef");
  19610.   count_def_code: print_esc("countdef");
  19611.   dimen_def_code: print_esc("dimendef");
  19612.   skip_def_code: print_esc("skipdef");
  19613.   mu_skip_def_code: print_esc("muskipdef");
  19614.   othercases print_esc("toksdef")
  19615.   endcases;
  19616. char_given: begin print_esc("char"); print_hex(chr_code);
  19617.   end;
  19618. math_given: begin print_esc("mathchar"); print_hex(chr_code);
  19619.   end;
  19620. @ We temporarily define |p| to be |relax|, so that an occurrence of |p|
  19621. while scanning the definition will simply stop the scanning instead of
  19622. producing an ``undefined control sequence'' error or expanding the
  19623. previous meaning.  This allows, for instance, `\.{\\chardef\\foo=123\\foo}'.
  19624. @<Assignments@>=
  19625. shorthand_def: begin n:=cur_chr; get_r_token; p:=cur_cs; define(p,relax,256);
  19626.   scan_optional_equals;
  19627.   case n of
  19628.   char_def_code: begin scan_char_num; define(p,char_given,cur_val);
  19629.     end;
  19630.   math_char_def_code: begin scan_fifteen_bit_int; define(p,math_given,cur_val);
  19631.     end;
  19632.   othercases begin scan_eight_bit_int;
  19633.     case n of
  19634.     count_def_code: define(p,assign_int,count_base+cur_val);
  19635.     dimen_def_code: define(p,assign_dimen,scaled_base+cur_val);
  19636.     skip_def_code: define(p,assign_glue,skip_base+cur_val);
  19637.     mu_skip_def_code: define(p,assign_mu_glue,mu_skip_base+cur_val);
  19638.     toks_def_code: define(p,assign_toks,toks_base+cur_val);
  19639.     end; {there are no other cases}
  19640.     end
  19641.   endcases;
  19642.   end;
  19643. @ @<Assignments@>=
  19644. read_to_cs: begin scan_int; n:=cur_val;
  19645.   if not scan_keyword("to") then
  19646.     begin print_err("Missing `to' inserted");
  19647. @.Missing `to'...@>
  19648.     help2("You should have said `\read<number> to \cs'.")@/
  19649.     ("I'm going to look for the \cs now."); error;
  19650.     end;
  19651.   get_r_token;
  19652.   p:=cur_cs; read_toks(n,p); define(p,call,cur_val);
  19653.   end;
  19654. @ The token-list parameters, \.{\\output} and \.{\\everypar}, etc., receive
  19655. their values in the following way. (For safety's sake, we place an
  19656. enclosing pair of braces around an \.{\\output} list.)
  19657. @<Assignments@>=
  19658. toks_register,assign_toks: begin q:=cur_cs;
  19659.   if cur_cmd=toks_register then
  19660.     begin scan_eight_bit_int; p:=toks_base+cur_val;
  19661.     end
  19662.   else p:=cur_chr; {|p=every_par_loc| or |output_routine_loc| or \dots}
  19663.   scan_optional_equals;
  19664.   @<Get the next non-blank non-relax non-call token@>;
  19665.   if cur_cmd<>left_brace then @<If the right-hand side is a token parameter
  19666.       or token register, finish the assignment and |goto done|@>;
  19667.   back_input; cur_cs:=q; q:=scan_toks(false,false);
  19668.   if link(def_ref)=null then {empty list: revert to the default}
  19669.     begin define(p,undefined_cs,null); free_avail(def_ref);
  19670.     end
  19671.   else  begin if p=output_routine_loc then {enclose in curlies}
  19672.       begin link(q):=get_avail; q:=link(q);
  19673.       info(q):=right_brace_token+"}";
  19674.       q:=get_avail; info(q):=left_brace_token+"{";
  19675.       link(q):=link(def_ref); link(def_ref):=q;
  19676.       end;
  19677.     define(p,call,def_ref);
  19678.     end;
  19679.   end;
  19680. @ @<If the right-hand side is a token parameter...@>=
  19681. begin if cur_cmd=toks_register then
  19682.   begin scan_eight_bit_int; cur_cmd:=assign_toks; cur_chr:=toks_base+cur_val;
  19683.   end;
  19684. if cur_cmd=assign_toks then
  19685.   begin q:=equiv(cur_chr);
  19686.   if q=null then define(p,undefined_cs,null)
  19687.   else  begin add_token_ref(q); define(p,call,q);
  19688.     end;
  19689.   goto done;
  19690.   end;
  19691. @ Similar routines are used to assign values to the numeric parameters.
  19692. @<Assignments@>=
  19693. assign_int: begin p:=cur_chr; scan_optional_equals; scan_int;
  19694.   word_define(p,cur_val);
  19695.   end;
  19696. assign_dimen: begin p:=cur_chr; scan_optional_equals;
  19697.   scan_normal_dimen; word_define(p,cur_val);
  19698.   end;
  19699. assign_glue,assign_mu_glue: begin p:=cur_chr; n:=cur_cmd; scan_optional_equals;
  19700.   if n=assign_mu_glue then scan_glue(mu_val)@+else scan_glue(glue_val);
  19701.   trap_zero_glue;
  19702.   define(p,glue_ref,cur_val);
  19703.   end;
  19704. @ When a glue register or parameter becomes zero, it will always point to
  19705. |zero_glue| because of the following procedure.
  19706. @<Declare subprocedures for |prefixed_command|@>=
  19707. procedure trap_zero_glue;
  19708. begin if (width(cur_val)=0)and(stretch(cur_val)=0)and(shrink(cur_val)=0) then
  19709.   begin add_glue_ref(zero_glue);
  19710.   delete_glue_ref(cur_val); cur_val:=zero_glue;
  19711.   end;
  19712. @ The various character code tables are changed by the |def_code| commands,
  19713. and the font families are declared by |def_family|.
  19714. @<Put each...@>=
  19715. primitive("catcode",def_code,cat_code_base);
  19716. @!@:cat_code_}{\.{\\catcode} primitive@>
  19717. primitive("mathcode",def_code,math_code_base);
  19718. @!@:math_code_}{\.{\\mathcode} primitive@>
  19719. primitive("lccode",def_code,lc_code_base);
  19720. @!@:lc_code_}{\.{\\lccode} primitive@>
  19721. primitive("uccode",def_code,uc_code_base);
  19722. @!@:uc_code_}{\.{\\uccode} primitive@>
  19723. primitive("sfcode",def_code,sf_code_base);
  19724. @!@:sf_code_}{\.{\\sfcode} primitive@>
  19725. primitive("delcode",def_code,del_code_base);
  19726. @!@:del_code_}{\.{\\delcode} primitive@>
  19727. primitive("textfont",def_family,math_font_base);
  19728. @!@:text_font_}{\.{\\textfont} primitive@>
  19729. primitive("scriptfont",def_family,math_font_base+script_size);
  19730. @!@:script_font_}{\.{\\scriptfont} primitive@>
  19731. primitive("scriptscriptfont",def_family,math_font_base+script_script_size);
  19732. @!@:script_script_font_}{\.{\\scriptscriptfont} primitive@>
  19733. @ @<Cases of |print_cmd_chr|...@>=
  19734. def_code: if chr_code=cat_code_base then print_esc("catcode")
  19735.   else if chr_code=math_code_base then print_esc("mathcode")
  19736.   else if chr_code=lc_code_base then print_esc("lccode")
  19737.   else if chr_code=uc_code_base then print_esc("uccode")
  19738.   else if chr_code=sf_code_base then print_esc("sfcode")
  19739.   else print_esc("delcode");
  19740. def_family: print_size(chr_code-math_font_base);
  19741. @ The different types of code values have different legal ranges; the
  19742. following program is careful to check each case properly.
  19743. @<Assignments@>=
  19744. def_code: begin @<Let |n| be the largest legal code value, based on |cur_chr|@>;
  19745.   p:=cur_chr; scan_char_num; p:=p+cur_val; scan_optional_equals;
  19746.   scan_int;
  19747.   if ((cur_val<0)and(p<del_code_base))or(cur_val>n) then
  19748.     begin print_err("Invalid code ("); print_int(cur_val);
  19749. @.Invalid code@>
  19750.     if p<del_code_base then print("), should be in the range 0..")
  19751.     else print("), should be at most ");
  19752.     print_int(n);
  19753.     help1("I'm going to use 0 instead of that illegal code value.");@/
  19754.     error; cur_val:=0;
  19755.     end;
  19756.   if p<math_code_base then define(p,data,cur_val)
  19757.   else if p<del_code_base then define(p,data,hi(cur_val))
  19758.   else word_define(p,cur_val);
  19759.   end;
  19760. @ @<Let |n| be the largest...@>=
  19761. if cur_chr=cat_code_base then n:=max_char_code
  19762. else if cur_chr=math_code_base then n:=@'100000
  19763. else if cur_chr=sf_code_base then n:=@'77777
  19764. else if cur_chr=del_code_base then n:=@'77777777
  19765. else n:=255
  19766. @ @<Assignments@>=
  19767. def_family: begin p:=cur_chr; scan_four_bit_int; p:=p+cur_val;
  19768.   scan_optional_equals; scan_font_ident; define(p,data,cur_val);
  19769.   end;
  19770. @ Next we consider changes to \TeX's numeric registers.
  19771. @<Assignments@>=
  19772. register,advance,multiply,divide: do_register_command(a);
  19773. @ We use the fact that |register<advance<multiply<divide|.
  19774. @<Declare subprocedures for |prefixed_command|@>=
  19775. procedure do_register_command(@!a:small_number);
  19776. label found,exit;
  19777. var l,@!q,@!r,@!s:pointer; {for list manipulation}
  19778. @!p:int_val..mu_val; {type of register involved}
  19779. begin q:=cur_cmd;
  19780. @<Compute the register location |l| and its type |p|; but |return| if invalid@>;
  19781. if q=register then scan_optional_equals
  19782. else if scan_keyword("by") then do_nothing; {optional `\.{by}'}
  19783. arith_error:=false;
  19784. if q<multiply then @<Compute result of |register| or
  19785.     |advance|, put it in |cur_val|@>
  19786. else @<Compute result of |multiply| or |divide|, put it in |cur_val|@>;
  19787. if arith_error then
  19788.   begin print_err("Arithmetic overflow");
  19789. @.Arithmetic overflow@>
  19790.   help2("I can't carry out that multiplication or division,")@/
  19791.     ("since the result is out of range.");
  19792.   error; return;
  19793.   end;
  19794. if p<glue_val then word_define(l,cur_val)
  19795. else  begin trap_zero_glue; define(l,glue_ref,cur_val);
  19796.   end;
  19797. exit: end;
  19798. @ Here we use the fact that the consecutive codes |int_val...mu_val| and
  19799. |assign_int..assign_mu_glue| correspond to each other nicely.
  19800. @<Compute the register location |l| and its type |p|...@>=
  19801. begin if q<>register then
  19802.   begin get_x_token;
  19803.   if (cur_cmd>=assign_int)and(cur_cmd<=assign_mu_glue) then
  19804.     begin l:=cur_chr; p:=cur_cmd-assign_int; goto found;
  19805.     end;
  19806.   if cur_cmd<>register then
  19807.     begin print_err("You can't use `"); print_cmd_chr(cur_cmd,cur_chr);
  19808. @.You can't use x after ...@>
  19809.     print("' after "); print_cmd_chr(q,0);
  19810.     help1("I'm forgetting what you said and not changing anything.");
  19811.     error; return;
  19812.     end;
  19813.   end;
  19814. p:=cur_chr; scan_eight_bit_int;
  19815. case p of
  19816. int_val: l:=cur_val+count_base;
  19817. dimen_val: l:=cur_val+scaled_base;
  19818. glue_val: l:=cur_val+skip_base;
  19819. mu_val: l:=cur_val+mu_skip_base;
  19820. end; {there are no other cases}
  19821. found:
  19822. @ @<Compute result of |register| or |advance|...@>=
  19823. if p<glue_val then
  19824.   begin if p=int_val then scan_int@+else scan_normal_dimen;
  19825.   if q=advance then cur_val:=cur_val+eqtb[l].int;
  19826.   end
  19827. else  begin scan_glue(p);
  19828.   if q=advance then @<Compute the sum of two glue specs@>;
  19829.   end
  19830. @ @<Compute the sum of two glue specs@>=
  19831. begin q:=new_spec(cur_val); r:=equiv(l);
  19832. delete_glue_ref(cur_val);
  19833. width(q):=width(q)+width(r);
  19834. if stretch(q)=0 then stretch_order(q):=normal;
  19835. if stretch_order(q)=stretch_order(r) then stretch(q):=stretch(q)+stretch(r)
  19836. else if (stretch_order(q)<stretch_order(r))and(stretch(r)<>0) then
  19837.   begin stretch(q):=stretch(r); stretch_order(q):=stretch_order(r);
  19838.   end;
  19839. if shrink(q)=0 then shrink_order(q):=normal;
  19840. if shrink_order(q)=shrink_order(r) then shrink(q):=shrink(q)+shrink(r)
  19841. else if (shrink_order(q)<shrink_order(r))and(shrink(r)<>0) then
  19842.   begin shrink(q):=shrink(r); shrink_order(q):=shrink_order(r);
  19843.   end;
  19844. cur_val:=q;
  19845. @ @<Compute result of |multiply| or |divide|...@>=
  19846. begin scan_int;
  19847. if p<glue_val then
  19848.   if q=multiply then
  19849.     if p=int_val then cur_val:=mult_integers(eqtb[l].int,cur_val)
  19850.     else cur_val:=nx_plus_y(eqtb[l].int,cur_val,0)
  19851.   else cur_val:=x_over_n(eqtb[l].int,cur_val)
  19852. else  begin s:=equiv(l); r:=new_spec(s);
  19853.   if q=multiply then
  19854.     begin width(r):=nx_plus_y(width(s),cur_val,0);
  19855.     stretch(r):=nx_plus_y(stretch(s),cur_val,0);
  19856.     shrink(r):=nx_plus_y(shrink(s),cur_val,0);
  19857.     end
  19858.   else  begin width(r):=x_over_n(width(s),cur_val);
  19859.     stretch(r):=x_over_n(stretch(s),cur_val);
  19860.     shrink(r):=x_over_n(shrink(s),cur_val);
  19861.     end;
  19862.   cur_val:=r;
  19863.   end;
  19864. @ The processing of boxes is somewhat different, because we may need
  19865. to scan and create an entire box before we actually change the value of the old
  19866. @<Assignments@>=
  19867. set_box: begin scan_eight_bit_int;
  19868.   if global then n:=256+cur_val@+else n:=cur_val;
  19869.   scan_optional_equals;
  19870.   if set_box_allowed then scan_box(box_flag+n)
  19871.   else begin print_err("Improper "); print_esc("setbox");
  19872. @.Improper \\setbox@>
  19873.     help2("Sorry, \setbox is not allowed after \halign in a display,")@/
  19874.     ("or between \accent and an accented character."); error;
  19875.     end;
  19876.   end;
  19877. @ The |space_factor| or |prev_depth| settings are changed when a |set_aux|
  19878. command is sensed. Similarly, |prev_graf| is changed in the presence of
  19879. |set_prev_graf|, and |dead_cycles| or |insert_penalties| in the presence of
  19880. |set_page_int|. These definitions are always global.
  19881. When some dimension of a box register is changed, the change isn't exactly
  19882. global; but \TeX\ does not look at the \.{\\global} switch.
  19883. @<Assignments@>=
  19884. set_aux:alter_aux;
  19885. set_prev_graf:alter_prev_graf;
  19886. set_page_dimen:alter_page_so_far;
  19887. set_page_int:alter_integer;
  19888. set_box_dimen:alter_box_dimen;
  19889. @ @<Declare subprocedures for |prefixed_command|@>=
  19890. procedure alter_aux;
  19891. var c:halfword; {|hmode| or |vmode|}
  19892. begin if cur_chr<>abs(mode) then report_illegal_case
  19893. else  begin c:=cur_chr; scan_optional_equals;
  19894.   if c=vmode then
  19895.     begin scan_normal_dimen; prev_depth:=cur_val;
  19896.     end
  19897.   else  begin scan_int;
  19898.     if (cur_val<=0)or(cur_val>32767) then
  19899.       begin print_err("Bad space factor");
  19900. @.Bad space factor@>
  19901.       help1("I allow only values in the range 1..32767 here.");
  19902.       int_error(cur_val);
  19903.       end
  19904.     else space_factor:=cur_val;
  19905.     end;
  19906.   end;
  19907. @ @<Declare subprocedures for |prefixed_command|@>=
  19908. procedure alter_prev_graf;
  19909. var p:0..nest_size; {index into |nest|}
  19910. begin nest[nest_ptr]:=cur_list; p:=nest_ptr;
  19911. while abs(nest[p].mode_field)<>vmode do decr(p);
  19912. scan_optional_equals; scan_int;
  19913. if cur_val<0 then
  19914.   begin print_err("Bad "); print_esc("prevgraf");
  19915. @.Bad \\prevgraf@>
  19916.   help1("I allow only nonnegative values here.");
  19917.   int_error(cur_val);
  19918.   end
  19919. else  begin nest[p].pg_field:=cur_val; cur_list:=nest[nest_ptr];
  19920.   end;
  19921. @ @<Declare subprocedures for |prefixed_command|@>=
  19922. procedure alter_page_so_far;
  19923. var c:0..7; {index into |page_so_far|}
  19924. begin c:=cur_chr; scan_optional_equals; scan_normal_dimen;
  19925. page_so_far[c]:=cur_val;
  19926. @ @<Declare subprocedures for |prefixed_command|@>=
  19927. procedure alter_integer;
  19928. var c:0..1; {0 for \.{\\deadcycles}, 1 for \.{\\insertpenalties}}
  19929. begin c:=cur_chr; scan_optional_equals; scan_int;
  19930. if c=0 then dead_cycles:=cur_val
  19931. else insert_penalties:=cur_val;
  19932. @ @<Declare subprocedures for |prefixed_command|@>=
  19933. procedure alter_box_dimen;
  19934. var c:small_number; {|width_offset| or |height_offset| or |depth_offset|}
  19935. @!b:eight_bits; {box number}
  19936. begin c:=cur_chr; scan_eight_bit_int; b:=cur_val; scan_optional_equals;
  19937. scan_normal_dimen;
  19938. if box(b)<>null then mem[box(b)+c].sc:=cur_val;
  19939. @ Paragraph shapes are set up in the obvious way.
  19940. @<Assignments@>=
  19941. set_shape: begin scan_optional_equals; scan_int; n:=cur_val;
  19942.   if n<=0 then p:=null
  19943.   else  begin p:=get_node(2*n+1); info(p):=n;
  19944.     for j:=1 to n do
  19945.       begin scan_normal_dimen;
  19946.       mem[p+2*j-1].sc:=cur_val; {indentation}
  19947.       scan_normal_dimen;
  19948.       mem[p+2*j].sc:=cur_val; {width}
  19949.       end;
  19950.     end;
  19951.   define(par_shape_loc,shape_ref,p);
  19952.   end;
  19953. @ Here's something that isn't quite so obvious. It guarantees that
  19954. |info(par_shape_ptr)| can hold any positive~|n| for which |get_node(2*n+1)|
  19955. doesn't overflow the memory capacity.
  19956. @<Check the ``constant''...@>=
  19957. if 2*max_halfword<mem_top-mem_min then bad:=41;
  19958. @ New hyphenation data is loaded by the |hyph_data| command.
  19959. @<Put each...@>=
  19960. primitive("hyphenation",hyph_data,0);
  19961. @!@:hyphenation_}{\.{\\hyphenation} primitive@>
  19962. primitive("patterns",hyph_data,1);
  19963. @!@:patterns_}{\.{\\patterns} primitive@>
  19964. @ @<Cases of |print_cmd_chr|...@>=
  19965. hyph_data: if chr_code=1 then print_esc("patterns")
  19966.   else print_esc("hyphenation");
  19967. @ @<Assignments@>=
  19968. hyph_data: if cur_chr=1 then
  19969.     begin @!init new_patterns; goto done;@;@+tini@/
  19970.     print_err("Patterns can be loaded only by INITEX");
  19971. @.Patterns can be...@>
  19972.     help0; error;
  19973.     repeat get_token; until cur_cmd=right_brace; {flush the patterns}
  19974.     return;
  19975.     end
  19976.   else  begin new_hyph_exceptions; goto done;
  19977.     end;
  19978. @ All of \TeX's parameters are kept in |eqtb| except the font information,
  19979. the interaction mode, and the hyphenation tables; these are strictly global.
  19980. @<Assignments@>=
  19981. assign_font_dimen: begin find_font_dimen(true); k:=cur_val;
  19982.   scan_optional_equals; scan_normal_dimen; font_info[k].sc:=cur_val;
  19983.   end;
  19984. assign_font_int: begin n:=cur_chr; scan_font_ident; f:=cur_val;
  19985.   scan_optional_equals; scan_int;
  19986.   if n=0 then hyphen_char[f]:=cur_val@+else skew_char[f]:=cur_val;
  19987.   end;
  19988. @ @<Put each...@>=
  19989. primitive("hyphenchar",assign_font_int,0);
  19990. @!@:hyphen_char_}{\.{\\hyphenchar} primitive@>
  19991. primitive("skewchar",assign_font_int,1);
  19992. @!@:skew_char_}{\.{\\skewchar} primitive@>
  19993. @ @<Cases of |print_cmd_chr|...@>=
  19994. assign_font_int: if chr_code=0 then print_esc("hyphenchar")
  19995.   else print_esc("skewchar");
  19996. @ Here is where the information for a new font gets loaded.
  19997. @<Assignments@>=
  19998. def_font: new_font(a);
  19999. @ @<Declare subprocedures for |prefixed_command|@>=
  20000. procedure new_font(@!a:small_number);
  20001. label common_ending;
  20002. var u:pointer; {user's font identifier}
  20003. @!s:scaled; {stated ``at'' size, or negative of scaled magnification}
  20004. @!f:internal_font_number; {runs through existing fonts}
  20005. @!t:str_number; {name for the frozen font identifier}
  20006. @!old_setting:0..max_selector; {holds |selector| setting}
  20007. @!flushable_string:str_number; {string not yet referenced}
  20008. begin if job_name=0 then open_log_file;
  20009.   {avoid confusing \.{texput} with the font name}
  20010. @.texput@>
  20011. get_r_token; u:=cur_cs;
  20012. if u>=hash_base then t:=text(u)
  20013. else if u>=single_base then
  20014.   if u=null_cs then t:="FONT"@+else t:=u-single_base
  20015. else  begin old_setting:=selector; selector:=new_string;
  20016.   print("FONT"); print(u-active_base); selector:=old_setting;
  20017. @.FONTx@>
  20018.   str_room(1); t:=make_string;
  20019.   end;
  20020. define(u,set_font,null_font); scan_optional_equals; scan_file_name;
  20021. @<Scan the font size specification@>;
  20022. @<If this font has already been loaded, set |f| to the internal
  20023.   font number and |goto common_ending|@>;
  20024. f:=read_font_info(u,cur_name,cur_area,s);
  20025. common_ending: equiv(u):=f; eqtb[font_id_base+f]:=eqtb[u]; font_id_text(f):=t;
  20026. @ @<Scan the font size specification@>=
  20027. name_in_progress:=true; {this keeps |cur_name| from being changed}
  20028. if scan_keyword("at") then @<Put the \(p)(positive) `at' size into |s|@>
  20029. @.at@>
  20030. else if scan_keyword("scaled") then
  20031. @.scaled@>
  20032.   begin scan_int; s:=-cur_val;
  20033.   if (cur_val<=0)or(cur_val>32768) then
  20034.     begin print_err("Illegal magnification has been changed to 1000");@/
  20035. @.Illegal magnification...@>
  20036.     help1("The magnification ratio must be between 1 and 32768.");
  20037.     int_error(cur_val); s:=-1000;
  20038.     end;
  20039.   end
  20040. else s:=-1000;
  20041. name_in_progress:=false
  20042. @ @<Put the \(p)(positive) `at' size into |s|@>=
  20043. begin scan_normal_dimen; s:=cur_val;
  20044. if (s<=0)or(s>=@'1000000000) then
  20045.   begin print_err("Improper `at' size (");
  20046.   print_scaled(s); print("pt), replaced by 10pt");
  20047. @.Improper `at' size...@>
  20048.   help2("I can only handle fonts at positive sizes that are")@/
  20049.   ("less than 2048pt, so I've changed what you said to 10pt.");
  20050.   error; s:=10*unity;
  20051.   end;
  20052. @ When the user gives a new identifier to a font that was previously loaded,
  20053. the new name becomes the font identifier of record. Font names `\.{xyz}' and
  20054. `\.{XYZ}' are considered to be different.
  20055. @<If this font has already been loaded...@>=
  20056. flushable_string:=str_ptr-1;
  20057. for f:=font_base+1 to font_ptr do
  20058.   if str_eq_str(font_name[f],cur_name)and str_eq_str(font_area[f],cur_area) then
  20059.     begin if cur_name=flushable_string then
  20060.       begin flush_string; cur_name:=font_name[f];
  20061.       end;
  20062.     if s>0 then
  20063.       begin if s=font_size[f] then goto common_ending;
  20064.       end
  20065.     else if font_size[f]=xn_over_d(font_dsize[f],-s,1000) then
  20066.       goto common_ending;
  20067.     end
  20068. @ @<Cases of |print_cmd_chr|...@>=
  20069. set_font:begin print("select font "); slow_print(font_name[chr_code]);
  20070.   if font_size[chr_code]<>font_dsize[chr_code] then
  20071.     begin print(" at "); print_scaled(font_size[chr_code]);
  20072.     print("pt");
  20073.     end;
  20074.   end;
  20075. @ @<Put each...@>=
  20076. primitive("batchmode",set_interaction,batch_mode);
  20077. @!@:batch_mode_}{\.{\\batchmode} primitive@>
  20078. primitive("nonstopmode",set_interaction,nonstop_mode);
  20079. @!@:nonstop_mode_}{\.{\\nonstopmode} primitive@>
  20080. primitive("scrollmode",set_interaction,scroll_mode);
  20081. @!@:scroll_mode_}{\.{\\scrollmode} primitive@>
  20082. primitive("errorstopmode",set_interaction,error_stop_mode);
  20083. @!@:error_stop_mode_}{\.{\\errorstopmode} primitive@>
  20084. @ @<Cases of |print_cmd_chr|...@>=
  20085. set_interaction: case chr_code of
  20086.   batch_mode: print_esc("batchmode");
  20087.   nonstop_mode: print_esc("nonstopmode");
  20088.   scroll_mode: print_esc("scrollmode");
  20089.   othercases print_esc("errorstopmode")
  20090.   endcases;
  20091. @ @<Assignments@>=
  20092. set_interaction: new_interaction;
  20093. @ @<Declare subprocedures for |prefixed_command|@>=
  20094. procedure new_interaction;
  20095. begin print_ln;
  20096. interaction:=cur_chr;
  20097. @<Initialize the print |selector| based on |interaction|@>;
  20098. if log_opened then selector:=selector+2;
  20099. @ The \.{\\afterassignment} command puts a token into the global
  20100. variable |after_token|. This global variable is examined just after
  20101. every assignment has been performed.
  20102. @<Glob...@>=
  20103. @!after_token:halfword; {zero, or a saved token}
  20104. @ @<Set init...@>=
  20105. after_token:=0;
  20106. @ @<Cases of |main_control| that don't...@>=
  20107. any_mode(after_assignment):begin get_token; after_token:=cur_tok;
  20108.   end;
  20109. @ @<Insert a token saved by \.{\\afterassignment}, if any@>=
  20110. if after_token<>0 then
  20111.   begin cur_tok:=after_token; back_input; after_token:=0;
  20112.   end
  20113. @ Here is a procedure that might be called `Get the next non-blank non-relax
  20114. non-call non-assignment token'.
  20115. @<Declare act...@>=
  20116. procedure do_assignments;
  20117. label exit;
  20118. begin loop begin @<Get the next non-blank non-relax...@>;
  20119.   if cur_cmd<=max_non_prefixed_command then return;
  20120.   set_box_allowed:=false; prefixed_command; set_box_allowed:=true;
  20121.   end;
  20122. exit:end;
  20123. @ @<Cases of |main_control| that don't...@>=
  20124. any_mode(after_group):begin get_token; save_for_after(cur_tok);
  20125.   end;
  20126. @ Files for \.{\\read} are opened and closed by the |in_stream| command.
  20127. @<Put each...@>=
  20128. primitive("openin",in_stream,1);
  20129. @!@:open_in_}{\.{\\openin} primitive@>
  20130. primitive("closein",in_stream,0);
  20131. @!@:close_in_}{\.{\\closein} primitive@>
  20132. @ @<Cases of |print_cmd_chr|...@>=
  20133. in_stream: if chr_code=0 then print_esc("closein")
  20134.   else print_esc("openin");
  20135. @ @<Cases of |main_control| that don't...@>=
  20136. any_mode(in_stream): open_or_close_in;
  20137. @ @<Declare act...@>=
  20138. procedure open_or_close_in;
  20139. var c:0..1; {1 for \.{\\openin}, 0 for \.{\\closein}}
  20140. @!n:0..15; {stream number}
  20141. begin c:=cur_chr; scan_four_bit_int; n:=cur_val;
  20142. if read_open[n]<>closed then
  20143.   begin a_close(read_file[n]); read_open[n]:=closed;
  20144.   end;
  20145. if c<>0 then
  20146.   begin scan_optional_equals; scan_file_name;
  20147.   if cur_ext="" then cur_ext:=".tex";
  20148.   pack_cur_name;
  20149.   if a_open_in(read_file[n]) then read_open[n]:=just_open;
  20150.   end;
  20151. @ The user can issue messages to the terminal, regardless of the
  20152. current mode.
  20153. @<Cases of |main_control| that don't...@>=
  20154. any_mode(message):issue_message;
  20155. @ @<Put each...@>=
  20156. primitive("message",message,0);
  20157. @!@:message_}{\.{\\message} primitive@>
  20158. primitive("errmessage",message,1);
  20159. @!@:err_message_}{\.{\\errmessage} primitive@>
  20160. @ @<Cases of |print_cmd_chr|...@>=
  20161. message: if chr_code=0 then print_esc("message")
  20162.   else print_esc("errmessage");
  20163. @ @<Declare act...@>=
  20164. procedure issue_message;
  20165. var old_setting:0..max_selector; {holds |selector| setting}
  20166. @!c:0..1; {identifies \.{\\message} and \.{\\errmessage}}
  20167. @!s:str_number; {the message}
  20168. begin c:=cur_chr; link(garbage):=scan_toks(false,true);
  20169. old_setting:=selector; selector:=new_string;
  20170. token_show(def_ref); selector:=old_setting;
  20171. flush_list(def_ref);
  20172. str_room(1); s:=make_string;
  20173. if c=0 then @<Print string |s| on the terminal@>
  20174. else @<Print string |s| as an error message@>;
  20175. flush_string;
  20176. @ @<Print string |s| on the terminal@>=
  20177. begin if term_offset+length(s)>max_print_line-2 then print_ln
  20178. else if (term_offset>0)or(file_offset>0) then print_char(" ");
  20179. slow_print(s); update_terminal;
  20180. @ If \.{\\errmessage} occurs often in |scroll_mode|, without user-defined
  20181. \.{\\errhelp}, we don't want to give a long help message each time. So we
  20182. give a verbose explanation only once.
  20183. @<Glob...@>=
  20184. @!long_help_seen:boolean; {has the long \.{\\errmessage} help been used?}
  20185. @ @<Set init...@>=long_help_seen:=false;
  20186. @ @<Print string |s| as an error message@>=
  20187. begin print_err(""); slow_print(s);
  20188. if err_help<>null then use_err_help:=true
  20189. else if long_help_seen then help1("(That was another \errmessage.)")
  20190. else  begin if interaction<error_stop_mode then long_help_seen:=true;
  20191.   help4("This error message was generated by an \errmessage")@/
  20192.   ("command, so I can't give any explicit help.")@/
  20193.   ("Pretend that you're Hercule Poirot: Examine all clues,")@/
  20194. @^Poirot, Hercule@>
  20195.   ("and deduce the truth by order and method.");
  20196.   end;
  20197. error; use_err_help:=false;
  20198. @ The |error| routine calls on |give_err_help| if help is requested from
  20199. the |err_help| parameter.
  20200. @p procedure give_err_help;
  20201. begin token_show(err_help);
  20202. @ The \.{\\uppercase} and \.{\\lowercase} commands are implemented by
  20203. building a token list and then changing the cases of the letters in it.
  20204. @<Cases of |main_control| that don't...@>=
  20205. any_mode(case_shift):shift_case;
  20206. @ @<Put each...@>=
  20207. primitive("lowercase",case_shift,lc_code_base);
  20208. @!@:lowercase_}{\.{\\lowercase} primitive@>
  20209. primitive("uppercase",case_shift,uc_code_base);
  20210. @!@:uppercase_}{\.{\\uppercase} primitive@>
  20211. @ @<Cases of |print_cmd_chr|...@>=
  20212. case_shift:if chr_code=lc_code_base then print_esc("lowercase")
  20213.   else print_esc("uppercase");
  20214. @ @<Declare act...@>=
  20215. procedure shift_case;
  20216. var b:pointer; {|lc_code_base| or |uc_code_base|}
  20217. @!p:pointer; {runs through the token list}
  20218. @!t:halfword; {token}
  20219. @!c:eight_bits; {character code}
  20220. begin b:=cur_chr; p:=scan_toks(false,false); p:=link(def_ref);
  20221. while p<>null do
  20222.   begin @<Change the case of the token in |p|, if a change is appropriate@>;
  20223.   p:=link(p);
  20224.   end;
  20225. back_list(link(def_ref)); free_avail(def_ref); {omit reference count}
  20226. @ When the case of a |chr_code| changes, we don't change the |cmd|.
  20227. We also change active characters, using the fact that
  20228. |cs_token_flag+active_base| is a multiple of~256.
  20229. @^data structure assumptions@>
  20230. @<Change the case of the token in |p|, if a change is appropriate@>=
  20231. t:=info(p);
  20232. if t<cs_token_flag+single_base then
  20233.   begin c:=t mod 256;
  20234.   if equiv(b+c)<>0 then info(p):=t-c+equiv(b+c);
  20235.   end
  20236. @ We come finally to the last pieces missing from |main_control|, namely the
  20237. `\.{\\show}' commands that are useful when debugging.
  20238. @<Cases of |main_control| that don't...@>=
  20239. any_mode(xray): show_whatever;
  20240. @ @d show_code=0 { \.{\\show} }
  20241. @d show_box_code=1 { \.{\\showbox} }
  20242. @d show_the_code=2 { \.{\\showthe} }
  20243. @d show_lists=3 { \.{\\showlists} }
  20244. @<Put each...@>=
  20245. primitive("show",xray,show_code);
  20246. @!@:show_}{\.{\\show} primitive@>
  20247. primitive("showbox",xray,show_box_code);
  20248. @!@:show_box_}{\.{\\showbox} primitive@>
  20249. primitive("showthe",xray,show_the_code);
  20250. @!@:show_the_}{\.{\\showthe} primitive@>
  20251. primitive("showlists",xray,show_lists);
  20252. @!@:show_lists_}{\.{\\showlists} primitive@>
  20253. @ @<Cases of |print_cmd_chr|...@>=
  20254. xray: case chr_code of
  20255.   show_box_code:print_esc("showbox");
  20256.   show_the_code:print_esc("showthe");
  20257.   show_lists:print_esc("showlists");
  20258.   othercases print_esc("show")
  20259.   endcases;
  20260. @ @<Declare act...@>=
  20261. procedure show_whatever;
  20262. label common_ending;
  20263. var p:pointer; {tail of a token list to show}
  20264. begin case cur_chr of
  20265. show_lists: begin begin_diagnostic; show_activities;
  20266.   end;
  20267. show_box_code: @<Show the current contents of a box@>;
  20268. show_code: @<Show the current meaning of a token, then |goto common_ending|@>;
  20269. othercases @<Show the current value of some parameter or register,
  20270.   then |goto common_ending|@>
  20271. endcases;@/
  20272. @<Complete a potentially long \.{\\show} command@>;
  20273. common_ending: if interaction<error_stop_mode then
  20274.   begin help0; decr(error_count);
  20275.   end
  20276. else if tracing_online>0 then
  20277.   begin@t@>@;@/
  20278.   help3("This isn't an error message; I'm just \showing something.")@/
  20279.   ("Type `I\show...' to show more (e.g., \show\cs,")@/
  20280.   ("\showthe\count10, \showbox255, \showlists).");
  20281.   end
  20282. else  begin@t@>@;@/
  20283.   help5("This isn't an error message; I'm just \showing something.")@/
  20284.   ("Type `I\show...' to show more (e.g., \show\cs,")@/
  20285.   ("\showthe\count10, \showbox255, \showlists).")@/
  20286.   ("And type `I\tracingonline=1\show...' to show boxes and")@/
  20287.   ("lists on your terminal as well as in the transcript file.");
  20288.   end;
  20289. error;
  20290. @ @<Show the current meaning of a token...@>=
  20291. begin get_token;
  20292. if interaction=error_stop_mode then wake_up_terminal;
  20293. print_nl("> ");
  20294. if cur_cs<>0 then
  20295.   begin sprint_cs(cur_cs); print_char("=");
  20296.   end;
  20297. print_meaning; goto common_ending;
  20298. @ @<Cases of |print_cmd_chr|...@>=
  20299. undefined_cs: print("undefined");
  20300. call: print("macro");
  20301. long_call: print_esc("long macro");
  20302. outer_call: print_esc("outer macro");
  20303. long_outer_call: begin print_esc("long"); print_esc("outer macro");
  20304.   end;
  20305. end_template: print_esc("outer endtemplate");
  20306. @ @<Show the current contents of a box@>=
  20307. begin scan_eight_bit_int; begin_diagnostic;
  20308. print_nl("> \box"); print_int(cur_val); print_char("=");
  20309. if box(cur_val)=null then print("void")
  20310. else show_box(box(cur_val));
  20311. @ @<Show the current value of some parameter...@>=
  20312. begin p:=the_toks;
  20313. if interaction=error_stop_mode then wake_up_terminal;
  20314. print_nl("> "); token_show(temp_head);
  20315. flush_list(link(temp_head)); goto common_ending;
  20316. @ @<Complete a potentially long \.{\\show} command@>=
  20317. end_diagnostic(true); print_err("OK");
  20318. @.OK@>
  20319. if selector=term_and_log then if tracing_online<=0 then
  20320.   begin selector:=term_only; print(" (see the transcript file)");
  20321.   selector:=term_and_log;
  20322.   end
  20323. @* \[50] Dumping and undumping the tables.
  20324. After \.{INITEX} has seen a collection of fonts and macros, it
  20325. can write all the necessary information on an auxiliary file so
  20326. that production versions of \TeX\ are able to initialize their
  20327. memory at high speed. The present section of the program takes
  20328. care of such output and input. We shall consider simultaneously
  20329. the processes of storing and restoring,
  20330. so that the inverse relation between them is clear.
  20331. @.INITEX@>
  20332. The global variable |format_ident| is a string that is printed right
  20333. after the |banner| line when \TeX\ is ready to start. For \.{INITEX} this
  20334. string says simply `\.{(INITEX)}'; for other versions of \TeX\ it says,
  20335. for example, `\.{(preloaded format=plain 82.11.19)}', showing the year,
  20336. month, and day that the format file was created. We have |format_ident=0|
  20337. before \TeX's tables are loaded.
  20338. @<Glob...@>=
  20339. @!format_ident:str_number;
  20340. @ @<Set init...@>=
  20341. format_ident:=0;
  20342. @ @<Initialize table entries...@>=
  20343. format_ident:=" (INITEX)";
  20344. @ @<Declare act...@>=
  20345. @!init procedure store_fmt_file;
  20346. label found1,found2,done1,done2;
  20347. var j,@!k,@!l:integer; {all-purpose indices}
  20348. @!p,@!q: pointer; {all-purpose pointers}
  20349. @!x: integer; {something to dump}
  20350. @!w: four_quarters; {four ASCII codes}
  20351. begin @<If dumping is not allowed, abort@>;
  20352. @<Create the |format_ident|, open the format file,
  20353.   and inform the user that dumping has begun@>;
  20354. @<Dump constants for consistency check@>;
  20355. @<Dump the string pool@>;
  20356. @<Dump the dynamic memory@>;
  20357. @<Dump the table of equivalents@>;
  20358. @<Dump the font information@>;
  20359. @<Dump the hyphenation tables@>;
  20360. @<Dump a couple more things and the closing check word@>;
  20361. @<Close the format file@>;
  20362. @ Corresponding to the procedure that dumps a format file, we have a function
  20363. that reads one in. The function returns |false| if the dumped format is
  20364. incompatible with the present \TeX\ table sizes, etc.
  20365. @d bad_fmt=6666 {go here if the format file is unacceptable}
  20366. @d too_small(#)==begin wake_up_terminal;
  20367.   wterm_ln('---! Must increase the ',#);
  20368. @.Must increase the x@>
  20369.   goto bad_fmt;
  20370.   end
  20371. @p @t\4@>@<Declare the function called |open_fmt_file|@>@;
  20372. function load_fmt_file:boolean;
  20373. label bad_fmt,exit;
  20374. var j,@!k:integer; {all-purpose indices}
  20375. @!p,@!q: pointer; {all-purpose pointers}
  20376. @!x: integer; {something undumped}
  20377. @!w: four_quarters; {four ASCII codes}
  20378. begin @<Undump constants for consistency check@>;
  20379. @<Undump the string pool@>;
  20380. @<Undump the dynamic memory@>;
  20381. @<Undump the table of equivalents@>;
  20382. @<Undump the font information@>;
  20383. @<Undump the hyphenation tables@>;
  20384. @<Undump a couple more things and the closing check word@>;
  20385. load_fmt_file:=true; return; {it worked!}
  20386. bad_fmt: wake_up_terminal;
  20387.   wterm_ln('(Fatal format file error; I''m stymied)');
  20388. @.Fatal format file error@>
  20389. load_fmt_file:=false;
  20390. exit:end;
  20391. @ The user is not allowed to dump a format file unless |save_ptr=0|.
  20392. This condition implies that |cur_level=level_one|, hence
  20393. the |xeq_level| array is constant and it need not be dumped.
  20394. @<If dumping is not allowed, abort@>=
  20395. if save_ptr<>0 then
  20396.   begin print_err("You can't dump inside a group");
  20397. @.You can't dump...@>
  20398.   help1("`{...\dump}' is a no-no."); succumb;
  20399.   end
  20400. @ Format files consist of |memory_word| items, and we use the following
  20401. macros to dump words of different types:
  20402. @d dump_wd(#)==begin fmt_file^:=#; put(fmt_file);@+end
  20403. @d dump_int(#)==begin fmt_file^.int:=#; put(fmt_file);@+end
  20404. @d dump_hh(#)==begin fmt_file^.hh:=#; put(fmt_file);@+end
  20405. @d dump_qqqq(#)==begin fmt_file^.qqqq:=#; put(fmt_file);@+end
  20406. @<Glob...@>=
  20407. @!fmt_file:word_file; {for input or output of format information}
  20408. @ The inverse macros are slightly more complicated, since we need to check
  20409. the range of the values we are reading in. We say `|undump(a)(b)(x)|' to
  20410. read an integer value |x| that is supposed to be in the range |a<=x<=b|.
  20411. @d undump_wd(#)==begin get(fmt_file); #:=fmt_file^;@+end
  20412. @d undump_int(#)==begin get(fmt_file); #:=fmt_file^.int;@+end
  20413. @d undump_hh(#)==begin get(fmt_file); #:=fmt_file^.hh;@+end
  20414. @d undump_qqqq(#)==begin get(fmt_file); #:=fmt_file^.qqqq;@+end
  20415. @d undump_end_end(#)==#:=x;@+end
  20416. @d undump_end(#)==(x>#) then goto bad_fmt@+else undump_end_end
  20417. @d undump(#)==begin undump_int(x); if (x<#) or undump_end
  20418. @d undump_size_end_end(#)==too_small(#)@+else undump_end_end
  20419. @d undump_size_end(#)==if x># then undump_size_end_end
  20420. @d undump_size(#)==begin undump_int(x);
  20421.   if x<# then goto bad_fmt; undump_size_end
  20422. @ The next few sections of the program should make it clear how we use the
  20423. dump/undump macros.
  20424. @<Dump constants for consistency check@>=
  20425. dump_int(@$);@/
  20426. dump_int(mem_bot);@/
  20427. dump_int(mem_top);@/
  20428. dump_int(eqtb_size);@/
  20429. dump_int(hash_prime);@/
  20430. dump_int(hyph_size)
  20431. @ Sections of a \.{WEB} program that are ``commented out'' still contribute
  20432. strings to the string pool; therefore \.{INITEX} and \TeX\ will have
  20433. the same strings. (And it is, of course, a good thing that they do.)
  20434. @.WEB@>
  20435. @^string pool@>
  20436. @<Undump constants for consistency check@>=
  20437. x:=fmt_file^.int;
  20438. if x<>@$ then goto bad_fmt; {check that strings are the same}
  20439. undump_int(x);
  20440. if x<>mem_bot then goto bad_fmt;
  20441. undump_int(x);
  20442. if x<>mem_top then goto bad_fmt;
  20443. undump_int(x);
  20444. if x<>eqtb_size then goto bad_fmt;
  20445. undump_int(x);
  20446. if x<>hash_prime then goto bad_fmt;
  20447. undump_int(x);
  20448. if x<>hyph_size then goto bad_fmt
  20449. @ @d dump_four_ASCII==
  20450.   w.b0:=qi(so(str_pool[k])); w.b1:=qi(so(str_pool[k+1]));
  20451.   w.b2:=qi(so(str_pool[k+2])); w.b3:=qi(so(str_pool[k+3]));
  20452.   dump_qqqq(w)
  20453. @<Dump the string pool@>=
  20454. dump_int(pool_ptr);
  20455. dump_int(str_ptr);
  20456. for k:=0 to str_ptr do dump_int(str_start[k]);
  20457. k:=0;
  20458. while k+4<pool_ptr do
  20459.   begin dump_four_ASCII; k:=k+4;
  20460.   end;
  20461. k:=pool_ptr-4; dump_four_ASCII;
  20462. print_ln; print_int(str_ptr); print(" strings of total length ");
  20463. print_int(pool_ptr)
  20464. @ @d undump_four_ASCII==
  20465.   undump_qqqq(w);
  20466.   str_pool[k]:=si(qo(w.b0)); str_pool[k+1]:=si(qo(w.b1));
  20467.   str_pool[k+2]:=si(qo(w.b2)); str_pool[k+3]:=si(qo(w.b3))
  20468. @<Undump the string pool@>=
  20469. undump_size(0)(pool_size)('string pool size')(pool_ptr);
  20470. undump_size(0)(max_strings)('max strings')(str_ptr);
  20471. for k:=0 to str_ptr do undump(0)(pool_ptr)(str_start[k]);
  20472. k:=0;
  20473. while k+4<pool_ptr do
  20474.   begin undump_four_ASCII; k:=k+4;
  20475.   end;
  20476. k:=pool_ptr-4; undump_four_ASCII;
  20477. init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr
  20478. @ By sorting the list of available spaces in the variable-size portion of
  20479. |mem|, we are usually able to get by without having to dump very much
  20480. of the dynamic memory.
  20481. We recompute |var_used| and |dyn_used|, so that \.{INITEX} dumps valid
  20482. information even when it has not been gathering statistics.
  20483. @<Dump the dynamic memory@>=
  20484. sort_avail; var_used:=0;
  20485. dump_int(lo_mem_max); dump_int(rover);
  20486. p:=mem_bot; q:=rover; x:=0;
  20487. repeat for k:=p to q+1 do dump_wd(mem[k]);
  20488. x:=x+q+2-p; var_used:=var_used+q-p;
  20489. p:=q+node_size(q); q:=rlink(q);
  20490. until q=rover;
  20491. var_used:=var_used+lo_mem_max-p; dyn_used:=mem_end+1-hi_mem_min;@/
  20492. for k:=p to lo_mem_max do dump_wd(mem[k]);
  20493. x:=x+lo_mem_max+1-p;
  20494. dump_int(hi_mem_min); dump_int(avail);
  20495. for k:=hi_mem_min to mem_end do dump_wd(mem[k]);
  20496. x:=x+mem_end+1-hi_mem_min;
  20497. p:=avail;
  20498. while p<>null do
  20499.   begin decr(dyn_used); p:=link(p);
  20500.   end;
  20501. dump_int(var_used); dump_int(dyn_used);
  20502. print_ln; print_int(x);
  20503. print(" memory locations dumped; current usage is ");
  20504. print_int(var_used); print_char("&"); print_int(dyn_used)
  20505. @ @<Undump the dynamic memory@>=
  20506. undump(lo_mem_stat_max+1000)(hi_mem_stat_min-1)(lo_mem_max);
  20507. undump(lo_mem_stat_max+1)(lo_mem_max)(rover);
  20508. p:=mem_bot; q:=rover;
  20509. repeat for k:=p to q+1 do undump_wd(mem[k]);
  20510. p:=q+node_size(q);
  20511. if (p>lo_mem_max)or((q>=rlink(q))and(rlink(q)<>rover)) then goto bad_fmt;
  20512. q:=rlink(q);
  20513. until q=rover;
  20514. for k:=p to lo_mem_max do undump_wd(mem[k]);
  20515. if mem_min<mem_bot-2 then {make more low memory available}
  20516.   begin p:=llink(rover); q:=mem_min+1;
  20517.   link(mem_min):=null; info(mem_min):=null; {we don't use the bottom word}
  20518.   rlink(p):=q; llink(rover):=q;@/
  20519.   rlink(q):=rover; llink(q):=p; link(q):=empty_flag;
  20520.   node_size(q):=mem_bot-q;
  20521.   end;
  20522. undump(lo_mem_max+1)(hi_mem_stat_min)(hi_mem_min);
  20523. undump(null)(mem_top)(avail); mem_end:=mem_top;
  20524. for k:=hi_mem_min to mem_end do undump_wd(mem[k]);
  20525. undump_int(var_used); undump_int(dyn_used)
  20526. @ @<Dump the table of equivalents@>=
  20527. @<Dump regions 1 to 4 of |eqtb|@>;
  20528. @<Dump regions 5 and 6 of |eqtb|@>;
  20529. dump_int(par_loc); dump_int(write_loc);@/
  20530. @<Dump the hash table@>
  20531. @ @<Undump the table of equivalents@>=
  20532. @<Undump regions 1 to 6 of |eqtb|@>;
  20533. undump(hash_base)(frozen_control_sequence)(par_loc);
  20534. par_token:=cs_token_flag+par_loc;@/
  20535. undump(hash_base)(frozen_control_sequence)(write_loc);@/
  20536. @<Undump the hash table@>
  20537. @ The table of equivalents usually contains repeated information, so we dump it
  20538. in compressed form: The sequence of $n+2$ values $(n,x_1,\ldots,x_n,m)$ in the
  20539. format file represents $n+m$ consecutive entries of |eqtb|, with |m| extra
  20540. copies of $x_n$, namely $(x_1,\ldots,x_n,x_n,\ldots,x_n)$.
  20541. @<Dump regions 1 to 4 of |eqtb|@>=
  20542. k:=active_base;
  20543. repeat j:=k;
  20544. while j<int_base-1 do
  20545.   begin if (equiv(j)=equiv(j+1))and(eq_type(j)=eq_type(j+1))and@|
  20546.     (eq_level(j)=eq_level(j+1)) then goto found1;
  20547.   incr(j);
  20548.   end;
  20549. l:=int_base; goto done1; {|j=int_base-1|}
  20550. found1: incr(j); l:=j;
  20551. while j<int_base-1 do
  20552.   begin if (equiv(j)<>equiv(j+1))or(eq_type(j)<>eq_type(j+1))or@|
  20553.     (eq_level(j)<>eq_level(j+1)) then goto done1;
  20554.   incr(j);
  20555.   end;
  20556. done1:dump_int(l-k);
  20557. while k<l do
  20558.   begin dump_wd(eqtb[k]); incr(k);
  20559.   end;
  20560. k:=j+1; dump_int(k-l);
  20561. until k=int_base
  20562. @ @<Dump regions 5 and 6 of |eqtb|@>=
  20563. repeat j:=k;
  20564. while j<eqtb_size do
  20565.   begin if eqtb[j].int=eqtb[j+1].int then goto found2;
  20566.   incr(j);
  20567.   end;
  20568. l:=eqtb_size+1; goto done2; {|j=eqtb_size|}
  20569. found2: incr(j); l:=j;
  20570. while j<eqtb_size do
  20571.   begin if eqtb[j].int<>eqtb[j+1].int then goto done2;
  20572.   incr(j);
  20573.   end;
  20574. done2:dump_int(l-k);
  20575. while k<l do
  20576.   begin dump_wd(eqtb[k]); incr(k);
  20577.   end;
  20578. k:=j+1; dump_int(k-l);
  20579. until k>eqtb_size
  20580. @ @<Undump regions 1 to 6 of |eqtb|@>=
  20581. k:=active_base;
  20582. repeat undump_int(x);
  20583. if (x<1)or(k+x>eqtb_size+1) then goto bad_fmt;
  20584. for j:=k to k+x-1 do undump_wd(eqtb[j]);
  20585. k:=k+x;
  20586. undump_int(x);
  20587. if (x<0)or(k+x>eqtb_size+1) then goto bad_fmt;
  20588. for j:=k to k+x-1 do eqtb[j]:=eqtb[k-1];
  20589. k:=k+x;
  20590. until k>eqtb_size
  20591. @ A different scheme is used to compress the hash table, since its lower
  20592. region is usually sparse. When |text(p)<>0| for |p<=hash_used|, we output
  20593. two words, |p| and |hash[p]|. The hash table is, of course, densely packed
  20594. for |p>=hash_used|, so the remaining entries are output in a~block.
  20595. @<Dump the hash table@>=
  20596. dump_int(hash_used); cs_count:=frozen_control_sequence-1-hash_used;
  20597. for p:=hash_base to hash_used do if text(p)<>0 then
  20598.   begin dump_int(p); dump_hh(hash[p]); incr(cs_count);
  20599.   end;
  20600. for p:=hash_used+1 to undefined_control_sequence-1 do dump_hh(hash[p]);
  20601. dump_int(cs_count);@/
  20602. print_ln; print_int(cs_count); print(" multiletter control sequences")
  20603. @ @<Undump the hash table@>=
  20604. undump(hash_base)(frozen_control_sequence)(hash_used); p:=hash_base-1;
  20605. repeat undump(p+1)(hash_used)(p); undump_hh(hash[p]);
  20606. until p=hash_used;
  20607. for p:=hash_used+1 to undefined_control_sequence-1 do undump_hh(hash[p]);
  20608. undump_int(cs_count)
  20609. @ @<Dump the font information@>=
  20610. dump_int(fmem_ptr);
  20611. for k:=0 to fmem_ptr-1 do dump_wd(font_info[k]);
  20612. dump_int(font_ptr);
  20613. for k:=null_font to font_ptr do
  20614.   @<Dump the array info for internal font number |k|@>;
  20615. print_ln; print_int(fmem_ptr-7); print(" words of font info for ");
  20616. print_int(font_ptr-font_base); print(" preloaded font");
  20617. if font_ptr<>font_base+1 then print_char("s")
  20618. @ @<Undump the font information@>=
  20619. undump_size(7)(font_mem_size)('font mem size')(fmem_ptr);
  20620. for k:=0 to fmem_ptr-1 do undump_wd(font_info[k]);
  20621. undump_size(font_base)(font_max)('font max')(font_ptr);
  20622. for k:=null_font to font_ptr do
  20623.   @<Undump the array info for internal font number |k|@>
  20624. @ @<Dump the array info for internal font number |k|@>=
  20625. begin dump_qqqq(font_check[k]);
  20626. dump_int(font_size[k]);
  20627. dump_int(font_dsize[k]);
  20628. dump_int(font_params[k]);@/
  20629. dump_int(hyphen_char[k]);
  20630. dump_int(skew_char[k]);@/
  20631. dump_int(font_name[k]);
  20632. dump_int(font_area[k]);@/
  20633. dump_int(font_bc[k]);
  20634. dump_int(font_ec[k]);@/
  20635. dump_int(char_base[k]);
  20636. dump_int(width_base[k]);
  20637. dump_int(height_base[k]);@/
  20638. dump_int(depth_base[k]);
  20639. dump_int(italic_base[k]);
  20640. dump_int(lig_kern_base[k]);@/
  20641. dump_int(kern_base[k]);
  20642. dump_int(exten_base[k]);
  20643. dump_int(param_base[k]);@/
  20644. dump_int(font_glue[k]);@/
  20645. dump_int(bchar_label[k]);
  20646. dump_int(font_bchar[k]);
  20647. dump_int(font_false_bchar[k]);@/
  20648. print_nl("\font"); print_esc(font_id_text(k)); print_char("=");
  20649. print_file_name(font_name[k],font_area[k],"");
  20650. if font_size[k]<>font_dsize[k] then
  20651.   begin print(" at "); print_scaled(font_size[k]); print("pt");
  20652.   end;
  20653. @ @<Undump the array info for internal font number |k|@>=
  20654. begin undump_qqqq(font_check[k]);@/
  20655. undump_int(font_size[k]);
  20656. undump_int(font_dsize[k]);
  20657. undump(min_halfword)(max_halfword)(font_params[k]);@/
  20658. undump_int(hyphen_char[k]);
  20659. undump_int(skew_char[k]);@/
  20660. undump(0)(str_ptr)(font_name[k]);
  20661. undump(0)(str_ptr)(font_area[k]);@/
  20662. undump(0)(255)(font_bc[k]);
  20663. undump(0)(255)(font_ec[k]);@/
  20664. undump_int(char_base[k]);
  20665. undump_int(width_base[k]);
  20666. undump_int(height_base[k]);@/
  20667. undump_int(depth_base[k]);
  20668. undump_int(italic_base[k]);
  20669. undump_int(lig_kern_base[k]);@/
  20670. undump_int(kern_base[k]);
  20671. undump_int(exten_base[k]);
  20672. undump_int(param_base[k]);@/
  20673. undump(min_halfword)(lo_mem_max)(font_glue[k]);@/
  20674. undump(0)(font_mem_size)(bchar_label[k]);
  20675. undump(min_quarterword)(non_char)(font_bchar[k]);
  20676. undump(min_quarterword)(non_char)(font_false_bchar[k]);
  20677. @ @<Dump the hyphenation tables@>=
  20678. dump_int(hyph_count);
  20679. for k:=0 to hyph_size do if hyph_word[k]<>0 then
  20680.   begin dump_int(k); dump_int(hyph_word[k]); dump_int(hyph_list[k]);
  20681.   end;
  20682. print_ln; print_int(hyph_count); print(" hyphenation exception");
  20683. if hyph_count<>1 then print_char("s");
  20684. if trie_not_ready then init_trie;
  20685. dump_int(trie_max);
  20686. for k:=0 to trie_max do dump_hh(trie[k]);
  20687. dump_int(trie_op_ptr);
  20688. for k:=1 to trie_op_ptr do
  20689.   begin dump_int(hyf_distance[k]);
  20690.   dump_int(hyf_num[k]);
  20691.   dump_int(hyf_next[k]);
  20692.   end;
  20693. print_nl("Hyphenation trie of length "); print_int(trie_max);
  20694. @.Hyphenation trie...@>
  20695. print(" has "); print_int(trie_op_ptr); print(" op");
  20696. if trie_op_ptr<>1 then print_char("s");
  20697. print(" out of "); print_int(trie_op_size);
  20698. for k:=255 downto 0 do if trie_used[k]>min_quarterword then
  20699.   begin print_nl("  "); print_int(qo(trie_used[k]));
  20700.   print(" for language "); print_int(k);
  20701.   dump_int(k); dump_int(qo(trie_used[k]));
  20702.   end
  20703. @ Only ``nonempty'' parts of |op_start| need to be restored.
  20704. @<Undump the hyphenation tables@>=
  20705. undump(0)(hyph_size)(hyph_count);
  20706. for k:=1 to hyph_count do
  20707.   begin undump(0)(hyph_size)(j);
  20708.   undump(0)(str_ptr)(hyph_word[j]);
  20709.   undump(min_halfword)(max_halfword)(hyph_list[j]);
  20710.   end;
  20711. undump_size(0)(trie_size)('trie size')(j); @+init trie_max:=j;@+tini
  20712. for k:=0 to j do undump_hh(trie[k]);
  20713. undump_size(0)(trie_op_size)('trie op size')(j); @+init trie_op_ptr:=j;@+tini
  20714. for k:=1 to j do
  20715.   begin undump(0)(63)(hyf_distance[k]); {a |small_number|}
  20716.   undump(0)(63)(hyf_num[k]);
  20717.   undump(min_quarterword)(max_quarterword)(hyf_next[k]);
  20718.   end;
  20719. init for k:=0 to 255 do trie_used[k]:=min_quarterword;@+tini@;@/
  20720. k:=256;
  20721. while j>0 do
  20722.   begin undump(0)(k-1)(k); undump(1)(j)(x);@+init trie_used[k]:=qi(x);@+tini@;@/
  20723.   j:=j-x; op_start[k]:=qo(j);
  20724.   end;
  20725. @!init trie_not_ready:=false @+tini
  20726. @ We have already printed a lot of statistics, so we set |tracing_stats:=0|
  20727. to prevent them appearing again.
  20728. @<Dump a couple more things and the closing check word@>=
  20729. dump_int(interaction); dump_int(format_ident); dump_int(69069);
  20730. tracing_stats:=0
  20731. @ @<Undump a couple more things and the closing check word@>=
  20732. undump(batch_mode)(error_stop_mode)(interaction);
  20733. undump(0)(str_ptr)(format_ident);
  20734. undump_int(x);
  20735. if (x<>69069)or eof(fmt_file) then goto bad_fmt
  20736. @ @<Create the |format_ident|...@>=
  20737. selector:=new_string;
  20738. print(" (preloaded format="); print(job_name); print_char(" ");
  20739. print_int(year mod 100); print_char(".");
  20740. print_int(month); print_char("."); print_int(day); print_char(")");
  20741. if interaction=batch_mode then selector:=log_only
  20742. else selector:=term_and_log;
  20743. str_room(1);
  20744. format_ident:=make_string;
  20745. pack_job_name(format_extension);
  20746. while not w_open_out(fmt_file) do
  20747.   prompt_file_name("format file name",format_extension);
  20748. print_nl("Beginning to dump on file ");
  20749. @.Beginning to dump...@>
  20750. slow_print(w_make_name_string(fmt_file)); flush_string;
  20751. print_nl(""); slow_print(format_ident)
  20752. @ @<Close the format file@>=
  20753. w_close(fmt_file)
  20754. @* \[51] The main program.
  20755. This is it: the part of \TeX\ that executes all those procedures we have
  20756. written.
  20757. Well---almost. Let's leave space for a few more routines that we may
  20758. have forgotten.
  20759. @p @<Last-minute procedures@>
  20760. @ We have noted that there are two versions of \TeX82. One, called \.{INITEX},
  20761. @.INITEX@>
  20762. has to be run first; it initializes everything from scratch, without
  20763. reading a format file, and it has the capability of dumping a format file.
  20764. The other one is called `\.{VIRTEX}'; it is a ``virgin'' program that needs
  20765. @.VIRTEX@>
  20766. to input a format file in order to get started. \.{VIRTEX} typically has
  20767. more memory capacity than \.{INITEX}, because it does not need the space
  20768. consumed by the auxiliary hyphenation tables and the numerous calls on
  20769. |primitive|, etc.
  20770. The \.{VIRTEX} program cannot read a format file instantaneously, of course;
  20771. the best implementations therefore allow for production versions of \TeX\ that
  20772. not only avoid the loading routine for \PASCAL\ object code, they also have
  20773. a format file pre-loaded. This is impossible to do if we stick to standard
  20774. \PASCAL; but there is a simple way to fool many systems into avoiding the
  20775. initialization, as follows:\quad(1)~We declare a global integer variable
  20776. called |ready_already|. The probability is negligible that this
  20777. variable holds any particular value like 314159 when \.{VIRTEX} is first
  20778. loaded.\quad(2)~After we have read in a format file and initialized
  20779. everything, we set |ready_already:=314159|.\quad(3)~Soon \.{VIRTEX}
  20780. will print `\.*', waiting for more input; and at this point we
  20781. interrupt the program and save its core image in some form that the
  20782. operating system can reload speedily.\quad(4)~When that core image is
  20783. activated, the program starts again at the beginning; but now
  20784. |ready_already=314159| and all the other global variables have
  20785. their initial values too. The former chastity has vanished!
  20786. In other words, if we allow ourselves to test the condition
  20787. |ready_already=314159|, before |ready_already| has been
  20788. assigned a value, we can avoid the lengthy initialization. Dirty tricks
  20789. rarely pay off so handsomely.
  20790. @^dirty \PASCAL@>
  20791. @^system dependencies@>
  20792. On systems that allow such preloading, the standard program called \.{TeX}
  20793. should be the one that has \.{plain} format preloaded, since that agrees
  20794. with {\sl The \TeX book}. Other versions, e.g., \.{AmSTeX}, should also
  20795. @:TeXbook}{\sl The \TeX book@>
  20796. @.AmSTeX@>
  20797. @.plain@>
  20798. be provided for commonly used formats.
  20799. @<Glob...@>=
  20800. @!ready_already:integer; {a sacrifice of purity for economy}
  20801. @ Now this is really it: \TeX\ starts and ends here.
  20802. The initial test involving |ready_already| should be deleted if the
  20803. \PASCAL\ runtime system is smart enough to detect such a ``mistake.''
  20804. @^system dependencies@>
  20805. @p begin @!{|start_here|}
  20806. history:=fatal_error_stop; {in case we quit during initialization}
  20807. t_open_out; {open the terminal for output}
  20808. if ready_already=314159 then goto start_of_TEX;
  20809. @<Check the ``constant'' values...@>@;
  20810. if bad>0 then
  20811.   begin wterm_ln('Ouch---my internal constants have been clobbered!',
  20812.     '---case ',bad:1);
  20813. @.Ouch...clobbered@>
  20814.   goto final_end;
  20815.   end;
  20816. initialize; {set global variables to their starting values}
  20817. @!init if not get_strings_started then goto final_end;
  20818. init_prim; {call |primitive| for each primitive}
  20819. init_str_ptr:=str_ptr; init_pool_ptr:=pool_ptr; fix_date_and_time;
  20820. tini@/
  20821. ready_already:=314159;
  20822. start_of_TEX: @<Initialize the output routines@>;
  20823. @<Get the first line of input and prepare to start@>;
  20824. history:=spotless; {ready to go!}
  20825. main_control; {come to life}
  20826. final_cleanup; {prepare for death}
  20827. end_of_TEX: close_files_and_terminate;
  20828. final_end: ready_already:=0;
  20829. @ Here we do whatever is needed to complete \TeX's job gracefully on the
  20830. local operating system. The code here might come into play after a fatal
  20831. error; it must therefore consist entirely of ``safe'' operations that
  20832. cannot produce error messages. For example, it would be a mistake to call
  20833. |str_room| or |make_string| at this time, because a call on |overflow|
  20834. might lead to an infinite loop.
  20835. @^system dependencies@>
  20836. Actually there's one way to get error messages, via |prepare_mag|;
  20837. but that can't cause infinite recursion.
  20838. @^recursion@>
  20839. This program doesn't bother to close the input files that may still be open.
  20840. @<Last-minute...@>=
  20841. procedure close_files_and_terminate;
  20842. var k:integer; {all-purpose index}
  20843. begin @<Finish the extensions@>;
  20844. @!stat if tracing_stats>0 then @<Output statistics about this job@>;@;@+tats@/
  20845. wake_up_terminal; @<Finish the \.{DVI} file@>;
  20846. if log_opened then
  20847.   begin wlog_cr; a_close(log_file); selector:=selector-2;
  20848.   if selector=term_only then
  20849.     begin print_nl("Transcript written on ");
  20850. @.Transcript written...@>
  20851.     slow_print(log_name); print_char(".");
  20852.     end;
  20853.   end;
  20854. @ The present section goes directly to the log file instead of using
  20855. |print| commands, because there's no need for these strings to take
  20856. up |str_pool| memory when a non-{\bf stat} version of \TeX\ is being used.
  20857. @<Output statistics...@>=
  20858. if log_opened then
  20859.   begin wlog_ln(' ');
  20860.   wlog_ln('Here is how much of TeX''s memory',' you used:');
  20861. @.Here is how much...@>
  20862.   wlog(' ',str_ptr-init_str_ptr:1,' string');
  20863.   if str_ptr<>init_str_ptr+1 then wlog('s');
  20864.   wlog_ln(' out of ', max_strings-init_str_ptr:1);@/
  20865.   wlog_ln(' ',pool_ptr-init_pool_ptr:1,' string characters out of ',
  20866.     pool_size-init_pool_ptr:1);@/
  20867.   wlog_ln(' ',lo_mem_max-mem_min+mem_end-hi_mem_min+2:1,@|
  20868.     ' words of memory out of ',mem_end+1-mem_min:1);@/
  20869.   wlog_ln(' ',cs_count:1,' multiletter control sequences out of ',
  20870.     hash_size:1);@/
  20871.   wlog(' ',fmem_ptr:1,' words of font info for ',
  20872.     font_ptr-font_base:1,' font');
  20873.   if font_ptr<>font_base+1 then wlog('s');
  20874.   wlog_ln(', out of ',font_mem_size:1,' for ',font_max-font_base:1);@/
  20875.   wlog(' ',hyph_count:1,' hyphenation exception');
  20876.   if hyph_count<>1 then wlog('s');
  20877.   wlog_ln(' out of ',hyph_size:1);@/
  20878.   wlog_ln(' ',max_in_stack:1,'i,',max_nest_stack:1,'n,',@|
  20879.     max_param_stack:1,'p,',@|
  20880.     max_buf_stack+1:1,'b,',@|
  20881.     max_save_stack+6:1,'s stack positions out of ',@|
  20882.     stack_size:1,'i,',
  20883.     nest_size:1,'n,',
  20884.     param_size:1,'p,',
  20885.     buf_size:1,'b,',
  20886.     save_size:1,'s');
  20887.   end
  20888. @ We get to the |final_cleanup| routine when \.{\\end} or \.{\\dump} has
  20889. been scanned and |its_all_over|\kern-2pt.
  20890. @<Last-minute...@>=
  20891. procedure final_cleanup;
  20892. label exit;
  20893. var c:small_number; {0 for \.{\\end}, 1 for \.{\\dump}}
  20894. begin c:=cur_chr;
  20895. if job_name=0 then open_log_file;
  20896. while open_parens>0 do
  20897.   begin print(" )"); decr(open_parens);
  20898.   end;
  20899. if cur_level>level_one then
  20900.   begin print_nl("("); print_esc("end occurred ");
  20901.   print("inside a group at level ");
  20902. @:end_}{\.{(\\end occurred...)}@>
  20903.   print_int(cur_level-level_one); print_char(")");
  20904.   end;
  20905. while cond_ptr<>null do
  20906.   begin print_nl("("); print_esc("end occurred ");
  20907.   print("when "); print_cmd_chr(if_test,cur_if);
  20908.   if if_line<>0 then
  20909.     begin print(" on line "); print_int(if_line);
  20910.     end;
  20911.   print(" was incomplete)");
  20912.   if_line:=if_line_field(cond_ptr);
  20913.   cur_if:=subtype(cond_ptr); cond_ptr:=link(cond_ptr);
  20914.   end;
  20915. if history<>spotless then
  20916.  if ((history=warning_issued)or(interaction<error_stop_mode)) then
  20917.   if selector=term_and_log then
  20918.   begin selector:=term_only;
  20919.   print_nl("(see the transcript file for additional information)");
  20920. @.see the transcript file...@>
  20921.   selector:=term_and_log;
  20922.   end;
  20923. if c=1 then
  20924.   begin @!init store_fmt_file; return;@+tini@/
  20925.   print_nl("(\dump is performed only by INITEX)"); return;
  20926. @:dump_}{\.{\\dump...only by INITEX}@>
  20927.   end;
  20928. exit:end;
  20929. @ @<Last-minute...@>=
  20930. @!init procedure init_prim; {initialize all the primitives}
  20931. begin no_new_control_sequence:=false;
  20932. @<Put each...@>;
  20933. no_new_control_sequence:=true;
  20934. @ When we begin the following code, \TeX's tables may still contain garbage;
  20935. the strings might not even be present. Thus we must proceed cautiously to get
  20936. bootstrapped in.
  20937. But when we finish this part of the program, \TeX\ is ready to call on the
  20938. |main_control| routine to do its work.
  20939. @<Get the first line...@>=
  20940. begin @<Initialize the input routines@>;
  20941. if (format_ident=0)or(buffer[loc]="&") then
  20942.   begin if format_ident<>0 then initialize; {erase preloaded format}
  20943.   if not open_fmt_file then goto final_end;
  20944.   if not load_fmt_file then
  20945.     begin w_close(fmt_file); goto final_end;
  20946.     end;
  20947.   w_close(fmt_file);
  20948.   while (loc<limit)and(buffer[loc]=" ") do incr(loc);
  20949.   end;
  20950. if end_line_char_inactive then decr(limit)
  20951. else  buffer[limit]:=end_line_char;
  20952. fix_date_and_time;@/
  20953. @<Compute the magic offset@>;
  20954. @<Initialize the print |selector|...@>;
  20955. if (loc<limit)and(cat_code(buffer[loc])<>escape) then start_input;
  20956.   {\.{\\input} assumed}
  20957. @* \[52] Debugging.
  20958. Once \TeX\ is working, you should be able to diagnose most errors with
  20959. the \.{\\show} commands and other diagnostic features. But for the initial
  20960. stages of debugging, and for the revelation of really deep mysteries, you
  20961. can compile \TeX\ with a few more aids, including the \PASCAL\ runtime
  20962. checks and its debugger. An additional routine called |debug_help|
  20963. will also come into play when you type `\.D' after an error message;
  20964. |debug_help| also occurs just before a fatal error causes \TeX\ to succumb.
  20965. @^debugging@>
  20966. @^system dependencies@>
  20967. The interface to |debug_help| is primitive, but it is good enough when used
  20968. with a \PASCAL\ debugger that allows you to set breakpoints and to read
  20969. variables and change their values. After getting the prompt `\.{debug \#}', you
  20970. type either a negative number (this exits |debug_help|), or zero (this
  20971. goes to a location where you can set a breakpoint, thereby entering into
  20972. dialog with the \PASCAL\ debugger), or a positive number |m| followed by
  20973. an argument |n|. The meaning of |m| and |n| will be clear from the
  20974. program below. (If |m=13|, there is an additional argument, |l|.)
  20975. @.debug \#@>
  20976. @d breakpoint=888 {place where a breakpoint is desirable}
  20977. @<Last-minute...@>=
  20978. @!debug procedure debug_help; {routine to display various things}
  20979. label breakpoint,exit;
  20980. var k,@!l,@!m,@!n:integer;
  20981. begin loop begin wake_up_terminal;
  20982.   print_nl("debug # (-1 to exit):"); update_terminal;
  20983. @.debug \#@>
  20984.   read(term_in,m);
  20985.   if m<0 then return
  20986.   else if m=0 then
  20987.     begin goto breakpoint;@\ {go to every label at least once}
  20988.     breakpoint: m:=0; @{'BREAKPOINT'@}@\
  20989.     end
  20990.   else  begin read(term_in,n);
  20991.     case m of
  20992.     @t\4@>@<Numbered cases for |debug_help|@>@;
  20993.     othercases print("?")
  20994.     endcases;
  20995.     end;
  20996.   end;
  20997. exit:end;
  20998. gubed
  20999. @ @<Numbered cases...@>=
  21000. 1: print_word(mem[n]); {display |mem[n]| in all forms}
  21001. 2: print_int(info(n));
  21002. 3: print_int(link(n));
  21003. 4: print_word(eqtb[n]);
  21004. 5: print_word(font_info[n]);
  21005. 6: print_word(save_stack[n]);
  21006. 7: show_box(n);
  21007.   {show a box, abbreviated by |show_box_depth| and |show_box_breadth|}
  21008. 8: begin breadth_max:=10000; depth_threshold:=pool_size-pool_ptr-10;
  21009.   show_node_list(n); {show a box in its entirety}
  21010.   end;
  21011. 9: show_token_list(n,null,1000);
  21012. 10: slow_print(n);
  21013. 11: check_mem(n>0); {check wellformedness; print new busy locations if |n>0|}
  21014. 12: search_mem(n); {look for pointers to |n|}
  21015. 13: begin read(term_in,l); print_cmd_chr(n,l);
  21016.   end;
  21017. 14: for k:=0 to n do print(buffer[k]);
  21018. 15: begin font_in_short_display:=null_font; short_display(n);
  21019.   end;
  21020. 16: panicking:=not panicking;
  21021. @* \[53] Extensions.
  21022. The program above includes a bunch of ``hooks'' that allow further
  21023. capabilities to be added without upsetting \TeX's basic structure.
  21024. Most of these hooks are concerned with ``whatsit'' nodes, which are
  21025. intended to be used for special purposes; whenever a new extension to
  21026. \TeX\ involves a new kind of whatsit node, a corresponding change needs
  21027. to be made to the routines below that deal with such nodes,
  21028. but it will usually be unnecessary to make many changes to the
  21029. other parts of this program.
  21030. In order to demonstrate how extensions can be made, we shall treat
  21031. `\.{\\write}', `\.{\\openout}', `\.{\\closeout}', `\.{\\immediate}',
  21032. `\.{\\special}', and `\.{\\setlanguage}' as if they were extensions.
  21033. These commands are actually primitives of \TeX, and they should
  21034. appear in all implementations of the system; but let's try to imagine
  21035. that they aren't. Then the program below illustrates how a person
  21036. could add them.
  21037. Sometimes, of course, an extension will require changes to \TeX\ itself;
  21038. no system of hooks could be complete enough for all conceivable extensions.
  21039. The features associated with `\.{\\write}' are almost all confined to the
  21040. following paragraphs, but there are small parts of the |print_ln| and
  21041. |print_char| procedures that were introduced specifically to \.{\\write}
  21042. characters. Furthermore one of the token lists recognized by the scanner
  21043. is a |write_text|; and there are a few other miscellaneous places where we
  21044. have already provided for some aspect of \.{\\write}.  The goal of a \TeX\
  21045. extender should be to minimize alterations to the standard parts of the
  21046. program, and to avoid them completely if possible. He or she should also
  21047. be quite sure that there's no easy way to accomplish the desired goals
  21048. with the standard features that \TeX\ already has. ``Think thrice before
  21049. extending,'' because that may save a lot of work, and it will also keep
  21050. incompatible extensions of \TeX\ from proliferating.
  21051. @^system dependencies@>
  21052. @^extensions to \TeX@>
  21053. @ First let's consider the format of whatsit nodes that are used to represent
  21054. the data associated with \.{\\write} and its relatives. Recall that a whatsit
  21055. has |type=whatsit_node|, and the |subtype| is supposed to distinguish
  21056. different kinds of whatsits. Each node occupies two or more words; the
  21057. exact number is immaterial, as long as it is readily determined from the
  21058. |subtype| or other data.
  21059. We shall introduce five |subtype| values here, corresponding to the
  21060. control sequences \.{\\openout}, \.{\\write}, \.{\\closeout}, \.{\\special}, and
  21061. \.{\\setlanguage}. The second word of I/O whatsits has a |write_stream| field
  21062. that identifies the write-stream number (0 to 15, or 16 for out-of-range and
  21063. positive, or 17 for out-of-range and negative).
  21064. In the case of \.{\\write} and \.{\\special}, there is also a field that
  21065. points to the reference count of a token list that should be sent. In the
  21066. case of \.{\\openout}, we need three words and three auxiliary subfields
  21067. to hold the string numbers for name, area, and extension.
  21068. @d write_node_size=2 {number of words in a write/whatsit node}
  21069. @d open_node_size=3 {number of words in an open/whatsit node}
  21070. @d open_node=0 {|subtype| in whatsits that represent files to \.{\\openout}}
  21071. @d write_node=1 {|subtype| in whatsits that represent things to \.{\\write}}
  21072. @d close_node=2 {|subtype| in whatsits that represent streams to \.{\\closeout}}
  21073. @d special_node=3 {|subtype| in whatsits that represent \.{\\special} things}
  21074. @d language_node=4 {|subtype| in whatsits that change the current language}
  21075. @d what_lang(#)==link(#+1) {language number, in the range |0..255|}
  21076. @d what_lhm(#)==type(#+1) {minimum left fragment, in the range |1..63|}
  21077. @d what_rhm(#)==subtype(#+1) {minimum right fragment, in the range |1..63|}
  21078. @d write_tokens(#) == link(#+1) {reference count of token list to write}
  21079. @d write_stream(#) == info(#+1) {stream number (0 to 17)}
  21080. @d open_name(#) == link(#+1) {string number of file name to open}
  21081. @d open_area(#) == info(#+2) {string number of file area for |open_name|}
  21082. @d open_ext(#) == link(#+2) {string number of file extension for |open_name|}
  21083. @ The sixteen possible \.{\\write} streams are represented by the |write_file|
  21084. array. The |j|th file is open if and only if |write_open[j]=true|. The last
  21085. two streams are special; |write_open[16]| represents a stream number
  21086. greater than 15, while |write_open[17]| represents a negative stream number,
  21087. and both of these variables are always |false|.
  21088. @<Glob...@>=
  21089. @!write_file:array[0..15] of alpha_file;
  21090. @!write_open:array[0..17] of boolean;
  21091. @ @<Set init...@>=
  21092. for k:=0 to 17 do write_open[k]:=false;
  21093. @ Extensions might introduce new command codes; but it's best to use
  21094. |extension| with a modifier, whenever possible, so that |main_control|
  21095. stays the same.
  21096. @d immediate_code=4 {command modifier for \.{\\immediate}}
  21097. @d set_language_code=5 {command modifier for \.{\\setlanguage}}
  21098. @<Put each...@>=
  21099. primitive("openout",extension,open_node);@/
  21100. @!@:open_out_}{\.{\\openout} primitive@>
  21101. primitive("write",extension,write_node); write_loc:=cur_val;@/
  21102. @!@:write_}{\.{\\write} primitive@>
  21103. primitive("closeout",extension,close_node);@/
  21104. @!@:close_out_}{\.{\\closeout} primitive@>
  21105. primitive("special",extension,special_node);@/
  21106. @!@:special_}{\.{\\special} primitive@>
  21107. primitive("immediate",extension,immediate_code);@/
  21108. @!@:immediate_}{\.{\\immediate} primitive@>
  21109. primitive("setlanguage",extension,set_language_code);@/
  21110. @!@:set_language_}{\.{\\setlanguage} primitive@>
  21111. @ The variable |write_loc| just introduced is used to provide an
  21112. appropriate error message in case of ``runaway'' write texts.
  21113. @<Glob...@>=
  21114. @!write_loc:pointer; {|eqtb| address of \.{\\write}}
  21115. @ @<Cases of |print_cmd_chr|...@>=
  21116. extension: case chr_code of
  21117.   open_node:print_esc("openout");
  21118.   write_node:print_esc("write");
  21119.   close_node:print_esc("closeout");
  21120.   special_node:print_esc("special");
  21121.   immediate_code:print_esc("immediate");
  21122.   set_language_code:print_esc("setlanguage");
  21123.   othercases print("[unknown extension!]")
  21124.   endcases;
  21125. @ When an |extension| command occurs in |main_control|, in any mode,
  21126. the |do_extension| routine is called.
  21127. @<Cases of |main_control| that are for extensions...@>=
  21128. any_mode(extension):do_extension;
  21129. @ @<Declare act...@>=
  21130. @t\4@>@<Declare procedures needed in |do_extension|@>@;
  21131. procedure do_extension;
  21132. var i,@!j,@!k:integer; {all-purpose integers}
  21133. @!p,@!q,@!r:pointer; {all-purpose pointers}
  21134. begin case cur_chr of
  21135. open_node:@<Implement \.{\\openout}@>;
  21136. write_node:@<Implement \.{\\write}@>;
  21137. close_node:@<Implement \.{\\closeout}@>;
  21138. special_node:@<Implement \.{\\special}@>;
  21139. immediate_code:@<Implement \.{\\immediate}@>;
  21140. set_language_code:@<Implement \.{\\setlanguage}@>;
  21141. othercases confusion("ext1")
  21142. @:this can't happen ext1}{\quad ext1@>
  21143. endcases;
  21144. @ Here is a subroutine that creates a whatsit node having a given |subtype|
  21145. and a given number of words. It initializes only the first word of the whatsit,
  21146. and appends it to the current list.
  21147. @<Declare procedures needed in |do_extension|@>=
  21148. procedure new_whatsit(@!s:small_number;@!w:small_number);
  21149. var p:pointer; {the new node}
  21150. begin p:=get_node(w); type(p):=whatsit_node; subtype(p):=s;
  21151. link(tail):=p; tail:=p;
  21152. @ The next subroutine uses |cur_chr| to decide what sort of whatsit is
  21153. involved, and also inserts a |write_stream| number.
  21154. @<Declare procedures needed in |do_ext...@>=
  21155. procedure new_write_whatsit(@!w:small_number);
  21156. begin new_whatsit(cur_chr,w);
  21157. if w<>write_node_size then scan_four_bit_int
  21158. else  begin scan_int;
  21159.   if cur_val<0 then cur_val:=17
  21160.   else if cur_val>15 then cur_val:=16;
  21161.   end;
  21162. write_stream(tail):=cur_val;
  21163. @ @<Implement \.{\\openout}@>=
  21164. begin new_write_whatsit(open_node_size);
  21165. scan_optional_equals; scan_file_name;@/
  21166. open_name(tail):=cur_name; open_area(tail):=cur_area; open_ext(tail):=cur_ext;
  21167. @ When `\.{\\write 12\{...\}}' appears, we scan the token list `\.{\{...\}}'
  21168. without expanding its macros; the macros will be expanded later when this
  21169. token list is rescanned.
  21170. @<Implement \.{\\write}@>=
  21171. begin k:=cur_cs; new_write_whatsit(write_node_size);@/
  21172. cur_cs:=k; p:=scan_toks(false,false); write_tokens(tail):=def_ref;
  21173. @ @<Implement \.{\\closeout}@>=
  21174. begin new_write_whatsit(write_node_size); write_tokens(tail):=null;
  21175. @ When `\.{\\special\{...\}}' appears, we expand the macros in the token
  21176. list as in \.{\\xdef} and \.{\\mark}.
  21177. @<Implement \.{\\special}@>=
  21178. begin new_whatsit(special_node,write_node_size); write_stream(tail):=null;
  21179. p:=scan_toks(false,true); write_tokens(tail):=def_ref;
  21180. @ Each new type of node that appears in our data structure must be capable
  21181. of being displayed, copied, destroyed, and so on. The routines that we
  21182. need for write-oriented whatsits are somewhat like those for mark nodes;
  21183. other extensions might, of course, involve more subtlety here.
  21184. @<Basic printing...@>=
  21185. procedure print_write_whatsit(@!s:str_number;@!p:pointer);
  21186. begin print_esc(s);
  21187. if write_stream(p)<16 then print_int(write_stream(p))
  21188. else if write_stream(p)=16 then print_char("*")
  21189. @.*\relax@>
  21190. else print_char("-");
  21191. @ @<Display the whatsit...@>=
  21192. case subtype(p) of
  21193. open_node:begin print_write_whatsit("openout",p);
  21194.   print_char("="); print_file_name(open_name(p),open_area(p),open_ext(p));
  21195.   end;
  21196. write_node:begin print_write_whatsit("write",p);
  21197.   print_mark(write_tokens(p));
  21198.   end;
  21199. close_node:print_write_whatsit("closeout",p);
  21200. special_node:begin print_esc("special");
  21201.   print_mark(write_tokens(p));
  21202.   end;
  21203. language_node:begin print_esc("setlanguage");
  21204.   print_int(what_lang(p)); print(" (hyphenmin ");
  21205.   print_int(what_lhm(p)); print_char(",");
  21206.   print_int(what_rhm(p)); print_char(")");
  21207.   end;
  21208. othercases print("whatsit?")
  21209. endcases
  21210. @ @<Make a partial copy of the whatsit...@>=
  21211. case subtype(p) of
  21212. open_node: begin r:=get_node(open_node_size); words:=open_node_size;
  21213.   end;
  21214. write_node,special_node: begin r:=get_node(write_node_size);
  21215.   add_token_ref(write_tokens(p)); words:=write_node_size;
  21216.   end;
  21217. close_node,language_node: begin r:=get_node(small_node_size);
  21218.   words:=small_node_size;
  21219.   end;
  21220. othercases confusion("ext2")
  21221. @:this can't happen ext2}{\quad ext2@>
  21222. endcases
  21223. @ @<Wipe out the whatsit...@>=
  21224. begin case subtype(p) of
  21225. open_node: free_node(p,open_node_size);
  21226. write_node,special_node: begin delete_token_ref(write_tokens(p));
  21227.   free_node(p,write_node_size); goto done;
  21228.   end;
  21229. close_node,language_node: free_node(p,small_node_size);
  21230. othercases confusion("ext3")
  21231. @:this can't happen ext3}{\quad ext3@>
  21232. endcases;@/
  21233. goto done;
  21234. @ @<Incorporate a whatsit node into a vbox@>=do_nothing
  21235. @ @<Incorporate a whatsit node into an hbox@>=do_nothing
  21236. @ @<Let |d| be the width of the whatsit |p|@>=d:=0
  21237. @ @d adv_past(#)==@+if subtype(#)=language_node then
  21238.     begin cur_lang:=what_lang(#); l_hyf:=what_lhm(#); r_hyf:=what_rhm(#);@+end
  21239. @<Advance \(p)past a whatsit node in the \(l)|line_break| loop@>=@+
  21240. adv_past(cur_p)
  21241. @ @<Advance \(p)past a whatsit node in the \(p)pre-hyphenation loop@>=@+
  21242. adv_past(s)
  21243. @ @<Prepare to move whatsit |p| to the current page, then |goto contribute|@>=
  21244. goto contribute
  21245. @ @<Process whatsit |p| in |vert_break| loop, |goto not_found|@>=
  21246. goto not_found
  21247. @ @<Output the whatsit node |p| in a vlist@>=
  21248. out_what(p)
  21249. @ @<Output the whatsit node |p| in an hlist@>=
  21250. out_what(p)
  21251. @ After all this preliminary shuffling, we come finally to the routines
  21252. that actually send out the requested data. Let's do \.{\\special} first
  21253. (it's easier).
  21254. @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
  21255. procedure special_out(@!p:pointer);
  21256. var old_setting:0..max_selector; {holds print |selector|}
  21257. @!k:pool_pointer; {index into |str_pool|}
  21258. begin synch_h; synch_v;@/
  21259. old_setting:=selector; selector:=new_string;
  21260. show_token_list(link(write_tokens(p)),null,pool_size-pool_ptr);
  21261. selector:=old_setting;
  21262. str_room(1);
  21263. if cur_length<256 then
  21264.   begin dvi_out(xxx1); dvi_out(cur_length);
  21265.   end
  21266. else  begin dvi_out(xxx4); dvi_four(cur_length);
  21267.   end;
  21268. for k:=str_start[str_ptr] to pool_ptr-1 do dvi_out(so(str_pool[k]));
  21269. pool_ptr:=str_start[str_ptr]; {erase the string}
  21270. @ To write a token list, we must run it through \TeX's scanner, expanding
  21271. macros and \.{\\the} and \.{\\number}, etc. This might cause runaways,
  21272. if a delimited macro parameter isn't matched, and runaways would be
  21273. extremely confusing since we are calling on \TeX's scanner in the middle
  21274. of a \.{\\shipout} command. Therefore we will put a dummy control sequence as
  21275. a ``stopper,'' right after the token list. This control sequence is
  21276. artificially defined to be \.{\\outer}.
  21277. @:end_write_}{\.{\\endwrite}@>
  21278. @<Initialize table...@>=
  21279. text(end_write):="endwrite"; eq_level(end_write):=level_one;
  21280. eq_type(end_write):=outer_call; equiv(end_write):=null;
  21281. @ @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
  21282. procedure write_out(@!p:pointer);
  21283. var old_setting:0..max_selector; {holds print |selector|}
  21284. @!old_mode:integer; {saved |mode|}
  21285. @!j:small_number; {write stream number}
  21286. @!q,@!r:pointer; {temporary variables for list manipulation}
  21287. begin @<Expand macros in the token list
  21288.   and make |link(def_ref)| point to the result@>;
  21289. old_setting:=selector; j:=write_stream(p);
  21290. if write_open[j] then selector:=j
  21291. else  begin {write to the terminal if file isn't open}
  21292.   if (j=17)and(selector=term_and_log) then selector:=log_only;
  21293.   print_nl("");
  21294.   end;
  21295. token_show(def_ref); print_ln;
  21296. flush_list(def_ref); selector:=old_setting;
  21297. @ The final line of this routine is slightly subtle; at least, the author
  21298. didn't think about it until getting burnt! There is a used-up token list
  21299. @^Knuth, Donald Ervin@>
  21300. on the stack, namely the one that contained |end_write_token|. (We
  21301. insert this artificial `\.{\\endwrite}' to prevent runaways, as explained
  21302. above.) If it were not removed, and if there were numerous writes on a
  21303. single page, the stack would overflow.
  21304. @d end_write_token==cs_token_flag+end_write
  21305. @<Expand macros in the token list and...@>=
  21306. q:=get_avail; info(q):=right_brace_token+"}";@/
  21307. r:=get_avail; link(q):=r; info(r):=end_write_token; ins_list(q);@/
  21308. begin_token_list(write_tokens(p),write_text);@/
  21309. q:=get_avail; info(q):=left_brace_token+"{"; ins_list(q);
  21310. {now we're ready to scan
  21311.   `\.\{$\langle\,$token list$\,\rangle$\.{\} \\endwrite}'}
  21312. old_mode:=mode; mode:=0;
  21313.   {disable \.{\\prevdepth}, \.{\\spacefactor}, \.{\\lastskip}, \.{\\prevgraf}}
  21314. cur_cs:=write_loc; q:=scan_toks(false,true); {expand macros, etc.}
  21315. get_token;@+if cur_tok<>end_write_token then
  21316.   @<Recover from an unbalanced write command@>;
  21317. mode:=old_mode;
  21318. end_token_list {conserve stack space}
  21319. @ @<Recover from an unbalanced write command@>=
  21320. begin print_err("Unbalanced write command");
  21321. @.Unbalanced write...@>
  21322. help2("On this page there's a \write with fewer real {'s than }'s.")@/
  21323. ("I can't handle that very well; good luck."); error;
  21324. repeat get_token;
  21325. until cur_tok=end_write_token;
  21326. @ The |out_what| procedure takes care of outputting whatsit nodes for
  21327. |vlist_out| and |hlist_out|\kern-.3pt.
  21328. @<Declare procedures needed in |hlist_out|, |vlist_out|@>=
  21329. procedure out_what(@!p:pointer);
  21330. var j:small_number; {write stream number}
  21331. begin case subtype(p) of
  21332. open_node,write_node,close_node:@<Do some work that has been queued up
  21333.   for \.{\\write}@>;
  21334. special_node:special_out(p);
  21335. language_node:do_nothing;
  21336. othercases confusion("ext4")
  21337. @:this can't happen ext4}{\quad ext4@>
  21338. endcases;
  21339. @ We don't implement \.{\\write} inside of leaders. (The reason is that
  21340. the number of times a leader box appears might be different in different
  21341. implementations, due to machine-dependent rounding in the glue calculations.)
  21342. @^leaders@>
  21343. @<Do some work that has been queued up...@>=
  21344. if not doing_leaders then
  21345.   begin j:=write_stream(p);
  21346.   if subtype(p)=write_node then write_out(p)
  21347.   else  begin if write_open[j] then a_close(write_file[j]);
  21348.     if subtype(p)=close_node then write_open[j]:=false
  21349.     else if j<16 then
  21350.       begin cur_name:=open_name(p); cur_area:=open_area(p);
  21351.       cur_ext:=open_ext(p);
  21352.       if cur_ext="" then cur_ext:=".tex";
  21353.       pack_cur_name;
  21354.       while not a_open_out(write_file[j]) do
  21355.         prompt_file_name("output file name",".tex");
  21356.       write_open[j]:=true;
  21357.       end;
  21358.     end;
  21359.   end
  21360. @ The presence of `\.{\\immediate}' causes the |do_extension| procedure
  21361. to descend to one level of recursion. Nothing happens unless \.{\\immediate}
  21362. is followed by `\.{\\openout}', `\.{\\write}', or `\.{\\closeout}'.
  21363. @^recursion@>
  21364. @<Implement \.{\\immediate}@>=
  21365. begin get_x_token;
  21366. if (cur_cmd=extension)and(cur_chr<=close_node) then
  21367.   begin p:=tail; do_extension; {append a whatsit node}
  21368.   out_what(tail); {do the action immediately}
  21369.   flush_node_list(tail); tail:=p; link(p):=null;
  21370.   end
  21371. else back_input;
  21372. @ The \.{\\language} extension is somewhat different.
  21373. We need a subroutine that comes into play when a character of
  21374. a non-|clang| language is being appended to the current paragraph.
  21375. @<Declare action...@>=
  21376. procedure fix_language;
  21377. var @!l:ASCII_code; {the new current language}
  21378. begin if language<=0 then l:=0
  21379. else if language>255 then l:=0
  21380. else l:=language;
  21381. if l<>clang then
  21382.   begin new_whatsit(language_node,small_node_size);
  21383.   what_lang(tail):=l; clang:=l;@/
  21384.   what_lhm(tail):=norm_min(left_hyphen_min);
  21385.   what_rhm(tail):=norm_min(right_hyphen_min);
  21386.   end;
  21387. @ @<Implement \.{\\setlanguage}@>=
  21388. if abs(mode)<>hmode then report_illegal_case
  21389. else begin new_whatsit(language_node,small_node_size);
  21390.   scan_int;
  21391.   if cur_val<=0 then clang:=0
  21392.   else if cur_val>255 then clang:=0
  21393.   else clang:=cur_val;
  21394.   what_lang(tail):=clang;
  21395.   what_lhm(tail):=norm_min(left_hyphen_min);
  21396.   what_rhm(tail):=norm_min(right_hyphen_min);
  21397.   end
  21398. @ @<Finish the extensions@>=
  21399. for k:=0 to 15 do if write_open[k] then a_close(write_file[k])
  21400. @* \[54] System-dependent changes.
  21401. This section should be replaced, if necessary, by any special
  21402. modifications of the program
  21403. that are necessary to make \TeX\ work at a particular installation.
  21404. It is usually best to design your change file so that all changes to
  21405. previous sections preserve the section numbering; then everybody's version
  21406. will be consistent with the published program. More extensive changes,
  21407. which introduce new sections, can be inserted here; then only the index
  21408. itself will get a new section number.
  21409. @^system dependencies@>
  21410. @* \[55] Index.
  21411. Here is where you can find all uses of each identifier in the program,
  21412. with underlined entries pointing to where the identifier was defined.
  21413. If the identifier is only one letter long, however, you get to see only
  21414. the underlined entries. {\sl All references are to section numbers instead of
  21415. page numbers.}
  21416. This index also lists error messages and other aspects of the program
  21417. that you might want to look up some day. For example, the entry
  21418. for ``system dependencies'' lists all sections that should receive
  21419. special attention from people who are installing \TeX\ in a new
  21420. operating environment. A list of various things that can't happen appears
  21421. under ``this can't happen''. Approximately 40 sections are listed under
  21422. ``inner loop''; these account for about 60\pct! of \TeX's running time,
  21423. exclusive of input and output.
  21424.