ńņš. 9 
18.11. According to the rule just stated, the ļ¬rst comma is an abbreviation for ā˜}} {{ā™.
Hence the ļ¬rst argument is a capsule containing the value of x; the second is the text
ā˜(,ā™ ; the third is the text ā˜(}})ā™.
18.12. This snares future pens before theyā™re converted to pens, because pickup
wants to yscale by aspect ratio before ellipses change to polygons.
250 Appendix A: Answers to All the Exercises
18.13. The construction ā˜hide ( statement list )ā™ expands into ā˜gobble begingroup vacuous
endfor
statement list ; endgroupā™, so the argument to gobble must be evaluated. The
show
begingroup causes to start executing statements. When that has been str
done, the ļ¬nal statement turns out to be empty , so the argument to gobble turns
out to be a vacuous expression (cf. Chapter 25). Finally, gobble ā™s replacement text is
empty, so the hidden text has indeed disappeared. (The hide macro in Appendix B is
actually a bit more eļ¬cient, but a bit trickier.)
ā™s āstomachā would see ā˜;ā™ if mag is known, but there would
19.1. Then
be no change if mag is unknown. An extra semicolon is harmless, since
statements can be empty . But itā™s wise to get in the habit of putting ā˜;ā™ before ļ¬,
because it saves a wee bit of time and because ā˜;ā™ deļ¬nitely belongs before endfor.
19.2. No; that would be shocking.
1
19.3. Yes, if and only if n ā’ is an even integer. (Because ambiguous values are
2
rounded up.)
19.4. No.
19.5. def even = not odd enddef .
19.6. The ļ¬rst is 5, because the pair is not considered to be a path. The second and
third are 0, because the pair is forced to become a path.
19.7. (a) The loop text is never executed. (b) Itā™s executed only once, for x = 1.
(c) Itā™s executed inļ¬nitely often, for x = 1, 1, 1, . . . . (d) Since ten times 
ā™s internal representation of .1 is slightly larger than 1, the answer is not what
you probably expect! The loop text is executed for x = 0, 0.1, 0.20001, 0.30002,
0.40002, 0.50003, 0.60004, 0.70004, 0.80005, and 0.90005 only. (If you want the values
(0, .1, .2, . . . , 1), say ā˜ for xx = 0 upto 10: x := xx /10; text endforā™ instead.)
19.8. m = 1, n = 0.
19.9. def exitunless expr b = exitif not b enddef . (The simpler alternative
ā˜def exitunless = exitif not enddef ā™ wouldnā™t work, since ā˜notā™ applies only to the
following primary .)
19.10. numeric p[]; boolean n_is_prime; p[1]=2; k:=1;
for n=3 step 2 until infinity:
n_is_prime:=true;
for j=2 upto k: if n mod p[j]=0: n_is_prime:=false; fi
exitif n/p[j]<p[j]; endfor
if n_is_prime: p[incr k]:=n; exitif k=30; fi
endfor fi
show for k=1 upto 30: str p[k]&"="&decimal p[k], endfor "done" end.
19.11. ā˜0; exitif true;ā™.
20.1. False; consider ā˜a1(2)ā™.
20.2. A value very close to z2 .
Appendix A: Answers to All the Exercises 251
20.3. vardef lo_cube(expr x)=x*x*x<10 enddef; **
tolerance
show solve lo_cube(0,10), 10**1/3; end.
str
(EXPR
With the default tolerance of 0.1, this will show the respective values 2.14844 and (SUFFIX
(TEXT
2.1544. A more general routine could also be written, with ā˜10ā™ as a parameter:
at sharp
at
vardef lo_cube[](expr x)=x*x*x<@ enddef;
sharp at
show solve lo_cube10(0,10); origin
skyline
if we ask for minimum tolerance (tolerance := epsilon ), the result is 2.15445; the true histogram
value is ā 2.15443469.
20.4. begingroup(p5dx,p5dy)endgroup.
20.5. Say ā˜first#@ā™ after deļ¬ning ā˜vardef first.a[]@#=@ enddefā™. (There are
other solutions, e.g., using substrings of str #@, but this one is perhaps the most
instructive.)
20.6. The machine answers thus:
incr=macro:<suffix>>
begingroup(SUFFIX2):=(SUFFIX2)+1;(SUFFIX2)endgroup
z@#=macro:>begingroup(x(SUFFIX2),y(SUFFIX2))endgroup
Parameters to a macro are numbered sequentially, starting with zero, and classiļ¬ed as
either (EXPRn ), (SUFFIXn ), or (TEXTn ). In a vardef, (SUFFIX0) and (SUFFIX1) are
always reserved for the implicit parameters #@ and @; (SUFFIX2) will be @#, if it is used
in the parameter heading, otherwise it will be the ļ¬rst explicit parameter, if it happens
to be a suļ¬x parameter.
20.7. secondarydef t transum tt =
begingroup save T; transform T;
for z=origin,up,right:
z transformed t + z transformed tt = z transformed T; endfor
T endgroup enddef.
21.1. False; about twice as often (2/3 versus 1/3).
21.2. 1+floor uniformdeviate n.
21.3. A random point on the straight line segment from z1 to z2 . (The point z1
itself will occur with probability about 1/65536; but point z2 will never occur.)
21.4. A random āskylineā texture, 100 pt wide Ć— 10 pt tall:
The density decreases uniformly as you go up in altitude.
21.5. A moreorless bellshaped histogram:
22.1. (a) Iļ¬ n is an integer between 0 and 255. (b) Iļ¬ s is a string of length 1.
22.2. Whoever says that thereā™s no such primitive operation has forgotten about
scantokens.
252 Appendix A: Answers to All the Exercises
22.3. vardef octal primary n = Hobby
save m,s; m:=abs round n; string s; s=decimal(m mod 8);
forever: m:=m div 8; exitif m=0;
s:=decimal(m mod 8) & s; endfor
s enddef;
ā˜str[m mod 8]ā™ could also be used instead of ā˜decimal(m mod 8)ā™.
23.1. Point (x, y) is the upper left corner, (x + c1 ā’ c0 , y) is the upper right corner,
(x, y ā’ r1 + r0 ) is the lower left corner, and (x + c1 ā’ c0 , y ā’ r1 + r0 ) is the lower right
corner. (Pixels outside this rectangle will not be displayed.)
23.2. Redeļ¬ne openit so that it puts the top left at (ā’50, 280).
23.3. (This routine is due to John Hobby.)
newinternal n_windows; % the number of windows allocated so far
newinternal screen_bot; % the first untouched screen row
pair screen_corner; % the upper left corner of next window
def wipescreen = % do this to initialize or reinitialize
for i:=1 upto n_windows: display blankpicture inwindow i; endfor
n_windows := screen_bot := 0; screen_corner := origin enddef;
wipescreen;
vardef new_window@#(expr u,v) = save r,c,up_lft; pair up_lft;
if n_windows=15: errmessage "No more windows left"
else: window@# := incr n_windows;
up_lft = (min(xpart u,xpart v), max(ypart u, ypart v));
(r,c) = (u+v2up_lft) rotated 90;
if ypart screen_corner + c > screen_cols:
screen_corner:=(screen_bot,0); fi
openwindow window@# from screen_corner
to screen_corner+(r,c) at up_lft;
screen_bot := max(screen_bot,xpart screen_corner + r);
screen_corner := screen_corner + (0,c) fi; enddef;
24.1. The entire path now has negative y coordinates except at point (0, 0), so
the outline of the ļ¬lled region is (0, ā’1)   (10, ā’1)   (10, 0)   (0, 0)   (0, 1)   cycle.
(Notice that the digitized outline actually goes up to (0, 1) before coming straight down
again. This ļ¬lls no pixels, but correctly puts ācancellingā edges from (0, 0)
to (0, 1) and back to (0, 0) into its edge structure, because the point (0, .5) is on the
boundary and rounds to (0, 1).)
24.2. The horizontal tangents are already taken care of by the equations top y1 =
h + o and bot y4 = ā’o, so nothing needs to be done there. We should, however, say
x2 = w ā’ x3 = good.x (1.5u + s)
so that vertical tangents will occur in good places. Since w is an integer, and since the
logo pen has leftright symmetry, w ā’ x3 will be good if and only if x3 is.
24.3. Let b be the pen breadth. Then .5w is a good x value if and only if lft .5w is
an integer; but lft .5w = .5w ā’ .5b, and this is an integer if and only if w ā’ b is even.
Appendix A: Answers to All the Exercises 253
24.4. There are no ambiguous points on the outlines of this stroke, except perhaps draw
ļ¬‚oor
on the top and bottom edges; the latter can occur only if round py is odd. Hence
there is always leftright symmetry, but topbottom symmetry might fail because of a
missing row at the bottom (e.g., when px = py = 3). In a case like the ā˜ ā™ we do have
both symmetries, because y1 and x4 are in good positions.
24.5. No matter where you place the octagon so that it isnā™t touching any ambiguous
points, exactly seven ambiguous points are inside it; hence every onepoint draw ļ¬lls
exactly seven pixels. (In fact, you always get one of the patterns , , , or .)
24.6. f = .5(x4 ā’x3 ); the desired equation is ā˜x1 ā’x2 = round(x1 ā’x2 +.5(x4 ā’x3 ))ā™.
24.7. Let x3 = n + 1 + Īø, where n is an integer and 0 ā¤ Īø < 1. By drawing lines of
2
slope 30ā—¦ from the pixel centers, we ļ¬nd that there are three cases for the rightmost
four columns:
Case A, ; Case B, ; Case C, .
ā ā ā
Case A occurs for 0 ā¤ Īø < 2 3 ā’ 3; Case B occurs for 2 3 ā’ 3 ā¤ Īø < 3 ā’ 1; Case C
ā
occurs for 3 ā’ 1 ā¤ Īø < 1. The tip in Case A looks a bit too sharp, and Case C looks
too blunt, so Case B seems best. This case occurs when x3 is near an integer, so itā™s
OK to let x3 be an integer.
ā ā
24.8. Let y1 = n + Īø. If Īø lies between 1 3 ā’ 1 and 1 3 + 1 , the top row after
6ā ā
2 2 2
digitization will contain two black pixels. If Īø lies between 1 3 + 1 and 5 3 ā’ 1 , we
6 2 6 2
get the desired shape. Otherwise we get ā˜ ā™.
ā
24.9. (We choose Īø = 1 3 in the previous exercise, since this is the midpoint of the
2
desirable interval.) The equations are changed to
x1 = x2 = w ā’ x3 = round s;
y3 = .5 + ļ¬‚oor .5h;
z1 ā’ z2 = (z3 ā’ z2 ) rotated 60;
y1 := .5 sqrt 3 + round(y1 ā’ .5 sqrt 3);
y2 := h ā’ y1 ;
and then we ļ¬ll z1   z2   z3   cycle as before.
24.10. vardef vround primary v =
ļ¬‚oor(v ā— aspect ratio + .5)/aspect ratio enddef ;
vardef good.y primary y =
vround (y + pen top ) ā’ pen top enddef .
24.11. (m + 1/2, (n + 1/2)/aspect ratio ). These are the points that currenttransform
maps into pixel centers.
25.1. By looking at the syntax rules, we ļ¬nd, for example,
boolean expression true
numeric expression 0
pair expression (0,0)
path expression makepath pencircle
pen expression nullpen
254 Appendix A: Answers to All the Exercises
picture expression nullpicture delimiter
Missing token has been inserted
string expression ""
capsule
transform expression Impossible!
vacuous expression begingroup endgroup
Every transform expression includes either a variable or a capsule. Incidentally, there
are some amusing alternative 5token solutions for pair expression :
postcontrol 0 of makepath nullpen
makepath pencircle intersectiontimes makepath nullpen
26.1. The responses are
> a=left delimiter that matches ::
> b=(outer) a
> c=a
because: a has been redeļ¬ned from internal quantity to delimiter; b is still an internal
quantity (named a), and it has been stamped outer; c denotes the same internal
quantity, but it hasnā™t got outerness.
27.1. We want to delete
0 [ 1 + sqrt 43 ]
from the sequence of tokens that is about to read next, in order to get
rid of the right bracket, which we can see is going to be just as erroneous as the left
bracket was. However, there is another way to proceed (and indeed, this alternative
would be preferable to counting tokens, if the bracketed expression were longer): We
could simply delete 2 tokens, then ā˜I(ā™. This would produce another error stop,
! Missing ā˜)ā™ has been inserted.
<to be read again>
]
<*> show round[1 + sqrt43]
;
?h
I found no right delimiter to match a left one. So Iā™ve
put one in, behind the scenes; this may fix the problem.
?
after which itā™s easy to delete the ā˜]ā™ and continue successfully.
27.2. looked ahead, to see if the expression being evaluated was going
to be something like ā˜round 0[1+sqrt43,x]ā™. But when it found no comma, it put
back several tokens so that they could be read again. (The subexpression 1+sqrt43
had already been evaluated, so a ācapsuleā for its value, 7.55743, was inserted among
the tokens to be reread.) The expression ended with ā˜0ā™, and ā˜round 0ā™ was shown.
Then found extra tokens following the show command; a semicolon should
have come next. To continue, the user should just plunge ahead recklessly once again,
letting delete those unwanted tokens.
Appendix A: Answers to All the Exercises 255
27.3. The little program counterclockwise
SHAKESPEARE
path p,q; p=flex((32,481),(42,455),(62,430)); KNUTH
q=flex((62,430),(20,452),(42,448));
show p intersectiontimes q, p intersectionpoint q,
angle direction 2 of p, angle direction 0 of q; end
gives the following results:
>> (1.88403,0.07692)
>> (59.32149,432.59523)
>> 43.14589
>> 45.47263
(Actually, the paths would also cross if 452 were 451, but itā™s such a close call that
doesnā™t call the path strange; prefers to turn counterclockwise
ā—¦
when the amount of turn is close enough to 180 , even if itā™s slightly more.)
27.4. If this exercise isnā™t just a joke, the title of this appendix is a lie. (When
youā™ve solved this exercise you might also try to ļ¬nd all the lies and/or jokes that are
the same in both this book and The TEXbook.)
Looke into this Businesse thorowly,
And call these foule Oļ¬endors to their Answeres.
ā” WILLIAM SHAKESPEARE, Second Part of Henry the Sixth (1594)
If you canā™t solve a problem,
you can always look up the answer.
But please, try ļ¬rst to solve it by yourself;
then youā™ll learn more and youā™ll learn faster.
ā” DONALD E. KNUTH, The book (1986)
(page 256)
B
Basic
Operations
Appendix B: Basic Operations 257
This appendix deļ¬nes the macros of the plain base. Letā™s begin with table, useful
inventory
an informal inventory of all the features that are available. Boolean
Numeric
known
Boolean things: true, false; expression ;
unknown
cycle
odd numeric ; charexists numeric ;
ļ£± ļ£¼
ļ£“ boolean ļ£“
ļ£“ numeric ļ£“ ļ£±ļ£¼
ļ£“ ļ£“ ļ£± ļ£¼ļ£“<ļ£“ļ£± ļ£¼
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ pair ļ£“ ļ£“ boolean ļ£“ ļ£“<=ļ£“ ļ£“ boolean
ļ£“ ļ£“ ļ£“ļ£“ ļ£“
ļ£“ numeric ļ£“ ļ£“ ļ£“ ļ£“ numeric ļ£“
ļ£“ ļ£“ ļ£“ ļ£“ļ£“ ļ£“ļ£“ ļ£“
ļ£“ ļ£“
ļ£² ļ£½ ļ£² ļ£½ļ£² ļ£½ļ£² ļ£½
=
path
expression ; pair pair ;
ļ£“ ļ£“ ļ£“ ļ£“ ļ£“<>ļ£“ ļ£“ ļ£“
ļ£“ string ļ£“ ļ£“ ļ£“ ļ£“ string ļ£“
ļ£“ ļ£“
pen
ļ£“
ļ£“ picture ļ£“ ļ£“ ļ£“ļ£“ ļ£“ļ£“ ļ£“
ļ£³ ļ£¾ ļ£“>=ļ£“ ļ£³ ļ£¾
ļ£“
ļ£“ ļ£“ļ£“
ļ£“
ļ£“ ļ£“ ļ£³ļ£¾
ļ£“ ļ£“ transform transform
ļ£“ string ļ£“
ļ£“ ļ£“
ļ£³ ļ£¾ >
transform
not boolean ; boolean and boolean ; boolean or boolean .
Numeric things: tracingtitles, . . . , yoffset (see Chapter 25);
eps, epsilon, infinity; tolerance, join_radius, displaying; constant ;
ļ£± lft ļ£¼
ļ£±sqrtļ£¼ ļ£± floor ļ£¼
ļ£“ rt ļ£“
ļ£“ ļ£“
ļ£“sindļ£“
ļ£“ ļ£“ round ļ£“
ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ ļ£“ ļ£“ ļ£“
ļ£² top ļ£“
ļ£² ļ£½ ļ£² ļ£½ ļ£½
cosd numeric ; numeric ; numeric ;
hround
ļ£“mlogļ£“ ļ£“ vround ļ£“ ļ£“ bot ļ£“
ļ£“ ļ£“ ļ£“ ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ ļ£“ ļ£“ ļ£“good.xļ£“
ļ£³ ļ£¾ ļ£³ ļ£¾ ļ£“ ļ£“
ļ£“ ļ£“
ļ£³ ļ£¾
mexp ceiling
good.y
ļ£±xxpartļ£¼
ļ£“
ļ£²xypartļ£“ ļ£½ ASCII
xpart pair
; transform ; string ;
oct
ļ£“yxpartļ£“
ypart transform ļ£³ ļ£¾ hex
yypart
normaldeviate; uniformdeviate numeric ; whatever;
angle pair ; turningnumber cycle ; totalweight picture ;
+
numeric
incr
 numeric ; variable ; byte ;
string
decr
constant
+ ++
numeric numeric ; numeric numeric ;
 ++
*
mod
numeric numeric ; numeric numeric ;
/
div
ļ£± ļ£¼
**
numeric ļ£“
ļ£“
ļ£² ļ£½
pair
abs
max
pair dotprod pair ; ( numerics ); ;
length ļ£“ path ļ£“
min ļ£³ ļ£¾
string
numeric [ numeric , numeric ]; solve function ( numeric , numeric );
directiontime pair of path .
258 Appendix B: Basic Operations
Pair things: left, right, up, down, origin; ( numeric , numeric ); Pair
Path
z suļ¬x ; dir numeric ; unitvector pair ; round pair ;
ļ£± ļ£¼ ļ£±good.lftļ£¼ ļ£± ļ£¼ Pen
ļ£“lftļ£“ ļ£“ ļ£“ ļ£“ ļ£“ Picture
point
ļ£² ļ£½ ļ£² good.rt ļ£½ ļ£² ļ£½ String
rt precontrol Transform
pair ; pair ; numeric of path ;
ļ£“topļ£“ ļ£“good.topļ£“ ļ£“postcontrolļ£“
ļ£³ ļ£¾ ļ£³ ļ£¾ ļ£³ ļ£¾
good.bot
bot direction
+
+
 pair ; pair pair ; numeric [ pair , pair ];

constant
*
numeric * pair ; pair numeric ; pair transformer ;
/
max
intersectionpoint
path path ; ( pairs );
min
intersectiontimes
penoffset pair of pen ; directionpoint pair of path .
Path things: quartercircle, halfcircle, fullcircle;
unitsquare; flex( pairs ); makepath pen ;
superellipse( pair , pair , pair , pair , numeric );
reverse path ; counterclockwise path ; tensepath path ;
path transformer ; interpath( numeric , path , path );
ļ£± ļ£¼
ļ£“ ļ£“
..
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
...
ļ£¼ ļ£“ .. tension .. ļ£“ ļ£±
ļ£“
ļ£± ļ£“ ļ£¼ļ£± ļ£¼
ļ£“ ļ£“
{ pair }ļ£½ ļ£“ ļ£“ ļ£²{ pair }ļ£½ ļ£² pair ļ£½
ļ£² ļ£² ļ£½
pair .. controls ..
{ curl } { curl } path ;
path ļ£³ ļ£¾ļ£“ ļ£“ļ£³ ļ£¾ļ£³ ļ£¾
ļ£“ ļ£“

ļ£“ ļ£“
empty empty cycle
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“

ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£³ ļ£¾
&
softjoin
subpath pair of path .
Pen things: pencircle, pensquare, penrazor, penspeck;
nullpen; currentpen; makepen path ; pen transformer .
Picture things: nullpicture, blankpicture; unitpixel;
+ +
picture ; picture picture ;
currentpicture;
 
picture transformer .
String things: "constant"; ditto; jobname; readstring;
str suļ¬x ; decimal numeric ; char numeric ;
max
string & string ; ( strings ); substring pair of string .
min
Transform things: identity; currenttransform;
inverse transform ; transform transformer .
Appendix B: Basic Operations 259
Transformers: transformed transform ; Transformers
Conditions
scaled Loops
rotated shifted Diagnostic things
numeric ; numeric ; pair ;
xscaled Starting a job
slanted zscaled
yscaled Conversion to pixel units
reflectedabout( pair , pair ); rotatedaround( pair , numeric ).
Conditions:
else: text
if boolean : text {elseif boolean : text } ā„0 fi.
empty
Loops: forever: text endfor;
ļ£± ļ£¼
ļ£² ļ£½
numeric upto numeric
=
for Ī½ numeric downto numeric : text(Ī½) endfor;
:= ļ£³ ļ£¾
numeric step numeric until numeric
=
expressions : text( ) endfor;
for
:=
=
forsuffixes Ļ suļ¬xes : text(Ļ) endfor;
:=
exitif boolean ; ; exitunless boolean ; .
Diagnostic things: ???; interact; hide( statements );
loggingall, tracingall, tracingnone.
numeric
Starting a job: \mode= modename ; mag= ;
magstep numeric
screenchars; screenstrokes; imagerules; gfcorners; nodisplays;
notransforms; input ļ¬lename .
Conversion to pixel units: mode_setup; fix_units;
pixels_per_inch, blacker, fillin, o_correction;
mm#, cm#, pt#, pc#, dd#, cc#, bp#, in#;
mm, cm, pt, pc, dd, cc, bp, in;
mode_def; extra_setup;
ļ£± ļ£¼
define_pixels
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
define_whole_pixels
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
define_whole_vertical_pixels
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
define_good_x_pixels
ļ£“ ļ£“
ļ£² ļ£½
define_good_y_pixels
( names ).
ļ£“ ļ£“
define_blacker_pixels
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
define_whole_blacker_pixels
ļ£“
ļ£“define_whole_vertical_blacker_pixelsļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
define_corrected_pixels
ļ£³ ļ£¾
define_horizontal_corrected_pixels
260 Appendix B: Basic Operations
Character and font administration: Drawing
Screen display
beginchar( code , width# , height# , depth# ); extra_beginchar; Statements
italcorr numeric# ; change_width; endchar; extra_endchar;
ļ£± ļ£¼
font_size
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ ļ£“ ļ£± ļ£¼
font_slant
ļ£“
ļ£“ font_normal_space ļ£“ ļ£“ ļ£“ligtable ligs/kerns
ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ ļ£“ charlist codes ļ£“
ļ£²font_normal_stretchļ£½ ļ£² ļ£½
=
numeric# ;
:= extensible codes ;
ļ£“ font_normal_shrink ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ ļ£“ fontdimen info ļ£“
empty
ļ£“ ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ ļ£³ ļ£¾
ļ£“ ļ£“
font_x_height
ļ£“ ļ£“
ļ£“ ļ£“ headerbytes info
ļ£“ ļ£“
ļ£“ ļ£“
font_quad
ļ£³ ļ£¾
font_extra_space
=
font_identifier := string .
font_coding_scheme empty
Drawing: penpos suļ¬x ( length , angle ); penstroke path(e) ;
pen
; pen number :=savepen; clear_pen_memory;
pickup
saved pen number
pen_lft, pen_rt, pen_top, pen_bot;
ļ£± ļ£¼
ļ£“ ļ£“
fill
ļ£² ļ£½ draw
unfill drawdot
cycle ; path ; pair ;
undraw
ļ£“ filldraw ļ£“
ļ£³ ļ£¾ undrawdot
cutdraw
unfilldraw
erase picture command ; cutoff( pair , angle );
addto picture variable also picture ;
ā„0
contour cycle withpen pen
addto picture variable ;
doublepath path withweight numeric
withweight numeric
keeping
cull picture variable pair .
empty
dropping
Screen display: currentwindow; screen_rows, screen_cols;
openwindow numeric from screen pair to screen pair at pair ;
display picture variable inwindow numeric .
Statements: empty ; string ; begingroup statements endgroup;
ļ£± ļ£¼ļ£¼
ļ£± ļ£¼ļ£± ļ£± ļ£¼
ļ£“ boolean ļ£“ ļ£“ ā„1
ļ£“ boolean ļ£“ ļ£“ ļ£“ boolean ļ£“
ļ£“ numeric ļ£“ ļ£“
ļ£“ numeric ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ numeric ļ£“
ļ£“
ļ£“ļ£“
ļ£“ļ£“ ļ£“
ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ pair ļ£“
ļ£“
ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“
ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ ļ£“ ļ£“
pair
pair ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ ļ£“
ļ£½ļ£² ļ£² ļ£½ļ£½
ļ£² ļ£² ļ£½
path
path = path
; names ;
ļ£“ ļ£“ := ļ£“ ļ£“ļ£“
ļ£“ ļ£“ ļ£“
pen
pen ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ ļ£“
pen
ļ£“ picture ļ£“ ļ£“
ļ£“ picture ļ£“ ļ£“ ļ£“
ļ£“ ļ£“
ļ£“ picture ļ£“
ļ£“ļ£“
ļ£“ļ£“ ļ£“
ļ£“ļ£“ ļ£“ ļ£“ļ£“
ļ£“ ļ£“ ļ£“
ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ string ļ£“
ļ£“
ļ£“ string ļ£“ ļ£“
ļ£“ string ļ£“ ļ£“ ļ£“
ļ£“ ļ£“ļ£“
ļ£“ ļ£“ļ£“ ļ£“ ļ£“
ļ£³ ļ£¾ļ£¾
ļ£³ ļ£¾ļ£³ ļ£³ ļ£¾
transform
transform transform
=
save names ; interim internal := numeric ; let name name ;
:=
Appendix B: Basic Operations 261
=
def
name parameters text enddef; Proofsheet
:=
vardef base ļ¬le
plain.mf
primarydef
=
Ī± name Ī² text(Ī±, Ī²) enddef;
secondarydef
:=
tertiarydef
showit; shipit; cullit; openit; clearit; clearxy; clearpen;
message
errmessage string ;
stop string ; show expressions ;
errhelp
showvariable showdependencies
names ; ;
showtoken showstats
see also Chapter 26 for some more exotic commands.
Proofsheet information:
ļ£± top ļ£¼
ļ£“ lft ļ£“
ļ£“ ļ£“
ļ£“ ļ£“
ļ£² ļ£½ nodot
labels
rt ( suļ¬xes );
penlabels ļ£“ ļ£“ bot ļ£“ empty
ļ£“
ļ£“ ļ£“
ļ£³ ļ£¾
empty
ļ£± top ļ£¼
ļ£± ļ£¼
ļ£“
ļ£“ lft ļ£“ ļ£“
ļ£“ ļ£“ ļ£“titlefontļ£“
ļ£² ļ£½ ļ£² ļ£½
nodot labelfont
rt ( string , pair ); name ;
makelabel
ļ£“ bot ļ£“ empty ļ£“ grayfont ļ£“
ļ£“ ļ£“ ļ£³ ļ£¾
ļ£“ ļ£“
ļ£³ ļ£¾ slantfont
empty
proofrule
( pair , pair ); makegrid( pairs )( pairs );
screenrule
proofrulethickness numeric ; proofoffset pair .
Hacks: gobble, gobbled, killtext; capsule_def; numtok.
The remainder of this appendix contains an edited transcript of the āplain
base ļ¬le,ā which is a set of macros that come with normal implementations
of . These macros serve three basic purposes: (1) They make 
usable, because ā™s primitive capabilities operate at a very low level.
A āvirginā system that has no macros is like a newborn baby that has
an immense amount to learn about the real world; but it is capable of learning fast.
(2) The plain macros provide a basis for more elaborate and powerful bases
tailored to individual tastes and applications. You can do a lot with plain ,
but pretty soon youā™ll want to do even more. (3) The macros also serve to illustrate
how additional bases can be designed.
Somewhere in your computer system you should be able to ļ¬nd a ļ¬le called
plain.mf that contains what has been preloaded into the running system
that you use. That ļ¬le should match the code discussed below, except that it might
do some things in an equivalent but slightly more eļ¬cient manner.
262 Appendix B: Basic Operations
When we come to macros whose use has not yet been explainedā”for example, INIMF
dump
somehow softjoin and stop never made it into Chapters 1 through 27ā”we shall
delimiters
consider them from a userā™s viewpoint. But most of the comments that follow are message
addressed to a potential baseļ¬le designer. blash blash
upto
A special program called INIMF is used to install ; INIMF is just downto
like except that it is able to ā˜dumpā™ a base ļ¬le suitable for preloading. exitunless
relax
This operation requires additional program space, so INIMF generally has less memory
]]
available than you would expect to ļ¬nd in a production version of . ā“
ā”
1. Getting started. A base ļ¬le has to have a delimiters command near the beginning, ...
since INIMF doesnā™t have any delimiters built in. The ļ¬rst few lines usually also give gobble
killtext
the base ļ¬le a name and version number as shown here. gobbled
hide
% This is the plain METAFONT base thatā™s described in The METAFONTbook.
???
% N.B.: Please change "base_version" whenever this file is modified! stop
MFT
% And donā™t modify the file under any circumstances.
prettyprinted
string base_name, base_version; base_name="plain"; base_version="2.71"; vacuous
exitif
message "Preloading the plain base, version " & base_version;
internal quantities
delimiters (); % this makes parentheses behave like parentheses smoothing
autorounding
Next we deļ¬ne some of the simplest macros, which provide āsyntactic sugarā turningcheck
granularity
for commonly occurring idioms. For example, ā˜stop "hello"ā™ displays ā˜helloā™ on the
interact
terminal and waits until return is typed.
def upto = step 1 until enddef; def downto = step 1 until enddef;
def exitunless expr c = exitif not c enddef;
let relax = \; % ignore the word ā˜relaxā™, as in TeX
let \\ = \; % double relaxation is like single
def ]] = ] ] enddef; % right brackets should be loners
def  = {curl 1}..{curl 1} enddef;
def  = .. tension infinity .. enddef;
def ... = .. tension atleast 1 .. enddef;
def gobble primary g = enddef; def killtext text t = enddef;
primarydef g gobbled gg = enddef;
def hide(text t) = exitif numeric begingroup t; endgroup; enddef;
def ??? = hide(interim showstopping:=1; showdependencies) enddef;
def stop expr s = message s; gobble readstring enddef;
(Chapter 20 points out that ā˜\ā™ is an expandable token that expands into nothing.
Plain allows also ā˜\\ā™, because thereā™s a formatting program called MFT
that uses \\ to insert extra spacing in a prettyprinted listing.) The ācleverā code for
hide is based on the fact that a vacuous expression is not numeric; hence no loop is
exited, and the computer doesnā™t mind the fact that we may not be in a loop at all.
The values of internal quantities are next on the agenda:
smoothing:=1; autorounding:=2; % this adjusts curves to the raster
turningcheck:=2; % this will warn about a "strange path"
granularity:=1; % this says that pixels are pixels
def interact = % prepares to make "show" commands stop
hide(showstopping:=1; tracingonline:=1) enddef;
Appendix B: Basic Operations 263
def loggingall = % puts tracing info into the log loggingall
tracingall
tracingcommands:=3; tracingedges:=2; tracingtitles:=1;
tracingnone
tracingequations:=1; tracingcapsules:=1; tracingspecs:=1; semicolon
eps
tracingpens:=1; tracingchoices:=1; tracingstats:=1;
epsilon
tracingoutput:=1; tracingmacros:=1; tracingrestores:=1; inļ¬nity
origin
enddef;
up
def tracingall = % turns on every form of tracing down
tracingonline:=1; showstopping:=1; loggingall enddef; right
left
def tracingnone = % turns off every form of tracing quartercircle
tracingcommands:=0; tracingonline:=0; showstopping:=0; halfcircle
fullcircle
tracingedges:=0; tracingtitles:=0; tracingequations:=0;
unitsquare
tracingcapsules:=0; tracingspecs:=0; tracingpens:=0; identity
blankpicture
tracingchoices:=0; tracingstats:=0; tracingoutput:=0;
unitpixel
tracingmacros:=0; tracingrestores:=0; enddef; ditto
The user can say interact in the midst of a statement; but loggingall, tracingall,
and tracingnone should come between statements. (You donā™t need a semicolon after
them, because they come equipped with their own closing ā˜;ā™.)
2. Math routines. The second major part of plain.mf contains the deļ¬nitions of basic
constants and mathematical macros that extend the primitive capabilities of 
ā™s expressions.
% numeric constants
newinternal eps,epsilon,infinity;
eps := .00049; % this is a pretty small positive number
epsilon := 1/256/256; % but this is the smallest
infinity := 4095.99998; % and this is the largest
% pair constants
pair right,left,up,down,origin;
origin=(0,0); up=down=(0,1); right=left=(1,0);
% path constants
path quartercircle,halfcircle,fullcircle,unitsquare;
quartercircle=(right{up}..(right+up)/sqrt2..up{left}) scaled .5;
halfcircle=quartercircle & quartercircle rotated 90;
fullcircle=halfcircle & halfcircle rotated 180 & cycle;
unitsquare=(0,0)(1,0)(1,1)(0,1)cycle;
% transform constants
transform identity;
for z=origin,right,up: z transformed identity = z; endfor
% picture constants
picture blankpicture,unitpixel;
blankpicture=nullpicture; % ā˜display blankpicture...ā™
unitpixel=nullpicture; addto unitpixel contour unitsquare;
% string constants
string ditto; ditto = char 34; % ASCII doublequote mark
264 Appendix B: Basic Operations
% pen constants pensquare
penrazor
def capsule_def(suffix s) primary u = def s = u enddef enddef; future pens
capsule_def(pensquare) makepen(unitsquare shifted (.5,.5)); capsule
capsule def
capsule_def(penrazor) makepen((.5,0)(.5,0)cycle);
penspeck
pen penspeck; penspeck=pensquare scaled eps; whatever
abs
round
The pensquare and penrazor constants are deļ¬ned here in a surprisingly roundabout
hround
way, just so that they can be future pens instead of pens. can transform a vround
future pen much faster than a pen, since pens have a complex internal data structure, ceiling
byte
so this trick saves time. But how does it work? Well, a variable cannot be a future pen,
dir
but a capsule can; hence pensquare and penrazor are deļ¬ned, via capsule def , to unitvector
be macros that expand into single capsules. Incidentally, penspeck is an extremely inverse
counterclockwise
tiny little pen that is used by the drawdot macro. Since it is not intended to be autorounding
transformed, we are better oļ¬ making it a pen; then itā™s immediately ready for use. turningnumber
tensepath
Now that the basic constants have been deļ¬ned, we turn to mathematical
operations. Thereā™s one operation that has no arguments:
% nullary operators
vardef whatever = save ?; ? enddef;
The reasoning behind this is discussed in exercise 17.2.
Operations that take one argument are introduced next.
% unary operators
let abs = length;
vardef round primary u =
if numeric u: floor(u+.5)
elseif pair u: (hround xpart u, vround ypart u)
else: u fi enddef;
vardef hround primary x = floor(x+.5) enddef;
vardef vround primary y = floor(y.o_+.5)_o_ enddef;
vardef ceiling primary x = floor(x) enddef;
vardef byte primary s = if string s: ASCII fi s enddef;
vardef dir primary d = right rotated d enddef;
vardef unitvector primary z = z/abs z enddef;
vardef inverse primary T =
transform T_; T_ transformed T = identity; T_ enddef;
vardef counterclockwise primary c =
if turningcheck>0:
interim autorounding:=0;
if turningnumber c <= 0: reverse fi fi c enddef;
vardef tensepath expr r =
for k=0 upto length r  1: point k of r  endfor
if cycle r: cycle else: point infinity of r fi enddef;
Appendix B: Basic Operations 265
Notice that the variable ā˜T_ā™ was not saved by the inverse function. The plain base eļ¬ciency
private
routines gain eļ¬ciency by using āprivateā tokens that are assumed to be distinct from
underscore
any of the userā™s tokens; these private tokens always end with the underscore charac mod
ter, ā˜_ā™. If ordinary user programs never contain such token names, no surprises will div
dotprod
occur, provided that diļ¬erent macro designers who combine their routines are careful takepower
that their private names are not in conļ¬‚ict. **
direction
The private tokens ā˜o_ā™ and ā˜_o_ā™ used in vround stand for ā˜*aspect_ratioā™
directionpoint
and ā˜/aspect_ratioā™, respectively, as we shall see shortly. directiontime
Now we deļ¬ne ā˜modā™ and ā˜divā™, being careful to do this in such a way that the intersectionpoint
intersectiontimes
identities a(x mod y) = (ax) mod (ay) and (ax) div (ay) = x div y are valid. internal quantity
eļ¬cient
% binary operators
primarydef x mod y = (xy*floor(x/y)) enddef;
primarydef x div y = floor(x/y) enddef;
primarydef w dotprod z = (xpart w * xpart z + ypart w * ypart z) enddef;
The ā˜**ā™ operator is designed to be most eļ¬cient when itā™s used for squaring.
A separate ā˜takepowerā™ routine is used for exponents other than 2, so that
doesnā™t have to skip over lots of tokens in the common case. The takepower routine is
careful to give the correct answer in expressions like ā˜(2)**(3)ā™ and ā˜0**0ā™.
primarydef x ** y = if y=2: x*x else: takepower y of x fi enddef;
def takepower expr y of x =
if x>0: mexp(y*mlog x)
elseif (x=0) and (y>0): 0
else: 1
if y=floor y:
if y>=0: for n=1 upto y: *x endfor
else: for n=1 downto y: /x endfor fi
else: hide(errmessage "Undefined power: " & decimal x&"**"&decimal y)
fi fi enddef;
ā™s primitive path operations have been deļ¬ned in such a way that
the following higherlevel operations are easy:
vardef direction expr t of p =
postcontrol t of p  precontrol t of p enddef;
vardef directionpoint expr z of p =
a_:=directiontime z of p;
if a_<0: errmessage("The direction doesnā™t occur"); fi
point a_ of p enddef;
secondarydef p intersectionpoint q =
begingroup save x_,y_; (x_,y_)=p intersectiontimes q;
if x_<0: errmessage("The paths donā™t intersect"); (0,0)
else: .5[point x_ of p, point y_ of q] fi endgroup
enddef;
The private token ā˜a_ā™ will be declared as an internal quantity. Internal quantities are
more eļ¬cient than ordinary numeric variables.
266 Appendix B: Basic Operations
Plain ā™s ā˜softjoinā™ operation provides a way to hook paths together softjoin
join radius
without the abrupt change of direction implied by ā˜&ā™. Assuming that the ļ¬nal point
Billawala
of p is the ļ¬rst point of q, the path ā˜p softjoin qā™ begins on p until coming within fullcircle
join radius of this common point; then it curves over and ļ¬nishes q in essentially the incr
decr
same way. The internal quantity join radius should be set to the desired value before transform
softjoin is applied. (This routine is due to N. N. Billawala.) reļ¬‚ectedabout
rotatedaround
tertiarydef p softjoin q = rotatedabout
max
begingroup c_:=fullcircle scaled 2join_radius shifted point 0 of q; min
a_:=ypart(c_ intersectiontimes p); b_:=ypart(c_ intersectiontimes q); setu
if a_<0:point 0 of p{direction 0 of p} else: subpath(0,a_) of p fi
... if b_<0:{direction infinity of q}point infinity of q
else: subpath(b_,infinity) of q fi endgroup enddef;
newinternal join_radius,a_,b_; path c_;
The remaining math operators donā™t fall into the ordinary patterns; something
is unusual about each of them. First we have ā˜incrā™ and ā˜decrā™, which apply only to
variables; they have the side eļ¬ect of changing the variableā™s value.
vardef incr suffix $ = $:=$+1; $ enddef;
vardef decr suffix $ = $:=$1; $ enddef;
You can say either ā˜incr xā™ or ā˜incr (x)ā™, within an expression; but ā˜incr xā™ by itself
is not a valid statement.
To reļ¬‚ect about a line, we compute a transform on the ļ¬‚y:
def reflectedabout(expr w,z) = % reflects about the line w..z
transformed
begingroup transform T_;
w transformed T_ = w; z transformed T_ = z;
xxpart T_ = yypart T_; xypart T_ = yxpart T_; % T_ is a reflection
T_ endgroup enddef;
def rotatedaround(expr z, d) = % rotates d degrees around z
shifted z rotated d shifted z enddef;
let rotatedabout = rotatedaround; % for roundabout people
Now we come to an interesting trick: The user writes something like ā˜min(a, b)ā™
or ā˜max(a, b, c, d)ā™, and ā™s notation for macro calls makes it easy to separate
the ļ¬rst argument from the restā”assuming that at least two arguments are present.
vardef max(expr u)(text t) = % t is a list of numerics, pairs, or strings
save u_; setu_ u; for uu = t: if uu>u_: u_:=uu; fi endfor
u_ enddef;
vardef min(expr u)(text t) = % t is a list of numerics, pairs, or strings
save u_; setu_ u; for uu = t: if uu<u_: u_:=uu; fi endfor
u_ enddef;
def setu_ primary u =
if pair u: pair u_ elseif string u: string u_ fi;
u_=u enddef;
Appendix D discusses some variations on this theme.
Appendix B: Basic Operations 267
The flex routine deļ¬nes part of a path whose directions at the endpoints will ļ¬‚ex
superellipse
depend on the environment, because this path is not enclosed in parentheses.
interpath
solve
def flex(text t) = % t is a list of pairs tolerance
hide(n_:=0; for z=t: z_[incr n_]:=z; endfor mm
cm
dz_:=z_[n_]z_1)
pt
z_1 for k=2 upto n_1: ...z_[k]{dz_} endfor ...z_[n_] enddef; pc
newinternal n_; pair z_[],dz_; dd
cc
The ļ¬ve parameters to ā˜superellipseā™ are the right, the top, the left, the bottom, bp
in
and the superness.
ļ¬x units
pixels per inch
def superellipse(expr r,t,l,b,s)=
r{up}...(s[xpart t,xpart r],s[ypart r,ypart t]){tr}...
t{left}...(s[xpart t,xpart l],s[ypart l,ypart t]){lt}...
l{down}...(s[xpart b,xpart l],s[ypart l,ypart b]){bl}...
b{right}...(s[xpart b,xpart r],s[ypart r,ypart b]){rb}...cycle enddef;
Chapter 14 illustrates the ā˜interpathā™ routine, which interpolates between
paths to ļ¬nd a path that would be written ā˜a[p, q]ā™ if ā™s macro notation
were more general.
vardef interpath(expr a,p,q) =
for t=0 upto length p1: a[point t of p, point t of q]
..controls a[postcontrol t of p, postcontrol t of q]
and a[precontrol t+1 of p, precontrol t+1 of q] .. endfor
if cycle p: cycle
else: a[point infinity of p, point infinity of q] fi enddef;
Finally we come to the solve macro, which has already been presented in
Chapter 20. Appendix D gives further illustrations of its use.
vardef solve@#(expr true_x,false_x)= % @#(true_x)=true, @#(false_x)=false
tx_:=true_x; fx_:=false_x;
forever: x_:=.5[tx_,fx_]; exitif abs(tx_fx_)<=tolerance;
if @#(x_): tx_ else: fx_ fi :=x_; endfor
x_ enddef; % now x_ is near where @# changes from true to false
newinternal tolerance, tx_,fx_,x_; tolerance:=.1;
3. Conversion to pixels. The next main subdivision of plain.mf contains macros and
constants that help convert dimensions from deviceindependent āsharpedā or ātrueā
units into the pixel units corresponding to a particular device. First comes a subroutine
that computes eight basic units, assuming that the number of pixels per inch is known:
def fix_units = % define the conversion factors, given pixels_per_inch
mm:=pixels_per_inch/25.4; cm:=pixels_per_inch/2.54;
pt:=pixels_per_inch/72.27; pc:=pixels_per_inch/6.0225;
dd:=1238/1157pt; cc:=12dd;
bp:=pixels_per_inch/72; in:=pixels_per_inch;
hppp:=pt; % horizontal pixels per point
vppp:=aspect_ratio*hppp; % vertical pixels per point
enddef;
268 Appendix B: Basic Operations
Sharped units are actually expressed in terms of points, but a virtuous user Sharped units
pixels per inch
will not write programs that exploit this fact.
blacker
o correction
mm#=2.84528; pt#=1; dd#=1.07001; bp#=1.00375; ļ¬llin
cm#=28.45276; pc#=12; cc#=12.84010; in#=72.27; deļ¬ne pixels (and nine others)
lowres ļ¬x
A particular device is supposed to be modeled by four parameters, called
pixels per inch , blacker , o correction , and ļ¬llin , as discussed in Chapter 11. Appro
priate values will be assigned to these internal quantities by mode setup.
newinternal pixels_per_inch; % the given resolution
newinternal blacker, o_correction; % deviceoriented corrections
(The fourth parameter, ļ¬llin , is already an internal quantity of .)
Here are the ten principal ways to convert from sharped units to pixels:
def define_pixels(text t) =
forsuffixes $=t: $:=$.#*hppp; endfor enddef;
def define_whole_pixels(text t) =
forsuffixes $=t: $:=hround($.#*hppp); endfor enddef;
def define_whole_vertical_pixels(text t) =
forsuffixes $=t: $:=vround($.#*hppp); endfor enddef;
def define_good_x_pixels(text t) =
forsuffixes $=t: $:=good.x($.#*hppp); endfor enddef;
def define_good_y_pixels(text t) =
forsuffixes $=t: $:=good.y($.#*hppp); endfor enddef;
def define_blacker_pixels(text t) =
forsuffixes $=t: $:=$.#*hppp+blacker; endfor enddef;
def define_whole_blacker_pixels(text t) =
forsuffixes $=t: $:=hround($.#*hppp+blacker);
if $<=0: $:=1; fi endfor enddef;
def define_whole_vertical_blacker_pixels(text t) =
forsuffixes $=t: $:=vround($.#*hppp+blacker);
if $<=0: $:=1_o_; fi endfor enddef;
def define_corrected_pixels(text t) =
forsuffixes $=t: $:=vround($.#*hppp*o_correction)+eps; endfor enddef;
def define_horizontal_corrected_pixels(text t) =
forsuffixes $=t: $:=hround($.#*hppp*o_correction)+eps; endfor enddef;
Chapter 24 discusses the lowres ļ¬x routine, which helps to correct anomalies
that may have occurred when sharped dimensions were rounded to whole pixels.
def lowres_fix(text t) expr ratio =
begingroup save min,max,first;
forsuffixes $=t:
if unknown min: min=max=first=$; min#=max#=$.#;
elseif $.#<min#: min:=$; min#:=$.#;
elseif $.#>max#: max:=$; max#:=$.#; fi endfor
if max/min>ratio*max#/min#: forsuffixes $=t: $:=first; endfor fi
endgroup enddef;
Appendix B: Basic Operations 269
4. Modes of operation. The standard way to create a font with plain is to **
mag
start up the program by saying
mode
input
\mode= mode name ; mag= magniļ¬cation ; input font ļ¬le name smode
mode setup
in response to ā™s initial ā˜**ā™. The mag is omitted if the magniļ¬cation is 1, smode
and the mode is omitted if mode=proof. Additional commands like ā˜screencharsā™ might displaying
extra setup
be given before the ā˜inputā™; we shall discuss them later. If you are using another
mode name
base ļ¬le, called say the ā˜superā™ base, this whole command line should be preceded scantokens
by ā˜&superā™. The mode name should have been predeclared in your base ļ¬le, by the
mode_def routine below. If, however, you need a special mode that isnā™t in the base,
you can put its commands into a ļ¬le (e.g., ā˜specmode.mfā™) and invoke it by saying
\smode="specmode"; mag= Ā· Ā· Ā·
instead of giving a predeclared mode name.
Here is the mode setup routine, which is usually one of the ļ¬rst macros to
be called in a program:
def mode_setup =
warningcheck:=0;
if unknown mode: mode=proof; fi
numeric aspect_ratio; transform currenttransform;
scantokens if string mode:("input "&mode) else: mode_name[mode] fi;
if unknown mag: mag=1; fi
if unknown aspect_ratio: aspect_ratio=1; fi
displaying:=proofing;
pixels_per_inch:=pixels_per_inch*mag;
if aspect_ratio=1: let o_=\; let _o_=\
else: def o_=*aspect_ratio enddef; def _o_=/aspect_ratio enddef fi;
fix_units;
scantokens extra_setup; % the userā™s special lastminute adjustments
currenttransform:=
if unknown currenttransform: identity else: currenttransform fi
yscaled aspect_ratio;
clearit;
pickup pencircle scaled (.4pt+blacker);
warningcheck:=1; enddef;
def smode = string mode; mode enddef;
string extra_setup, mode_name[];
extra_setup=""; % usually thereā™s nothing special to do
newinternal displaying; % if positive, endchar will ā˜showitā™
The ļ¬rst ā˜scantokensā™ in mode setup either reads a special ļ¬le or calls a macro that
expands into commands deļ¬ning the mode. Notice that aspect ratio is always cleared to
an undeļ¬ned value when these commands are performed; you canā™t simply give a value
to aspect ratio when you set mode and mag . If the aspect ratio isnā™t assigned a deļ¬nite
value by the mode routine, it will become unity, and the ā˜o_ā™ and ā˜_o_ā™ operations will
be omitted from subsequent calculations. Notice also that the mode commands might
do something special to mag , since mag isnā™t examined until after the mode routine
has acted. The currenttransform might also be given a special value. ā™s
270 Appendix B: Basic Operations
warningcheck is temporarily disabled during these computations, since there might be warningcheck
mexp
more than 4096 pixels per inch. After mode setup is ļ¬nished, the currentpicture will
magstep
be null, the currenttransform will take the aspect ratio into account, and the currentpen underscore
will be a circular nib with the standard default thickness of 0.4 pt. (You should save expandafter
quote
this pen if you want to use it in a character, because beginchar will clear it away.) mode def
Plain TEX has a convention for magnifying fonts in terms of āmagsteps,ā where Leban
magstep m = 1.2m . A geometric progression of font sizes is convenient, because scaling proof
smoke
by magstep m followed by magstep n is equivalent to scaling by magstep m + n. fontmaking
lowres
vardef magstep primary m = mexp(46.67432m) enddef;
When a mode is deļ¬ned (e.g., ā˜proofā™), a numeric variable of that name is
created and assigned a unique number (e.g., 1). Then an underscore character is ap
pended, and a macro is deļ¬ned for the resulting name (e.g., ā˜proof_ā™). The mode name
array is used to convert between number and name (e.g., mode name 1 = "proof_").
def mode_def suffix $ =
$:=incr number_of_modes;
mode_name[$]:=str$ & "_";
expandafter quote def scantokens mode_name[$] enddef;
newinternal number_of_modes;
(This mode def strategy was suggested by Bruce Leban.)
Three basic modes are now deļ¬ned, starting with two for prooļ¬ng:
% proof mode: for initial design of characters
mode_def proof =
proofing:=2; % yes, weā™re making full proofs
fontmaking:=0; % no, weā™re not making a font
tracingtitles:=1; % yes, show titles online
pixels_per_inch:=2601.72; % thatā™s 36 pixels per pt
blacker:=0; % no additional blackness
fillin:=0; % no compensation for fillin
o_correction:=1; % no reduction in overshoot
enddef;
% smoke mode: for labelfree proofs to mount on the wall
mode_def smoke =
proof_; % same as proof mode, except:
proofing:=1; % yes, weā™re making unlabeled proofs
extra_setup:=extra_setup&"grayfont black"; % with solid black pixels
let makebox=maketicks; % make the boxes less obtrusive
enddef;
Notice that smoke mode saves a lot of fuss by calling on ā˜proof_ā™; this is the macro
that was deļ¬ned by the ļ¬rst mode def .
A typical mode for font generation appears next.
% lowres mode: for certain devices that print 200 pixels per inch
mode_def lowres =
proofing:=0; % no, weā™re not making proofs
fontmaking:=1; % yes, we are making a font
Appendix B: Basic Operations 271
tracingtitles:=0; % no, donā™t show titles at all currentpen
currentpicture
pixels_per_inch:=200; % thatā™s pretty low resolution
currenttransform
blacker:=.65; % make pens a bit blacker ļ¬ll
draw
fillin:=.2; % compensate for diagonal fillin
ļ¬lldraw
o_correction:=.4; % but donā™t overshoot as much drawdot
enddef; unļ¬ll
undraw
localfont:=lowres; % the mode most commonly used to make fonts unļ¬lldraw
undrawdot
Installations of typically have several more predeļ¬ned modes, and they erase
generally set localfont to something else. Such alterations should not be made in the cutdraw
master ļ¬le plain.mf; they should appear in a separate ļ¬le, as discussed below.
5. Drawing and ļ¬lling. Now we come to the macros that provide an interface between
the user and ā™s primitive picture commands. First, some important program
variables are introduced:
pen currentpen;
path currentpen_path;
picture currentpicture;
transform currenttransform;
def t_ = transformed currenttransform enddef;
The key macros are ļ¬ll, draw, ļ¬lldraw, and drawdot.
def fill expr c = addto_currentpicture contour c.t_ enddef;
def addto_currentpicture = addto currentpicture enddef;
def draw expr p =
addto_currentpicture doublepath p.t_ withpen currentpen enddef;
def filldraw expr c = fill counterclockwise c withpen currentpen enddef;
def drawdot expr z = if unknown currentpen_path: def_pen_path_ fi
addto_currentpicture contour
currentpen_path shifted (z.t_) withpen penspeck enddef;
def def_pen_path_ =
hide(currentpen_path=tensepath makepath currentpen) enddef;
And they have negative counterparts:
def unfill expr c = fill c withweight 1 enddef;
def undraw expr p = draw p withweight 1 enddef;
def unfilldraw expr c = filldraw c withweight 1 enddef;
def undrawdot expr z = drawdot z withweight 1 enddef;
def erase text t = begingroup interim default_wt_:=1;
cullit; t withweight 1; cullit; endgroup enddef;
newinternal default_wt_; default_wt_:=1;
Itā™s more diļ¬cult to cut oļ¬ the ends of a stroke, but the following macros
(discussed near the end of Chapter 16) do the job:
def cutdraw expr p = % caution: you may need autorounding=0
cutoff(point 0 of p, 180+angle direction 0 of p);
cutoff(point infinity of p, angle direction infinity of p);
culldraw p enddef;
272 Appendix B: Basic Operations
def culldraw expr p = addto pic_ doublepath p.t_ withpen currentpen; culldraw
cutoļ¬
cull pic_ dropping(infinity,0) withweight default_wt_;
default wt
addto_currentpicture also pic_; pic_:=nullpicture; killtext enddef; erase
pen lft
vardef cutoff(expr z,theta) =
pen rt
interim autorounding := 0; interim smoothing := 0; pen top
pen bot
addto pic_ doublepath z.t_ withpen currentpen;
pickup
addto pic_ contour savepen
(cut_ scaled (1+max(pen_lft,pen_rt,pen_top,pen_bot)) clearpen
rotated theta shifted z)t_;
cull pic_ keeping (2,2) withweight default_wt_;
addto currentpicture also pic_; pic_:=nullpicture enddef;
picture pic_; pic_:=nullpicture;
path cut_; cut_ = ((0,1)(1,1)(1,1)(0,1)cycle) scaled 1.42;
The use of default wt here makes ā˜erase cutdrawā™ work. The private variable pic is
usually kept equal to nullpicture in order to conserve memory space.
Picking up a pen not only sets currentpen , it also establishes the values of
pen lft , pen rt , pen top , and pen bot , which are used by lft , rt , top , and bot .
def pickup secondary q =
if numeric q: numeric_pickup_ else: pen_pickup_ fi q enddef;
def numeric_pickup_ primary q =
if unknown pen_[q]: errmessage "Unknown pen"; clearpen
else: currentpen:=pen_[q];
pen_lft:=pen_lft_[q]; pen_rt:=pen_rt_[q];
pen_top:=pen_top_[q]; pen_bot:=pen_bot_[q];
currentpen_path:=pen_path_[q] fi; enddef;
def pen_pickup_ primary q =
currentpen:=q yscaled aspect_ratio;
pen_lft:=xpart penoffset down of currentpen;
pen_rt:=xpart penoffset up of currentpen;
pen_top:=(ypart penoffset left of currentpen)_o_;
pen_bot:=(ypart penoffset right of currentpen)_o_;
path currentpen_path; enddef;
newinternal pen_lft,pen_rt,pen_top,pen_bot,pen_count_;
And saving a pen saves all the relevant values for later retrieval.
vardef savepen = pen_[incr pen_count_]=currentpen;
pen_lft_[pen_count_]=pen_lft;
pen_rt_[pen_count_]=pen_rt;
pen_top_[pen_count_]=pen_top;
pen_bot_[pen_count_]=pen_bot;
pen_path_[pen_count_]=currentpen_path;
pen_count_ enddef;
def clearpen = currentpen:=nullpen;
pen_lft:=pen_rt:=pen_top:=pen_bot:=0;
path currentpen_path; enddef;
Appendix B: Basic Operations 273
def clear_pen_memory = clear pen memory
lft
pen_count_:=0;
rt
numeric pen_lft_[],pen_rt_[],pen_top_[],pen_bot_[]; top
bot
pen currentpen,pen_[];
round
path currentpen_path, pen_path_[]; good.x
enddef; good.y
good.lft
good.rt
The four basic penedge functions oļ¬er no surprises:
good.top
good.bot
vardef lft primary x = x + if pair x: (pen_lft,0) else: pen_lft fi enddef; penpos
vardef rt primary x = x + if pair x: (pen_rt,0) else: pen_rt fi enddef; penstroke
vardef top primary y = y + if pair y: (0,pen_top) else: pen_top fi enddef;
vardef bot primary y = y + if pair y: (0,pen_bot) else: pen_bot fi enddef;
There are six functions that round to good positions for pen placement.
vardef good.x primary x = hround(x+pen_lft)pen_lft enddef;
vardef good.y primary y = vround(y+pen_top)pen_top enddef;
vardef good.lft primary z = save z_; pair z_;
(z_+(pen_lft,0))t_=round((z+(pen_lft,0))t_); z_ enddef;
vardef good.rt primary z = save z_; pair z_;
(z_+(pen_rt,0))t_=round((z+(pen_rt,0))t_); z_ enddef;
vardef good.top primary z = save z_; pair z_;
(z_+(0,pen_top))t_=round((z+(0,pen_top))t_); z_ enddef;
vardef good.bot primary z = save z_; pair z_;
(z_+(0,pen_bot))t_=round((z+(0,pen_bot))t_); z_ enddef;
So much for ļ¬xed pens. When penlike strokes are deļ¬ned by outlines, the
penpos macro is of primary importance. Since penpos may be used quite frequently,
we might as well write out the x and y coordinates explicitly instead of using the
(somewhat slower) z convention:
vardef penpos@#(expr b,d) =
(x@#rx@#l,y@#ry@#l)=(b,0) rotated d;
x@#=.5(x@#l+x@#r); y@#=.5(y@#l+y@#r) enddef;
Simulated pen strokes are provided by the convenient penstroke command.
def penstroke text t =
forsuffixes e = l,r: path_.e:=t; endfor
if cycle path_.l: cyclestroke_
else: fill path_.l  reverse path_.r  cycle fi enddef;
def cyclestroke_ =
begingroup interim turningcheck:=0;
addto pic_ contour path_.l.t_ withweight 1;
addto pic_ contour path_.r.t_ withweight 1;
cull pic_ dropping origin withweight default_wt_;
addto_currentpicture also pic_;
pic_:=nullpicture endgroup enddef;
path path_.l,path_.r;
274 Appendix B: Basic Operations
6. Proof labels and rules. The next main section of plain.mf is devoted to macros for special
numspecial
the annotations on proofsheets. These macros are discussed in Appendix H, and they
lcode
use the special and numspecial commands discussed in Appendix G. makelabel
Labels are generated at the lowest level by makelabel : prooļ¬ng
labels
penlabels
vardef makelabel@#(expr s,z) = % puts string s at point z
range
if known z: special lcode_@# & s; numtok
numspecial xpart(z.t_); numspecial ypart(z.t_) fi enddef; thru
forsuļ¬xes
string lcode_,lcode_.top,lcode_.lft,lcode_.rt,lcode_.bot, proofrule
lcode_.top.nodot,lcode_.lft.nodot,lcode_.rt.nodot,lcode_.bot.nodot; screenrule
lcode_.top=" 1"; lcode_.lft=" 2"; lcode_.rt=" 3"; lcode_.bot=" 4";
lcode_=" 0"; % change to " /" to avoid listing in overflow column
lcode_.top.nodot=" 5"; lcode_.lft.nodot=" 6";
lcode_.rt.nodot=" 7"; lcode_.bot.nodot=" 8";
Users generally donā™t invoke makelabel directly, because thereā™s a conve
nient shorthand. For example, ā˜labels(1, 2, 3)ā™ expands into ā˜makelabel ("1", z1 );
makelabel ("2", z2 ); makelabel ("3", z3 )ā™. (But nothing happens if prooļ¬ng ā¤ 1.)
vardef labels@#(text t) =
if proofing>1: forsuffixes $=t: makelabel@#(str$,z$); endfor fi enddef;
vardef penlabels@#(text t) =
if proofing>1: forsuffixes $$=l,,r: forsuffixes $=t:
makelabel@#(str$.$$,z$.$$); endfor endfor fi enddef;
When there are lots of purely numeric labels, you can say, e.g.,
labels(1, range 5 thru 9, range 100 thru 124, 223)
which is equivalent to ā˜labels(1, 5, 6, 7, 8, 9, 100, 101, . . . , 124, 223)ā™. Labels are omitted
from the proofsheets if the corresponding z value isnā™t known, so it doesnā™t hurt (much)
to include unused subscript numbers in a range.
def range expr x = numtok[x] enddef;
def numtok suffix x=x enddef;
tertiarydef m thru n =
m for x=m+1 step 1 until n: , numtok[x] endfor enddef;
ńņš. 9 