met a post

109
METAPOST a user s manual John D. Hobby and the MetaPost development team documented v ersion: 1.212 October 19, 2010

Upload: rayan-bao

Post on 06-Apr-2018

219 views

Category:

Documents


0 download

TRANSCRIPT

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 1/109

METAPOST

a user’s manual

John D. Hobby

and the MetaPost development team

documented version: 1.212

October 19, 2010

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 2/109

Contents

1 Introduction 1

2 Basic Drawing Statements 2

3 The MetaPost Workow 3

4 Curves 54.1 Bézier Cubic Curves . . . . . . . 74.2 Speciying Direction, Tension,

and Curl . . . . . . . . . . . . . . 74.3 Summary o Path Syntax . . . . 9

5 Linear Equations 11

5.1 Equations and Coordinate Pairs . 115.2 Dealing with Unknowns . . . . . 13

6 Expressions 14

6.1 Data Types . . . . . . . . . . . . 146.2 Operators . . . . . . . . . . . . . 156.3 Fractions, Mediation, and Unary

Operators . . . . . . . . . . . . . 177 Variables 18

7.1 Tokens . . . . . . . . . . . . . . . 187.2 Variable Declarations . . . . . . . 19

8 Integrating Text and Graphics 21

8.1 Typesetting Your Labels . . . . . 228.2 Font Map Files . . . . . . . . . . 258.3 The infont Operator . . . . . . 268.4 Measuring Text . . . . . . . . . . 27

9 Advanced Graphics 28

9.1 Building Cycles . . . . . . . . . . 309.2 Dealing with Paths Parametrically 32

9.3 Ane Transormations . . . . . . 359.4 Dashed Lines . . . . . . . . . . . 379.5 Local specials . . . . . . . . . . . 40

9.6 Other Options . . . . . . . . . . 409.7 Pens . . . . . . . . . . . . . . . . 439.8 Clipping and Low-Level Draw-

ing Commands . . . . . . . . . . 449.9 Directing Output to a Picture

Variable . . . . . . . . . . . . . . 469.10 Inspecting the Components o a

Picture . . . . . . . . . . . . . . . 469.11 Decomposing the Glyphs o a Font 48

10 Macros 50

10.1 Grouping . . . . . . . . . . . . . 5110.2 Parameterized Macros . . . . . . 5210.3 Sux and Text Parameters . . . 5510.4 Varde Macros . . . . . . . . . . 5810.5 Dening Unary and Binary Macros 59

11 Loops 61

12 Reading and Writing Files 62

13 Utility Routines 63

13.1 TEX.mp . . . . . . . . . . . . . . . 63

14 Another Look at the MetaPost

Workow 65

14.1 Customizing Run-Time Behavior 6514.2 Previewing PostScript Output . . 6714.3 Debugging . . . . . . . . . . . . . 6914.4 Importing MetaPost Graphics

into External Applications . . . . 71

A Reerence Manual 75

A.1 The MetaPost Language . . . . . 75A.2 Command-Line Syntax . . . . . . 94

B Legacy Inormation 97B.1 MetaPost Versus METAFONT . . 97B.2 File Name Templates . . . . . . . 100

1 Introduction

MetaPost is a programming language much like Knuth’s METAFONT1 [5] except that it outputsvector graphics, either PostScript programs or SVG graphics, instead o bitmaps. Borrowed romMETAFONT are the basic tools or creating and manipulating pictures. These include numbers, co-ordinate pairs, cubic splines, ane transormations, text strings, and boolean quantities. Additionaleatures acilitate integrating text and graphics and accessing special eatures o PostScript2 suchas clipping, shading, and dashed lines. Another eature borrowed rom METAFONT is the ability

to solve linear equations that are given implicitly, thus allowing many programs to be written ina largely declarative style. By building complex operations rom simpler ones, MetaPost achievesboth power and exibility.

MetaPost is particularly well-suited to generating gures or technical documents where someaspects o a picture may be controlled by mathematical or geometrical constraints that are best

1METAFONT is a trademark o Addison Wesley Publishing company.

2PostScript is a trademark o Adobe Systems Inc.

1

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 3/109

expressed symbolically. In other words, MetaPost is not meant to take the place o a reehand draw-ing tool or even an interactive graphics editor. It is really a programming language or generatinggraphics, especially gures or TEX3 and trof documents.

This document introduces the MetaPost language, beginning with the eatures that are easiestto use and most important or simple applications. The rst ew sections describe the language asit appears to the novice user with key parameters at their deault values. Some eatures describedin these sections are part o a predened macro package called Plain. Later sections summarize thecomplete language and distinguish between primitives and preloaded macros rom the Plain macropackage. Reading the manual and creating moderately complex graphics with MetaPost does notrequire knowledge o METAFONT or access to The  METAFONT  book  [5]. However, to really masterMetaPost, both are benecial, since the MetaPost language is based on Knuth’s METAFONT to alarge extent. Appendix B.1 gives a detailed comparison o MetaPost and METAFONT.

MetaPost documentation is completed by “Drawing Boxes with MetaPost” and “Drawing Graphswith MetaPost”—the manuals o the boxes and graph packages originally developed by John D.Hobby.

The MetaPost home page is http://tug.org/metapost. It has links to much additional in-ormation, including many articles that have been written about MetaPost. For general help, trythe [email protected] mailing list; you can subscribe to this list at http://tug.org/mailman/

listinfo/metapost.

The development is currently hosted at http://foundry.supelec.fr/projects/metapost/;visit this site or the current development team members, sources, and much else.Please report bugs and request enhancements either on the [email protected] list, or through

the address given above. (Please do not send reports directly to Dr. Hobby any more.)

2 Basic Drawing Statements

The simplest drawing statements are the ones that generate straight lines. Thus

draw (20,20)--(0,0)

draws a diagonal line and

draw (20,20)--(0,0)--(0,30)--(30,0)--(0,0)

draws a polygonal line like this:

MetaPost also has a drawdot command to draw a single point with the current pen, as indrawdot (30,0).

What is meant by coordinates like (30,0)? MetaPost uses the same deault coordinate systemthat PostScript does. This means that (30,0) is 30 units to the right o the origin, where a unitis 1

72o an inch. We shall reer to this deault unit as a PostScript point to distinguish it rom the

standard printer’s point which is 172.27

inches.MetaPost uses the same names or units o measure that T

EX and METAFONT do. Thus bp reers

to PostScript points (“big points”) and pt reers to printer’s points. Other units o measure includein or inches, cm or centimeters, and mm or millimeters. For example,

(2cm,2cm)--(0,0)--(0,3cm)--(3cm,0)--(0,0)

3TEX is a trademark o the American Mathematical Society.

2

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 4/109

generates a larger version o the above diagram. It is OK to say 0 instead 0cm because cm is really just a conversion actor and 0cm just multiplies the conversion actor by zero. (MetaPost understandsconstructions like 2cm as shorthand or 2*cm).

It is convenient to introduce your own scale actor, say . Then you can dene coordinates interms o  and decide later whether you want to begin with u=1cm or u=0.5cm. This gives youcontrol over what gets scaled and what does not so that changing will not afect eatures such asline widths.

There are many ways to afect the appearance o a line besides just changing its width, so thewidth-control mechanisms allow a lot o generality that we do not need yet. This leads to the strangelooking statement

pickup pencircle scaled 4pt

or setting the line width (actually the pen size) or subsequent draw or drawdot statements to 4points. (This is about eight times the deault pen size).

With such a large pen size, the drawdot statement draws rather bold dots. We can use this tomake a grid o dots by nesting drawdot in a pair o loops:

for i=0 upto 2:

for j=0 upto 2: drawdot (i*u,j*u); endfor

endfor

The outer loop runs or = 0, 1, 2 and the inner loop runs or = 0, 1, 2. The result is a three-by-three grid o bold dots as shown in Figure 1. The gure also includes a larger version o thepolygonal line diagram that we saw beore.

beginfig(2);

u=1cm;

draw (2u,2u)--(0,0)--(0,3u)--(3u,0)--(0,0);

pickup pencircle scaled 4pt;

for i=0 upto 2:

for j=0 upto 2: drawdot (i*u,j*u); endfor

endfor

endfig;

Figure 1: MetaPost commands and the resulting output

3 The MetaPost Workow

Beore describing the MetaPost language in detail, let’s have a look at MetaPost’s graphic designworkow. This section also contains a ew technical details about MetaPost’s compilation process,

 just enough to get you started. Section 14 is more elaborate on this topic.In this manual, we’ll assume a stand-alone command-line executable o the MetaPost compiler

is used, which is usually called mpost. The syntax and program name itsel are system-dependent;sometimes it is named mp. The executable is actually a small wrapper program around mplib, alibrary containing the MetaPost compiler. The library can as well be embedded into third-party

applications.4 Section 14.4 has some brie inormation on how to use the MetaPost compiler built-into LuaTEX. For more inormation, please reer to the documentation o the embedding application.

The basic MetaPost workow is depicted in gure 2. Being a graphics description language,creating graphics with MetaPost ollows the edit-compile-debug  paradigm known rom other pro-gramming languages.

4C API and Lua bindings are described in fle manual/mplibapi.pdf as part o the MetaPost distribution.

3

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 5/109

Editor 

fig.mp

MetaPost 

fig.1

fig.log

Previewer 

Figure 2: The basic MetaPost workow

To create graphics with MetaPost, you prepare a text le containing code in the MetaPostlanguage and then invoke the compiler, usually by giving a command o the orm

 mpost ⟨input le⟩

on the command-line. MetaPost input les normally have names ending .mp but this part o thename can be omitted when invoking MetaPost. A complete description o the command-line syntax

can be ound in Section A.2.Any terminal I/O during the compilation process is summarized in a transcript le called ⟨ job-name⟩.log, where ⟨ jobname⟩ is the base name o the input le. This includes error messages andany MetaPost commands entered in interactive mode.

I all goes well during compilation, MetaPost outputs one or more graphic les in a variant o the PostScript ormat, by deault. PostScript output can be previewed with any decent PostScriptviewer, e.g., GSview or PS_View. Section 14.2 has some tips and discusses several more elaborateways or previewing PostScript output. Particularly, i graphics contain text labels, some more workmight be required to get robust results in a PostScript viewer. Starting with version 1.200, MetaPostis also capable o generating graphics in the SVG ormat. SVG les can be previewed with certainweb browsers, or example Fireox 3 or Konqueror 4.2.

What does one do with all the graphic les? PostScript les are perectly suitable or inclusioninto documents created by TEX or trof. The SVG ormat, as an XML descendant (Extensible Meta

Language), is more aiming at automated data processing/interchanging and is widely used or webapplications. Section 14.4 deals with the import o MetaPost graphics into external applications.A MetaPost input le normally contains a sequence o  beginfig(), endfig pairs with an end

statement ater the last one.5 These are macros that perorm various administrative unctions andensure that the results o all drawing operations get packaged up and translated into PostScript

5Omitting the fnal end statement causes MetaPost to enter interactive mode ater processing the input fle.

4

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 6/109

or SVG ormat. The numeric argument to the beginfig macro determines the name o the corre-sponding output le, whose name, by deault, is o the orm ⟨ jobname⟩.⟨n⟩, where ⟨n⟩ is the currentargument to beginfig rounded to the nearest integer. As an example, i a le is named fig.mp andcontains the lines

beginfig(1);

⟨drawing statements⟩endfig;

endthe output rom statements between beginfig(1) and the next endfig is written in a le fig.1.

Statements can also appear outside beginfig . . . endfig. Such statements are processed, butdrawing operations generate no visible output. Typically, global congurations are put outsidebeginfig . . . endfig, e.g., assignments to internal variables, such as outputtemplate, or a LATEXpreamble declaration or enhanced text rendering. Comments in MetaPost code are introduced bythe percent sign %, which causes the remainder o the current line to be ignored.

The remainder o this section briey introduces three assignments to internal variables, each oneuseul by itsel, that can oten be ound in MetaPost input les:

prologues := 3;

outputtemplate := "%j-%c.mps";

outputformat := "svg";

I your graphics contain text labels, you might want to set variable prologues to 3 to makesure the correct onts are used under all possible circumstances. The second assignment changes theoutput le naming scheme to the orm ⟨ jobname⟩-⟨n⟩.mps. That way, instead o a numeric index,all output les get a uniorm le extension mps, which is typically used or MetaPost’s PostScriptoutput. The last assignment lets MetaPost write output les in the SVG ormat rather than in thePostScript ormat. More inormation can be ound in Sections 8.1 and 14.

4 Curves

MetaPost is perectly happy to draw curved lines as well as straight ones. A draw statement withthe points separated by .. draws a smooth curve through the points. For example consider theresult o 

draw z0..z1..z2..z3..z4

ater dening ve points as ollows:

z0 = (0,0); z1 = (60,40);

z2 = (40,90); z3 = (10,70);

z4 = (30,50);

Figure 3 shows the curve with points z0 through z4 labeled.There are many other ways to draw a curved path through the same ve points. To make a

smooth closed curve, connect z4 back to the beginning by appending ..cycle to the draw statementas shown in Figure 4a. It is also possible in a single draw statement to mix curves and straight linesas shown in Figure 4b. Just use -- where you want straight lines and .. where you want curves.Thus

draw z0..z1..z2..z3--z4--cycleproduces a curve through points 0, 1, 2, and 3, then a polygonal line rom point 3 to point 4 andback to point 0. The result is essentially the same as having two draw statements

draw z0..z1..z2..z3

anddraw z3--z4--z0

5

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 7/109

0

2

4

3

1

Figure 3: The result o draw z0..z1..z2..z3..z4

2

4

0

3

1

()

2

4

0

3

1

()

Figure 4: (a) The result o  draw z0..z1..z2..z3..z4..cycle; (b) the result o  draw z0..z1..

z2..z3–z4–cycle.

6

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 8/109

4.1 Bézier Cubic Curves

When MetaPost is asked to draw a smooth curve through a sequence o points, it constructs apiecewise cubic curve with continuous slope and approximately continuous curvature. This meansthat a path specication such as

z0..z1..z2..z3..z4..z5

results in a curve that can be dened parametrically as ( (),  ()) or 0 ≤ ≤ 5, where  ()and  () are piecewise cubic unctions. That is, there is a diferent pair o cubic unctions or eachinteger-bounded -interval. I z0 = (0, 0), z1 = (1, 1), z2 = (2, 2), . . . , MetaPost selects Béziercontrol points (+

0 , +0 ), (−1 , −1 ), (+1 , +1 ), . . . , where

 ( + ) = (1 − )3 + 3(1 − )2+ + 32(1 − )−+1 + 3+1,

 ( + ) = (1 − )3 + 3(1 − )2+ + 32(1 − )−+1 + 3+1

or 0 ≤ ≤ 1. The precise rules or choosing the Bézier control points are described in [4] and inThe METAFONT  book  [5].

In order or the path to have a continuous slope at (, ), the incoming and outgoing directionsat ( (),  ()) must match. Thus the vectors

( − − , − − ) and (+ − , + − )

must have the same direction; i.e., (, ) must be on the line segment between (− , − ) and(+

, + ). This situation is illustrated in Figure 5 where the Bézier control points selected by Meta-Post are connected by dashed lines. For those who are amiliar with the interesting properties o this construction, MetaPost allows the control points to be specied directly in the ollowing ormat:

draw (0,0)..controls (26.8,-1.8) and (51.4,14.6)

..(60,40)..controls (67.1,61.0) and (59.8,84.6)

..(40,90)..controls (25.4,94.0) and (10.5,84.5)

..(10,70)..controls ( 9.6,58.8) and (18.8,49.6)

..(30,50);

For a way to extract the control points o a path, given by the user or calculated by MetaPost,

see section 9.2.

0

2

4

3

1

Figure 5: The result o  draw z0..z1..z2..z3..z4 with the automatically-selected Bézier controlpolygon illustrated by dashed lines.

4.2 Speciying Direction, Tension, and Curl

MetaPost provides many ways o controlling the behavior o a curved path without actually speciyingthe control points. For instance, some points on the path may be selected as vertical or horizontal

7

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 9/109

extrema. I z1 is to be a horizontal extreme and z2 is to be a vertical extreme, you can speciy that( (),  ()) should go upward at z1 and to the let at z2:

draw z0..z1{up}..z2{left}..z3..z4;

The resulting shown in Figure 6 has the desired vertical and horizontal directions at z1 and z2,but it does not look as smooth as the curve in Figure 3. The reason is the large discontinuity in

curvature at z1. I it were not or the specied direction at z1, the MetaPost interpreter would havechosen a direction designed to make the curvature above z1 almost the same as the curvature belowthat point.

0

2

4

3

1

Figure 6: The result o  draw z0..z1{up}..z2{left}..z3..z4.

How can the choice o directions at given points on a curve determine whether the curvaturewill be continuous? The reason is that curves used in MetaPost come rom a amily where a path isdetermined by its endpoints and the directions there. Figures 7 and 8 give a good idea o what thisamily o curves is like.

beginfig(7)

for a=0 upto 9:

draw (0,0){dir 45}..{dir -10a}(6cm,0);

endfor

endfig;

Figure 7: A curve amily and the MetaPost instructions or generating it

beginfig(8)

for a=0 upto 7:

draw (0,0){dir 45}..{dir 10a}(6cm,0);

endfor

endfig;

Figure 8: Another curve amily with the corresponding MetaPost instructions

Figures 7 and 8 illustrate a ew new MetaPost eatures. The rst is the dir operator that takes

an angle in degrees and generates a unit vector in that direction. Thus dir 0 is equivalent to rightand dir 90 is equivalent to up. There are also predened direction vectors left and down or dir

180 and dir 270.The direction vectors given in {} can be o any length, and they can come beore a point as well

as ater one. It is even possible or a path specication to have directions given beore and ater apoint. For example a path specication containing

..{dir 60}(10,0){up}..

8

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 10/109

produces a curve with a corner at (10, 0).Note that some o the curves in Figure 7 have points o inection. This is necessary in order to

produce smooth curves in situations like Figure 4a, but it is probably not desirable when dealingwith vertical and horizontal extreme points as in Figure 9a. I  z1 is supposed to be the topmostpoint on the curve, this can be achieved by using ... instead o .. in the path specication as shownin Figure 9b. The meaning o ... is “choose an inection-ree path between these points unless theendpoint directions make this impossible.” (It would be possible to avoid inections in Figure 7, butnot in Figure 8).

0

1

2draw z0{up}..z1{right}..z2{down}

0

1

2draw z0{up}...z1{right}...z2{down}

Figure 9: Two draw statements and the resulting curves.

Another way to control a misbehaving path is to increase the “tension” parameter. Using .. ina path specication sets the tension parameter to the deault value 1. I this makes some part o apath a little too wild, we can selectively increase the tension. I Figure 10a is considered “too wild,”a draw statement o the ollowing orm increases the tension between z1 and z2:

draw z0..z1..tension 1.3..z2..z3

This produces Figure 10b. For an asymmetrical efect like Figure 10c, the draw statement becomes

draw z0..z1..tension 1.5 and 1..z2..z3

The tension parameter can be less than one, but it must be at least 34

.

0

1 2

3()

0

1 2

3()

0

1 2

3()

Figure 10: Results o draw z0..z1..tension and ..z2..z3 or various and : (a) = = 1;(b) = = 1.3; (c) = 1.5, = 1.

MetaPost paths also have a parameter called “curl” that afects the ends o a path. In the absenceo any direction specications, the rst and last segments o a non-cyclic path are approximatelycircular arcs as in the = 1 case o Figure 11. To use a diferent value or the curl parameter, speciy{curl c} or some other value o  . Thus

draw z0{curl c}..z1..{curl c}z2

sets the curl parameter or z0 and z2. Small values o the curl parameter reduce the curvature atthe indicated path endpoints, while large values increase the curvature as shown in Figure 11. Inparticular, a curl value o zero makes the curvature approach zero.

4.3 Summary o Path Syntax

There are a ew other eatures o MetaPost path syntax, but they are relatively unimportant. SinceMETAFONT uses the same path syntax, interested readers can reer to [5, chapter 14]. The summaryo path syntax in Figure 12 includes everything discussed so ar including the -- and ... construc-tions which [5] shows to be macros rather than primitives. A ew comments on the semantics are in

9

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 11/109

0

1

2

= 00

1

2

= 10

1

2

= 20

1

2

= ∞

Figure 11: Results o draw z0{curl c}..z1..{curl c}z2 or various values o the curl parameter .

order here: I there is a non-empty ⟨direction specier⟩ beore a ⟨path knot⟩ but not ater it, or viceversa, the specied direction (or curl amount) applies to both the incoming and outgoing path seg-ments. A similar arrangement applies when a ⟨controls⟩ specication gives only one ⟨pair primary⟩.Thus

..controls (30,20)..

is equivalent to...controls (30,20) and (30,20)..

⟨path expression⟩ → ⟨path subexpression⟩| ⟨path subexpression⟩⟨direction specier⟩| ⟨path subexpression⟩⟨path join⟩ cycle

⟨path subexpression⟩ → ⟨path knot⟩| ⟨path expression⟩⟨path join⟩⟨path knot⟩

⟨path join⟩ → --

| ⟨direction specier⟩⟨basic path join⟩⟨direction specier⟩⟨direction specier⟩ → ⟨empty⟩

| {curl ⟨numeric expression⟩}

|{⟨pair expression

⟩}

| {⟨numeric expression⟩,⟨numeric expression⟩}

⟨basic path join⟩ → .. | ... | ..⟨tension⟩.. | ..⟨controls⟩..

⟨tension⟩ → tension⟨numeric primary⟩| tension⟨numeric primary⟩and⟨numeric primary⟩

⟨controls⟩ → controls⟨pair primary⟩| controls⟨pair primary⟩and⟨pair primary⟩

Figure 12: The syntax or path construction

A pair o coordinates like (30,20) or a z variable that represents a coordinate pair is whatFigure 12 calls a ⟨pair primary⟩. A ⟨path knot⟩ is similar except that it can take on other ormssuch as a path expression in parentheses. Primaries and expressions o various types will be discussedin ull generality in Section 6.

10

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 12/109

5 Linear Equations

An important eature taken rom METAFONT is the ability to solve linear equations so that programscan be written in a partially declarative ashion. For example, the MetaPost interpreter can read

a+b=3; 2a=b+3;

and deduce that = 2 and = 1. The same equations can be written slightly more compactly bystringing them together with multiple equal signs:

a+b = 2a-b = 3;

Whichever way you give the equations, you can then give the command

show a,b;

to see the values o  a and b. MetaPost responds by typing

>> 2

>> 1

Note that = is not an assignment operator; it simply declares that the let-hand side equalsthe right-hand side. Thus a=a+1 produces an error message complaining about an “inconsistentequation.” The way to increase the value o  a is to use the assignment operator := as ollows:

a:=a+1;

In other words, := is or changing existing values while = is or giving linear equations to solve.There is no restriction against mixing equations and assignment operations as in the ollowing

example:a = 2 ; b = a ; a : = 3 ; c = a ;

Ater the rst two equations set a and b equal to 2, the assignment operation changes a to 3 withoutafecting b. The nal value o  c is 3 since it is equated to the new value o  a. In general, anassignment operation is interpreted by rst computing the new value, then eliminating the old value

rom all existing equations beore actually assigning the new value.

5.1 Equations and Coordinate Pairs

MetaPost can also solve linear equations involving coordinate pairs. We have already seen manytrivial examples o this in the orm o equations like

z1=(0,.2in)

Each side o the equation must be ormed by adding or subtracting coordinate pairs and multiplyingor dividing them by known numeric quantities. Other ways o naming pair-valued variables will bediscussed later, but the z⟨number⟩ is convenient because it is an abbreviation or

(x

⟨number

⟩, y

⟨number

⟩)

This makes it possible to give values to z variables by giving equations involving their coordinates.For instance, points z1, z2, z3, and z6 in Figure 13 were initialized via the ollowing equations:

z1=-z2=(.2in,0);

x3=-x6=.3in;

x3+y3=x6+y6=1.1in;

11

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 13/109

Exactly the same points could be obtained by setting their values directly:

z1=(.2in,0); z2=(-.2in,0);

z3=(.3in,.8in); z6=(-.3in,1.4in);

Ater reading the equations, the MetaPost interpreter knows the values o  z1, z2, z3, and z6.The next step in the construction o Figure 13 is to dene points z4 and z5 equally spaced alongthe line rom z3 to z6. Since this operation comes up oten, MetaPost has a special syntax or it.This mediation construction

z4=1/3[z3,z6]

means that z4 is 13

o the way rom 3 to 6; i.e.,

z4 = z3 +1

3(z6 − z3).

Similarlyz5=2/3[z3,z6]

makes z5 23

o the way rom 3 to 6.

beginfig(13);

z1=-z2=(.2in,0);x3=-x6=.3in;

x3+y3=x6+y6=1.1in;

z4=1/3[z3,z6];

z5=2/3[z3,z6];

z20=whatever[z1,z3]=whatever[z2,z4];

z30=whatever[z1,z4]=whatever[z2,z5];

z40=whatever[z1,z5]=whatever[z2,z6];

draw z1--z20--z2--z30--z1--z40--z2;

pickup pencircle scaled 1pt;

draw z1--z2;

draw z3--z6;

endfig;

12

3

6

203040

Figure 13: MetaPost commands and the resulting gure. Point labels have been added to the gureor clarity.

Mediation can also be used to say that some point is at an unknown position along the linebetween two known points. For instance, we could a introduce new variable aa and write somethinglike

z20=aa[z1,z3];

This says that z20 is some unknown raction aa o the way along the line between z1 and z3.Another such equation involving a diferent line is sucient to x the value o z20. To say that z20

is at the intersection o the z1-z3 line and the z2-z4 line, introduce another variable ab and set

z20=ab[z2,z4];

This allows MetaPost to solve or x20, y20, aa, and ab.It is a little painul to keep thinking up new names like aa and ab. This can be avoided by using

a special eature called whatever. This macro generates a new anonymous variable each time itappears. Thus the statement

z20=whatever[z1,z3]=whatever[z2,z4]

12

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 14/109

sets z20 as beore, except it uses whatever to generate two diferent  anonymous variables insteado aa and ab. This is how Figure 13 sets z20, z30, and z40.

5.2 Dealing with Unknowns

A system o equations such as those used in Figure 13 can be given in any order as long as all theequations are linear and all the variables can be determined beore they are needed. This meansthat the equations

z1=-z2=(.2in,0);

x3=-x6=.3in;

x3+y3=x6+y6=1.1in;

z4=1/3[z3,z6];

z5=2/3[z3,z6];

suce to determine z1 through z6, no matter what order the equations are given in. On the otherhand

z20=whatever[z1,z3]

is legal only when a known value has previously been specied or the diference z3 − z1, becausethe equation is equivalent toz20 = z1 + whatever*(z3-z1)

and the linearity requirement disallows multiplying unknown components o  z3 − z1 by the anony-mous unknown result o  whatever. The general rule is that you cannot multiply two unknownquantities or divide by an unknown quantity, nor can an unknown quantity be used in a draw

statement. Since only linear equations are allowed, the MetaPost interpreter can easily solve theequations and keep track o what values are known.

The most natural way to ensure that MetaPost can handle an expression like

whatever[z1,z3]

is to ensure that z1 and z3 are both known. However this is not actually required since MetaPost

may be able to deduce a known value or z3−z1 beore either o z1 and z3 are known. For instance,MetaPost will accept the equations

z3=z1+(.1in,.6in); z20=whatever[z1,z3];

but it will not be able to determine any o the components o z1, z3, or z20.These equations do give partial inormation about z1, z3, and z20. A good way to see this is to

give another equation such asx20-x1=(y20-y1)/6;

This produces the error message “! Redundant equation.” MetaPost assumes that you are tryingto tell it something new, so it will usually warn you when you give a redundant equation. I the newequation had been

(x20-x1)-(y20-y1)/6=1in;

the error message would have been

! Inconsistent equation (off by 71.99979).

This error message illustrates roundof error in MetaPost’s linear equation solving mechanism.Roundof error is normally not a serious problem, but it is likely to cause trouble i you are tryingto do something like nd the intersection o two lines that are almost parallel.

13

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 15/109

6 Expressions

It is now time or a more systematic view o the MetaPost language. We have seen that thereare numeric quantities and coordinate pairs, and that these can be combined to speciy paths ordraw statements. We have also seen how variables can be used in linear equations, but we have notdiscussed all the operations and data types that can be used in equations.

It is possible to experiment with expressions involving any o the data types mentioned below

by using the statementshow ⟨expression⟩

to ask MetaPost to print a symbolic representation o the value o each expression. For knownnumeric values, each is printed on a new line preceded by “>> ”. Other types o result are printedsimilarly, except that complicated values are sometimes not printed on standard output. Thisproduces a reerence to the transcript le that looks like this:

>> picture (see the transcript file)

I you want to the ull results o show statements to be printed on your terminal, assign a positivevalue to the internal variable tracingonline.

6.1 Data TypesMetaPost actually has ten basic data types: numeric, pair, path, transorm, (rgb)color, cmykcolor,string, boolean, picture, and pen. Let us consider these one at a time beginning with the numerictype.

Numeric quantities in MetaPost are represented in xed point arithmetic as integer multiples o 1

65536. They must normally have absolute values less than 4096 but intermediate results can be eight

times larger. This should not be a problem or distances or coordinate values since 4096 PostScriptpoints is more than 1.4 meters. I you need to work with numbers o magnitude 4096 or more, settingthe internal variable warningcheck to zero suppresses the warning messages about large numericquantities.

The pair type is represented as a pair o numeric quantities. We have seen that pairs are used togive coordinates in draw statements. Pairs can be added, subtracted, used in mediation expressions,

or multiplied or divided by numerics.Paths have already been discussed in the context o  draw statements, but that discussion did notmention that paths are rst-class objects that can be stored and manipulated. A path represents astraight or curved line that is dened parametrically.

Another data type represents an arbitrary ane transormation. A transorm  can be any com-bination o rotating, scaling, slanting, and shiting. I  p = ( , ) is a pair and T is a transorm,

p transformed T

is a pair o the orm( +   +  , +   +  ),

where the six numeric quantities (, , , , , ) determine T. Transorms can also be appliedto paths, pictures, pens, and transorms.

The color type is like the pair type, except that it has three components instead o two andeach component is normally between 0 and 1. Like pairs, colors can be added, subtracted, used inmediation expressions, or multiplied or divided by numerics. Colors can be specied in terms o thepredened constants black, white, red, green, blue, or the red, green, and blue components canbe given explicitly. Black is (0,0,0) and white is (1,1,1). A level o gray such as (.4,.4,.4)

can also be specied as 0.4white. Although color typed variables may be any ordered triplet, whenadding an object to a picture, MetaPost will convert its color by clipping each component between

14

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 16/109

0 and 1. For example, MetaPost will output the color (1,2,3) as (1,1,1). MetaPost solves linearequations involving colors the same way it does or pairs. The type ‘rgbcolor’ is an alias o type‘color’.

The cmykcolor type is similar to the color type except that it has our components instead o three. This type is used to speciy colors by their cyan, magenta, yellow, and black componentsexplicitly. Because CMYK colors deal with pigments instead o light rays, the color white would beexpressed as (0,0,0,0) and black as (0,0,0,1). In theory, the colors (,,,1) and (1,1,1,)

should result in black or any values o  , , and , too. But in practice, this is avoided since itis a waste o colored ink and can lead to unsatisactory results.

A string represents a sequence o characters. String constants are given in double quotes"like this". String constants cannot contain double quotes or newlines, but there is a way toconstruct a string containing any sequence o eight-bit characters.

Conversion rom strings to other types, notably numeric, can be accomplished by the scantokens

primitive:

n := scantokens(str );

More generally, scantokens parses a string into a token sequence, as i MetaPost had read it asinput.

The boolean type has the constants true and false and the operators and, or, not. The relations

= and <> test objects o any type or equality and inequality. Comparison relations <, <=, >, and>= are dened lexicographically or strings and in the obvious way or numerics. Ordering relationsare also dened or booleans, pairs, colors, and transorms, but the comparison rules are not worthdiscussing here.

The picture data type is just what the name implies. Anything that can be drawn in MetaPostcan be stored in a picture variable. In act, the draw statement actually stores its results in a specialpicture variable called currentpicture. Pictures can be added to other pictures and operated onby transorms.

Finally, there is a data type called a pen. The main unction o pens in MetaPost is to determineline thickness, but they can also be used to achieve calligraphic efects. The statement

pickup ⟨pen expression⟩

causes the given pen to be used in subsequent draw or drawdot statements. Normally, the penexpression is o the ormpencircle scaled ⟨numeric primary⟩.

This denes a circular pen that produces lines o constant thickness. I calligraphic efects aredesired, the pen expression can be adjusted to give an elliptical pen or a polygonal pen.

6.2 Operators

There are many diferent ways to make expressions o the ten basic types, but most o the operationst into a airly simple syntax with our levels o precedence as shown in Figure 14. There areprimaries, secondaries, tertiaries, and expressions o each o the basic types, so the syntax rulescould be specialized to deal with items such as ⟨numeric primary⟩, ⟨boolean tertiary⟩, etc. Thisallows the result type or an operation to depend on the choice o operator and the types o itsoperands. For example, the < relation is a ⟨tertiary binary⟩ that can be applied to a ⟨numericexpression⟩ and a ⟨numeric tertiary⟩ to give a ⟨boolean expression⟩. The same operator can acceptother operand types such as ⟨string expression⟩ and ⟨string tertiary⟩, but an error message resultsi the operand types do not match.

The multiplication and division operators * and / are examples o what Figure 14 calls a ⟨primarybinop⟩. Each can accept two numeric operands or one numeric operand and one operand o type pairor color. The exponentiation operator ** is a ⟨primary binop⟩ that requires two numeric operands.

15

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 17/109

⟨primary⟩ → ⟨variable⟩| (⟨expression⟩)

| ⟨nullary op⟩| ⟨o operator⟩⟨expression⟩of⟨primary⟩| ⟨unary op⟩⟨primary⟩

⟨secondary⟩ → ⟨primary⟩

| ⟨secondary

⟩⟨primary binop

⟩⟨primary

⟩⟨tertiary⟩ → ⟨secondary⟩| ⟨tertiary⟩⟨secondary binop⟩⟨secondary⟩

⟨expression⟩ → ⟨tertiary⟩| ⟨expression⟩⟨tertiary binop⟩⟨tertiary⟩

Figure 14: The overall syntax rules or expressions

Placing this at the same level o precedence as multiplication and division has the unortunateconsequence that 3*a**2 means (3)2, not 3(2). Since unary negation applies at the primary level,it also turns out that -a**2 means (−)2. Fortunately, subtraction has lower precedence so thata-b**2 does mean − (2) instead o ( − )2.

Another ⟨primary binop⟩ is the dotprod operator that computes the vector dot product o twopairs. For example, z1 dotprod z2 is equivalent to x1*x2 + y1*y2.The additive operators + and - are ⟨secondary binops⟩ that operate on numerics, pairs, or colors

and produce results o the same type. Other operators that all in this category are “Pythagoreanaddition” ++ and “Pythagorean subtraction” +-+: a++b means

√ 2 + 2 and a+-+b means

√ 2 − 2.

There are too many other operators to list here, but some o the most important are the booleanoperators and and or. The and operator is a ⟨primary binop⟩ and the or operator is a ⟨secondarybinop⟩.

The basic operations on strings are concatenation, substring construction and calculating thelength o a string. The ⟨tertiary binop⟩ & implements concatenation; e.g.,

"abc" & "de"

produces the string "abcde". The length operator returns the number o characters in a string i the argument is a ⟨string primary⟩; e.g.,

length "abcde"

returns 5. Another application o the length operator is discussed on p. 33. For substring construc-tion, the ⟨o operator⟩ substring is used like this:

substring⟨pair expression⟩ of ⟨string primary⟩The ⟨pair expression⟩ determines what part o the string to select. For this purpose, the string isindexed so that integer positions all between  characters. Pretend the string is written on a piece o graph paper so that the rst character occupies coordinates between zero and one and the nextcharacter covers the range 1 ≤ ≤ 2, etc. Thus the string "abcde" should be thought o like this

a1b

2c

3d

4e

5x = 0

and substring (2,4) of "abcde" is "cd". This takes a little getting used to but it tends to avoidannoying “of by one” errors.

Some operators take no arguments at all. An example o what Figure 14 calls a ⟨nullary op⟩ isnullpicture which returns a completely blank picture.

16

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 18/109

The basic syntax in Figure 14 only covers aspects o the expression syntax that are relativelytype-independent. For instance, the complicated path syntax given in Figure 12 gives alternativerules or constructing a ⟨path expression⟩. An additional rule

⟨path knot⟩ → ⟨pair tertiary⟩ | ⟨path tertiary⟩

explains the meaning o 

⟨path knot

⟩in Figure 12. This means that the path expression

z1+(1,1){right}..z2

does not need parentheses around z1+(1,1).

6.3 Fractions, Mediation, and Unary Operators

Mediation expressions do not appear in the basic expression syntax o Figure 14. Mediation expres-sions are parsed at the ⟨primary⟩ level, so the general rule or constructing them is

⟨primary⟩ → ⟨numeric atom⟩[⟨expression⟩,⟨expression⟩]

where each ⟨expression⟩ can be o type numeric, pair, or color. The ⟨numeric atom⟩ in a mediationexpression is an extra simple type o 

⟨numeric primary

⟩as shown in Figure 15. The meaning o all

this is that the initial parameter in a mediation expression needs to be parenthesized when it is not just a variable, a positive number, or a positive raction. For example,

-1[a,b] and (-1)[a,b]

are very diferent: the ormer is − since it is equivalent to -(1[a,b]); the latter is − ( − ) or2 − .

⟨numeric primary⟩ → ⟨numeric atom⟩| ⟨numeric atom⟩[⟨numeric expression⟩,⟨numeric expression⟩]

| ⟨o operator⟩⟨expression⟩of⟨primary⟩| ⟨unary op⟩⟨primary⟩

⟨numeric atom⟩ → ⟨numeric variable⟩| ⟨number or raction⟩| (⟨numeric expression⟩)

| ⟨numeric nullary op⟩⟨number or raction⟩ → ⟨number⟩/⟨number⟩

| ⟨number not ollowed by ‘/⟨number⟩’⟩

Figure 15: Syntax rules or numeric primaries

A noteworthy eature o the syntax rules in Figure 15 is that the / operator binds most tightlywhen its operands are numbers. Thus 2/3 is a ⟨numeric atom⟩ while (1+1)/3 is only a ⟨numericsecondary⟩. Applying a ⟨unary op⟩ such as sqrt makes the diference clear:

sqrt 2/3

means 

23

whilesqrt(1+1)/3

means√ 

2/3. Operators such as sqrt can be written in standard unctional notation, but it is otenunnecessary to parenthesize the argument. This applies to any unction that is parsed as a ⟨unaryop⟩. For instance abs(x) and abs x both compute the absolute value o x. The same holds or the

17

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 19/109

round, floor, ceiling, sind, and cosd unctions. The last two o these compute trigonometricunctions o angles in degrees.

Not all unary operators take numeric arguments and return numeric results. For instance, theabs operator can be applied to a pair to compute the Euclidean length o a vector. Applying theunitvector operator to a pair produces the same pair rescaled so that its Euclidean length is 1. Thedecimal operator takes a number and returns the string representation. The angle operator takesa pair and computes the two-argument arctangent; i.e., angle is the inverse o the dir operatorthat was discussed in Section 4.2. There is also an operator cycle that takes a ⟨path primary⟩ andreturns a boolean result indicating whether the path is a closed curve.

There is a whole class o other operators that classiy expressions and return boolean results. Atype name such as pair can operate on any type o ⟨primary⟩ and return a boolean result indicatingwhether the argument is a pair. Similarly, each o the ollowing can be used as a unary operator:numeric, boolean, cmykcolor, color, string, transform, path, pen, picture, and rgbcolor.Besides just testing the type o a ⟨primary⟩, you can use the known and unknown operators to testi it has a completely known value.

Even a number can behave like an operator in some contexts. This reers to the trick that allows3x and 3cm as alternatives to 3*x and 3*cm. The rule is that a ⟨number or raction⟩ that is notollowed by +, -, or another ⟨number or raction⟩ can serve as a ⟨primary binop⟩. Thus 2/3x is twothirds o x but (2)/3x is 2

3and 3 3 is illegal.

There are also operators or extracting numeric subelds rom pairs, colors, cmykcolors, and eventransorms. I p is a ⟨pair primary⟩, xpart p and ypart p extract its components so that

(xpart p, ypart p)

is equivalent to p even i  p is an unknown pair that is being used in a linear equation. Similarly, acolor c is equivalent to

(redpart c, greenpart c, bluepart c).

For a cmykcolor c, the components are

(cyanpart c, magentapart c, yellowpart c, blackpart c)

and or a greyscale color c, there is only one component

greypart c.

All color component operators are discussed in more detail in section 9.10. Part speciers ortransorms are discussed in section 9.3.

7 Variables

MetaPost allows compound variable names such as z.a, x2r, y2r, and z2r, where z2r means(x2r,y2r) and z.a means (x.a,y.a). In act there is a broad class o suxes such that z⟨su-x⟩ means

(⟨sux⟩, ⟨sux⟩).

Since a ⟨sux⟩ is composed o tokens, it is best to begin with a ew comments about tokens.

7.1 Tokens

A MetaPost input le is treated as a sequence o numbers, string constants, and symbolic tokens. Anumber consists o a sequence o digits possibly containing a decimal point. Technically, the minussign in ront o a negative number is a separate token. Since MetaPost uses xed point arithmetic,

18

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 20/109

ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz

:<=>|

#&@$

/*\

+-

!?

’‘

^~

{}

[

]

Table 1: Character classes or tokenization

it does not understand exponential notation such as 6.02E23. MetaPost would interpret this as thenumber 6.02, ollowed by the symbolic token E, ollowed by the number 23.

Anything between a pair o double quotes " is a string constant. It is illegal or a string constantto start on one line and end on a later line. Nor can a string constant contain double quotes " oranything other than printable ASCII characters.

Everything in a line o input other than numbers and string constants is broken into symbolictokens. A symbolic token is a sequence o one or more similar characters, where characters are“similar” i they occur on the same row o Table 1.

Thus A_alpha and +-+ are symbolic tokens but != is interpreted as two tokens and x34 is asymbolic token ollowed by a number. Since the brackets [ and ] are listed on lines by themselves,the only symbolic tokens involving them are [, [[, [[[, etc. and ], ]], etc.

Some characters are not listed in Table 1 because they need special treatment. The our characters,;() are “loners”: each comma, semicolon, or parenthesis is a separate token even when they occurconsecutively. Thus (()) is our tokens, not one or two. The percent sign is very special because itintroduces comments. The percent sign and everything ater it up to the end o the line are ignored.

Another special character is the period. Two or more periods together orm a symbolic token,but a single period is ignored, and a period preceded or ollowed by digits is part o a number Thus

.. and ... are symbolic tokens while a.b is just two tokens a and b. It conventional to use periodsto separate tokens in this ashion when naming a variable that is more than one token long.

7.2 Variable Declarations

A variable name is a symbolic token or a sequence o symbolic tokens. Most symbolic tokens arelegitimate variable names, but anything with a predened meaning like draw, +, or .. is disallowed;i.e., variable names cannot be macros or MetaPost primitives. This minor restriction allows anamazingly broad class o variable names: alpha, ==>, @&#$&, and ~~ are all legitimate variablenames. Such symbolic tokens without special meanings are called tags.

A variable name can be a sequence o tags like f.bot or f.top. The idea is to provide some o the unctionality o Pascal records or C structures. It is also possible to simulate arrays by usingvariable names that contain numbers as well as symbolic tokens. For example, the variable name

x2r consists o the tag x, the number 2, and the tag r. There can also be variables named x3r andeven x3.14r. These variables can be treated as an array via constructions like x[i]r, where i hasan appropriate numeric value. The overall syntax or variable names is shown in Figure 16.

Variables like x2 and y2 take on numeric values by deault, so we can use the act that z⟨sux⟩is an abbreviation or

(⟨sux⟩, ⟨sux⟩)

to generate pair-valued variables when needed. It turns out that the beginfig macro wipes out

19

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 21/109

⟨variable⟩ → ⟨tag⟩⟨sux⟩⟨sux⟩ → ⟨empty⟩ | ⟨sux⟩⟨subscript⟩ | ⟨sux⟩⟨tag⟩⟨subscript⟩ → ⟨number⟩ | [⟨numeric expression⟩]

Figure 16: The syntax or variable names.

pre-existing values variables that begin with the tags x or y so that beginfig . . . endfig blocks donot interere with each other when this naming scheme is used. In other words, variables that startwith x, y, z are local to the gure they are used in. General mechanisms or making variables localwill be discussed in Section 10.1.

Type declarations make it possible to use almost any naming scheme while still wiping out anyprevious value that might cause intererence. For example, the declaration

pair pp, a.b;

makes pp and a.b unknown pairs. Such a declaration is not strictly local since pp and a.b are notautomatically restored to their previous values at the end o the current gure. O course, they arerestored to unknown pairs i the declaration is repeated.

Declarations work the same way or any o the other nine types: numeric, path, transorm, color,cmykcolor, string, boolean, picture, and pen. The only restriction is that you cannot give explicitnumeric subscripts in a variable declaration. Do not give the illegal declaration

numeric q1, q2, q3;

use the generic subscript symbol [] instead, to declare the whole array:

numeric q[];

You can also declare “multidimensional” arrays. Ater the declaration

path p[]q[], pq[][];

p2q3 and pq1.4 5 are both paths.Internal variables like tracingonline cannot be declared in the normal ashion. All the internalvariables discussed in this manual are predened and do not have to be declared at all, but there is away to declare that a variable should behave like a newly-created internal variable. The declarationis newinternal ollowed by an optional type specier numeric or string and a list o symbolictokens. For example,

newinternal numeric n, m;

newinternal string s, t;

newinternal num;

are valid declarations that declare three internal numeric variables n, m, and num and two internalstring variables s and t.

Internal variables always have known values, and these values can only be changed by using theassignment operator :=. Internal numeric variables are initially zero and internal string variables

are initially the empty string "", except that the Plain macro package gives some o the variablesdiferent initial values. (The Plain macros are normally preloaded automatically as explained inSection 1.)

Internal string variables have been introduced in MetaPost version 1.200. For backwards com-patibility, i the type specier is missing, internal variables deault to a numeric type, as in thelast example. The declarations newinternal numeric; and newinternal string; are invalid andthrow an error.

20

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 22/109

8 Integrating Text and Graphics

MetaPost has a number o eatures or including labels and other text in the gures it generates.The simplest way to do this is to use the label statement

label⟨label sux⟩(⟨string or picture expression⟩, ⟨pair expression⟩);

The ⟨string or picture expression⟩ gives the label and the ⟨pair expression⟩ says where to put it.The ⟨label sux⟩ can be ⟨empty⟩ in which case the label is just centered on the given coordinates.I you are labeling some eature o a diagram you probably want to ofset the label slightly to avoidoverlapping. This is illustrated in Figure 17 where the "a" label is placed above the midpoint o theline it reers to and the "b" label is to the let o the midpoint o its line. This is achieved by usinglabel.top or the "a" label and label.lft or the "b" label as shown in the gure. The ⟨labelsux⟩ species the position o the label relative to the specied coordinates. The complete set o possibilities is

⟨label sux⟩ → ⟨empty⟩ | lft | rt | top | bot | ulft | urt | llft | lrt

where lft and rt mean let and right and llft, ulft, etc. mean lower let, upper let, etc. Theactual amount by which the label is ofset in whatever direction is determined by the internal variable

labeloffset.beginfig(17);

a=.7in; b=.5in;

z0=(0,0);

z1=-z3=(a,0);

z2=-z4=(0,b);

draw z1..z2..z3..z4..cycle;

draw z1--z0--z2;

label.top("a", .5[z0,z1]);

label.lft("b", .5[z0,z2]);

dotlabel.bot("(0,0)", z0);

endfig;

ab

(0,0)

Figure 17: MetaPost code and the resulting output

Figure 17 also illustrates the dotlabel statement. This is efectively like a label statementollowed by a statement drawing a dot at the indicated coordinates. For example

dotlabel.bot("(0,0)", z0)

places a dot at z0 and then puts the label “(0,0)” just below the dot. The diameter o the dotdrawn by the dotlabel statement is determined by the value o the internal variable dotlabeldiam.Deault value is 3bp.

Another alternative is the macro thelabel. This has the same syntax as the label and dotlabel

statements except that it returns the label as a ⟨picture primary⟩ instead o actually drawing it.

Thuslabel.bot("(0,0)", z0)

is equivalent todraw thelabel.bot("(0,0)", z0)

For simple applications o labeled gures, you can normally get by with just label and dotlabel.In act, you may be able to use a short orm o the dotlabel statement that saves a lot o typing

21

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 23/109

when you have many points z0, z1, z.a, z.b, etc. and you want to use the z suxes as labels. Thestatement

dotlabels.rt(0, 1, a);

is equivalent to

dotlabel.rt("0",z0); dotlabel.rt("1",z1); dotlabel.rt("a",z.a);

Thus the argument to dotlabels is a list o suxes or which z variables are known, and the ⟨labelsux⟩ given with dotlabels is used to position all the labels.

There is also a labels statement that is analogous to dotlabels but its use is discouragedbecause it presents compatibility problems with METAFONT. Some versions o the preloaded Plainmacro package dene labels to be synonymous with dotlabels.

For labeling statements such as label and dotlabel that use a string expression or the labeltext, the string gets typeset in a deault ont as determined by the string variable defaultfont.The initial value o defaultfont is likely to be "cmr10", but it can be changed to a diferent ontname by giving an assignment such as

defaultfont:="ptmr8r"

ptmr8r is a typical way to reer to the Times-Roman ont in TEX. The discussion o ont names on

p. 22 explains urther.There is also a numeric quantity called defaultscale that determines the type size. When

defaultscale is 1, you get the “normal size” which is usually 10 point, but this can also be changed.For instance

defaultscale := 1.2

makes labels come out twenty percent larger. I you do not know the normal size and you want tobe sure the text comes out at some specic size, say 12 points, you can use the fontsize operatorto determine the normal size: e.g.,

defaultscale := 12pt/fontsize defaultfont;

When you change defaultfont, the new ont name should be something that TEX would under-stand since MetaPost gets height and width inormation by reading a tfm le. (This is explained inThe T E Xbook  [6].) It should be possible to use built-in PostScript onts, but the names or them aresystem-dependent. Some typical ones are ptmr8r or Times-Roman, pplr8r or Palatino, and phvr

or Helvetica. The Fontname document, available at http://tug.org/fontname, has much moreinormation about ont names and TEX. A TEX ont such as cmr10 is a little dangerous because itdoes not have a space character or certain ASCII symbols.

MetaPost does not use the ligatures and kerning inormation that comes with a TEX ont. Further,MetaPost itsel does not interpret virtual onts.

8.1 Typesetting Your Labels

TEX may be used to ormat complex labels. I you say

btex

⟨typesetting commands

⟩etex

in a MetaPost input le, the ⟨typesetting commands⟩ get processed by TEX and translated into apicture expression (actually a ⟨picture primary⟩) that can be used in a label or dotlabel statement.Any spaces ater btex or beore etex are ignored. For instance, the statement

label.lrt(btex $\sqrt x$ etex, (3,sqrt 3)*u)

in Figure 18 places the label√ 

at the lower right o the point (3,sqrt 3)*u.

22

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 24/109

beginfig(18);

numeric u;

u = 1cm;

draw (0,2u)--(0,0)--(4u,0);

pickup pencircle scaled 1pt;

draw (0,0){up}

for i=1 upto 8: ..(i/2,sqrt(i/2))*u endfor;

label.lrt(btex $\sqrt x$ etex, (3,sqrt 3)*u);label.bot(btex $x$ etex, (2u,0));

label.lft(btex $y$ etex, (0,u));

endfig;

√ x

x

y

Figure 18: Arbitrary TEX as labels

Figure 19 illustrates some o the more complicated things that can be done with labels. Since theresult o btex . . . etex is a picture, it can be operated on like a picture. In particular, it is possibleto apply transormations to pictures. We have not discussed the syntax or this yet, but a ⟨picturesecondary⟩ can be

⟨picture secondary

⟩rotated

⟨numeric primary

⟩This is used in Figure 19 to rotate the label “ axis” so that it runs vertically.

beginfig(19);

numeric ux, uy;

120ux=1.2in; 4uy=2.4in;

draw (0,4uy)--(0,0)--(120ux,0);

pickup pencircle scaled 1pt;

draw (0,uy){right}

for ix=1 upto 8:

..(15ix*ux, uy*2/(1+cosd 15ix))

endfor;

label.bot(btex $x$ axis etex, (60ux,0));

label.lft(btex $y$ axis etex rotated 90,(0,2uy));

label.lft(

btex $\displaystyle y={2\over1+\cos x}$ etex,

(120ux, 4uy));

endfig;x axis

     y

     a     x       i     s

y =2

1 + cos x

Figure 19: TEX labels with display math, and rotated by MetaPost

Another complication in Figure 19 is the use o the displayed equation

=2

1 + cos

as a label. It would be more natural to code this as

$$y={2\over 1+\cos x}$$

but this would not work because TEX typesets the labels in “horizontal mode.”For a way to typeset variable text as labels, see the TEX utility routine described on p. 63.

23

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 25/109

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 26/109

• In PostScript output mode, when prologues is 2, the MetaPost output is EPSF and assumesthat the text comes rom PostScript onts provided by the “environment”, such as the documentviewer or embedded application using the output. MetaPost will attempt to set up the ontencodings correctly, based on fontmapfile and fontmapline commands.

A prologues:=2 setting is currently ignored in SVG output mode. The value is reserved oruture use (possibly or external font-face denitions).

• In PostScript output mode, when prologues is 3, the MetaPost output will be EPSF but willcontain the PostScript ont(s) (or a subset) used based on the fontmapfile and fontmapline

commands. This value is useul or generating stand-alone PostScript graphics.

In SVG mode, the ont glyphs are converted to path denitions that are included at the topo the output le.

The correct setting or variable prologues depends on how MetaPost graphics are post-processed.Here are recommendations or some popular use-cases:

Previewing: Section 14.2 discusses previewing PostScript output.

T E X and dvips: When including PostScript gures into a TEX document that is processed by TEXand a DVI output processer, e.g., dvips, variable prologues should not  be set to the value 1,unless the used onts are known to be resident in the PostScript interpreter. Make sure thatvariable prologues is set to either 0 (ont inclusion handled by dvips, but without re-encodingsupport), 2 (ont inclusion by dvips, with ont re-encoding i necessary), or 3 (ont inclusionand re-encoding by MetaPost). Value 3 is saest, but may result in slightly larger output.

pdT E X: When generating PDF les with pdTEX (and the mptopd bundle), variable prologues isnot relevant.

PostScript in external applications: Some text processors or graphics applications can directly im-port EPSF les, while or others MetaPost’s PostScript output has to be converted to a diferentvector or even a bitmap ormat rst. In any case, as soon as PostScript graphics generated byMetaPost are leaving the TEX ecosystem, variable prologues should be set to 3, so that allneeded onts are embedded (as a subset).

SVG output: Converting ont glyphs to paths by setting variable prologues to 3 is currently theonly reliable way to export text objects to SVG.

It is worth noting that the value o  prologues has no efect on METAFONT onts in your MetaPostles, i. e., MetaPost never embeds such onts. Only output drivers, e. g., dvips or pdLATEX willhandle those.

The details on how to include PostScript gures in a paper done in TEX or trof are system-dependent. They can generally be ound in manual pages and other on-line documentation, buthave a look at section 14.4 o this manual or some brie instructions that in many cases shouldwork. The manual or the widely-used Dvips processor is in a le dvips.texi, included in mostdistributions, and is available online at http://tug.org/texinfohtml/dvips.html, among manyother places and ormats.

8.2 Font Map Files

I  prologues is set to 2, any used onts in the output le are automatically re-encoded, and theencoding vector le specied in the ontmap entry will be embedded in the output le. I  prologues

is set to 3, MetaPost will also attempt to include (a subset o) the used PostScript onts. For thisto work, it needs to acquire ont map inormation.

25

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 27/109

The code is based on the ont library used by pdTEX. Following in the ootsteps o pdTEX,there are two new associated primitives: fontmapfile and fontmapline. Here is a simple example,speciying the map le or Latin Modern onts in YandY (LATEX LY1) encoding:

prologues:=2;

fontmapfile "texnansi-lm.map";

beginfig(1);

draw "Helló, világ" infont "texnansi-lmr10";endfig;

Using fontmapline, you can speciy ont mapping inormation inside the gure:

prologues:=2;

fontmapline "pplbo8r URWPalladioL-Bold "&ditto&

".167 SlantFont"&ditto&" <8r.enc <uplb8a.pfb";

beginfig(1);

draw "Hello, world" infont "pplbo8r";

endfig;

This will attempt to reencode the PostScript ont URWPalladioL-Bold whose tm le is pplbo8r.tm.The encoding is ound in the le 8r.enc, and will be included into the output le.

I the same example was run with prologues:=3, MetaPost would include a subset o the ontthat resides in uplb8a.pb into the output. In this case, the subset o the ont is reorganized so thatit has the correct encoding internally, 8r.enc will not be embedded also.

The argument to both commands has an optional ag character at the very beginning. Thisoptional ag has the same meaning as in pdTEX:

Option Meaning+ extend the ont list, but ignore duplicates= extend the ont list, replacing duplicates− remove all matching onts rom the ont list

Without any option, the current list will be completely replaced.I  prologues is set to two or three, yet there are no fontmapfile statements, MetaPost will

attempt to locate a deault map le, with a preerence to read mpost.map. I that ails, it willalso attempt either troff.map or pdftex.map, depending on whether or not trof mode is enabled.I  prologues is set to 1, MetaPost attempts to read a le called psfonts.map, regardless o anyfontmapfile statement. Again, this is or backward compatibility only.

8.3 The infont Operator

Regardless o whether you use TEX or trof, all the real work o adding text to pictures is done by aMetaPost primitive operator called infont. It is a ⟨primary binop⟩ that takes a ⟨string secondary⟩as its let argument and a ⟨string primary⟩ as its right argument. The let argument is text, and theright argument is a ont name. The result o the operation is a ⟨picture secondary⟩, which can thenbe transormed in various ways. One possibility is enlargement by a given actor via the syntax

⟨picture secondary

⟩scaled

⟨numeric primary

⟩Thus label("text",z0) is equivalent to

label("text" infont defaultfont scaled defaultscale, z0)

I it is not convenient to use a string constant or the let argument o  infont, you can use

char ⟨numeric primary⟩

26

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 28/109

to select a character based on its numeric position in the ont. Thus

char(n+64) infont "ptmr8r"

is a picture containing character n+64 o the ont ptmr8r, which is a typical TEX way to reer toTimes-Roman. See p. 22 or urther discussion.

Bare MetaPost does not do any kind o input reencoding, so when you use infont string orlabels (instead o btex . . . etex), the string has to be specied in the ont encoding.

8.4 Measuring Text

MetaPost makes readily available the physical dimensions o pictures generated by the infont

operator. There are unary operators llcorner, lrcorner, urcorner, ulcorner, and center thattake a ⟨picture primary⟩ and return the corners o its “bounding box” as illustrated in Figure 20.The center operator also accepts ⟨path primary⟩ and ⟨pen primary⟩ operands. In MetaPost Version0.30 and higher, llcorner, lrcorner, etc. accept all three argument types as well.

The argument type restrictions on the corner operators are not very important because their mainpurpose is to allow label and dotlabel statements to center their text properly. The predenedmacro

bbox ⟨picture primary⟩

nds a rectangular path that represents the bounding box o a given picture. I  p is a picture, bboxp is equivalent to

(llcorner p--lrcorner p--urcorner p--ulcorner p--cycle)

except that it allows or a small amount o extra space around p as specied by the internal variablebboxmargin.

testingllcorner lrcorner

ulcorner urcorner

Figure 20: A bounding box and its corner points.

Note that MetaPost computes the bounding box o a btex . . . etex picture just the way TEXdoes. This is quite natural, but it has certain implications in view o the act that TEX has eatureslike \strut and \rlap that allow TEX users to lie about the dimensions o a box.

When TEX commands that lie about the dimensions o a box are translated in to low-levelMetaPost code, a setbounds statement does the lying:

setbounds⟨picture variable⟩ to ⟨path expression⟩makes the ⟨picture variable⟩ behave as i its bounding box were the same as the given path. Thepath has to be a cycle, i.e., it must be a closed path. To get the true bounding box o such a picture,assign a positive value to the internal variable truecorners:7 i.e.,

show urcorner btex $\bullet$\rlap{ A} etex

produces “>> (4.9813,6.8078)” while

truecorners:=1; show urcorner btex $\bullet$\rlap{ A} etex

produces “>> (15.7742,6.8078).”7The setbounds and truecorners eatures are only ound in MetaPost version 0.30 and higher.

27

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 29/109

9 Advanced Graphics

All the examples in the previous sections have been simple line drawings with labels added. Thissection describes shading and tools or generating not-so-simple line drawings. Shading is done withthe fill statement. In its simplest orm, the fill statement requires a ⟨path expression⟩ that givesthe boundary o the region to be lled. In the syntax

fill ⟨path expression⟩the argument should be a cyclic path, i.e., a path that describes a closed curve via the ..cycle or--cycle notation. For example, the fill statement in Figure 21 builds a closed path by extendingthe roughly semicircular path p. This path has a counter-clockwise orientation, but that does notmatter because the fill statement uses PostScript’s non-zero winding number rule [1].

beginfig(21);

path p;

p = (-1cm,0)..(0,-1cm)..(1cm,0);

fill p{up}..(0,0){-1,-2}..{up}cycle;

draw p..(0,1cm)..cycle;

endfig;

Figure 21: MetaPost code and the corresponding output.

The general fill statement

fill ⟨path expression⟩ withcolor⟨color expression⟩

species a shade o gray or (i you have a color printer) some rainbow color. The ⟨color expression⟩can have ve possible values, mapping to our possible color models:

Actual input Remapped meaningwithcolor ⟨rgbcolor⟩ withrgbcolor withcolor ⟨cmykcolor⟩ withcmykcolor

withcolor ⟨numeric⟩ withgreyscale withcolor ⟨alse⟩ withoutcolorwithcolor ⟨true⟩ ⟨current deault color model⟩

For the specic color models, there are also:

fill ⟨path expression⟩ withrgbcolor⟨rgbcolor expression⟩

fill ⟨path expression⟩ withcmykcolor⟨cmykcolor expression⟩fill ⟨path expression⟩ withgreyscale⟨numeric⟩

fill ⟨path expression⟩ withoutcolor

An image object cannot have more then one color model, the last withcolor, withrgbcolor,withcmykcolor, withgreyscale or withoutcolor specication sets the color model or any partic-ular object.

The model withoutcolor needs a bit more explanation: selecting this model means that Meta-Post will not write a color selection statement to the PostScript output le or this object.

The ‘current deault’ color model can be set up using the internal variable defaultcolormodel.Table 2 lists the valid values.

Figure 22 illustrates several applications o the ll command to ll areas with shades o gray.The paths involved are intersecting circles a and b and a path ab that bounds the region inside both

28

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 30/109

Value Color model1 no model3 greyscale5 rgb (deault)7 cmyk

Table 2: Supported color models.

circles. Circles a and b are derived rom a predened path fullcircle that approximates a circleo unit diameter centered on the origin. There is also a predened path halfcircle that is the parto  fullcircle above the axis. Path ab is then initialized using a predened macro buildcycle

that will be discussed shortly.

beginfig(22);

path a, b, aa, ab;

a = fullcircle scaled 2cm;

b = a shifted (0,1cm);

aa = halfcircle scaled 2cm;

ab = buildcycle(aa, b);

picture pa, pb;pa = thelabel(btex $A$ etex, (0,-.5cm));

pb = thelabel(btex $B$ etex, (0,1.5cm));

fill a withcolor .7white;

fill b withcolor .7white;

fill ab withcolor .4white;

unfill bbox pa;

draw pa;

unfill bbox pb;

draw pb;

label.lft(btex $U$ etex, (-1cm,.5cm));

draw bbox currentpicture;

endfig;

A

B

Figure 22: MetaPost code and the corresponding output.

Filling circle a with the light gray color .7white and then doing the same with circle b doublylls the region where the disks overlap. The rule is that each fill statement assigns the given colorto all points in the region covered, wiping out whatever was there previously including lines andtext as well as lled regions. Thus it is important to give fill commands in the right order. In theabove example, the overlap region gets the same color twice, leaving it light gray ater the rst twofill statements. The third ll statement assigns the darker color .4white to the overlap region.

At this point the circles and the overlap region have their nal colors but there are no cutoutsor the labels. The cutouts are achieved by the unfill statements that efectively erase the re-gions bounded by bbox pa and bbox pb. More precisely, unfill is shorthand or lling withcolor

background, where background is normally equal to white as is appropriate or printing on white

paper. I necessary, you can assign a new color value to background.The labels need to be stored in pictures pa and pb to allow or measuring their bounding box

beore actually drawing them. The macro thelabel creates such pictures and shits them intoposition so that they are ready to draw. Using the resulting pictures in draw statements o the orm

draw ⟨picture expression⟩adds them to currentpicture so that they overwrite a portion o what has already been drawn. In

29

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 31/109

Figure 22 just the white rectangles produced by unfill get overwritten.

9.1 Building Cycles

The buildcycle command constructs paths or use with the fill or unfill macros. When giventwo or more paths such as aa and b, the buildcycle macro tries to piece them together so as to orma cyclic path. In this case path aa is a semicircle that starts just to the right o the intersection withpath b, then passes through b and ends just outside the circle on the let as shown in Figure 23a.

Figure 23b shows how buildcycle orms a closed cycle rom the pieces o paths aa and b. Thebuildcycle macro detects the two intersections labeled 1 and 2 in Figure 23b. Then it constructsthe cyclic path shown in bold in the gure by going orward along path aa rom intersection 1 tointersection 2 and then orward around the counter-clockwise path b back to intersection 1. It turnsout that buildcycle(a,b) would have produced the same result, but the reasoning behind this isa little conusing.

12

aa

b

()

12

aa

b

()

Figure 23: (a) The semicircular path aa with a dashed line marking path b; (b) paths aa and b withthe portions selected by buildcycle shown by heavy lines.

It is a easier to use the buildcycle macro in situations like Figure 24 where there are more thantwo path arguments and each pair o consecutive paths has a unique intersection. For instance, theline q0.5 and the curve p2 intersect only at point  ; and the curve p2 and the line q1.5 intersectonly at point . In act, each o the points  , , ,   is a unique intersection, and the result o 

buildcycle(q0.5, p2, q1.5, p4)

takes q0.5 rom   to  , then p2 rom   to , then q1.5 rom to , and nally p4 rom backto  . An examination o the MetaPost code or Figure 24 reveals that you have to go backwardsalong p2 in order to get rom   to . This works perectly well as long as the intersection points areuniquely dened but it can cause unexpected results when pairs o paths intersect more than once.

The general rule or the buildcycle macro is that

buildcycle( 1, 2, 3, . . . , )

chooses the intersection between each and +1 to be as late as possible on and as early aspossible on +1. There is no simple rule or resolving conicts between these two goals, so youshould avoid cases where one intersection point occurs later on and another intersection pointoccurs earlier on +1.

The preerence or intersections as late as possible on and as early as possible on +1 leads toambiguity resolution in avor o orward-going subpaths. For cyclic paths such as path b in Figure 23“early” and “late” are relative to a start/nish point which is where you get back to when you say“..cycle”. For the path b, this turns out to be the rightmost point on the circle.

A more direct way to deal with path intersections is via the ⟨secondary binop⟩ intersection-

point that nds the points  , , , and   in Figure 24. This macro nds a point where twogiven paths intersect. I there is more than one intersection point, it just chooses one; i there is nointersection, the macro generates an error message.

30

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 32/109

beginfig(24);

h=2in; w=2.7in;

path p[], q[], pp;

for i=2 upto 4: ii:=i**2;

p[i] = (w/ii,h){1,-ii}...(w/i,h/i)...(w,h/ii){ii,-1};

endfor

q0.5 = (0,0)--(w,0.5h);

q1.5 = (0,0)--(w/1.5,h);

pp = buildcycle(q0.5, p2, q1.5, p4);

fill pp withcolor .7white;

z0=center pp;picture lab; lab=thelabel(btex $f>0$ etex, z0);

unfill bbox lab; draw lab;

draw q0.5; draw p2; draw q1.5; draw p4;

dotlabel.top(btex $P$ etex, p2 intersectionpoint q0.5);

dotlabel.rt(btex $Q$ etex, p2 intersectionpoint q1.5);

dotlabel.lft(btex $R$ etex, p4 intersectionpoint q1.5);

dotlabel.bot(btex $S$ etex, p4 intersectionpoint q0.5);

endfig;

f > 0 P 

Q

R

Figure 24: MetaPost code and the corresponding output.

31

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 33/109

9.2 Dealing with Paths Parametrically

The intersectionpoint macro is based on a primitive operation called intersectiontimes. This⟨secondary binop⟩ is one o several operations that deal with paths parametrically. It locates anintersection between two paths by giving the “time” parameter on each path. This reers to theparameterization scheme rom Section 4 that described paths as piecewise cubic curves

( (),  ()

)where ranges rom zero to the number o curve segments. In other words, when a path is specied

as passing through a sequence o points, where = 0 at the rst point, then = 1 at the next, and = 2 at the next, etc. The result o 

a intersectiontimes b

is (−1, −1) i there is no intersection; otherwise you get a pair (, ), where is a time on path a

when it intersects path b, and is the corresponding time on path b.For example, suppose path a is denoted by the thin line in Figure 25 and path b is denoted by

the thicker line. I the labels indicate time values on the paths, the pair o time values computed by

a intersectiontimes b

must be one o (0.25, 1.77), (0.75, 1.40), or (2.58, 0.24),

depending on which o the three intersection points is chosen by the MetaPost interpreter. Theexact rules or choosing among multiple intersection points are a little complicated, but it turns outthat you get the time values (0.25, 1.77) in this example. Smaller time values are preerred overlarger ones so that (, ) is preerred to (′, ′) whenever < ′ and < ′. When no singlealternative minimizes both the and components the component tends to get priority, butthe rules get more complicated when there are no integers between and ′. (For more details, seeThe METAFONT  book  [5, Chapter 14]).

0 1 2

30

12

Figure 25: Two intersecting paths with time values marked on each path.

The intersectiontimes operator is more exible than intersectionpoint because there area number o things that can be done with time values on a path. One o the most important is justto ask “where is path p at time t?” The construction

point ⟨numeric expression⟩ of ⟨path primary⟩

answers this question. I the ⟨numeric expression⟩ is less than zero or greater than the time value

assigned to the last point on the path, the point of construction normally yields an endpoint o the path. Hence, it is common to use the predened constant infinity (equal to 4095.99998) asthe ⟨numeric expression⟩ in a point of construction when dealing with the end o a path.

Such “innite” time values do not work or a cyclic path, since time values outside o the normalrange can be handled by modular arithmetic in that case; i.e., a cyclic path p through points 0, 1,2, . . . , −1 has the normal parameter range 0 ≤ < , but

point t of p

32

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 34/109

can be computed or any by rst reducing modulo . I the modulus is not readily available,

length ⟨path primary⟩

gives the integer value o the upper limit o the normal time parameter range or the specied path.MetaPost uses the same correspondence between time values and points on a path to evaluate

the subpath operator. The syntax or this operator is

subpath ⟨pair expression⟩ of ⟨path primary⟩

I the value o the ⟨pair expression⟩ is (1, 2) and the ⟨path primary⟩ is , the result is a path thatollows rom point 1 of to point 2 of . I 2 < 1, the subpath runs backwards along .

An important operation based on the subpath operator is the ⟨tertiary binop⟩ cutbefore. Forintersecting paths 1 and 2,

 1 cutbefore 2

is equivalent to

subpath (xpart( 1 intersectiontimes 2), length 1) of 1

except that it also sets the path variable cuttings to the portion o  1 that gets cut of. In other

words, cutbefore returns its rst argument with the part beore the intersection cut of. Withmultiple intersections, it tries to cut of as little as possible. I the paths do not intersect, cutbefore

returns its rst argument.There is also an analogous ⟨tertiary binop⟩ called cutafter that works by applying cutbefore

with time reversed along its rst argument. Thus

 1 cutafter 2

tries to cut of the part o 1 ater its last intersection with 2.The control points o a path can be requested by the two operators

precontrol⟨numeric expression⟩ of ⟨path primary⟩,

postcontrol

⟨numeric expression

⟩of

⟨path primary

⟩.

For integer time values , these operators return the control points beore and ater a cardinalpoint o a path. A segment −1.. o a path has thereore control points

postcontrol − 1 of

andprecontrol of .

For decimal time values, precontrol of returns the last control point o sub-path (0, ) andpostcontrol of returns the rst control point o sub-path (, ∞) o a path. In other words, thecontrol points at ractional time values correspond to a virtual cardinal point inserted at the giventime value without modiying path shape.

Another operator

direction⟨numeric expression⟩ of ⟨path primary⟩

nds a vector in the direction o the ⟨path primary⟩. This is dened or any time value analogouslyto the point of construction. The resulting direction vector has the correct orientation and asomewhat arbitrary magnitude. Combining point of and direction of constructions yields theequation or a tangent line as illustrated in Figure 26.

33

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 35/109

beginfig(26);numeric scf, #, t[];

3.2scf = 2.4in;

path fun;

# = .1; % Keep the function single-valued

fun = ((0,-1#)..(1,.5#){right}..(1.9,.2#){right}..{curl .1}(3.2,2#))

yscaled(1/#) scaled scf;

x1 = 2.5scf;

for i=1 upto 2:

(t[i],whatever) =

fun intersectiontimes ((x[i],-infinity)--(x[i],infinity));

z[i] = point t[i] of fun;

z[i]-(x[i+1],0) = whatever*direction t[i] of fun;

draw (x[i],0)--z[i]--(x[i+1],0);fill fullcircle scaled 3bp shifted z[i];

endfor

label.bot(btex $x_1$ etex, (x1,0));

label.bot(btex $x_2$ etex, (x2,0));

label.bot(btex $x_3$ etex, (x3,0));

draw (0,0)--(3.2scf,0);

pickup pencircle scaled 1pt;

draw fun;

endfig;

x1x2x3

Figure 26: MetaPost code and the resulting gure

34

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 36/109

I you know a slope and you want to nd a point on a curve where the tangent line has thatslope, the directiontime operator inverts the direction of operation. Given a direction vectorand a path,

directiontime⟨pair expression⟩ of ⟨path primary⟩returns a numeric value that gives the rst time when the path has the indicated direction. (I there is no such time, the result is −1). For example, i  a is the path drawn as a thin curve in

Figure 25, directiontime (1,1) of a returns 0.2084.There is also an predened macro

directionpoint⟨pair expression⟩ of ⟨path primary⟩that nds the rst point on a path where a given direction is achieved. The directionpoint macroproduces an error message i the direction does not occur on the path.

Operators arclength and arctime of relate the “time” on a path to the more amiliar concepto arc length.8 The expression

arclength ⟨path primary⟩gives the arc length o a path. I  p is a path and a is a number between 0 and arclength p,

arctime a of p

gives the time t such that

arclength subpath (0,t) of p = a.

9.3 Ane Transormations

Note how path fun in Figure 26 is rst constructed as

(0,-.1)..(1,.05){right}..(1.9,.02){right}..{curl .1}(3.2,.2)

and then the yscaled and scaled operators are used to adjust the shape and size o the path. Asthe name suggests, an expression involving “yscaled 10” multiplies coordinates by ten so thatevery point (, ) on the original path corresponds to a point (, 10) on the transormed path.

Including scaled and yscaled, there are seven transormation operators that take a numeric orpair argument:

(, ) shifted (, ) = ( + , + );

(, ) rotated = ( cos − sin , sin + cos );

(, ) slanted = ( + , );

(, ) scaled = (, );

(, ) xscaled = (, );

(, ) yscaled = (, );

(, ) zscaled (, ) = ( − , + ).

Most o these operations are sel-explanatory except or zscaled which can be thought o as multi-

plication o complex numbers. The efect o  zscaled (, ) is to rotate and scale so as to map (1, 0)into (, ). The efect o rotated is rotate degrees counter-clockwise.

Any combination o shiting, rotating, slanting, etc. is an ane transormation, the net efect o which is to transorm any pair (, ) into

( + + , + + ),

8The arclength and arctime operators are only ound in MetaPost version 0.50 and higher.

35

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 37/109

or some sextuple (, , , , , ). This inormation can be stored in a variable o typetransorm so that transformed T might be equivalent to

xscaled -1 rotated 90 shifted (1,1)

i T is an appropriate transorm variable. The transorm T could then be initialized with an expressiono type transorm as ollows:

transform T;

T = identity xscaled -1 rotated 90 shifted (1,1);

As this example indicates, transorm expressions can be built up by applying transormation opera-tors to other transorms. The predened transormation identity is a useul starting point or thisprocess. This can be illustrated by paraphrasing the above equation or T into English: “T shouldbe the transorm obtained by doing whatever identity does. Then scaling coordinates by −1,rotating 90∘, and shiting by (1, 1).” This works because identity is the identity transormationwhich does nothing; i.e., transformed identity is a no-op.

The syntax or transorm expressions and transormation operators is given in Figure 27. Itincludes two more options or ⟨transormer⟩:

reflectedabout( ,)

reects about the line dened by points and ; and

rotatedaround( ,)

rotates degrees counter-clockwise around point . For example, the equation or initializing trans-orm T could have been

T = identity reflectedabout((2,0), (0,2)).

⟨pair secondary⟩ → ⟨pair secondary⟩⟨transormer⟩⟨path secondary⟩ → ⟨path secondary⟩⟨transormer⟩

⟨picture secondary

⟩ → ⟨picture secondary

⟩⟨transormer

⟩⟨pen secondary⟩ → ⟨pen secondary⟩⟨transormer⟩⟨transorm secondary⟩ → ⟨transorm secondary⟩⟨transormer⟩⟨transormer⟩ → rotated⟨numeric primary⟩

| scaled⟨numeric primary⟩| shifted⟨pair primary⟩| slanted⟨numeric primary⟩| transformed⟨transorm primary⟩| xscaled⟨numeric primary⟩| yscaled⟨numeric primary⟩| zscaled⟨pair primary⟩| reflectedabout(⟨pair expression⟩,⟨pair expression⟩)

|rotatedaround(

⟨pair expression

⟩,

⟨numeric expression

⟩)

Figure 27: The syntax or transorms and related operators

There is also a unary operator inverse that takes a transorm and nds another transorm thatundoes the efect o the rst transorm. Thus i 

  = transformed  

36

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 38/109

then = transformed inverse .

It is not legal to take the inverse o an unknown transorm but we have already seen that youcan say

T = ⟨transorm expression⟩when T has not been given a value yet. It is also possible to apply an unknown transorm to aknown pair or transorm and use the result in a linear equation. Three such equations are sucientto determine a transorm. Thus the equations

(0,1) transformed T’ = (3,4);

(1,1) transformed T’ = (7,1);

(1,0) transformed T’ = (4,-3);

allow MetaPost to determine that the transorm T’ is a combination o rotation and scaling with

= 4, = −3,

= 3, = 4,

= 0, = 0.

Equations involving an unknown transorm are treated as linear equations in the six parametersthat dene the transorm. These six parameters can also be reerred to directly as

xpart T, ypart T, xxpart T, xypart T, yxpart T, yypart T,

where T is a transorm. For instance, Figure 28 uses the equations

xxpart T=yypart T; yxpart T=-xypart T

to speciy that T is shape preserving; i.e., it is a combination o rotating, shiting, and uniormscaling.

9.4 Dashed Lines

The MetaPost language provides many ways o changing the appearance o a line besides justchanging its width. One way is to use dashed lines as was done in Figures 5 and 23. The syntax orthis is

draw ⟨path expression⟩ dashed ⟨dash pattern⟩where a ⟨dash pattern⟩ is really a special type o  ⟨picture expression⟩. There is a predened ⟨dashpattern⟩ called evenly that makes dashes 3 PostScript points long separated by gaps o the samesize. Another predened dash pattern withdots produces dotted lines with dots 5 PostScript pointsapart.9 For dots urther apart or longer dashes urther apart, the ⟨dash pattern⟩ can be scaled asshown in Figure 29.

Another way to change a dash pattern is to alter its phase by shiting it horizontally. Shitingto the right makes the dashes move orward along the path and shiting to the let moves thembackward. Figure 30 illustrates this efect. The dash pattern can be thought o as an innitely

repeating pattern strung out along a horizontal line where the portion o the line to the right o the axis is laid out along the path to be dashed.

When you shit a dash pattern so that the axis crosses the middle o a dash, the rst dashgets truncated. Thus the line with dash pattern e4 starts with a dash o length 12bp ollowed by a12bp gap and another 12bp dash, etc., while e4 shifted (-6bp,0) produces a 6bp dash, a 12 bp

9withdots is only ound in MetaPost version 0.50 and higher.

37

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 39/109

beginfig(28);

path p[];

p1 = fullcircle scaled .6in;

z1=(.75in,0)=-z3;

z2=directionpoint left of p1=-z4;

p2 = z1..z2..{curl1}z3..z4..{curl 1}cycle;fill p2 withcolor .4[white,black];

unfill p1;

draw p1;

transform T;

z1 transformed T = z2;

z3 transformed T = z4;

xxpart T=yypart T; yxpart T=-xypart T;

picture pic;

pic = currentpicture;

for i=1 upto 2:

pic:=pic transformed T;

draw pic;

endfor

dotlabels.top(1,2,3); dotlabels.bot(4);

endfig;

1

2

3

4

Figure 28: MetaPost code and the resulting “ractal” gure

dashed evenly

dashed evenly scaled 2dashed evenly scaled 4

dashed withdots

dashed withdots scaled 2

Figure 29: Dashed lines each labeled with the ⟨dash pattern⟩ used to create it.

02

4

6

1 draw z0..z1 dashed e43 draw z2..z3 dashed e4 shifted (6bp,0)

5 draw z4..z5 dashed e4 shifted (12bp,0)

7 draw z6..z7 dashed e4 shifted (18bp,0)

Figure 30: Dashed lines and the MetaPost statements or drawing them where e4 reers to the dashpattern evenly scaled 4.

38

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 40/109

gap, then a 12bp dash, etc. This dash pattern could be specied more directly via the dashpattern

unction:dashpattern(on 6bp off 12bp on 6bp)

This means “draw the rst 6bp o the line, then skip the next 12bp, then draw another 6bp andrepeat.” I the line to be dashed is more than 30bp long, the last 6bp o the rst copy o the dashpattern will merge with the rst 6bp o the next copy to orm a dash 12bp long. The general syntax

or the dashpattern unction is shown in Figure 31.

⟨dash pattern⟩ → dashpattern(⟨on/of list⟩)

⟨on/of list⟩ → ⟨on/of list⟩⟨on/of clause⟩ | ⟨on/of clause⟩⟨on/of clause⟩ → on⟨numeric tertiary⟩ | off⟨numeric tertiary⟩

Figure 31: The syntax or the dashpattern unction

Since a dash pattern is really just a special kind o picture, the dashpattern unction returnsa picture. It is not really necessary to know the structure o such a picture, so the casual readerwill probably want to skip on to Section 9.6. For those who want to know, a little experimentationshows that i d is

dashpattern(on 6bp off 12bp on 6bp),then llcorner d is (0, 24) and urcorner d is (24, 24). Drawing d directly without using it as adash pattern produces two thin horizontal line segments like this:

The lines in this example are specied as having width zero, but this does not matter because theline width is ignored when a picture is used as a dash pattern.

The general rule or interpreting a picture d as a dash pattern is that the line segments in d areprojected onto the -axis and the resulting pattern is replicated to innity in both directions byplacing copies o the pattern end-to-end. The actual dash lengths are obtained by starting at = 0and scanning in the positive direction.

To make the idea o “replicating to innity” more precise, let  (d) be the projection o  d onto

the axis, and let shift( (d), ) be the result o shiting d by . The pattern resulting rom innitereplication is ⋃

integers

shift( (), · ℓ()),

where ℓ() measures the length o   (). The most restrictive possible denition o this length ismax − min, where [min, max] is the range o  coordinates in  (). In act, MetaPost uses

max(|0(d)| , max − min),

where 0(d) is the coordinate o the contents o  d. The contents o  d should lie on a horizontalline, but i they do not, the MetaPost interpreter just picks a coordinate that occurs in d.

A picture used as a dashed pattern must contain no text or lled regions, but it can containlines that are themselves dashed. This can give small dashes inside o larger dashes as shown inFigure 32.

Also, dashed patterns are intended to be used either with pencircle or no pen at all; pensquare

and other complex pens should be avoided. This is because the output uses the PostScript prim-itive setdash, which does not interact well with the lled paths created by polygonal pens. SeeSection 9.7, p. 43.

39

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 41/109

beginfig(32);

draw dashpattern(on 15bp off 15bp) dashed evenly;

picture p;

p=currentpicture;

currentpicture:=nullpicture;

draw fullcircle scaled 1cm xscaled 3 dashed p;

endfig;

Figure 32: MetaPost code or dashed patterns and the corresponding output

9.5 Local specials

I you want to attach a special bit o PostScript code, you can use

withprescript⟨string expression⟩and

withpostscript⟨string expression⟩The strings will be written to the output le beore and ater the current object, each beginning ontheir own line. You can speciy multiple withprescript or withpostscript options i you like.

When you speciy more than one withprescript or more than one withpostscript option, bewary o the act that the scripts use a orm o nesting: the withprescript items are written to thePostScript le in last in, rst out order; whereas the withpostscript items are written in rst in,rst out order.

9.6 Other Options

You might have noticed that the dashed lines produced by dashed evenly appear to have moreblack than white. This is an efect o the linecap parameter that controls the appearance o theends o lines as well as the ends o dashes. There are also a number o other ways to afect theappearance o things drawn with MetaPost.

The linecap parameter has three diferent settings just as in PostScript. Plain MetaPost givesthis internal variable the deault value rounded which causes line segments to be drawn with roundedends like the segment rom z0 to z3 in Figure 33. Setting linecap := butt cuts the ends of ushso that dashes produced by dashed evenly have length 3bp, not 3bp plus the line width. You canalso get squared-of ends that extend past the specied endpoints by setting linecap := squared aswas done in the line rom z2 to z5 in Figure 33.

Another parameter borrowed rom PostScript afects the way a draw statement treats sharpcorners in the path to be drawn. The linejoin parameter can be rounded, beveled, or mitered

as shown in Figure 34. The deault value or plain MetaPost is rounded which gives the efect o drawing with a circular brush.

When linejoin is mitered, sharp corners generate long pointed eatures as shown in Figure 35.Since this might be undesirable, there is an internal variable called miterlimit that controls howextreme the situation can get beore the mitered join is replaced by a beveled join. For PlainMetaPost, miterlimit has a deault value o 10.0 and line joins revert to beveled when the ratio o 

miter length to line width reaches this value.The linecap, linejoin, and miterlimit parameters are especially important because they alsoafect things that get drawn behind the scenes. For instance, Plain MetaPost has statements ordrawing arrows, and the arrowheads are slightly rounded when linejoin is rounded. The efectdepends on the line width and is quite subtle at the deault line width o 0.5bp as shown in Figure 36.

Drawing arrows like the ones in Figure 36 is simply a matter o saying

drawarrow⟨path expression⟩

40

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 42/109

beginfig(33);

for i=0 upto 2:

z[i]=(0,40i); z[i+3]-z[i]=(100,30);

endfor

pickup pencircle scaled 18;

draw z0..z3 withcolor .8white;

linecap:=butt;draw z1..z4 withcolor .8white;

linecap:=squared;

draw z2..z5 withcolor .8white;

dotlabels.top(0,1,2,3,4,5);

endfig; linecap:=rounded;

0

1

2

3

4

5

Figure 33: MetaPost code and the corresponding output

beginfig(34);

for i=0 upto 2:

z[i]=(0,50i); z[i+3]-z[i]=(60,40);

z[i+6]-z[i]=(120,0);endfor

pickup pencircle scaled 24;

draw z0--z3--z6 withcolor .8white;

linejoin:=mitered;

draw z1..z4--z7 withcolor .8white;

linejoin:=beveled;

draw z2..z5--z8 withcolor .8white;

dotlabels.bot(0,1,2,3,4,5,6,7,8);

endfig; linejoin:=rounded;

0

1

2

3

4

5

6

7

8

Figure 34: MetaPost code and the corresponding output

miter length

line width

Figure 35: The miter length and line width whose ratio is limited by miterlimit.

1

3

5

2 drawarrow z1..z2

4 drawarrow reverse(z3..z4)

6 drawdblarrow z5..z6

Figure 36: Three ways o drawing arrows.

41

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 43/109

instead o  draw ⟨path expression⟩. This draws the given path with an arrowhead at the last pointon the path. I you want the arrowhead at the beginning o the path, just use the unary operatorreverse to take the original path and make a new one with its time sense reversed; i.e., or a path p

with length p = ,point of reverse p and point − of p

are synonymous.

As shown in Figure 36, a statement beginningdrawdblarrow⟨path expression⟩

draws a double-headed arrow. The size o the arrowhead is guaranteed to be larger than the linewidth, but it might need adjusting i the line width is very great. This is done by assigning a newvalue to the internal variable ahlength that determines arrowhead length as shown in Figure 37.Increasing ahlength rom the deault value o 4 PostScript points to 1.5 centimeters produces thelarge arrowhead in Figure 37. There is also an ahangle parameter that controls the angle at the tipo the arrowhead. The deault value o this angle is 45 degrees as shown in the gure.

ahlength

ahlengthahangle

Figure 37: A large arrowhead with key parameters labeled and paths used to draw it marked withwhite lines.

The arrowhead is created by lling the triangular region that is outlined in white in Figure 37 andthen drawing around it with the currently picked up pen. This combination o lling and drawingcan be combined into a single filldraw statement:

filldraw

⟨path expression

⟩ ⟨optional dashed and withcolor and withpen clauses

⟩;

The ⟨path expression⟩ should be a closed cycle like the triangular path in Figure 37. This pathshould not be conused with the path argument to drawarrow which is indicated by a white line inthe gure.

White lines like the ones in the gure can be created by an undraw statement. This is an erasingversion o draw that draws withcolor background just as the unfill statement does. There is alsoan unfilldraw statement just in case someone nds a use or it.

The filldraw, undraw and unfilldraw statements and all the arrow drawing statements are likethe fill and draw statements in that they take dashed, withpen, and withcolor options. Whenyou have a lot o drawing statements it is nice to be able to apply an option such as withcolor

0.8white to all o them without having to type this repeatedly as was done in Figures 33 and 34.The statement or this purpose is

drawoptions(

⟨text

⟩)

where the ⟨text⟩ argument gives a sequence o  dashed, withcolor, and withpen options to beapplied automatically to all drawing statements. I you speciy

drawoptions(withcolor .5[black,white])

and then want to draw a black line, you can override the drawoptions by speciying

draw ⟨path expression⟩ withcolor black

42

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 44/109

To turn of drawoptions all together, just give an empty list:

drawoptions()

(This is done automatically by the beginfig macro).Since irrelevant options are ignored, there is no harm in giving a statement like

drawoptions(dashed evenly)ollowed by a sequence o draw and fill commands. It does not make sense to use a dash patternwhen lling so the dashed evenly gets ignored or fill statements. It turns out that

drawoptions(withpen ⟨pen expression⟩)

does afect fill statements as well as draw statements. In act there is a special pen variable calledcurrentpen such that fill . . . withpen currentpen is equivalent to a filldraw statement.

Precisely what does it mean to say that drawing options afect those statements where they makesense? The dashed ⟨dash pattern⟩ option only afects

draw ⟨path expression⟩statements, and text appearing in the

⟨picture expression

⟩argument to

draw ⟨picture expression⟩statement is only afected by the withcolor ⟨color expression⟩ option. For all other combinationso drawing statements and options, there is some efect. An option applied to a draw ⟨pictureexpression⟩ statement will in general afect some parts o the picture but not others. For instance,a dashed or withpen option will afect all the lines in the picture but none o the labels.

9.7 Pens

Previous sections have given numerous examples o  pickup ⟨pen expression⟩ and withpen ⟨penexpression⟩, but there have not been any examples o pen expressions other than

pencircle scaled ⟨numeric primary⟩which produces lines o a specied width. For calligraphic efects such in Figure 38, you can apply anyo the transormation operators discussed in Section 9.3. The starting point or such transormationsis pencircle, a circle one PostScript point in diameter. Thus ane transormations produce acircular or elliptical pen shape. The width o lines drawn with the pen depends on how nearlyperpendicular the line is to the long axis o the ellipse.

Figure 38 demonstrates operators lft, rt, top, and bot that answer the question, “I the currentpen is placed at the position given by the argument, where will its let, right, top, or bottom edgebe?” In this case the current pen is the ellipse given in the pickup statement and its bounding boxis 0.1734 inches wide and 0.1010 inches high, so rt x3 is x3 + 0.0867in and bot y5 is y5−0.0505in.The lft, rt, top, and bot operators also accept arguments o type pair in which case they computethe and coordinates o the letmost, rightmost, topmost, or bottommost point on the pen shape.For example,

rt(, ) = (, ) + (0.0867in, 0.0496in)

or the pen in Figure 38. Note that beginfig resets the current pen to a deault value o 

pencircle scaled 0.5bp

at the beginning o each gure. This value can be reselected at any time by giving the commandpickup defaultpen.

43

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 45/109

beginfig(38);

pickup pencircle scaled .2in yscaled .08 rotated 30;

x0=x3=x4;

z1-z0 = .45in*dir 30;

z2-z3 = whatever*(z1-z0);

z6-z5 = whatever*(z1-z0);

z1-z6 = 1.2*(z3-z0);

rt x3 = lft x2;x5 = .55[x4,x6];

y4 = y6;

lft x3 = bot y5 = 0;

top y2 = .9in;

draw z0--z1--z2--z3--z4--z5--z6 withcolor .7white;

dotlabels.top(0,1,2,3,4,5,6);

endfig;

0

1

23

45

6

Figure 38: MetaPost code and the resulting “calligraphic” gure.

This would be the end o the story on pens, except that or compatibility with METAFONT,

MetaPost also allows pen shapes to be polygonal. There is a predened pen called pensquare thatcan be transormed to yield pens shaped like parallelograms.

In act, there is even an operator called makepen that takes a convex-polygon-shaped path andmakes a pen that shape and size. I the path is not exactly convex or polygonal, the makepen

operator will straighten the edges and/or drop some o the vertices. In particular, pensquare isequivalent to

 makepen((-.5,-.5)--(.5,-.5)--(.5,.5)--(-.5,.5)--cycle)

pensquare and makepen should not be used with dash patterns. See the end o Section 9.4, p.39.

The inverse o  makepen is the makepath operator that takes a ⟨pen primary⟩ and returns thecorresponding path. Thus makepath pencircle produces a circular path identical to fullcircle.

This also works or a polygonal pen so that makepath makepen⟨path expression⟩

will take any cyclic path and turn it into a convex polygon.

9.8 Clipping and Low-Level Drawing Commands

Drawing statements such as draw, fill, filldraw, and unfill are part o the Plain macro packageand are dened in terms o more primitive statements. The main diference between the drawingstatements discussed in previous sections and the more primitive versions is that the primitivedrawing statements all require you to speciy a picture variable to hold the results. For fill, draw,and related statements, the results always go to a picture variable called currentpicture. Thesyntax or the primitive drawing statements that allow you to speciy a picture variable is shown inFigure 39.

The syntax or primitive drawing commands is compatible with METAFONT. Table 3 shows howthe primitive drawing statements relate to the amiliar draw and fill statements. Each o thestatements in the rst column o the table could be ended with an ⟨option list⟩ o its own, whichis equivalent to appending the ⟨option list⟩ to the corresponding entry in the second column o thetable. For example,

draw withpen pencircle

44

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 46/109

⟨addto command⟩ →addto⟨picture variable⟩also⟨picture expression⟩⟨option list⟩| addto⟨picture variable⟩contour⟨path expression⟩⟨option list⟩| addto⟨picture variable⟩doublepath⟨path expression⟩⟨option list⟩

⟨option list⟩ → ⟨empty⟩ | ⟨drawing option⟩⟨option list⟩⟨drawing option⟩ → withcolor⟨color expression⟩

|withrgbcolor

⟨rgbcolor expression

⟩ |withcmykcolor

⟨cmykcolor expression

⟩| withgreyscale⟨numeric expression⟩ | withoutcolor

| withprescript⟨string expression⟩ | withpostscript⟨string expression⟩| withpen⟨pen expression⟩ | dashed⟨picture expression⟩

Figure 39: The syntax or primitive drawing statements

is equivalent to

addto currentpicture doublepath withpen currentpen withpen pencircle

where currentpen is a special pen variable that always holds the last pen picked up. The secondwithpen option silently overrides the withpen currentpen rom the expansion o  draw.

statement equivalent primitivesdraw pic addto currentpicture also picdraw addto currentpicture doublepath withpen fill addto currentpicture contour filldraw addto currentpicture contour withpen undraw pic addto currentpicture also pic withcolor undraw addto currentpicture doublepath withpen withcolor unfill addto currentpicture contour withcolor unfilldraw addto currentpicture contour withpen withcolor

Table 3: Common drawing statements and equivalent primitive versions, where stands orcurrentpen, stands or background, stands or any path, stands or a cyclic path, and picstands or a ⟨picture expression⟩. Note that nonempty drawoptions would complicate the entriesin the second column.

There are two more primitive drawing commands that do not accept any drawing options. Oneis the setbounds command that was discussed in Section 8.4; the other is the clip command:

clip ⟨picture variable⟩ to ⟨path expression⟩Given a cyclic path, this statement trims the contents o the ⟨picture variable⟩ to eliminate everythingoutside o the cyclic path. There is no “high level” version o this statement, so you have to use

clip currentpicture to ⟨path expression⟩i you want to clip currentpicture. Figure 40 illustrates clipping.

All the primitive drawing operations would be useless without one last operation called shipout.The statement

shipout ⟨picture expression⟩writes out a picture as a PostScript le whose le name is determined by outputtemplate (seeSection 14.1). By deault, the le name ends .nnn , where nnn is the decimal representation o thevalue o the internal variable charcode. (The name “charcode” is or compatibility with META-FONT.) Normally, beginfig sets charcode, and endfig invokes shipout.

45

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 47/109

beginfig(40);

path p[];

p1 = (0,0){curl 0}..(5pt,-3pt)..{curl 0}(10pt,0);

p2 = p1..(p1 yscaled-1 shifted(10pt,0));

p0 = p2;

for i=1 upto 3: p0:=p0.. p2 shifted (i*20pt,0);

endfor

for j=0 upto 8: draw p0 shifted (0,j*10pt);endfor

p3 = fullcircle shifted (.5,.5) scaled 72pt;

clip currentpicture to p3;

draw p3;

endfig;

Figure 40: MetaPost code and the resulting “clipped” gure.

9.9 Directing Output to a Picture Variable

Sometimes, it might be desirable to save the output o a drawing operation and re-use them later.

This can easily be done with MetaPost primitives like addto. On the other hand, since the higher-level drawing commands dened in the Plain macro package always write to the currentpicture,saving their output required to temporarily save currentpicture, reset it to nullpicture, executethe drawing operations, save the currentpicture to a new picture variable and nally restorecurrentpicture to the saved state. In MetaPost version 0.60 a new macro

image( ⟨drawing commands⟩ )

was introduced that eases this task. It takes as input a sequence o arbitrary drawing operations andreturns a picture variable containing the corresponding output, without afecting currentpicture.

As an example, in the code o gure 41 an object wheel has been dened that saves the outputo two draw operations as ollows:

picture wheel;

wheel := image(

draw fullcircle scaled 2u xscaled .8 rotated 30;

draw fullcircle scaled .15u xscaled .8 rotated 30;

);

This wheel object is re-used in the denition o another object car. Figure 41 shows three car

objects drawn with two diferent slant values.

9.10 Inspecting the Components o a Picture

MetaPost pictures are composed o stroked lines, lled outlines, pieces o typeset text, clipping paths,and setbounds paths. (A setbounds path gives an articial bounding box as is needed or TEX

Figure 41: Copying objects with the image operator.

46

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 48/109

output.) A picture can have many components o each type. They can be accessed via an iterationo the orm

for ⟨symbolic token⟩ within ⟨picture expression⟩: ⟨loop text⟩ endfor

The ⟨loop text⟩ can be anything that is balanced with respect to for and endfor. The ⟨symbolictoken

⟩is a loop variable that scans the components o the picture in the order in which they were

drawn. The component or a clipping or setbounds path includes everything the path applies to.Thus i a single clipping or setbounds path applies to everything in the ⟨picture expression⟩, thewhole picture could be thought o as one big component. In order to make the contents o such apicture accessible, the for. . . within iteration ignores the enclosing clipping or setbounds path inthis case. The number o components that a for. . . within iteration would nd is returned by

length ⟨picture primary⟩

Once the for. . . within iteration has ound a picture component, there are numerous operatorsor identiying it and extracting relevant inormation. The operator

stroked ⟨primary expression⟩

tests whether the expression is a known picture whose rst component is a stroked line. Similarly,the filled and textual operators return true i the rst component is a lled outline or a pieceo typeset text. The clipped and bounded operators test whether the argument is a known picturethat starts with a clipping path or a setbounds path. This is true i the rst component is clippedor bounded or i the entire picture is enclosed in a clipping or setbounds path.

There are also numerous part extraction operators that test the rst component o a picture. I p is a picture and stroked p is true, pathpart p is the path describing the line that got stroked,penpart p is the pen that was used, dashpart p is the dash pattern. I the line is not dashed,dashpart p returns an empty picture.

The same part extraction operators work when filled p is true, except that dashpart p is notmeaningul in that case.

For text components, textual p is true, textpart p gives the text that got typeset, fontpart

p gives the ont that was used, and xpart p, ypart p, xxpart p, xypart p, yxpart p, yypart p

tell how the text has been shited, rotated, and scaled.Finally, or stroked, filled and textual components the color can be examined by saying

colorpart ⟨item⟩

This returns the color o a component in its respective color model. The color model o a componentcan be identied by the colormodel operator (c. Table 2 on p. 29).

For more ne grained color operations there are operators to extract single color components o an item. Depending on the color model the color o a picture component p is

(cyanpart p, magentapart p, yellowpart p, blackpart p)

or(redpart p, greenpart p, bluepart p)

orgreypart p

orfalse.

47

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 49/109

Note, color part operators redpart, cyanpart etc. have to match the color model o the picturecomponent in question. Applying a non-matching color part operator to a picture component triggersan error and returns a black color part in the requested color model. That is, or the code

picture pic;

pic := image(fill unitsquare scaled 1cm withcolor (0.3, 0.6, 0.9););

for item within pic:

show greypart item;show cyanpart item;

show blackpart item;

show redpart item;

endfor

the output is (omitting the error messages)

>> 0

>> 0

>> 1

>> 0.3

since in grey scale color model black is 0 and in CMYK color model black is (0,0,0,1). For thematching RGB color model the true color component is returned.

When clipped p or bounded p is true, pathpart p gives the clipping or setbounds path andthe other part extraction operators are not meaningul. Such non-meaningul part extractions donot generate errors. Instead, they return null values or black color (components): the trivial path(0,0) or pathpart, nullpen or penpart, an empty picture or dashpart, the null string ortextpart or fontpart, zero or colormodel, greypart, redpart, greenpart, bluepart, cyanpart,

 magentapart, yellowpart, one or blackpart, and black in the current deault color model orcolorpart.

To summarize the discussion o mismatching part operators:

1. Asking or non-meaningul parts o an item—such as the redpart o a clipping path, thetextpart o a stroked item, or the pathpart o a textual item—is silently accepted andreturns a null value or a black color (component).

2. Explicitly asking or a color part o a colored item in the wrong color model returns a black

color component. This operation triggers an error.

9.11 Decomposing the Glyphs o a Font

MetaPost provides a primitive to convert a glyph o a ont in the Adobe Type 1 Font ormat intoits constituent lled paths—the strokes—and store them in a picture variable. A glyph is the visualrepresentation o a character in a ont. A character is a certain slot (index) in a ont with anassociated meaning, e.g., the capital letter “M” or the exclamation mark. The meaning o a slot isdened by the ont encoding. In general, the same character is represented by diferent glyphs indiferent onts. Figure 42 shows some glyphs or the character at slot 103 in the T1 encoding, i.e.,the lower-case letter “g”. All glyphs are at the same nominal size. Note, how glyphs may extendbeyond their bounding box.

The glyphs o an Adobe Type 1 ont are composed o two types o contours: Clockwise orientedcontours add to the shape o a glyph and are lled with black ink. Counter-clockwise orientedcontours erase parts o other contours, i.e., make them transparent again. To save the contours o a glyph in a picture, the glyph operator can be used. There are two ways to identiy a glyph in aont:

glyph ⟨numeric expression⟩ of ⟨string expression⟩and

48

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 50/109

g g g g Figure 42: Diferent glyphs representing the same character.

glyph ⟨string expression⟩ of ⟨string expression⟩ .

I the rst argument is a numeric expression, it has to be a slot number between 0 and 255.Fractional slot numbers are rounded to the nearest integer value. Slot numbers outside the allowedrange trigger an error. I the rst argument is string, it has to be a CharString name in the PostScriptont’s source le. A CharString name is a unique text label or a glyph in a PostScript ont (a ontencoding actually maps CharStrings to slots). This second syntax can be used to address glyphswithout having to think about ont encodings. The second argument to the glyph operator is astring containing a ont name (section 8 has more on ont names).

The glyph operator looks-up the ont name in the ont map to determine the encoding and tond the ont’s PostScript source le. It returns a picture consisting o the glyph’s contour lines,explicitly lled black and white in the greyscale color model according to the rules laid out above.

Additionally, the contours are sorted, such that all black contours are drawn beore white contours.The lling and sorting is necessary or the picture to resembles the corresponding glyph visually10,since Adobe Type 1 onts use a generalized variant o the non-zero winding number ll rule, whichMetaPost doesn’t implement (MetaPost cannot handle non-contiguous paths). As a side efect,the interiors o the erasing contours are an opaque white in the returned picture, while they weretransparent in the original glyph. One can think o erasing contours to be unlled (see p. 29). Forinstance, the ollowing code saves the contours o the lower case letter “g”, bound to slot 103 in theOT1 encoding, in the Computer Modern Roman ont in a picture variable:

fontmapline "cmr10 CMR10 <cmr10.pfb";

picture g;

g := glyph 103 of "cmr10";

The glyph operator returns an empty picture, i the .tfm or .pfb le cannot be ound, i the

encoding given in the ont map cannot be ound or the slot number is not covered by the encoding ori the CharString name cannot be ound. Note, while MetaPost delegates the actual ont handling toa rendering application or infont and btex . . . etex blocks, the glyph operator directly operateson ont ressources. For that reason, a ont map entry is mandatory or the ont in question, giveneither by fontmapline or fontmapfile (see section 8.2).

In Figure 43, the contours o the upper case letter “Ď” in the Latin Modern Roman ont aresaved in a picture variable. The glyph is identied by its CharString name “Dcaron”. The code theniterates over all contours and draws them together with their cardinal (black) and control points(red). As it turns out, many o the control points coincide with cardinal points in this glyph.

The contours in a picture returned by the glyph operator are no raw copies o the contours oundin the ont sources, but the glyph operator applies a number o transormations to them. First, thedirection o all contours is reversed, so that contours lled black become counter-clockwise oriented(mathematically positive) and contours lled white become clockwise oriented (mathematically neg-

ative). Second, in an Adobe Type 1 ont, contours are in general closed by repeating the startingpoint beore applying the closepath operator. The MetaPost representation o such a path wouldbe:

0..controls..1.. · · · ....controls..0--cycle

10Plain contours already carry enough inormation to completely reconstruct a glyph, the orientation o a contour

can be computed rom its cardinal and control points. MetaPost has a turningnumber primitive to do that.

49

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 51/109

fontmapfile "=lm-ec.map";

beginfig(56);

picture q;

path p;

interim ahlength := 12bp;

interim ahangle := 25;

q := glyph "Dcaron" of "ec-lmr10" scaled .2;for item within q:

p := pathpart item;

drawarrow p withcolor (.6,.9,.6)

withpen pencircle scaled 1.5;

for j=0 upto length p:

pickup pencircle scaled .7;

draw (point j of p -- precontrol j of p)

dashed evenly withcolor blue;

draw (point j of p -- postcontrol j of p)

dashed evenly withcolor blue;

pickup pencircle scaled 3;

draw precontrol j of p withcolor red;

draw postcontrol j of p withcolor red;pickup pencircle scaled 2;

draw point j of p withcolor black;

endfor

endfor

endfig;

Figure 43: Iterating over the contours o a glyph

However, a more natural MetaPost representation o that path would be:

0..controls..1..

· · ·....controls..cycle

The glyph operator transorms all paths into the latter representation, i.e., the last point is removed,whenever it matches the starting point. Finally, the picture returned by the glyph operator isscaled, such that one ont design unit equals one PostScript point (bp). A usual ont design unit is athousandth part o the ont design size. Thereore, the returned picture will typically have a heighto around 1000bp.

Converting a text into plain curves is part o a process otentimes called “attening” a document.During attening, all hinting inormation in onts are lost. Hinting inormation aid a renderingapplication in aligning certain parts o a glyph on a low-resolution output device. A attened textmay thereore look distorted on screen. In SVG output, all text is automatically attened, i theinternal variable prologues is set to 3 (see section 8.1).

10 MacrosAs alluded to earlier, MetaPost has a set o automatically included macros called the Plain macropackage, and some o the commands discussed in previous sections are dened as macros instead o being built into MetaPost. The purpose o this section is to explain how to write such macros.

Macros with no arguments are very simple. A macro denition

def ⟨symbolic token⟩ = ⟨replacement text⟩ enddef

50

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 52/109

makes the ⟨symbolic token⟩ an abbreviation or the ⟨replacement text⟩, where the ⟨replacement text⟩can be virtually any sequence o tokens. For example, the Plain macro package could almost denethe fill statement like this:

def fill = addto currentpicture contour enddef

Macros with arguments are similar, except they have ormal parameters that tell how to use the

arguments in the ⟨replacement text⟩. For example, the rotatedaround macro is dened like this:

def rotatedaround(expr z, d) =

shifted -z rotated d shifted z enddef;

The expr in this denition means that ormal parameters z and d can be arbitrary expressions.(They should be pair expressions but the MetaPost interpreter does not immediately check orthat.)

Since MetaPost is an interpreted language, macros with arguments are a lot like subroutines.MetaPost macros are oten used like subroutines, so the language includes programming conceptsto support this. These concepts include local variables, loops, and conditional statements.

10.1 Grouping

Grouping in MetaPost is essential or unctions and local variables. The basic idea is that a group isa sequence o statements possibly ollowed by an expression with the provision that certain symbolictokens can have their old meanings restored at the end o the group. I the group ends with anexpression, the group behaves like a unction call that returns that expression. Otherwise, the groupis just a compound statement. The syntax or a group is

begingroup⟨statement list⟩ endgroup

orbegingroup⟨statement list⟩ ⟨expression⟩ endgroup

where a ⟨statement list⟩ is a sequence o statements each ollowed by a semicolon. A group with an⟨expression⟩ ater the ⟨statement list⟩ behaves like a ⟨primary⟩ in Figure 14 or like a ⟨numeric atom⟩

in Figure 15.Since the ⟨replacement text⟩ or the beginfig macro starts with begingroup and the ⟨replace-ment text⟩ or endfig ends with endgroup, each gure in a MetaPost input le behaves like agroup. This is what allows gures can have local variables. We have already seen in Section 7.2that variable names beginning with x or y are local in the sense that they have unknown values atthe beginning o each gure and these values are orgotten at the end o each gure. The ollowingexample illustrates how locality works:

x23 = 3.1;

beginfig(17);

...

y3a=1; x23=2;

...

endfig;

show x23, y3a;

The result o the show command is>> 3.1

>> y3a

51

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 53/109

indicating that x23 has returned to its ormer value o 3.1 and y3a is completely unknown as it wasat beginfig(17).

The locality o x and y variables is achieved by the statement

save x,y

in the

⟨replacement text

⟩or beginfig. In general, variables are made local by the statement

save ⟨symbolic token list⟩

where ⟨symbolic token list⟩ is a comma-separated list o tokens:

⟨symbolic token list⟩ → ⟨symbolic token⟩| ⟨symbolic token⟩,⟨symbolic token list⟩

All variables whose names begin with one o the specied symbolic tokens become unknown numericsand their present values are saved or restoration at the end o the current group. I the save

statement is used outside o a group, the original values are simply discarded.The main purpose o the save statement is to allow macros to use variables without interering

with existing variables or variables in other calls to the same macro. For example, the predenedmacro whatever has the

⟨replacement text

⟩begingroup save ?; ? endgroup

This returns an unknown numeric quantity, but it is no longer called question mark since that namewas local to the group. Asking the name via show whatever yields

>> %CAPSULEnnnn 

where nnnn  is an identication number that is chosen when save makes the name question markdisappear.

In spite o the versatility o  save, it cannot be used to make local changes to any o MetaPost’sinternal variables. A statement such as

save linecap

would cause MetaPost to temporarily orget the special meaning o this variable and just make itan unknown numeric. I you want to draw one dashed line with linecap:=butt and then go backto the previous value, you can use the interim statement as ollows:

begingroup interim linecap:=butt;

draw ⟨path expression⟩ dashed evenly; endgroup

This saves the value o the internal variable linecap and temporarily gives it a new value withoutorgetting that linecap is an internal variable. The general syntax is

interim ⟨internal variable⟩ := ⟨numeric expression⟩ | ⟨string expression⟩

10.2 Parameterized Macros

The basic idea behind parameterized macros is to achieve greater exibility by allowing auxiliaryinormation to be passed to a macro. We have already seen that macro denitions can have ormalparameters that represent expressions to be given when the macro is called. For instance a denitionsuch as

def rotatedaround(expr z, d) = ⟨replacement text⟩ enddef

52

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 54/109

allows the MetaPost interpreter to understand macro calls o the orm

rotatedaround(⟨expression⟩,⟨expression⟩)

The keyword expr in the macro denition means that the parameters can be expressions o any type. When the denition species (expr z, d), the ormal parameters z and d behave likevariables o the appropriate types. Within the

⟨replacement text

⟩, they can be used in expressions

  just like variables, but they cannot be redeclared or assigned to. There is no restriction againstunknown or partially known arguments. Thus the denition

def midpoint(expr a, b) = (.5[a,b]) enddef

works perectly well when a and b are unknown. An equation such as

  midpoint(z1,z2) = (1,1)

could be used to help determine z1 and z2.Notice that the above denition or midpoint works or numerics, pairs, or colors as long as both

parameters have the same type. I or some reason we want a middlepoint macro that works or asingle path or picture, it would be necessary to do an if test on the argument type. This uses theact there is a unary operator

path ⟨primary⟩that returns a boolean result indicating whether its argument is a path. Since the basic if test hasthe syntax

if ⟨boolean expression⟩: ⟨balanced tokens⟩ else: ⟨balanced tokens⟩ fi

where the ⟨balanced tokens⟩ can be anything that is balanced with respect to if and fi, the complete middlepoint macro with type test looks like this:

def middlepoint(expr a) = if path a: (point .5*length a of a)

else: .5(llcorner a + urcorner a) fi enddef;

The complete syntax or if tests is shown in Figure 44. It allows multiple if tests like

if 1: ... else: if 2: ... else: ... fi fi

to be shortened toif 1: ... elseif 2: ... else: ... fi

where 1 and 2 represent boolean expressions.Note that if tests are not statements and the ⟨balanced tokens⟩ in the syntax rules can be any

sequence o balanced tokens even i they do not orm a complete expression or statement. Thus wecould have saved two tokens at the expense o clarity by dening middlepoint like this:

def middlepoint(expr a) = if path a: (point .5*length a of

else: .5(llcorner a + urcorner fi a) enddef;

The real purpose o macros and if tests is to automate repetitive tasks and allow importantsubtasks to be solved separately. For example, Figure 45 uses macros draw_marked, mark_angle,and mark_rt_angle to mark lines and angles that appear in the gure.

The task o the draw_marked macro is to draw a path with a given number o cross marksnear its midpoint. A convenient starting place is the subproblem o drawing a single cross markperpendicular to a path p at some time t. The draw_mark macro in Figure 46 does this by rstnding a vector dm perpendicular to p at t. To simpliy positioning the cross mark, the draw_marked

macro is dened to take an arc length a along p and use the arctime operator to compute t

53

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 55/109

⟨i test⟩ → if⟨boolean expression⟩:⟨balanced tokens⟩⟨alternatives⟩fi

⟨alternatives⟩ → ⟨empty⟩

|else:

⟨balanced tokens

⟩| elseif⟨boolean expression⟩:⟨balanced tokens⟩⟨alternatives⟩

Figure 44: The syntax or if tests.

beginfig(42);

pair a,b,c,d;b=(0,0); c=(1.5in,0); a=(0,.6in);

d-c = (a-b) rotated 25;

dotlabel.lft("a",a);

dotlabel.lft("b",b);

dotlabel.bot("c",c);

dotlabel.llft("d",d);

z0=.5[a,d];

z1=.5[b,c];

(z.p-z0) dotprod (d-a) = 0;

(z.p-z1) dotprod (c-b) = 0;

draw a--d;

draw b--c;

draw z0--z.p--z1;draw_marked(a--b, 1);

draw_marked(c--d, 1);

draw_marked(a--z.p, 2);

draw_marked(d--z.p, 2);

draw_marked(b--z.p, 3);

draw_marked(c--z.p, 3);

  mark_angle(z.p, b, a, 1);

  mark_angle(z.p, c, d, 1);

  mark_angle(z.p, c, b, 2);

  mark_angle(c, b, z.p, 2);

  mark_rt_angle(z.p, z0, a);

  mark_rt_angle(z.p, z1, b);

endfig;

a

b c

d

Figure 45: MetaPost code and the corresponding gure

54

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 56/109

 marksize=4pt;

def draw_mark(expr p, a) =

begingroup

save t, dm; pair dm;

t = arctime a of p;

dm = marksize*unitvector direction t of p

rotated 90;draw (-.5dm.. .5dm) shifted point t of p;

endgroup

enddef;

def draw_marked(expr p, n) =

begingroup

save amid;

amid = .5*arclength p;

for i=-(n-1)/2 upto (n-1)/2:

draw_mark(p, amid+.6marksize*i);

endfor

draw p;

endgroup

enddef;

Figure 46: Macros or drawing a path p with n cross marks.

With the subproblem o drawing a single mark out o the way, the draw_marked macro only needsto draw the path and call draw_mark with the appropriate arc length values. The draw_marked macroin Figure 46 uses n equally-spaced a values centered on .5*arclength p.

Since draw_marked works or curved lines, it can be used to draw the arcs that the mark_angle

macro generates. Given points a, b, and c that dene a counter-clockwise angle at b, the mark_angle

needs to generate a small arc rom segment ba to segment bc. The macro denition in Figure 47does this by creating an arc p o radius one and then computing a scale actor s that makes it bigenough to see clearly.

The mark_rt_angle macro is much simpler. It takes a generic right-angle corner and uses thezscaled operator to rotate it and scale it as necessary.

10.3 Sux and Text Parameters

Macro parameters need not always be expressions as in the previous examples. Replacing thekeyword expr with suffix or text in a macro denition declares the parameters to be variablenames or arbitrary sequences o tokens. For example, there is a predened macro called hide thattakes a text parameter and interprets it as a sequence o statements while ultimately producing anempty ⟨replacement text⟩. In other words, hide executes its argument and then gets the next tokenas i nothing happened. Thus

show hide(numeric a,b; a+b=3; a-b=1) a;

prints “>> 2.”I the hide macro were not predened, it could be dened like this:

def ignore(expr a) = enddef;

def hide(text t) = ignore(begingroup t; 0 endgroup) enddef;

55

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 57/109

angle_radius=8pt;

def mark_angle(expr a, b, c, n) =

begingroup

save s, p; path p;

p = unitvector(a-b){(a-b)rotated 90}..unitvector(c-b);

s = .9marksize/length(point 1 of p - point 0 of p);

if s<angle_radius: s:=angle_radius; fidraw_marked(p scaled s shifted b, n);

endgroup

enddef;

def mark_rt_angle(expr a, b, c) =

draw ((1,0)--(1,1)--(0,1))

zscaled (angle_radius*unitvector(a-b)) shifted b

enddef;

Figure 47: Macros or marking angles.

The statements represented by the text parameter t would be evaluated as part o the group thatorms the argument to ignore. Since ignore has an empty ⟨replacement text⟩, expansion o thehide macro ultimately produces nothing.

Another example o a predened macro with a text parameter is dashpattern. The denitiono dashpattern starts

def dashpattern(text t) =

begingroup save on, off;

then it denes on and off to be macros that create the desired picture when the text parameter t

appears in the replacement text.Text parameters are very general, but their generality sometimes gets in the way. I you just

want to pass a variable name to a macro, it is better to declare it as a sux parameter. For example,

def incr(suffix $) = begingroup $:=$+1; $ endgroup enddef;

denes a macro that will take any numeric variable, add one to it, and return the new value. Sincevariable names can be more than one token long,

incr(a3b)

is perectly acceptable i a3b is a numeric variable. Sux parameters are slightly more general thanvariable names because the denition in Figure 16 allows a ⟨sux⟩ to start with a ⟨subscript⟩.

Figure 48 shows how sux and expr parameters can be used together. The getmid macro takesa path variable and creates arrays o points and directions whose names are obtained by appending

 mid, off, and dir to the path variable. The joinup macro takes arrays o points and directions andcreates a path o length n that passes through each pt[i] with direction d[i] or −d[i].

A denition that starts

def joinup(suffix pt, d)(expr n) =

might suggest that calls to the joinup macro should have two sets o parentheses as in

joinup(p.mid, p.dir)(36)

instead o joinup(p.mid, p.dir, 36)

56

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 58/109

def getmid(suffix p) =pair p.mid[], p.off[], p.dir[];

for i=0 upto 36:

p.dir[i] = dir(5*i);

p.mid[i]+p.off[i] = directionpoint p.dir[i] of p;

p.mid[i]-p.off[i] = directionpoint -p.dir[i] of p;

endfor

enddef;

def joinup(suffix pt, d)(expr n) =

begingroup

save res, g; path res;

res = pt[0]{d[0]};for i=1 upto n:

g:= if (pt[i]-pt[i-1]) dotprod d[i] <0: - fi 1;

res := res{g*d[i-1]}...{g*d[i]}pt[i];

endfor

res

endgroup

enddef;

beginfig(45)

path p, q;

p = ((5,2)...(3,4)...(1,3)...(-2,-3)...(0,-5)...(3,-4)

...(5,-3)...cycle) scaled .3cm shifted (0,5cm);

getmid(p);draw p;

draw joinup(p.mid, p.dir, 36)..cycle;

q = joinup(p.off, p.dir, 36);

draw q..(q rotated 180)..cycle;

drawoptions(dashed evenly);

for i=0 upto 3:

draw p.mid[9i]-p.off[9i]..p.mid[9i]+p.off[9i];

draw -p.off[9i]..p.off[9i];

endfor

endfig;

Figure 48: MetaPost code and the corresponding gure

57

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 59/109

In act, both orms are acceptable. Parameters in a macro call can be separated by commas or by)( pairs. The only restriction is that a text parameter must be ollowed by a right parenthesis. Forinstance, a macro foo with one text parameter and one expr parameter can be called

foo(a,b)(c)

in which case the text parameter is “a,b” and the expr parameter is c, but

foo(a,b,c)

sets the text parameter to “a,b,c” and leaves the MetaPost interpreter still looking or the exprparameter.

10.4 Varde Macros

A macro denition can begin with vardef instead o  def. Macros dened in this way are calledvarde macros. They are particularly well-suited to applications where macros are being used likeunctions or subroutines. The main idea is that a varde macro is like a variable o type “macro.”

Instead o def ⟨symbolic token⟩, a varde macro begins

vardef⟨generic variable

⟩where a ⟨generic variable⟩ is a variable name with numeric subscripts replaced by the generic sub-script symbol []. In other words, the name ollowing vardef obeys exactly the same syntax as thename given in a variable declaration. It is a sequence o tags and generic subscript symbols startingwith a tag, where a tag is a symbolic token that is not a macro or a primitive operator as explainedin Section 7.2.

The simplest case is when the name o a varde macro consists o a single tag. Under suchcircumstances, def and vardef provide roughly the same unctionality. The most obvious diferenceis that begingroup and endgroup are automatically inserted at the beginning and end o the ⟨re-placement text⟩ o every varde macro. This makes the ⟨replacement text⟩ a group so that a varde macro behaves like a subroutine or a unction call.

Another property o varde macros is that they allow multi-token macro names and macro namesinvolving generic subscripts. When a varde macro name has generic subscripts, numeric values haveto be given when the macro is called. Ater a macro denition

vardef a[]b(expr p) = ⟨replacement text⟩ enddef;

a2b((1,2)) and a3b((1,2)..(3,4)) are macro calls. But how can the ⟨replacement text⟩ tell thediference between a2b and a3b? Two implicit sux parameters are automatically provided or thispurpose. Every varde macro has sux parameters #@ and @, where @ is the last token in the namerom the macro call and #@ is everything preceding the last token. Thus #@ is a2 when the name isgiven as a2b and a3 when the name is given as a3b.

Suppose, or example, that the a[]b macro is to take its argument and shit it by an amountthat depends on the macro name. The macro could be dened like this:

vardef a[]b(expr p) = p shifted (#@,b) enddef;

Then a2b((1,2)) means (1,2) shifted (a2,b) and a3b((1,2)..(3,4)) means

((1,2)..(3,4)) shifted (a3,b).

I the macro had been a.b[], #@ would always be a.b and the @ parameter would give thenumeric subscript. Then a@ would reer to an element o the array a[]. Note that @ is a suxparameter, not an expr parameter, so an expression like @+1 would be illegal. The only way to

58

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 60/109

get at the numeric values o subscripts in a sux parameter is by extracting them rom the stringreturned by the str operator. This operator takes a sux and returns a string representation o asux. Thus str @ would be "3" in a.b3 and "3.14" in a.b3.14 or a.b[3.14]. Since the syntaxor a ⟨sux⟩ in Figure 16 requires negative subscripts to be in brackets, str @ returns "[-3]" ina.b[-3].

The str operator is generally or emergency use only. It is better to use sux parameters onlyas variable names or suxes. The best example o a varde macro involving suxes is the z macrothat denes the z convention. The denition involves a special token @# that reers to the suxollowing the macro name:

vardef z@#=(x@#,y@#) enddef;

This means that any variable name whose rst token is z is equivalent to a pair o variables whosenames are obtained by replacing z with x and y. For instance, z.a1 calls the z macro with the suxparameter @# set to a1.

In general,vardef ⟨generic variable⟩@#

is an alternative to vardef ⟨generic variable⟩ that causes the MetaPost interpreter to look or asux ollowing the name given in the macro call and makes this available as the @# sux parameter.

To summarize the special eatures o varde macros, they allow a broad class o macro names as

well as macro names ollowed by a special sux parameter. Furthermore, begingroup and endgroupare automatically added to the ⟨replacement text⟩ o a varde macro. Thus using vardef instead o def to dene the joinup macro in Figure 48 would have avoided the need to include begingroup

and endgroup explicitly in the macro denition.In act, most o the macro denitions given in previous examples could equally well use vardef

instead o  def. It usually does not matter very much which you use, but a good general rule isto use vardef i you intend the macro to be used like a unction or a subroutine. The ollowingcomparison should help in deciding when to use vardef.

• Varde macros are automatically surrounded by begingroup and endgroup.

• The name o a varde macro can be more than one token long and it can contain subscripts.

• A varde macro can have access to the sux that ollows the macro name when the macro is

called.

• When a symbolic token is used in the name o a varde macro it remains a tag and can stillbe used in other variable names. Thus p5dir is a legal variable name even though dir is avarde macro, but an ordinary macro such as ... cannot be used in a variable name. (This isortunate since z5...z6 is supposed to be a path expression, not an elaborate variable name).

10.5 Defning Unary and Binary Macros

It has been mentioned several times that some o the operators and commands discussed so arare actually predened macros. These include unary operators such as round and unitvector,statements such as fill and draw, and binary operators such as dotprod and intersectionpoint.The main diference between these macros and the ones we already know how to dene is their

argument syntax.The round and unitvector macros are examples o what Figure 14 calls ⟨unary op⟩. That is,they are ollowed by a primary expression. To speciy a macro argument o this type, the macrodenition should look like this:

vardef round primary u = ⟨replacement text⟩ enddef;

59

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 61/109

The u parameter is an expr parameter and it can be used exactly like the expr parameter denedusing the ordinary

(expr u)

syntax.As the round example suggests, a macro can be dened to take a ⟨secondary⟩, ⟨tertiary⟩, or an

⟨expression

⟩parameter. For example, the predened denition o the fill macro is roughly

def fill expr c = addto currentpicture contour c enddef;

It is even possible to dene a macro to play the role o  ⟨o operator⟩ in Figure 14. For example,the direction of macro has a denition o this orm:

vardef direction expr t of p = ⟨replacement text⟩ enddef;

Macros can also be dened to behave like binary operators. For instance, the denition o thedotprod macro has the orm

primarydef w dotprod z = ⟨replacement text⟩ enddef;

This makes dotprod a

⟨primary binop

⟩. Similarly, secondarydef and tertiarydef introduce

⟨sec-

ondary binop⟩ and ⟨tertiary binop⟩ denitions. These all dene ordinary macros, not varde macros;e.g., there is no “primaryvardef.”

Thus macro denitions can be introduced by def, vardef, primarydef, secondarydef, ortertiarydef. A ⟨replacement text⟩ is any list o tokens that is balanced with respect to def-enddef pairs where all ve macro denition tokens are treated like def or the purpose o def-enddef

matching.The rest o the syntax or macro denitions is summarized in Figure 49. The syntax contains

a ew surprises. The macro parameters can have a ⟨delimited part⟩ and an ⟨undelimited part⟩.Normally, one o these is ⟨empty⟩, but it is possible to have both parts nonempty:

def foo(text a) expr b = ⟨replacement text⟩ enddef;

This denes a macro foo to take a text parameter in parentheses ollowed by an expression.

⟨macro denition⟩ → ⟨macro heading⟩=⟨replacement text⟩ enddef

⟨macro heading⟩ → def ⟨symbolic token⟩⟨delimited part⟩⟨undelimited part⟩| vardef ⟨generic variable⟩⟨delimited part⟩⟨undelimited part⟩| vardef ⟨generic variable⟩@#⟨delimited part⟩⟨undelimited part⟩| ⟨binary de ⟩⟨parameter⟩⟨symbolic token⟩⟨parameter⟩

⟨delimited part⟩ → ⟨empty⟩| ⟨delimited part⟩(⟨parameter type⟩⟨parameter tokens⟩)

⟨parameter type⟩ → expr | suffix | text

⟨parameter tokens⟩ → ⟨parameter⟩ | ⟨parameter tokens⟩,⟨parameter⟩⟨parameter⟩ → ⟨symbolic token⟩⟨undelimited part⟩ → ⟨empty⟩

| ⟨parameter type

⟩⟨parameter

⟩| ⟨precedence level⟩⟨parameter⟩| expr ⟨parameter⟩ of ⟨parameter⟩⟨precedence level⟩ → primary | secondary | tertiary

⟨binary de ⟩ → primarydef | secondarydef | tertiatydef

Figure 49: The syntax or macro denitions

60

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 62/109

The syntax also allows the ⟨undelimited part⟩ to speciy an argument type o  suffix or text.An example o a macro with an undelimited sux parameter is the predened macro incr that isactually dened like this:

vardef incr suffix $ = $:=$+1; $ enddef;

This makes incr a unction that takes a variable, increments it, and returns the new value. Un-

delimited sux parameters may be parenthesized, so incr a and incr(a) are both legal i  a is anumeric variable. There is also a similar predened macro decr that subtracts 1.Undelimited text parameters run to the end o a statement. More precisely, an undelimited text

parameter is the list o tokens ollowing the macro call up to the rst “;” or “endgroup” or “end”except that an argument containing “begingroup” will always include the matching “endgroup.”An example o an undelimited text parameter comes rom the predened macro cutdraw whosedenition is roughly

def cutdraw text t =

begingroup interim linecap:=butt; draw t; endgroup enddef;

This makes cutdraw synonymous with draw except or the linecap value. (This macro is providedmainly or compatibility with METAFONT.)

11 Loops

Numerous examples in previous sections have used simple for loops o the orm

for ⟨symbolic token⟩ = ⟨expression⟩ upto ⟨expression⟩ : ⟨loop text⟩ endfor

It is equally simple to construct a loop that counts downward: just replace upto by downto makethe second ⟨expression⟩ smaller than the rst. This section covers more complicated types o pro-gressions, loops where the loop counter behaves like a sux parameter, and ways o exiting rom aloop.

The rst generalization is suggested by the act that upto is a predened macro or

step 1 until

and downto is a macro or step -1 until. A loop begining

for i=a step b until c

scans a sequence o  i values a, a + b, a + 2b, . . . , stopping beore i passes c; i.e., the loop scans i

values where i ≤ c i b > 0 and i ≥ c i  b < 0. For b = 0 the loop never terminates, even i  a = c.It is best to use this eature only when the step size is an integer or some number that can be

represented exactly in xed point arithmetic as a multiple o  165536

. Otherwise, error will accumulateand the loop index might not reach the expected termination value. For instance,

for i=0 step .1 until 1: show i; endfor

shows ten i values the last o which is 0.90005.

The standard way o avoid the problems associated with non-integer step sizes is to iterate overinteger values and then multiply by a scale actor when using the loop index as was done in Figures1 and 40.

Alternatively, the values to iterate over can be given explicitly. Any sequence o zero or moreexpressions separated by commas can be used in place o a step b upto c. In act, the expressionsneed not all be the same type and they need not have known values. Thus

for t=3.14, 2.78, (a,2a), "hello": show t; endfor

61

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 63/109

shows the our values listed.Note that the loop body in the above example is a statement ollowed by a semicolon. It is

common or the body o a loop to be one or more statements, but this need not be the case. Aloop is like a macro denition ollowed by calls to the macro. The loop body can be virtually anysequence o tokens as long as they make sense together. Thus, the (ridiculous) statement

draw for p=(3,1),(6,2),(7,5),(4,6),(1,3): p-- endfor cycle;

is equivalent todraw (3,1)--(6,2)--(7,5)--(4,6)--(1,3)--cycle;

(See Figure 18 or a more realistic example o this.)I a loop is like a macro denition, the loop index is like an expr parameter. It can represent any

value, but it is not a variable and it cannot be changed by an assignment statement. In order to dothat, you need a forsuffixes loop. A forsuffixes loop is a lot like a for loop, except the loopindex behaves like a sux parameter. The syntax is

forsuffixes⟨symbolic token⟩ = ⟨sux list⟩ : ⟨loop text⟩ endfor

where a ⟨sux list⟩ is a comma-separated list o suxes. I some o the suxes are ⟨empty⟩, the

⟨loop text

⟩gets executed with the loop index parameter set to the empty sux.

A good example o a forsuffixes loop is the denition o the dotlabels macro:vardef dotlabels@#(text t) =

forsuffixes $=t: dotlabel@#(str$,z$); endfor enddef;

This should make it clear why the parameter to dotlabels has to be a comma-separated listo suxes. Most macros that accept variable-length comma-separated lists use them in for orforsuffixes loops in this ashion as values to iterate over.

When there are no values to iterate over, you can use a forever loop:

forever: ⟨loop text⟩ endfor

To terminate such a loop when a boolean condition becomes true, use an exit clause:

exitif

⟨boolean expression

⟩;

When the MetaPost interpreter encounters an exit clause, it evaluates the ⟨boolean expression⟩ andexits the current loop i the expression is true. I it is more convenient to exit the loop when anexpression becomes alse, use the predened macro exitunless.

Thus MetaPost’s version o a while loop is

forever: exitunless ⟨boolean expression⟩; ⟨loop text⟩ endfor

The exit clause could equally well come just beore endfor or anywhere in the ⟨loop text⟩. In actany for, forever, or forsuffixes loop can contain any number o exit clauses.

The summary o loop syntax shown in Figure 50 does not mention exit clauses explicitly becausea ⟨loop text⟩ can be virtually any sequence o tokens. The only restriction is that a ⟨loop text⟩ mustbe balanced with respect to for and endfor. O course this balancing process treats forsuffixes

and forever just like for.

12 Reading and Writing Files

File access was one o the new language eatures introduced in version 0.60 o the MetaPost language.A new operator

readfrom ⟨le name⟩

62

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 64/109

⟨loop⟩ → ⟨loop header⟩: ⟨loop text⟩endfor

⟨loop header⟩ → for ⟨symbolic token⟩ = ⟨progression⟩| for ⟨symbolic token⟩ = ⟨or list⟩| forsuffixes⟨symbolic token⟩ = ⟨sux list⟩| forever

⟨progression⟩ → ⟨numeric expression⟩ upto ⟨numeric expression⟩

| ⟨numeric expression

⟩downto

⟨numeric expression

⟩| ⟨numeric expression⟩ step ⟨numeric expression⟩ until ⟨numeric expression⟩⟨or list⟩ → ⟨expression⟩ | ⟨or list⟩, ⟨expression⟩⟨sux list⟩ → ⟨sux⟩ | ⟨sux list⟩, ⟨sux⟩

Figure 50: The syntax or loops

returns a string giving the next line o input rom the named le. The ⟨le name⟩ can be any primaryexpression o type string. I the le has ended or cannot be read, the result is a string consistingo a single null character. The preloaded plain macro package introduces the name EOF or thisstring. Ater readfrom has returned EOF, additional reads rom the same le cause the le to bereread rom the start.

All les opened by readfrom that have not completely been read yet are closed automaticallywhen the program terminates, but there exists a command

closefrom ⟨le name⟩

to close les opened by readfrom explicitly. It is wise to manually close les you do not need toread completely (i.e. until EOF is returned) because otherwise such les will continue to use internalresources and perhaps cause a capacity exceeded! error.

The opposite o readfrom is the command

write ⟨string expression⟩ to ⟨le name⟩

This writes a line o text to the specied output le, opening the le rst i necessary. All such lesare closed automatically when the program terminates. They can also be closed explicitly by usingEOF as the ⟨string expression⟩. The only way to tell i a write command has succeeded is to closethe le and use readfrom to look at it.

13 Utility Routines

This section describes some o the utility routines included in the mplib directory o the developmentsource hierarchy. Future versions o this documentation may include more; meanwhile, please readthe source les, most have explanatory comments at the top. They are also included in the MetaPostand larger TEX distributions, typically in a texmf/metapost/base directory.

13.1 TEX.mp

TEX.mp provides a way to typeset the text o a MetaPost string expression. Suppose, or example,you need labels o the orm 0, 1, . . . , 10 across the axis. You can do this (relatively) conveniently

63

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 65/109

with TEX.mp, as ollows:

input TEX;

beginfig(100)

last := 10;

for i := 0 upto last:

label(TEX("$n_{" & decimal(i) & "}$"), (5mm*i,0));

endfor...

endfig;

In contrast, the basic btex command (see p. 22) typesets verbatim text. That is, btex s etex

typesets the literal character ‘s’; TEX(s) typesets the value o the MetaPost text variable .In version 0.9, TEX.mp acquired two additional routines to acilitate using LATEX to typeset labels:

TEXPRE and TEXPOST. Their values are remembered, and included beore and ater (respectively)each call to TEX. Otherwise, each TEX call is efectively typeset independently. TEX calls also do notinterere with uses o verbatimtex (p. 24).

Here’s the same example as above, using the LATEX commands \( and \):

input TEX;

TEXPRE("%&latex" & char(10) & "\documentclass{article}\begin{document}");TEXPOST("\end{document}");

beginfig(100)

last := 10;

for i := 0 upto last:

label(TEX("\( n_{" & decimal(i) & "} \)"), (5mm*i,0));

endfor

...

endfig;

Explanation:

• The %&latex causes LATEX to be invoked instead o TEX. (See below, also.) Web2C- andMiKTeX-based TEX implementations, at least, understand this %& specication; see, e.g., the

Web2C documentation or details, http://tug.org/web2c. (Inormation on how to do thesame with other systems would be most welcome.)

• The char(10) puts a newline (ASCII character code 10, decimal) in the output.

• The \documentclass... is the usual way to start a LATEX document.

• The TEXPOST("\end{document}") is not strictly necessary, due to the behavior o  mpto, butit is saer to include it.

Unortunately, TEX \special instructions vanish in this process. So it is not possible to usepackages such as xcolor and hyperref.

In case you’re curious, these routines are implemented very simply: they write btex commandsto a temporary le and then use scantokens (p. 15) to process it. The makempx mechanism (p. 24)

does all the work o running TEX.The %& magic on the rst line is not the only way to speciy invoking a diferent program than(plain) TEX. It has the advantage o maximum exibility: diferent TEX constructs can use diferentTEX processors. But at least two other methods are possible:

• Set the environment variable TEX to latex—or whatever processor you want to invoke. (Tohandle ConTEXt ragments, texexec could be used.) This might be convenient when writinga script, or working on a project that always requires latex.

64

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 66/109

• Invoke MetaPost with the command-line option -tex=latex (or whatever processor, o course).This might be useul rom a Makele, or just a one-of run.

14 Another Look at the MetaPost Workow

In Section 3 we already had a brie look at how MetaPost compiles input les and generates output

les. This section contains some more inormation and discusses internal variables that can be usedto control MetaPost’s run-time behavior, previewing PostScript output, debugging MetaPost code,and importing MetaPost graphics into third-party applications.

14.1 Customizing Run-Time Behavior

MetaPost knows and obeys a number o internal variables that have no direct impact on drawingcommands, but can be used to customize the way the MetaPost compiler processes input les. Theollowing paragraphs describe those variables (in no particular order).

Date and Time MetaPost provides a number o internal numeric variables that store the dateand time a job was started, i.e., the MetaPost executable was called on the command-line. Variablesyear, month, day, hour, and minute should be sel-explanatory. Variable time returns the number

o minutes past midnight, since the job was started, i.e., time = 60 * hour + minute.

Output File Names As discussed in Section 3, by deault, every beginfig . . . endfig group inan input le corresponds to an output le that ollows the naming scheme ⟨ jobname⟩.⟨n⟩. That is,all les have varying numeric le extensions. MetaPost provides a template mechanism that allowsor more exible output le names. The template mechanism uses printf-style escape sequencesthat are re-evaluated at ship-out time, i.e., beore each gure is written to disk.

To congure the output le naming scheme a string containing the corresponding escape se-quences has to be assigned to the internal string variable outputtemplate. The escape sequencesprovided are listed in table 4. As an example, i this code is saved in a le fig.mp,

outputtemplate := "%j-%c.mps";

beginfig(1);

drawdot origin;

endfig;

end

it will create the output le fig-1.mps instead o  fig.1. The le extension mps is conventionallychosen or MetaPost’s PostScript output (see Section 14.4). For SVG output one would want to usesvg instead.

Numeric variables reerred to in escape sequences, including %{...}, are always rounded to thenearest integer beore they are converted to a string expression. In such escape sequences, therecan be an optional number (0–99) ollowing % that determines the minimum number o digits in theresulting string expression, like %2m. The actual string length may exceed the requested length, i the decimal representation o the internal variable needs more digits. I it needs ewer digits, thestring is padded to the requested length with zeros rom let.

For backwards compatibility, the %c escape sequence is handled special. I the result o roundingthe charcode value is negative, %c evaluates to the string ps. This transormation can be bypassedby using %{charcode} instead o %c.

The template mechanism can also be used or naming graphic les individually, yet keeping allsources in one le. Collecting, e.g., diferent diagram sources in a single le fig.mp, it might beeasier to recall the correct diagram names in a TEX document than with numbered le names. Note,

65

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 67/109

Escape sequence Meaning Equivalent%% percent sign%{⟨internal variable⟩} evaluate internal variable%j current jobname %{jobname}

%c charcode value (beginfig argument) %{charcode}

%y current year %{year}

%m month (numeric) %{month}

%d day o the month %{day}

%H hour %{hour}

%M minute %{minute}

Table 4: Allowed escape sequences or outputtemplate

the argument to beginfig is not relevant as long as there’s no %c pattern in the le name templatestring.

outputtemplate := "fig-quality.mps";

beginfig(1);

...

endfig;

outputtemplate := "fig-cost-vs-productivity.mps";

beginfig(2);

...

endfig;

To ensure compatibility with older les, the deault value o  outputtemplate is %j.%c. I youassign an empty string, it will revert to that deault. MetaPost versions 1.000 to 1.102 used adiferent template mechanism, see Section B.2 or more inormation.

Output Format MetaPost can generate graphics in two output ormats: Encapsulated PostScript(EPSF) and, since version 1.200, Scalable Vector Graphics (SVG) ollowing version 1.1 o the SVGspecication [11]. By deault, MetaPost outputs PostScript les—hence the name MetaPost. The

output ormat can be changed to SVG by assigning the value "svg" to the internal string variableoutputformat:outputformat := "svg";

Any other value makes MetaPost all back to PostScript output. Variable outputformat is case-sensitive, so assigning it the string "SVG" enables PostScript output, too. Deault value o variableoutputformat is "eps".

PostScript Dictionary For PostScript output, MetaPost can dene a dictionary o abbreviationso the PostScript commands, e.g., l instead o  lineto, to reduce the size o output les. Settingthe internal variable mpprocset to 1 makes MetaPost create an extended preamble setting-up thedictionary. Deault value o variable mpprocset is 0, that is, no dictionary is used. For SVG output,variable mpprocset is not relevant.

Version Number The version number o the MetaPost compiler can be determined rom withina MetaPost program via the predened constant string mpversion (since version 0.9). For instancethe ollowing code

  message "mp = " & mpversion;

writes  mp = 1.212

66

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 68/109

to the console and the transcript le. Variable mpversion can be used to execute code dependingon the MetaPost version like this:

if unknown mpversion: string mpversion; mpversion := "0.000"; fi

if scantokens(mpversion) < 1.200:

errmessage "MetaPost v1.200 or later required (found v" & mpversion & ")";

else:

⟨code⟩fi

The rst line is optional and only added to handle ancient MetaPost versions graceully that don’teven know about variable mpversion (prior to v0.9). The second test does the actual work.

The version number is also written to output les and the transcript le. For PostScript outputthe version number can be ound in the Creator comment. SVG les contain a simple commentline near the beginning o the le. The transcript le starts with a banner line that identies theversion o the MetaPost compiler.

14.2 Previewing PostScript Output

Previewing MetaPost’s PostScript output is not dicult, but there are some catches that one shouldknow about. This section deals with the ollowing questions: How can graphics be clipped to their

true bounding box in the PostScript viewer application? Why are my text labels rendered withan ugly ont (or not at all) and how to avoid that? How can several graphics be combined into amulti-page document that can be previewed within one instance o the viewer application?

14.2.1 Bounding Box

With deault settings, MetaPost writes very much stripped-down PostScript code, containing onlythe bare graphics code, but no other ressources, like onts etc. The PostScript code is somewhatdecient, because it ails to correctly identiy as Encapsulated PostScript (EPSF) in the header.Note, Encapsulated PostScript les don’t have an associated page size, but provide bounding boxinormation, because they are meant or inclusion into other documents. Instead MetaPost outputwrongly pretends to be ull PostScript (PS), which it is not.

This is just ne or including MetaPost graphics in, say, TEX documents (see Section 14.4), but

some PostScript viewers have diculties rendering those PostScript les correctly. As an example,because o the wrong “PS” header, GSview—not knowing better—ignores bounding box inormationand then clips all contents to a (congurable) page size. Graphic elements laying outside those xedpage boundaries are thereore not visible, e.g., when they have negative coordinates.

To avoid such situations, the rst rule when previewing MetaPost’s PostScript output is to putthe line

prologues := 2;

beore the rst beginfig in MetaPost input les (see the discussion about prologues in Section 8.1).That way, MetaPost’s PostScript output correctly identies as Encapsulated PostScript and viewerapplications should always obey the le’s bounding box or on-screen rendering.

A workaround or MetaPost’s decient deault PostScript code that can sometimes be seen is tomove the lower let corner o a gure to the origin as a last operation by saying

currentpicture := currentpicture shifted -llcorner currentpicture;

beore endfig. But this doesn’t prevent rom clipping on the right and upper page boundaries.Additionally, the line is required or all gures, cluttering source code, and it alters all coordinatesin PostScript output, which might complicate debugging. Applying such a manual transormationis thereore not recommended (which is why the line is grayed out). Instead, users are advised toadjust prologues once in the preamble o the input le and enable clipping to the bounding box

67

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 69/109

in the PostScript viewer. For GSview, that can be done by activating Options → EPS Clip andoptionally Options → Show Bounding Box or verication.

14.2.2 Text Labels

Another popular previewing issue concerns graphics that contain text labels. An observation Meta-Post users can oten make is that text labels in graphics are rendered with wrong onts, wrong

glyphs, and sometimes even not at all. The reason is that with deault settings, again, MetaPost’sPostScript output is decient, in that it uses a simple, non-standard way to declare what ontsare used in a graphic. Setting variable prologues to 2, as shown in the previous section, makesMetaPost generate more complex PostScript code to declare all needed PostScript onts and embedthe necessary encoding inormation. I the PostScript viewer can provide the requested onts, thismight be sucient to get text labels rendered correctly. I you still observe wrong or missing glyphsyou should put the line

prologues := 3;

into the preamble o the input le. That way, MetaPost embeds the used PostScript onts into theoutput le so that they are always available (see the discussion about prologues in Section 8.1).Note, this might enlarge the size o output les considerably. Additionally, onts might be embeddedmultiple times when several graphics using the same onts are included into a document. For that

reason, it is recommended to reset variable prologues to 0 beore nally including MetaPost graphicsinto external documents.

14.2.3 Proo Sheets

I you have lots o gures in a source le and need to preview many o them at the same time,opening every graphic in a new instance o the viewer application and switching between them backand orth can get cumbersom. An alternative is to collect all graphics generated rom a MetaPostinput le in a proo sheet, a multi-page document, that can be previewed and navigated in a singleinstance o the viewer application. The MetaPost distribution contains two (plain) TEX scripts,

 mproof.tex and mpsproof.tex, that help with the latter approach.

mproof.tex To write a proo sheet or MetaPost output, call mproof.tex as

tex mproof ⟨MetaPost output les⟩

Then process the resulting .dvi le as usual. That way, there’s no need to care about diferentsettings o variable prologues, since in proo sheets MetaPost graphics are already embedded.

Note, the parameters ater mproof are an explicit list o MetaPost output les, possibly generatedrom diferent input les. On shells that support POSIX shell patterns, these can be used to avoidtyping a long list o les. As an example, or a le fig.mp containing three gures with charcodes1, 2, and 3, the proo sheet can be generated by calling

tex mproof fig.?

The pattern fig.? is automatically expanded to fig.1 fig.2 fig.3 by the shell (but not neces-sarily in numerically increasing order) beore T

EX is run. I there were an output le fig.10, using

patterns fig.?? or fig.* to cover two-digit indices would ail, since those covered the source lefig.mp as well. To avoid that, output le names have to be made more signicant, e.g., by settingvariable outputtemplate to %j-%c.mps (see Section 14.1). The proo sheet can then be generatedwith

tex mproof *.mps

68

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 70/109

mpsproof.tex An alternative to mproof.tex is the script mpsproof.tex, which is similar, butmore powerul. While the ormer script only runs with TEX and requires a DVI output driver togenerate PostScript les, mpsproof.tex can as well be run through pdTEX to directly generatePDF les. Additionally, it provides some command-line options.

With the \noheaders option, le names, date stamps, and page numbers are omitted rom theproo sheet. Use it like

tex mpsproof \noheaders ⟨MetaPost output les⟩The \bbox option can be used to generate an output le that has exactly the same page size as

a gure’s bounding box (\bbox is actually an alias or the longer \encapsulate). With this optiononly one gure can be processed at a time, e.g.,

pdftex mpsproof \bbox fig.1

Alternatives Other alternatives or previewing MetaPost gures, which are not part o the Meta-Post distribution, are the mptopd bundle or the Perl script mpstoeps.pl. There is also an onlinecompiler and viewer or MetaPost code at http://tlhiv.org/mppreview/.

14.3 DebuggingMetaPost inherits rom METAFONT numerous acilities or interactive debugging, most o which canonly be mentioned briey here. Further inormation on error messages, debugging, and generatingtracing inormation can be ound in The METAFONT  book  [5].

Suppose your input le saysdraw z1--z2;

on line 17 without rst giving known values to z1 and z2. Figure 51 shows what the MetaPostinterpreter prints on your terminal when it nds the error. The actual error message is the linebeginning with “!”; the next six lines give the context that shows exactly what input was beingread when the error was ound; and the “?” on last line is a prompt or your response. Since theerror message talks about an undened coordinate, this value is printed on the rst line ater the“>>”. In this case the coordinate o  z1 is just the unknown variable x1, so the interpreter prints

the variable name x1 just as it would i it were told to “show x1” at this point.

>> x1

! Undefined x coordinate has been replaced by 0.

<to be read again>

{

--->{

curl1}..{curl1}

l.17 draw z1--

z2;

?

Figure 51: An example o an error message.

The context listing may seem a little conusing at rst, but it really just gives a ew lines o textshowing how much o each line has been read so ar. Each line o input is printed on two lines likethis:

⟨descriptor⟩ Text read so ar

Text yet to be read

69

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 71/109

The ⟨descriptor⟩ identies the input source. It is either a line number like “l.17” or line 17 o the current le; or it can be a macro name ollowed by “->”; or it is a descriptive phrase in anglebrackets. Thus, the meaning o the context listing in Figure 51 is that the interpreter has just readline 17 o the input le up to “--,” the expansion o the -- macro has just started, and the initial“{” has been reinserted to allow or user input beore scanning this token.

Among the possible responses to a ? prompt are the ollowing:

x terminates the run so that you can x your input le and start over.

h prints a help message ollowed by another ? prompt.

⟨return⟩ causes the interpreter to proceed as best it can.

? prints a listing o the options available, ollowed by another ? prompt.

This interactive mode is not only entered when MetaPost nds an error in the code. It can beexplicitly entered by the errmessage command. The message command writes a string argumentto a new line on the terminal. The errmessage command is similar, but the string argument ispreceded by "! " and ollowed by ".". Additionally, some lines o context are appended as inMetaPost’s normal error messages. I the user now types “h”, the most recent errhelp string willbe shown (unless it was empty).

⟨message command⟩ → errhelp⟨string expression⟩| errmessage⟨string expression⟩| message⟨string expression⟩

Figure 52: The syntax or message commands

Error messages and responses to show commands are also written into the transcript le whosename is obtained rom the name o the main input le by changing “.mp” to “.log”. When theinternal variable tracingonline is at its deault value o zero, some show commands print theirresults in ull detail only in the transcript le.

Only one type o show command has been discussed so ar: show ollowed by a comma-separatedlist o expressions prints symbolic representations o the expressions.

The showtoken command can be used to show the parameters and replacement text o a macro.It takes a comma-separated list o tokens and identies each one. I the token is a primitive as in“showtoken +” it is just identied as being itsel:

> +=+

Applying showtoken to a variable or a vardef macro yields

> ⟨token⟩=variable

To get more inormation about a variable, use showvariable instead o  showtoken. The argu-ment to showvariable is a comma-separated list o symbolic tokens and the result is a descriptiono all the variables whose names begin with one o the listed tokens. This even works or vardef

macros. For example, showvariable z yieldsz@#=macro:->begingroup(x(SUFFIX2),y(SUFFIX2))endgroup

There is also a showdependencies command that takes no arguments and prints a list o alldependent  variables and how the linear equations given so ar make them depend on other variables.Thus ater

z2-z1=(5,10); z1+z2=(a,b);

70

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 72/109

x2=0.5a+2.5

y2=0.5b+5

x1=0.5a-2.5

y1=0.5b-5

Figure 53: The result o z2-z1=(5,10); z1+z2=(a,b); showdependencies;

showdependencies prints what is shown in Figure 53. This could be useul in answering a questionlike “What does it mean ‘! Undefined x coordinate?’ I thought the equations given so ar woulddetermine x1.”

When all else ails, the predened macro tracingall causes the interpreter to print a detailedlisting o everything it is doing. Since the tracing inormation is oten quite voluminous, it may bebetter to use the loggingall macro that produces the same inormation but only writes it in thetranscript le. There is also a tracingnone macro that turns of all the tracing output.

Tracing output is controlled by the set o internal variables summarized below. When any oneo these variables is given a positive value, the corresponding orm o tracing is turned on. Here isthe set o tracing variables and what happens when each o them is positive:

tracingcapsules shows the values o temporary quantities (capsules) when they become known.

tracingchoices shows the Bézier control points o each new path when they are chosen.

tracingcommands shows the commands beore they are perormed. A setting > 1 also shows if

tests and loops beore they are expanded; a setting > 2 shows algebraic operations beorethey are perormed.

tracingequations shows each variable when it becomes known.

tracinglostchars warns about characters omitted rom a picture because they are not in the ontbeing used to typeset labels.

tracingmacros shows macros beore they are expanded.

tracingoutput shows pictures as they are being shipped out as PostScript les.

tracingrestores shows symbols and internal variables as they are being restored at the end o agroup.

tracingspecs shows the outlines generated when drawing with a polygonal pen.

tracingstats shows in the transcript le at the end o the job how many o the MetaPost inter-preter’s limited resources were used.

14.4 Importing MetaPost Graphics into External Applications

MetaPost is very well suited or creating graphics that are to be included into third-party appli-cations, such as text documents, presentations or web pages, because MetaPost outputs graphicsin vector ormats, which can be scaled without quality degradation. However, practice shows, that

vector graphics, too, are best created with a rough target size already in mind. Scaling a vectorgraphic calls or non-proportional scaling o certain technical parameters, such as line width, arrowsize or onts. Otherwise, with growing scale actors scalable graphics tend to change their visualcharacter. Additionally, during import into a main document, they’ll likely ail to match, e.g., strokewidth o the document. To circumvent this, it is advisable to apply only small post-processing scaleactors to vector graphics. The ollowing sections briey discuss how to import MetaPost graphicsinto documents with selected applications.

71

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 73/109

fig.mp

MetaPost 

fig.1

doc.tex

T E X 

doc.dvi

dvips

doc.ps

boundingbox

Figure 54: A diagram o the processing or a TEX document embedding MetaPost gures

14.4.1 TEX and Friends

MetaPost graphics in the PostScript ormat can be easily integrated into documents prepared withTEX and riends. MetaPost’s PostScript output is a low-eatured dialect o the Postscript language,called puried EPS , which can be converted into the Portable Document Format (PDF) languageon-the-y. For that reason, external MetaPost graphics can be used on both routes: a) using thetraditional TEX engine together with an external PostScript output driver and b) using newer TEX

engines, like pdTEX or its successor LuaTEX, which contain a built-in PDF output driver. LuaTEXcan additionally process embedded MetaPost code natively, alling back to the built-in mplib library.Figure 54 shows the process o including an external MetaPost graphic into a TEX document

using the PostScript route. In the TEX source a “magic macro” provided by the ormat or anexternal package is used or including a graphic le. During the typesetting stage, the macro onlyreads bounding box inormation of the PostScript le and reserves the required space on the pagevia an empty box. The le reerence is passed-on to the output driver and only then, nally, the leis embedded into the document. The reely available program dvips is used as an output driver inthis example.11 The next paragraphs give more detailed inormation on some popular combinationso TEX ormats and engines.

Plain TEX Format For users o the Plain TEX ormat and the traditional TEX engine with DeviceIndependend output (DVI) the epsf package provides the “magic macro”

\epsfbox{⟨lename⟩}

or embedding graphics, e.g., \epsfbox{fig.1}.Users o the pdTEX engine should reer to the standalone macros o the mptopd bundle, which

can be ound at http://context.aanhet.net/mptopdf.htm.

11The C source or dvips comes with the web2c TEX distribution. Similar programs are available rom other sources.

72

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 74/109

With the LuaTEX engine, embedding external graphics works the same as with pdTEX. Ad-ditionally, LuaTEX users can inline MetaPost code directly into Plain TEX documents. LuaTEXis able to process such MetaPost code snippets, alling back to the built-in mplib library. Note,mplib doesn’t support verbatimtex/btex . . . etex constructs, currently. Here is an example o aMetaPost graphic inlined into a Plain TEX document. For more inormation, please reer to theLuaTEX [9, chap. 4.8] and luamplib [3] documentation.

\input luamplib.sty\mplibcode

beginfig(1);

...

endfig;

\endmplibcode

\bye

LATEX Format For users o the LATEX ormat and the traditional TEX engine with Device Inde-pendent output (DVI) the well-known graphics (or graphicx) package aids in external graphicsinclusion. The package supports diferent engines, guessing the correct output driver automatically,and can handle several graphic ormats. The “magic macro” is

\includegraphics{⟨lename⟩}

In DVI output driver mode the graphics package assumes all les with an unknown le extension,such as .1 etc., to be in the EPS ormat. It thereore handles MetaPost les with a numeric deaultle extension correctly (see [10] or more inormation).

When using the pdTEX engine with a built-in PDF output driver, the situation is a bit di-erent. Only les with le extension .mps are recognized as puried EPS and can be converted toPDF on-the-y. The recommended procedure or embedding MetaPost graphics into LATEX doc-uments compiled with pdTEX is thereore to change MetaPost’s output le name extension viaoutputtemplate (see p. 65). In the LATEX document include the graphic les with ull name, e.g.,

\includegraphics{fig-1.mps}

Note, the latter approach works with the dvips driver, too. Even though, again, this time .mps

is an unknown le extension, triggering EPS le handling in a all-back procedure. This propertyo the graphics package, which comes in handy or MetaPost les, is the reason many MetaPostsource les start with the line

outputtemplate := "%j-%c.mps";

With the LuaTEX engine, embedding external graphics works the same as with pdTEX. Addi-tionally, LuaTEX users can inline MetaPost code directly into LaTEX documents. LuaTEX is ableto process such MetaPost code snippets, alling back to the built-in mplib library. Note, mplibdoesn’t support verbatimtex/btex . . . etex constructs, currently. Here is an example o a Meta-Post graphic inlined into a LATEX document. For more inormation, please reer to the LuaTEX [9,chap. 4.8] and luamplib [3] documentation.

\documentclass{article}

\usepackage{luamplib}

\begin{document}\begin{mplibcode}

beginfig(1);

...

endfig;

\end{mplibcode}

\end{document}

73

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 75/109

ConTEXt Format In ConTEXt graphics support is integrated in the kernel, covering advancedeatures like shading, transparency, color spaces or image inclusion. The “magic macro” or embed-ding external graphics is

\externalfigure[⟨lename⟩]

The macro can handle numbered les as well as les with the mps sux.Alternatively, ConTEXt users can inline MetaPost code in the document source, which allows

or more natural interacing with document properties, ont support, and automatic processing [2].Here is an example o a MetaPost graphic inlined into a ConTEXt document.

\starttext

\startuseMPgraphic{⟨name⟩}

...

\stopuseMPgraphic

\useMPgraphic{⟨name⟩}

\stoptext

ConTEXt MkIV, being based on the LuaTEX engine, provides a much tighter integration o MetaPost than older versions, since it can all-back to the built-in mplib library.

14.4.2 Trof It is also possible to include MetaPost output in a GNU trof document. The procedure is similar toFigure 54: the grops output processor includes PostScript les when they are requested via trof’s\X command. The -mpspic macro package provides a command .PSPIC, which does just that whenincluding an encapsulated PostScript le in the source code. For instance, the trof command

.PSPIC fig.1

includes fig.1, using the natural height and width o the image as given in the le’s bounding box.

14.4.3 Web Applications

An SVG le fig.svg can be easily embedded into HTML documents with the ollowing code snippet:

<p>

<object data="fig.svg" type="image/svg+xml" width="300" height="200">

</object>

</p>

SVG les can also be imported by various interactive graphics editing programs, or exampleGIMP or Inkscape. See Section 8.1 or inormation on ont handling in SVG graphics.

Acknowledgement

I would like to thank Don Knuth or making this work possible by developing METAFONT andplacing it in the public domain. I am also indebted to him or helpul suggestions, particularly with

regard to the treatment o included TEX material.

74

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 76/109

A Reerence Manual

A.1 The MetaPost Language

Tables 5–11 summarize the built-in eatures o Plain MetaPost. Features rom the Plain macropackage are marked by † symbols. The distinction between primitives and plain macros can beignored by the casual user.

The tables in this appendix give the name o each eature, the page number where it is explained,and a short description. A ew eatures are not explained elsewhere and have no page numberlisted. These eatures exist primarily or compatibility with METAFONT and are intended to besel-explanatory. Certain other eatures rom METAFONT are omitted entirely because they are o limited interest to the MetaPost users and/or would require long explanations. All o these aredocumented in The METAFONT  book  [5] as explained in Appendix B.1.

Tables 5 and 6 list internal variables that take on numeric and string values. Table 7 listspredened variables o other types. Table 8 lists predened constants. Some o these are implementedas variables whose values are intended to be let unchanged.

Table 9 summarizes MetaPost operators and lists the possible argument and result types or eachone. A “–” entry or the let argument indicates a unary operator; “–” entries or both argumentsindicate a nullary operator. Operators that take sux parameters are not listed in this table becausethey are treated as “unction-like macros”.

The last two tables are Table 10 or commands and Table 11 macros that behave like unctionsor procedures. Such macros take parenthesized argument lists and/or sux parameters, returningeither a value whose type is listed in the table, or nothing. The latter case is or macros that behavelike procedures. Their return values are listed as “–”.

The gures in this appendix present the syntax o the MetaPost language starting with expres-sions in Figures 55–57. Although the productions sometimes speciy types or expressions, primaries,secondaries, and tertiaries, no attempt is made to give separate syntaxes or ⟨numeric expression⟩,⟨pair expression⟩, etc. The simplicity o the productions in Figure 58 is due to this lack o typeinormation. Type inormation can be ound in Tables 5–11.

Figures 59, 60 and 61 give the syntax or MetaPost programs, including statements and com-mands. They do not mention loops and if tests because these constructions do not behave likestatements. The syntax given in Figures 55–62 applies to the result o expanding all conditionalsand loops. Conditionals and loops do have a syntax, but they deal with almost arbitrary sequenceso tokens. Figure 62 species conditionals in terms o ⟨balanced tokens⟩ and loops in terms o ⟨looptext⟩, where ⟨balanced tokens⟩ is any sequence o tokens balanced with respect to if and fi, and⟨loop text⟩ is a sequence o tokens balanced with respect to for, forsuffixes, forever, and endfor.

75

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 77/109

Table 5: Internal variables with numeric values

Name Page Explanation†ahangle 42 Angle or arrowheads in degrees (deault: 45)†ahlength 42 Size o arrowheads (deault: 4bp)†bboxmargin 27 Extra space allowed by bbox (deault 2bp)charcode 45 The number o the current gureday 65 The current day o the monthdefaultcolormodel 28 The initial color model (deault: 5, rgb)†defaultpen 43 Numeric index used by pickup to select deault pen†defaultscale 22 Font scale actor or label strings (deault 1)†dotlabeldiam 21 Diameter o the dot drawn by dotlabel (deault 3bp)hour 65 The hour o the day this job started†labeloffset 21 Ofset distance or labels (deault 3bp)

linecap 40 0 or butt, 1 or round, 2 or squarelinejoin 40 0 or mitered, 1 or round, 2 or beveled

 minute 65 The minute o the hour this job started miterlimit 40 Controls miter length as in PostScript month 65 The current month (e.g, 3 ≡ March) mpprocset 66 Create a PostScript dictionary o command abbreviationspausing – > 0 to display lines on the terminal beore they are readprologues 24 > 0 to output conorming PostScript using built-in ontsrestoreclipcolor – Restore the graphics state ater clip operations (deault: 1)showstopping – > 0 to stop ater each show commandtime 65 The number o minutes past midnight when this job startedtracingcapsules 71 > 0 to show capsules too

tracingchoices 71 > 0 to show the control points chosen or pathstracingcommands 71 > 0 to show commands and operations as they are perormedtracingequations 71 > 0 to show each variable when it becomes knowntracinglostchars 71 > 0 to show characters that aren’t infont

tracingmacros 71 > 0 to show macros beore they are expandedtracingonline 14 > 0 to show long diagnostics on the terminaltracingoutput 71 > 0 to show digitized edges as they are outputtracingrestores 71 > 0 to show when a variable or internal is restoredtracingspecs 71 > 0 to show path subdivision when using a polygonal a pentracingstats 71 > 0 to show memory usage at end o jobtracingtitles – > 0 to show titles online when they appeartroffmode 24 Set to 1 i a -troff or -T option was giventruecorners 27 > 0 to make llcorner etc. ignore setbounds

warningcheck 14 Controls error message when variable value is largeyear 65 The current year (e.g., 1992)

76

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 78/109

Table 6: Internal string variables

Name Page Explanation

jobname – The name o this joboutputformat 66 Output backend to be used (deault: “eps”)outputtemplate 65 Output lename template (deault: “%j.%c”)

Table 7: Other Predened Variables

Name Type Page Explanation

†background color 29 Color or unfill and undraw (usually white)†currentpen pen 45 Last pen picked up (or use by the draw command)†currentpicture picture 44 Accumulate results o draw and fill commands†cuttings path 33 Subpath cut of by last cutbefore or cutafter

†defaultfont string 22 Font used by label commands or typesetting strings†extra_beginfig string 100 Commands or beginfig to scan†extra_endfig string 100 Commands or endfig to scan

77

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 79/109

Table 8: Predened Constants

Name Type Page Explanation

†beveled numeric 40 linejoin value or beveled joins [2]†black color 14 Equivalent to (0,0,0)

†blue color 14 Equivalent to (0,0,1)

†bp numeric 2 One PostScript point in bp units [1]†butt numeric 40 linecap value or butt end caps [0]†cc numeric – One cicero in bp units [12.79213]†cm numeric 2 One centimeter in bp units [28.34645]†dd numeric – One didot point in bp units [1.06601]†ditto string – The " character as a string o length 1†down pair 8 Downward direction vector (0, −1)†epsilon numeric – Smallest positive MetaPost number [ 1

65536]

†evenly picture 37 Dash pattern or equal length dashes†EOF string 63 Single null character

false boolean 15 The boolean value alse†fullcircle path 29 Circle o diameter 1 centered on (0, 0)†green color 14 Equivalent to (0,1,0)

†halfcircle path 29 Upper hal o a circle o diameter 1†identity transorm 36 Identity transormation†in numeric 2 One inch in bp units [72]†infinity numeric 32 Large positive value [4095.99998]†left pair 8 Letward direction (−1, 0)† mitered numeric 40 linejoin value or mitered joins [0]† mm numeric 2 One millimeter in bp units [2.83464]

 mpversion string 66 MetaPost version numbernullpen pen 48 Empty pen

nullpicture picture 16 Empty picture†origin pair – The pair (0, 0)†pc numeric – One pica in bp units [11.95517]pencircle pen 43 Circular pen o diameter 1†pensquare pen 44 Square pen o height 1 and width 1†pt numeric 2 One printer’s point in bp units [0.99626]†quartercircle path – First quadrant o a circle o diameter 1†red color 14 Equivalent to (1,0,0)

†right pair 8 Rightward direction (1, 0)†rounded numeric 40 linecap and linejoin value or round joins

and end caps [1]†squared numeric 40 linecap value or square end caps [2]true boolean 15 The boolean value true

†unitsquare path – The path (0,0)--(1,0)--(1,1)--(0,1)--cycle

†up pair 8 Upward direction (0, 1)†white color 14 Equivalent to (1,1,1)

†withdots picture 37 Dash pattern that produces dotted lines

78

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 80/109

Table 9: Operators

Name Argument/result types Page ExplanationLet Right Result

& stringpath

stringpath

stringpath

16 Concatenation—works orpaths & i  starts

exactly where the ends* numeric (cmyk)colornumericpair

(cmyk)colornumericpair

15 Multiplication

* (cmyk)colornumericpair

numeric (cmyk)colornumericpair

15 Multiplication

** numeric numeric numeric 15 Exponentiation+ (cmyk)color

numericpair

(cmyk)colornumericpair

(cmyk)colornumericpair

16 Addition

++ numeric numeric numeric 16 Pythagorean addition√ 2 + 2

+-+ numeric numeric numeric 16 Pythagorean subtraction√ 2 − 2

- (cmyk)colornumericpair

(cmyk)colornumericpair

(cmyk)colornumericpair

16 Subtraction

- – (cmyk)colornumericpair

(cmyk)colornumericpair

16 Negation

/ (cmyk)colornumericpair

numeric (cmyk)colornumericpair

15 Division

< = >

<= >=

<>

stringnumericpair(cmyk)colortransorm

stringnumericpair(cmyk)colortransorm

boolean 15 Comparison operators

†abs – numericpair

numeric 17 Absolute valueEuclidean length√ 

(xpart )2 + (ypart )2

and boolean boolean boolean 15 Logical andangle – pair numeric 18 2−argument arctangent

(in degrees)arclength – path numeric 35 Arc length o a patharctime of numeric path numeric 35 Time on a path where arc

length rom the start

reaches a given valueASCII – string numeric – ASCII value o rstcharacter in string

†bbox – picturepathpen

path 27 A rectangular path or thebounding box

79

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 81/109

Table 9: Operators (continued)

Name Argument/result types Page ExplanationLet Right Result

blackpart – cmykcolor numeric 18 Extract the ourthcomponent

bluepart – color numeric 18 Extract the thirdcomponentboolean – any boolean 18 Is the expression o type

boolean?†bot – numeric

pairnumericpair

43 Bottom o current penwhen centered at the givencoordinate(s)

bounded – any boolean 47 Is argument a picture witha bounding box?

†ceiling – numeric numeric 18 Least integer greater thanor equal to

†center – picturepath

pen

pair 27 Center o the boundingbox

char – numeric string 26 Character with a givenASCII code

clipped – any boolean 47 Is argument a clippedpicture?

cmykcolor – any boolean 18 Is the expression o typecmykcolor?

color – any boolean 18 Is the expression o typecolor?

colormodel – imageobject

numeric 47 What is the color model o the image object?

†colorpart – imageobject

(cmyk)colornumericboolean

47 What is the color o theimage object?

cosd – numeric numeric 18 Cosine o angle in degrees†cutafter path path path 33 Let argument with part

ater the intersectiondropped

†cutbefore path path path 33 Let argument with partbeore the intersectiondropped

cyanpart – cmykcolor numeric 18 Extract the rstcomponent

cycle – path boolean 18 Determines whether apath is cyclic

dashpart – picture picture 47 Dash pattern o a path ina stroked picturedecimal – numeric string 18 The decimal

representation†dir – numeric pair 8 (cos , sin ) given in

degrees

80

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 82/109

Table 9: Operators (continued)

Name Argument/result types Page ExplanationLet Right Result

†direction

of

numeric path pair 33 The direction o a path ata given ‘time’

†direction-point of pair path numeric 35 Point where a path has agiven directiondirection-

time of

pair path numeric 35 ‘Time’ when a path has agiven direction

†div numeric numeric numeric – Integer division ⌊/⌋†dotprod pair pair numeric 16 Vector dot productfilled – any boolean 47 Is argument a lled

outline?floor – numeric numeric 18 Greatest integer less than

or equal tofontpart – picture string 47 Font o a textual picture

componentfontsize – string numeric 22 The point size o a ont

glyph of numericstring

string picture 48 Convert a glyph o a ontto contours

greenpart – color numeric 18 Extract the secondcomponent

greypart – numeric numeric 18 Extract the rst (only)component

hex – string numeric – Interpret as a hexadecimalnumber

infont string string picture 26 Typeset string in givenont

†intersec-

tionpointpath path pair 30 An intersection point

intersec-

tiontimes

path path pair 32 Times (,

) on paths

and when the pathsintersect

†inverse – transorm transorm 36 Invert a transormationknown – any boolean 18 Does argument have a

known value?length – path

stringpicture

numeric 331647

Number o components(arcs, characters, strokes,. . . ) in the argument

†lft – numericpair

numericpair

43 Let side o current penwhen its center is at thegiven coordinate(s)

llcorner – picture

pathpen

pair 27 Lower-let corner o 

bounding box

lrcorner – picturepathpen

pair 27 Lower-right corner o bounding box

 magentapart – cmykcolor numeric 18 Extract the secondcomponent

81

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 83/109

Table 9: Operators (continued)

Name Argument/result types Page ExplanationLet Right Result

 makepath – pen path 44 Cyclic path bounding thepen shape

 makepen – path pen 44 A polygonal pen maderom the convex hull o thepath knots

 mexp – numeric numeric – The unction exp(/256) mlog – numeric numeric – The unction 256 ln()† mod – numeric numeric – The remainder unction

− ⌊/⌋normal-

deviate– – numeric – Choose a random number

with mean 0 and standarddeviation 1

not – boolean boolean 15 Logical negationnumeric – any boolean 18 Is the expression o type

numeric?

oct – string numeric – Interpret string as octalnumber

odd – numeric boolean – Is the closest integer oddor even?

or boolean boolean boolean 15 Logical inclusive orpair – any boolean 18 Is the expression o type

pair?path – any boolean 18 Is the expression o type

path?pathpart – picture path 47 Path o a stroked picture

componentpen – any boolean 18 Is the expression o type

pen?penoffset

of

pair pen pair – Point on the pen urthestto the right o the givendirection

penpart – picture pen 47 Pen o a stroked picturecomponent

picture – any boolean 18 Is the expression o typepicture?

point of numeric path pair 32 Point on a path given atime value

postcontrol

ofnumeric path pair 33 First Bézier control point

on path segment startingat the given time

precontrolof

numeric path pair 33 Last Bézier control pointon path segment ending atthe given time

readfrom – string string 63 Read a line rom leredpart – color numeric 18 Extract the rst

component

82

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 84/109

Table 9: Operators (continued)

Name Argument/result types Page ExplanationLet Right Result

reverse – path path 42 ‘time’-reversed path,beginning swapped with

endingrgbcolor – any boolean 18 Is the expression o typecolor?

rotated picturepathpairpentransorm

numeric picturepathpairpentransorm

35 Rotate counterclockwise agiven number o degrees

†round – numericpair

numericpair

18 Round each component tothe nearest integer

†rt – numericpair

numericpair

43 Right side o current penwhen centered at givencoordinate(s)

scaled picturepathpairpentransorm

numeric picturepathpairpentransorm

35 Scale all coordinates bythe given amount

scantokens – string tokensequence

15 Converts a string to atoken or token sequence.Provides string to numericconversion, etc.

shifted picturepathpairpen

transorm

pair picturepathpairpen

transorm

35 Add the given shitamount to each pair o coordinates

sind – numeric numeric 18 Sine o an angle in degreesslanted picture

pathpairpentransorm

numeric picturepathpairpentransorm

35 Apply the slantingtransormation that maps(, ) into ( + ,),where is the numericargument

sqrt – numeric numeric 17 Square rootstr – sux string 59 String representation or a

suxstring – any boolean 18 Is the expression o type

string?

stroked – any boolean 47 Is argument a stroked line?subpath of pair path path 33 Portion o a path or givenrange o time values

substring

of

pair string string 16 Substring bounded bygiven indices

textpart – picture string 47 Text o a textual picturecomponent

83

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 85/109

Table 9: Operators (continued)

Name Argument/result types Page ExplanationLet Right Result

textual – any boolean 47 Is argument typeset text?†top – numeric

pair

numeric

pair

43 Top o current pen when

centered at the givencoordinate(s)transform – any boolean 18 Is the argument o type

transorm?transformed picture

pathpairpentransorm

transorm picturepathpairpentransorm

36 Apply the given transormto all coordinates

ulcorner – picturepathpen

pair 27 Upper-let corner o bounding box

uniform-

deviate

– numeric numeric – Random number between

zero and the value o theargument

†unitvector – pair pair 18 Rescale a vector so itslength is 1

unknown – any boolean 18 Is the value unknown?urcorner – picture

pathpen

pair 27 Upper-right corner o bounding box

†whatever – – numeric 12 Create a new anonymousunknown

xpart – pairtransorm

number 18 or component

xscaled picturepathpairpentransorm

numeric picturepathpairpentransorm

35 Scale all coordinates bythe given amount

xxpart – transorm number 37 entry intransormation matrix

xypart – transorm number 37 entry intransormation matrix

yellowpart – cmykcolor numeric 18 Extract the thirdcomponent

ypart – pairtransorm

number 18 or component

yscaled picturepathpairpentransorm

numeric picturepathpairpentransorm

35 Scale all coordinates bythe given amount

yxpart – transorm number 37 entry intransormation matrix

84

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 86/109

Table 9: Operators (continued)

Name Argument/result types Page ExplanationLet Right Result

yypart – transorm number 37 entry in transormationmatrix

zscaled picturepathpairpentransorm

pair picturepathpairpentransorm

35 Rotate and scale allcoordinates so that (1, 0)is mapped into the givenpair; i.e., do complexmultiplication.

85

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 87/109

Table 10: Commands

Name Page Explanation

addto 45 Low-level command or drawing and lling

clip 45 Applies a clipping path to a pictureclosefrom 63 Close a le opened by readfrom

†cutdraw 61 Draw with butt end capsdashed 37 Apply dash pattern to drawing command†draw 5 Draw a line or a picture†drawarrow 40 Draw a line with an arrowhead at the end†drawdblarrow 42 Draw a line with arrowheads at both endserrhelp 70 Declare help message or interactive modeerrmessage 70 Show error message on the terminal and enter interactive modefilenametemplate 100 Set output le name pattern (deprecated, see outputtemplate)†fill 28 Fill inside a cyclic path†filldraw 42 Draw a cyclic path and ll inside it

fontmapfile 26 Read ont map entries rom lefontmapline 26 Declare a ont map entryinterim 52 Make a local change to an internal variablelet – Assign one symbolic token the meaning o another†loggingall 71 Turn on all tracing (log le only)

 message 70 Show message string on the terminalnewinternal 20 Declare new internal variables†pickup 15 Speciy new pen or line drawingsave 52 Make variables localsetbounds 27 Make a picture lie about its bounding boxshipout 45 Low-level command to output a gureshow 14 Print out expressions symbolicallyshowdependencies 70 Print out all unsolved equationsshowtoken 70 Print an explanation o what a token isshowvariable 70 Print variables symbolicallyspecial 100 Print a string directly in the PostScript output le†tracingall 71 Turn on all tracing†tracingnone 71 Turn of all tracing†undraw 42 Erase a line or a picture†unfill 29 Erase inside a cyclic path†unfilldraw 42 Erase a cyclic path and its insidewithcmykcolor 28 Apply CMYK color to drawing commandwithcolor 28 Apply generic color specication to drawing commandwithgreyscale 28 Apply greyscale color to drawing commandwithoutcolor 28 Don’t apply any color specication to drawing command

withpen 43 Apply pen to drawing operationwithpostscript 40 End raw PostScript codewithprescript 40 Begin raw PostScript codewithrgbcolor 28 Apply RGB color to drawing commandwrite to 63 Write string to le

86

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 88/109

Table 11: Function-Like Macros

Name Arguments Result Page Explanation

†buildcycle list o paths path 30 Build a cyclic path†dashpattern on/of distances picture 39 Create a pattern or dashed lines

†decr numeric variable numeric 61 Decrement and return new value†dotlabel sux, picture, pair – 21 Mark point and draw picture nearby†dotlabel sux, string, pair – 21 Mark point and place text nearby†dotlabels sux, point numbers – 22 Mark z points with their numbers†drawdot pair – 2 Draw a dot at the given point†drawoptions drawing options – 42 Set options or drawing commands†image string picture 46 Return picture rom text†incr numeric variable numeric 61 Increment and return new value†label sux, picture, pair – 21 Draw picture near given point†label sux, string, pair – 21 Place text near given point†labels sux, point numbers – 22 Draw z point numbers; no dots† max list o numerics numeric – Find the maximum

† max list o strings string – Find the lexicographically last string† min list o numerics numeric – Find the minimum† min list o strings string – Find the lexicographically rst string†thelabel sux, picture, pair picture 21 Picture shited as i to label a point†thelabel sux, string, pair picture 21 Text positioned as i to label a point†z sux pair 19 The pair x⟨sux⟩, y⟨sux⟩)

87

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 89/109

⟨atom⟩ → ⟨variable⟩ | ⟨argument⟩| ⟨number or raction⟩| ⟨internal variable⟩| (⟨expression⟩)

| begingroup⟨statement list⟩⟨expression⟩endgroup

| ⟨nullary op⟩

|btex

⟨typesetting commands

⟩etex

| ⟨pseudo unction⟩⟨primary⟩ → ⟨atom⟩

| (⟨numeric expression⟩,⟨numeric expression⟩)

| (⟨numeric expression⟩,⟨numeric expression⟩,⟨numeric expression⟩)

| ⟨o operator⟩⟨expression⟩of⟨primary⟩| ⟨unary op⟩⟨primary⟩| str⟨sux⟩| z⟨sux⟩| ⟨numeric atom⟩[⟨expression⟩,⟨expression⟩]

| ⟨scalar multiplication op⟩⟨primary⟩⟨secondary⟩ → ⟨primary⟩

| ⟨secondary⟩⟨primary binop⟩⟨primary⟩

| ⟨secondary⟩⟨transormer⟩⟨tertiary⟩ → ⟨secondary⟩| ⟨tertiary⟩⟨secondary binop⟩⟨secondary⟩

⟨subexpression⟩ → ⟨tertiary⟩| ⟨path expression⟩⟨path join⟩⟨path knot⟩

⟨expression⟩ → ⟨subexpression⟩| ⟨expression⟩⟨tertiary binop⟩⟨tertiary⟩| ⟨path subexpression⟩⟨direction specier⟩| ⟨path subexpression⟩⟨path join⟩cycle

⟨path knot⟩ → ⟨tertiary⟩⟨path join⟩ → --

| ⟨direction specier⟩⟨basic path join⟩⟨direction specier⟩⟨direction specier⟩ → ⟨empty⟩| {curl⟨numeric expression⟩}

| {⟨pair expression⟩}

| {⟨numeric expression⟩,⟨numeric expression⟩}

⟨basic path join⟩ → .. | ... | ..⟨tension⟩.. | ..⟨controls⟩..

⟨tension⟩ → tension⟨numeric primary⟩| tension⟨numeric primary⟩and⟨numeric primary⟩

⟨controls⟩ → controls⟨pair primary⟩| controls⟨pair primary⟩and⟨pair primary⟩

⟨argument⟩ → ⟨symbolic token⟩⟨number or raction⟩ → ⟨number⟩/⟨number⟩

| ⟨number not ollowed by ‘/

⟨number

⟩’

⟩⟨scalar multiplication op⟩ → + | −| ⟨‘⟨number or raction⟩’ not ollowed by ‘⟨add op⟩⟨number⟩’⟩

Figure 55: Part 1 o the syntax or expressions

88

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 90/109

⟨transormer⟩ → rotated⟨numeric primary⟩| scaled⟨numeric primary⟩| shifted⟨pair primary⟩| slanted⟨numeric primary⟩| transformed⟨transorm primary⟩| xscaled⟨numeric primary⟩

|yscaled

⟨numeric primary

⟩| zscaled⟨pair primary⟩| reflectedabout(⟨pair expression⟩,⟨pair expression⟩)

| rotatedaround(⟨pair expression⟩,⟨numeric expression⟩)

⟨nullary op⟩ → false | normaldeviate | nullpen | nullpicture | pencircle

| true | whatever

⟨unary op⟩ → ⟨type⟩| abs | angle | arclength | ASCII | bbox | blackpart | bluepart | bot | bounded

| ceiling | center | char | clipped | colormodel | cosd | cyanpart | cycle

| dashpart | decimal | dir | floor | filled | fontpart | fontsize

| greenpart | greypart | hex | inverse | known | length | lft | llcorner

| lrcorner | magentapart | makepath | makepen | mexp | mlog | not | oct | odd

|pathpart

|penpart

|readfrom

|redpart

|reverse

|round

|rt

|sind

|sqrt

| stroked | textpart | textual | top | ulcorner

| uniformdeviate | unitvector | unknown | urcorner | xpart | xxpart

| xypart | yellowpart | ypart | yxpart | yypart

⟨type⟩ → boolean | cmykcolor | color | numeric | pair

| path | pen | picture | rgbcolor | string | transform

⟨internal type⟩ → numeric | string

⟨primary binop⟩ → * | / | ** | and

| dotprod | div | infont | mod

⟨secondary binop⟩ → + | − | + + | + − + | or

| intersectionpoint | intersectiontimes

⟨tertiary binop⟩ → & | < | <= | <> | = | > | >=

| cutafter | cutbefore

⟨o operator⟩ → arctime | direction | directiontime | directionpoint| glyph | penoffset | point | postcontrol | precontrol

| subpath | substring

⟨variable⟩ → ⟨tag⟩⟨sux⟩⟨sux⟩ → ⟨empty⟩ | ⟨sux⟩⟨subscript⟩ | ⟨sux⟩⟨tag⟩

| ⟨sux parameter⟩⟨subscript⟩ → ⟨number⟩ | [⟨numeric expression⟩]

⟨internal variable⟩ → ahangle | ahlength | bboxmargin

| charcode | day | defaultcolormodel | defaultpen | defaultscale

| hour | jobname | labeloffset | linecap | linejoin | minute | miterlimit | month

|outputformat

|outputtemplate

|pausing

|prologues

|showstopping

| time | tracingoutput | tracingcapsules | tracingchoices | tracingcommands| tracingequations | tracinglostchars | tracingmacros

| tracingonline | tracingrestores | tracingspecs

| tracingstats | tracingtitles | truecorners

| warningcheck | year

| ⟨symbolic token dened by newinternal⟩

Figure 56: Part 2 o the syntax or expressions

89

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 91/109

⟨pseudo unction⟩ → min(⟨expression list⟩)

| max(⟨expression list⟩)

|incr(

⟨numeric variable

⟩)

| decr(⟨numeric variable⟩)| dashpattern(⟨on/of list⟩)

| interpath(⟨numeric expression⟩,⟨path expression⟩,⟨path expression⟩)

| buildcycle(⟨path expression list⟩)

| thelabel⟨label sux⟩(⟨expression⟩,⟨pair expression⟩)

⟨path expression list⟩ → ⟨path expression⟩| ⟨path expression list⟩,⟨path expression⟩

⟨on/of list⟩ → ⟨on/of list⟩⟨on/of clause⟩ | ⟨on/of clause⟩⟨on/of clause⟩ → on⟨numeric tertiary⟩ | off⟨numeric tertiary⟩

Figure 57: The syntax or unction-like macros

⟨boolean expression⟩ → ⟨expression⟩⟨cmykcolor expression⟩ → ⟨expression⟩⟨color expression⟩ → ⟨expression⟩⟨numeric atom⟩ → ⟨atom⟩⟨numeric expression⟩ → ⟨expression⟩

⟨numeric primary

⟩ → ⟨primary

⟩⟨numeric tertiary⟩ → ⟨tertiary⟩⟨numeric variable⟩ → ⟨variable⟩ | ⟨internal variable⟩⟨pair expression⟩ → ⟨expression⟩⟨pair primary⟩ → ⟨primary⟩⟨path expression⟩ → ⟨expression⟩⟨path subexpression⟩ → ⟨subexpression⟩⟨pen expression⟩ → ⟨expression⟩⟨picture expression⟩ → ⟨expression⟩⟨picture variable⟩ → ⟨variable⟩⟨rgbcolor expression⟩ → ⟨expression⟩⟨string expression⟩ → ⟨expression⟩⟨sux parameter⟩ → ⟨parameter⟩⟨transorm primary⟩ → ⟨primary⟩

Figure 58: Miscellaneous productions needed to complete the BNF

90

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 92/109

⟨program⟩ → ⟨statement list⟩end

⟨statement list⟩ → ⟨empty⟩ | ⟨statement list⟩;⟨statement⟩⟨statement⟩ → ⟨empty⟩

| ⟨equation⟩ | ⟨assignment⟩

| ⟨declaration

⟩ | ⟨macro denition

⟩| ⟨compound⟩ | ⟨pseudo procedure⟩| ⟨command⟩⟨compound⟩ → begingroup⟨statement list⟩endgroup

| beginfig(⟨numeric expression⟩);⟨statement list⟩;endfig

⟨equation⟩ → ⟨expression⟩=⟨right-hand side⟩⟨assignment⟩ → ⟨variable⟩:=⟨right-hand side⟩

| ⟨internal variable⟩:=⟨right-hand side⟩⟨right-hand side⟩ → ⟨expression⟩ | ⟨equation⟩ | ⟨assignment⟩

⟨declaration⟩ → ⟨type⟩⟨declaration list⟩⟨declaration list⟩ → ⟨generic variable⟩

| ⟨declaration list

⟩,

⟨generic variable

⟩⟨generic variable⟩ → ⟨symbolic token⟩⟨generic sux⟩⟨generic sux⟩ → ⟨empty⟩ | ⟨generic sux⟩⟨tag⟩

| ⟨generic sux⟩[]

⟨macro denition⟩ → ⟨macro heading⟩=⟨replacement text⟩enddef

⟨macro heading⟩ → def⟨symbolic token⟩⟨delimited part⟩⟨undelimited part⟩| vardef⟨generic variable⟩⟨delimited part⟩⟨undelimited part⟩| vardef⟨generic variable⟩@#⟨delimited part⟩⟨undelimited part⟩| ⟨binary de ⟩⟨parameter⟩⟨symbolic token⟩⟨parameter⟩

⟨delimited part⟩ → ⟨empty⟩| ⟨delimited part⟩(⟨parameter type⟩⟨parameter tokens⟩)

⟨parameter type⟩ → expr | suffix | text

⟨parameter tokens⟩ → ⟨parameter⟩ | ⟨parameter tokens⟩,⟨parameter⟩⟨parameter⟩ → ⟨symbolic token⟩

⟨undelimited part⟩ → ⟨empty⟩| ⟨parameter type⟩⟨parameter⟩| ⟨precedence level⟩⟨parameter⟩| expr⟨parameter⟩of⟨parameter⟩

⟨precedence level⟩ → primary | secondary | tertiary

⟨binary de ⟩ → primarydef | secondarydef | tertiarydef

⟨pseudo procedure⟩ → drawoptions(⟨option list⟩)

| label⟨label sux⟩(⟨expression⟩,⟨pair expression⟩)

| dotlabel⟨label sux⟩(⟨expression⟩,⟨pair expression⟩)

| labels⟨label sux⟩(⟨point number list⟩)

| dotlabels⟨label sux⟩(⟨point number list⟩)⟨point number list⟩ → ⟨sux⟩ | ⟨point number list⟩,⟨sux⟩⟨label sux⟩ → ⟨empty⟩ | lft | rt | top | bot | ulft | urt | llft | lrt

Figure 59: Overall syntax or MetaPost programs

91

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 93/109

⟨command⟩ → clip⟨picture variable⟩to⟨path expression⟩| interim⟨internal variable⟩:=⟨right-hand side⟩| let⟨symbolic token⟩=⟨symbolic token⟩| pickup⟨expression⟩| randomseed:=⟨numeric expression⟩| save⟨symbolic token list⟩

|setbounds

⟨picture variable

⟩to

⟨path expression

⟩| shipout⟨picture expression⟩| write⟨string expression⟩to⟨string expression⟩| ⟨addto command⟩| ⟨drawing command⟩| ⟨ont metric command⟩| ⟨newinternal command⟩| ⟨message command⟩| ⟨mode command⟩| ⟨show command⟩| ⟨special command⟩| ⟨tracing command⟩

⟨show command⟩ →show

⟨expression list⟩| showvariable⟨symbolic token list⟩| showtoken⟨symbolic token list⟩| showdependencies

⟨symbolic token list⟩ → ⟨symbolic token⟩| ⟨symbolic token⟩,⟨symbolic token list⟩

⟨expression list⟩ → ⟨expression⟩ | ⟨expression list⟩,⟨expression⟩

⟨addto command⟩ →addto⟨picture variable⟩also⟨picture expression⟩⟨option list⟩| addto⟨picture variable⟩contour⟨path expression⟩⟨option list⟩| addto⟨picture variable⟩doublepath⟨path expression⟩⟨option list⟩

⟨option list⟩ → ⟨empty⟩ | ⟨drawing option⟩⟨option list⟩⟨drawing option⟩ → withcolor⟨color expression⟩| withrgbcolor⟨rgbcolor expression⟩ | withcmykcolor⟨cmykcolor expression⟩| withgreyscale⟨numeric expression⟩ | withoutcolor

| withprescript⟨string expression⟩ | withpostscript⟨string expression⟩| withpen⟨pen expression⟩ | dashed⟨picture expression⟩

⟨drawing command⟩ → draw⟨picture expression⟩⟨option list⟩| ⟨ll type⟩⟨path expression⟩⟨option list⟩

⟨ll type⟩ → fill | draw | filldraw | unfill | undraw | unfilldraw

| drawarrow | drawdblarrow | cutdraw

⟨newinternal command

⟩ →newinternal

⟨internal type

⟩⟨symbolic token list

⟩| newinternal⟨symbolic token list⟩⟨message command⟩ → errhelp⟨string expression⟩

| errmessage⟨string expression⟩| filenametemplate⟨string expression⟩| message⟨string expression⟩

Figure 60: Part 1 o the syntax or commands

92

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 94/109

⟨mode command⟩ → batchmode | nonstopmode

| scrollmode | errorstopmode

⟨special command⟩ → fontmapfile⟨string expression⟩| fontmapline⟨string expression⟩| special⟨string expression⟩

⟨tracing command⟩ → tracingall | loggingall | tracingnone

Figure 61: Part 2 o the syntax or commands

⟨i test⟩ → if⟨boolean expression⟩:⟨balanced tokens⟩⟨alternatives⟩fi

⟨alternatives⟩ → ⟨empty⟩| else:⟨balanced tokens⟩| elseif⟨boolean expression⟩:⟨balanced tokens⟩⟨alternatives⟩

⟨loop⟩ → ⟨loop header⟩:⟨loop text⟩endfor

⟨loop header⟩ → for⟨symbolic token⟩=⟨progression⟩| for⟨symbolic token⟩=⟨or list⟩| for⟨symbolic token⟩within⟨picture expression⟩| forsuffixes⟨symbolic token⟩=⟨sux list⟩| forever

⟨progression⟩ → ⟨numeric expression⟩upto⟨numeric expression⟩| ⟨numeric expression⟩downto⟨numeric expression⟩| ⟨numeric expression⟩step⟨numeric expression⟩until⟨numeric expression⟩

⟨or list⟩ → ⟨expression⟩ | ⟨or list⟩,⟨expression⟩⟨sux list⟩ → ⟨sux⟩ | ⟨sux list⟩,⟨sux⟩

Figure 62: The syntax or conditionals and loops

93

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 95/109

A.2 Command-Line Syntax

A.2.1 The MetaPost Program

The MetaPost program processes commands in the MetaPost language, either read rom a le ortyped-in interactively, and compiles them into PostScript or SVG graphics. The run-time behavior o the executable can be controlled by command-line parameters, environment variables, and congu-ration les. The MetaPost executable is named mpost (or occasionally just mp). The command-linesyntax o the executable is

 mpost[⟨switches⟩] [&⟨memle⟩] [⟨inle⟩] [⟨commands⟩]

Any o the parameters is optional. I no argument is given to the mpost command, MetaPost entersinteractive mode, indicated by a ** prompt, waiting or a le name to be typed-in by keyboard.The le is then read-in and processed as i it were given as parameter ⟨inle⟩ on the command-line.

⟨inle⟩ A MetaPost input le is a text le containing statements in the MetaPost language. Typi-cally, input les have le extension mp, e.g., fig.mp. Here is how MetaPost searches or inputles. I ⟨inle⟩ doesn’t end with .mp, MetaPost rst looks or a le ⟨inle⟩.mp. Only i that ledoesn’t exist, it looks or le ⟨inle⟩ literally. That way, the mp le extension can be omittedwhen calling MetaPost. I 

⟨inle

⟩already ends with .mp, no special le name handling takes

place and MetaPost looks or that le only.As an example, i there are two les fig and fig.mp in the current directory and MetaPost isinvoked with ’mpost fig’, the le that gets processed is fig.mp. To process le fig in thissituation, MetaPost can be called as ’mpost fig.’. Note, the trailing dot is only needed aslong as there exists a le fig.mp alongside le fig.

I MetaPost cannot nd any input le by the rules specied above, it complaints with an errormessage and interactively asks or a new input le name.

⟨commands⟩ All text on the command-line ater ⟨inle⟩ is interpreted as MetaPost code and isprocessed ater ⟨inle⟩ is read. I ⟨inle⟩ already contains an end statement, ⟨commands⟩ getsefectively ignored. I MetaPost doesn’t encounter an end statement neither in ⟨inle⟩ nor in⟨commands⟩, it enters interactive mode ater processing all input.

&⟨memle⟩ to be completed 

⟨switches⟩ MetaPost provides a number o command-line switches that control the run-time behav-ior. Switches can be prexed by one or two dashes. Both orms have the same meaning. Anexemplary call to MetaPost that compiles a le fig.mp, using LATEX to typeset btex/etex

labels, would look like:  mpost -tex=latex fig

Here’s a summary o the command-line switches provided by mpost:

-debug Don’t delete intermediate les.

-dvitomp Act as the dvitomp executable (see below).

-file-line-error Start error messages with ‘filename:lineno:’ insteado ‘!’.

-halt-on-error Immediately exit ater the rst error occurred.

-help Show help on command-line switches.

-ini Be the INI variant o the program.

-interaction=⟨string⟩ Set interaction mode to one o  batchmode,nonstopmode, scrollmode, errorstopmode.

94

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 96/109

-jobname=⟨ jobname⟩ Set the name o the job (afects output le names).

-kpathsea-debug=⟨number⟩ Set debugging ags or path searching.

-mem=⟨string⟩ Use ⟨string⟩ as memory dump name (same as &⟨string⟩)

-no-file-line-error Enable normal MetaPost and TEX style error messages.

-no-kpathsea Do not use the kpathsea program to nd les. All leshave to be in the current directory or specied via a ullpath.

-progname=⟨string⟩ Pretend to be the ⟨string⟩ executable.

-recorder Write a list o all opened disk les to ⟨ jobname⟩.fls.(This unctionality is provided by kpathsea.)

-s ⟨key⟩=⟨value⟩ Set internal variable ⟨key⟩ to ⟨value⟩. This switch canbe given multiple times on the command-line. Theassignments are applied just beore the input le isread-in. ⟨value⟩ can be an integer between -16383 and16383 or a string in double quotes. For strings, doublequotes are stripped, but no other processing takesplace. To avoid double quotes being already stripped bythe shell, the whole assignment can be enclosed inanother pair o single quotes. Example:-s ’outputformat="svg"’ -s prologues=3

Use SVG backend converting ont shapes to paths.

-tex=⟨texprogram⟩ Load ormat ⟨texprogram⟩ or rendering TEX material.

-troff, -T Output trof compatible PostScript les.

-version Print version inormation and exit.

The ollowing command-line switches are silently ignored in mplib-based MetaPost (v1.100 orlater), because they are always ‘on’:

-8bit

-parse-first-line

The ollowing command-line switches are ignored, but trigger a warning:

-no-parse-first-line

-output-directory=⟨string⟩-translate-file=⟨string⟩

A.2.2 The dvitomp Program

The dvitomp program converts DVI les into low-level MetaPost code. MetaPost uses the dvitomp

program when typesetting btex/etex labels by TEX or the nal conversion back into MetaPostcode. The command-line syntax o the executable is

dvitomp[⟨switches⟩] ⟨inle⟩ [⟨outle⟩]

Parameters ⟨switches⟩ and ⟨outle⟩ are optional.

⟨inle⟩ This is the name o the DVI le to convert. I the name doesn’t end with .dvi, that

95

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 97/109

extension is appended. Note, dvitomp never opens les not ending .dvi. This le is in generalautomatically generated by TEX or trof, driven by MetaPost.

⟨outle⟩ This is the name o the output le containing the MetaPost code equivalent to ⟨inle⟩. I ⟨outle⟩ is not given, ⟨outle⟩ is ⟨inle⟩ with the extension .dvi replaced by .mpx. I ⟨outle⟩is given and doesn’t end with .mpx, that extension is appended.

⟨switches⟩ Command-line switches can be prexed by one or two dashes. Both orms have the samemeaning. The ollowing command-line switches are provided by dvitomp:

-help Show help on command-line switches.

-kpathsea-debug=⟨number⟩ Set debugging ags or path searching.

-progname=⟨string⟩ Pretend to be the ⟨string⟩ executable.

-version Print version inormation and exit.

The dvitomp program used to be part o a set o external tools, called mpware12, which were usedby MetaPost or processing btex/etex labels. Since MetaPost version 1.100, the label conversion ishandled internally by the mpost program. The mpware tools are thereore obsolete and no longerpart o the MetaPost distribution. Nowadays, dvitomp is either a copy o the mpost executable withthe name dvitomp or a wrapper, calling mpost as

 mpost -dvitomp ⟨inle⟩ ⟨outle⟩

12makempx, mpto, dvitomp, and dmp.

96

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 98/109

B Legacy Inormation

B.1 MetaPost Versus METAFONT

Since the METAFONT and MetaPost languages have so much in common, expert users o  META-FONT will want to skip most o the explanations in this document and concentrate on concepts thatare unique to MetaPost. The comparisons in this appendix are intended to help experts that are

amiliar with The  METAFONT  book  as well as other users that want to benet rom Knuth’s moredetailed explanations [5].

Since METAFONT is intended or making TEX onts, it has a number o primitives or generatingthe tfm les that TEX needs or character dimensions, spacing inormation, ligatures and kerning.MetaPost can also be used or generating onts, and it also has METAFONT’s primitives or makingtfm les. These are listed in Table 16. Explanations can be ound in the METAFONT documentation[5, 8].

commands charlist, extensible, fontdimen, headerbyte

kern, ligtable

ligtable operators ::, =:, =:|, =:|>, |=:, |=:>,|=:|, |=:|>, |=:|>>, ||:

internal variables boundarychar, chardp, charext, charht,charic, charwd, designsize, fontmaking

other operators charexists

Table 16: MetaPost primitives or making tfm les.

Even though MetaPost has the primitives or generating onts, many o the ont-making primitivesand internal variables that are part o Plain METAFONT are not dened in Plain MetaPost. Instead,there is a separate macro package called mfplain that denes the macros required to allow MetaPostto process Knuth’s Computer Modern onts as shown in Table 17 [7]. To load these macros, put“&mfplain” beore the name o the input le. This can be done at the ** prompt ater invoking theMetaPost interpreter with no arguments, or on a command line that looks something like this:13

  mpost ’&mfplain’ cmr10

The analog o a METAFONT command line like

  mf ’\mode=lowres; mag=1.2; input cmr10’

is  mpost ’&mfplain \mode=lowres; mag=1.2; input cmr10’

The result is a set o PostScript les, one or each character in the ont. Some editing would berequired in order to merge them into a downloadable Type 3 PostScript ont [1].

Another limitation o the mfplain package is that certain internal variables rom Plain META-FONT cannot be given reasonable MetaPost denitions. These include displaying, currentwindow,screen_rows, and screen_cols which depend on METAFONT’s ability to display images on the

computer screen. In addition, pixels_per_inch is irrelevant since MetaPost uses xed units o PostScript points.The reason why some macros and internal variables are not meaningul in MetaPost is that

METAFONT primitive commands cull, display, openwindow, numspecial and totalweight arenot implemented in MetaPost. Also not implemented are a number o internal variables as well as

13Command line syntax is system dep endent. Quotes are needed on most Unix systems to protect special characters

like &.

97

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 99/109

Dened in the mfplain packagebeginchar font_identifier

blacker font_normal_shrink

capsule_def font_normal_space

change_width font_normal_stretch

define_blacker_pixels font_quad

define_corrected_pixels font_size

define_good_x_pixels font_slant

define_good_y_pixels font_x_height

define_horizontal_corrected_pixels italcorr

define_pixels labelfont

define_whole_blacker_pixels makebox

define_whole_pixels makegrid

define_whole_vertical_blacker_pixels maketicks

define_whole_vertical_pixels mode_def

endchar mode_setup

extra_beginchar o_correction

extra_endchar proofrule

extra_setup proofrulethickness

font_coding_scheme rulepen

font_extra_space smode

Dened as no-ops in the mfplain packagecullit proofoffset

currenttransform screencharsgfcorners screenrule

grayfont screenstrokes

hround showit

imagerules slantfont

lowres_fix titlefont

nodisplays unitpixel

notransforms vround

openit

Table 17: Macros and internal variables dened only in the mfplain package.

98

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 100/109

MetaPost primitives not ound in METAFONT

blackpart

bluepart

bounded

btex

clip

clipped

closefrom

cmykcolor

color

colormodel

cyanpart

dashed

dashpartdefaultcolormodel

etex

filenametemplate

filled

fontmapfile

fontmapline

fontpart

fontsize

for within

glyph of

greenpart

greypart

hour

infont

jobname

linecap

linejoin

llcorner

lrcorner

 magentapart

 minute

 miterlimit mpprocset

 mpxbreak

outputformat

outputtemplate

pathpart

penpart

prologues

readfrom

redpart

restoreclipcolor

rgbcolor

setbounds

stroked

textpart

textual

tracinglostchars

troffmode

truecorners

ulcorner

urcorner

verbatimtex

withcmykcolorwithcolor

withgreyscale

withoutcolor

withpostscript

withprescript

withrgbcolor

write to

yellowpart

Variables and Macros dened only in Plain MetaPostahangle

ahlength

backgroundbbox

bboxmargin

beginfig

beveled

black

blue

buildcycle

butt

center

colorpart

cutafter

cutbefore

cuttings

dashpatterndefaultfont

defaultpen

defaultscale

dotlabel

dotlabels

drawarrow

drawdblarrow

drawoptions

endfig

EOF

evenly

extra_beginfig

extra_endfig

greenimage

label

labeloffset

 mitered

red

rounded

squared

thelabel

white

Table 18: Macros and internal variables dened in MetaPost but not METAFONT.

99

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 101/109

the ⟨drawing option⟩ withweight. Here is a complete listing o the internal variables whose primitivemeanings in METAFONT do not make sense in MetaPost:

autorounding fillin proofing tracingpens xoffset

chardx granularity smoothing turningcheck yoffset

chardy hppp tracingedges vppp

There is also oneMETAFONT

primitive that has a slightly diferent meaning in MetaPost. Bothlanguages allow statements o the orm

special ⟨string expression⟩;

but METAFONT copies the string into its “generic ont” output le, while MetaPost interprets thestring as a sequence o PostScript commands that are to be placed at the beginning o the nextoutput le.

In this regard, it is worth mentioning that rules in TEX material included via btex..etex inMetaPost are rounded to the correct number o pixels according to PostScript conversion rules [1].In METAFONT, rules are not generated directly, but simply included in specials and interpreted laterby other programs, such as gftodvi, so there is no special conversion.

All the other diferences betweenMETAFONT and MetaPost are eatures ound only in MetaPost.

These are listed in Table 18. The only commands listed in this table that the preceding sectionsdo not discuss are extra_beginfig, extra_endfig, and mpxbreak. The rst two are strings thatcontain extra commands to be processed by beginfig and endfig just as extra_beginchar andextra_endchar are processed by beginchar and endchar. (The le boxes.mp uses these eatures).

The other new eature listed in Table 18 not listed in the index is mpxbreak. This is used toseparate blocks o translated TEX or trof commands in mpx les. It should be o no concern to userssince mpx les are generated automatically.

B.2 File Name Templates

The output le naming template mechanism introduced in MetaPost version 1.000 originally useda primitive called filenametemplate, as opposed to the internal string variable outputtemplate de-scribed in section 14.1. This primitive took a string argument with the same syntax as outputtemplate,

except that it didn’t know about the %{...} escape sequence or evaluating internal variables, e.g.,:

filenametemplate "%j-%c.mps";

The filenametemplate primitive has been deprecated since the introduction o outputtemplate

(version 1.200), but is still supported. I you happen to need writing uture-proo source les, that atthe same time are backwards compatible to MetaPost versions between 1.000 and 1.200, this outputlename template declaration might help:

if scantokens(mpversion) < 1.200:

filenametemplate

else:

outputtemplate :=

fi

"%j-%c.mps";

100

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 102/109

Reerences

[1] Adobe Systems Inc. PostScript Language Reerence Manual . Addison Wesley, Reading, Mas-sachusetts, second edition, 1990.

[2] Hans Hagen. Metaun , January 2002. http://www.pragma-ade.com/general/manuals/

 metafun-s.pdf.

[3] Hans Hagen, Taco Hoekwater, and Elie Roux. The luamplib package.CTAN://macros/luatex/generic/luamplib/luamplib.pdf.

[4] J. D. Hobby. Smooth, easy to compute interpolating splines. Discrete and Computational Geometry , 1(2), 1986.

[5] D. E. Knuth. The METAFONT  book . Addison Wesley, Reading, Massachusetts, 1986. Volume Co Computers and Typesetting .

[6] D. E. Knuth. The T E Xbook . Addison Wesley, Reading, Massachusetts, 1986. Volume A o Computers and Typesetting .

[7] D. E. Knuth. Computer Modern Typeaces. Addison Wesley, Reading, Massachusetts, 1986.Volume E o  Computers and Typesetting .

[8] D. E. Knuth. The new versions o TEX and METAFONT. TUGboat, the T E X User’s GroupNewsletter , 10(3):325–328, November 1989.

[9] LuaTEX development team. LuaT E X: Reerence Manual . http://www.luatex.org/svn/

trunk/manual/luatexref-t.pdf.

[10] Keith Reckdahl. Using Imported Graphics in LAT E X and pdLAT E X , 3.0.1 edition, January 2006.CTAN://info/epslatex.

[11] World Wide Web Consortium (W3C). Scalable Vector Graphics (SVG) 1.1 Specication , Jan-uary 2003. http://www.w3.org/TR/SVG11/.

101

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 103/109

Index

#@, 58&, 16, 79*, 79**, 15, 79

prompt, 94+, 79++, 16, 79+-+, 16, 79-, 79--, 2.., 5..., 9, 59/, 79:=, 11, 20<, 15, 79<=, 15, 79

<>, 15, 79=, 11, 79>, 15, 79>=, 15, 79@, 58@#, 59[]

array, 20mediation, 12vardef macro, 58

%, 5%H, 66%M, 66

%%, 66%&, 64%{⟨internal variable⟩}, 66%c, 66%c, 65%d, 66%j, 66%m, 66%y, 66

abs, 17, 18, 79addto also, 45addto contour, 45

addto doublepath, 45Adobe Type 1 Font, 48, 49ahangle, 42ahlength, 42and, 15, 16, 79angle, 18, 79arc length, 35, 53

arclength, 35, 55, 79arctime, 53arctime of, 35, 79arithmetic, 14, 18, 61arrays, 19, 20

multidimensional, 20arrows, 40

double-headed, 42ASCII, 79assignment, 11, 20, 62

background, 29, 42⟨balanced tokens⟩, 53, 93batchmode, 93bbox, 27, 29, 79bboxmargin, 27beginfig, 4, 19, 43, 45, 51, 52, 100begingroup, 51, 58beveled, 40black, 14, 48blackpart, 18, 47–48, 80blue, 14bluepart, 18, 47–48, 80boolean, 18, 80boolean type, 15bot, 21, 43, 44, 80bounded, 47–48, 80bounding box, 67boxes.mp, 100

bp, 2btex, 22, 24, 27buildcycle, 29, 30butt, 40, 61

CAPSULE, 52cc, 78ceiling, 18, 80center, 27, 80char, 26, 80character, 48charcode, 45CharString name, 49

clip, 45, 46clipped, 47–48, 80closefrom, 63cm, 2cmykcolor, 18, 80cmykcolor type, 15color, 18, 80

102

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 104/109

color type, 14colormodel, 47–48, 80colorpart, 47–48, 80command-line

dvitomp

-help, 96-kpathsea-debug, 96-progname, 96-version, 96

dvitomp, 95 mpost

-8bit, 95-T, 95-debug, 94-dvitomp, 94-file-line-error, 94-halt-on-error, 94-help, 94-ini, 94

-interaction, 94-jobname, 95-kpathsea-debug, 95-mem, 95-no-file-line-error, 95-no-kpathsea, 95-no-parse-first-line, 95-output-directory, 95-parse-first-line, 95-progname, 95-recorder, 95-s, 95-tex, 95

-translate-file, 95-troff, 95-version, 95

 mpost, 94comments, 5, 19comparison, 15compile, 3, 4compound statement, 51Computer Modern Roman, 49concatenation, 16ConTEXt, 74

ormatimporting MetaPost les, 74

control points, 7, 71controls, 7convex polygons, 44corners, 40cosd, 18, 80Courier, 24

Creator comment in PostScript output, see PostScript,Creator comment

curl, 9currentpen, 43, 45currentpicture, 15, 29, 44–46, 67curvature, 7–9cutafter, 33, 80cutbefore, 33, 80cutdraw, 61cuttings, 33cyanpart, 18, 47–48, 80cycle, 5, 18, 80

⟨dash pattern⟩, 37, 39recursive, 39

dash pattern, 39dashed, 37, 42, 45dashpart, 47–48, 80dashpattern, 56day, 65, 76Dcaron, 49dd, 78debug, 3, 69decimal, 18, 80declarations, 20decr, 61def, 50defaultcolormodel, 28defaultfont, 22defaultpen, 43defaultscale, 22dir, 8, 80

direction of, 33, 60, 81directionpoint of, 35, 81directiontime of, 35, 81ditto, 78div, 81dotlabel, 21dotlabeldiam, 21dotlabels, 22, 62dotprod, 16, 59, 60, 81down, 8downto, 61draw, 2, 15, 29, 59draw_mark, 53

draw_marked, 53drawarrow, 40drawdblarrow, 42drawdot, 2, 15⟨drawing option⟩, 45drawoptions, 42, 45dvi le, 24, 68, 72, 73, 95

103

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 105/109

dvips, 25dvips, 72, 73dvitomp, 95dvitomp, 24, 95

edit, 3, 4else, 53elseif, 53encoding, 48

OT1, 49end, 4, 61enddef, 50endfig, 4, 45, 51, 100endfor, 3, 61endgroup, 51, 58, 61EOF, 63EPS, 73

puried, 72, 73EPSF, 24, 66, 67epsf.tex, 72\epsfbox, 72epsilon, 78erasing, 29, 42, 48, 49errhelp, 70errmessage, 70errorstopmode, 93etex, 22, 24, 27evenly, 37, 40exitif, 62exitunless, 62exponentiation, 15expr, 51, 53

⟨expression⟩, 15, 60, 88\externalfigure, 74extra_beginfig, 100extra_endfig, 100

alse, 15fi, 53filenametemplate, 100les

closing, 63dvi, 24, 68, 95fls, 95input, 4

log, 4, 24, 70 mp, 4, 70, 94 mps, 5, 65, 73 mpx, 24, 96, 100output, 5pfb, 49reading, 63

svg, 65, 74tfm, 22, 49, 97transcript, 4, 14, 67, 70, 71writing, 63

fill, 28, 51, 59, 60ll rule

non-zero, 28, 49filldraw, 42filled, 47–48, 81Fireox, 4attening, 50floor, 18, 81fls le, 95ont

Adobe Type 1, 48, 49character, 48design size, 50design unit, 50encoding, 48

glyph, 48PostScript, 48, 49slot, 48

fontmapfile, 26fontmapline, 26fontpart, 47, 81fontsize, 22, 81for, 3, 61for within, 46–47forever, 62forsuffixes, 62ractions, 17fullcircle, 29, 44

unctions, 51

⟨generic variable⟩, 58, 91getmid, 56gftodvi, 100GIMP, 74glyph, 48glyph, 48, 81graphics, 73graphicx, 73green, 14greenpart, 18, 47–48, 81greypart, 18, 47–48, 81

grops, 74GSview, 4, 67, 68

halfcircle, 29Helvetica, 22hex, 81hide, 55

104

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 106/109

hour, 65, 76HTML, 74

identity, 36if, 53, 71, 75image, 46in, 2\includegraphics, 73Inconsistent equation, 11, 13incr, 56, 61indexing, 16inequality, 15infinity, 32inections, 9infont, 26, 81Inkscape, 74interactive mode, 4, 94interim, 52, 61internal variables, 14, 20, 21, 27, 40, 42, 45, 52,

65, 66, 70, 71, 97numeric, 20string, 20

intersection, 30, 32intersectionpoint, 30, 32, 59, 81intersections, 30intersectiontimes, 32, 81inverse, 36, 81

jobname, 77joinup, 56, 59

kerning, 22, 97known, 18, 81Konqueror, 4

label, 21⟨label sux⟩, 21, 90, 91labeloffset, 21labels, 22labels, typesetting, 22labels, with variable text, 63LATEX

ormatimporting MetaPost les, 73

typesetting labels with, 64Latin Modern Roman, 49left, 8length, 16, 33, 47, 81let, 86lft, 21, 43, 44, 81ligatures, 22, 97linecap, 40, 52, 61linejoin, 40

llcorner, 27, 67, 81llft, 21locality, 20, 51log le, 4, 24, 70loggingall, 71loops, 3, 61, 75lrcorner, 27, 81lrt, 21luamplib, 73LuaTEX

engine, 73

 magentapart, 18, 47–48, 81 makempx, 24 makepath, 44, 82 makepen, 44, 82 mark_angle, 55 mark_rt_angle, 55 max, 87mediation, 12, 13, 17

 message, 70METAFONT, 1, 22, 44, 45, 61, 69, 75, 97

 metapost/base, 63 mexp, 82 mfplain, 97 middlepoint, 53 midpoint, 53 min, 87 minute, 65, 76 mitered, 40 miterlimit, 40 mlog, 82

 mm, 2 mod, 82 month, 65, 76 mp le, 4, 70, 94mplib, 3, 73, 74

C API, 3Lua bindings, 3

 mplibapi.pdf, 3 mplib, 63mpost, 94, 96

 mpost, 3, 4, 94, 96 mpprocset, 66 mproof.tex, 68

 mps le, 5, 65, 73-mpspic, 74

 mpsproof.tex, 69\bbox, 69\encapsulate, 69\noheaders, 69

 mpstoeps.pl, 69

105

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 107/109

MPTEXPRE, 24 mpto, 24mptopd, 25, 69, 72

 mpversion, 66mpware tools, 96

 mpx le, 24, 96, 100 mpxbreak, 100MPXCOMMAND, 24

 mpxerr.log, 24 mpxerr.tex, 24multiplication, implicit, 3, 18

newinternal, 20non-zero ll rule, 28, 49nonstopmode, 93normaldeviate, 82not, 15, 82⟨nullary op⟩, 16, 88, 89nullpen, 48nullpicture, 16, 46numeric, 18, 82⟨numeric atom⟩, 17numeric type, 14

oct, 82odd, 82⟨o operator⟩, 60, 88, 89⟨option list⟩, 45, 92or, 15, 16, 82origin, 78OT1 encoding, 49outputformat, 66outputtemplate, 45, 65, 73, 100

pair, 18, 82pair type, 14Palatino, 22, 26parameter

expr, 53, 60, 62sux, 56, 58, 59, 61, 62text, 55, 58, 61

parameterization, 7parsing irregularities, 16–18path, 18, 53, 82⟨path knot⟩, 17, 88path type, 14pathpart, 47–48, 82pausing, 76pc, 78PDF, 72, 73pdTEX

engine, 72, 73pen, 18, 82

pen type, 15pencircle, 3, 43penoffset of, 82penpart, 47–48, 82pens

elliptical, 43polygonal, 44, 71

pensquare, 44pfb le, 49pickup, 3, 15picture, 18, 82picture type, 15⟨picture variable⟩, 27, 92Plain macros, 2, 20, 22, 44, 50, 75, 97point

PostScript, 2, 50, 97printer’s, 2

point of, 32, 82POSIX

shell patterns, 68postcontrol of, 33, 82PostScript, 1, 28, 45, 72, 97, 100

bounding box, 67closepath operator, 49conversion rules, 100coordinate system, 2Creator comment, 67ll rule, 28, 49onts, 22, 25, 48, 49, 68point, 2, 50, 97structured, 24, 66

precontrol of, 33, 82

preview, 4PostScript, 67⟨primary⟩, 15, 88⟨primary binop⟩, 16, 26, 60, 88, 89primarydef, 60prologues, 24, 50, 67, 68proo sheets, 68PS, 67.PSPIC, 74PS_View, 4pt, 2

quartercircle, 78

readfrom, 63, 82red, 14redpart, 18, 47–48, 82Redundant equation, 13reflectedabout, 36⟨replacement text⟩, 50, 60, 91

106

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 108/109

reverse, 42, 83rgbcolor, 18, 83right, 8\rlap, 27rotated, 23, 35, 83rotated text, 23rotatedaround, 36, 51round, 18, 59, 83rounded, 40roundof error, 13rt, 21, 43, 83runtime behavior

customize, 65

save, 52scaled, 3, 26, 35, 37, 83scantokens, 15, 83scrollmode, 93⟨secondary⟩, 15, 60, 88

⟨secondary binop

⟩, 16, 30, 60, 88, 89

secondarydef, 60semicolon, 61setbounds, 27, 46–48shell patterns, 68shifted, 35, 83shipout, 45show, 11, 14, 51, 52, 69, 70showdependencies, 70showstopping, 76showtoken, 70showvariable, 70sind, 18, 83

size, 27slanted, 35, 83slot, 48special, 100sqrt, 17, 83squared, 40step, 61str, 59, 62, 83string, 18, 83string constants, 15, 19string expressions, as labels, 63string type, 15stroked, 47–48, 83

\strut, 27subpath, 33, 83subroutines, 51subscript

generic, 20, 58⟨subscript⟩, 20, 56, 89substring of, 16, 83

⟨sux⟩, 18, 20, 56, 59, 88, 89, 91, 93suffix, 55, 61SVG, 1, 4, 66

les, 74svg le, 65, 74

tags, 19, 58, 59

tension, 9⟨tertiary⟩, 15, 60, 88⟨tertiary binop⟩, 16, 33, 60, 88, 89tertiarydef, 60TEX, 2, 4, 22, 27, 100

and riends, 72engine, 72, 73errors, 24onts, 22ormat, plain

importing MetaPost les, 72TEX.mp, 63text, 55, 61text and graphics, 21text processor, 25textpart, 47, 83textual, 47–48, 84tfm le, 22, 49, 97thelabel, 21, 29time, 65, 76Times-Roman, 22, 24tokens, 18

symbolic, 18, 19, 51, 52top, 21, 43, 44, 84tracingall, 71

tracingcapsules, 71tracingchoices, 71tracingcommands, 71tracingequations, 71tracinglostchars, 71tracingmacros, 71tracingnone, 71tracingonline, 14, 70tracingoutput, 71tracingrestores, 71tracingspecs, 71tracingstats, 71tracingtitles, 76

transcript le, see les, transcripttransform, 18, 84transorm type, 14, 35transormation

unknown, 37transformed, 14, 36, 84trof, 2, 4, 24, 74, 100

107

8/3/2019 Met a Post

http://slidepdf.com/reader/full/met-a-post 109/109

importing MetaPost les, 74troffmode, 24true, 15truecorners, 27turningnumber, 49type declarations, 20types, 14

ulcorner, 27, 84ulft, 21⟨unary op⟩, 16, 88, 89undraw, 42unfill, 29unfilldraw, 42uniformdeviate, 84unitsquare, 78unitvector, 18, 59, 84Unix, 24unknown, 18, 84until, 61up, 8upto, 61urcorner, 27, 84urt, 21URWPalladioL-Bold, 26utility routines, 63

vardef, 58variables

internal, 14, 20, 21, 27, 40, 42, 45, 52, 65,66, 70, 71, 97

numeric, 20

string, 20local, 20, 51verbatimtex, 24, 64version number, 67

warningcheck, 14whatever, 12, 52, 84

\X, 74xpart, 18, 37, 47, 84xscaled, 35, 84xxpart, 37, 47, 84xypart, 37, 47, 84

year, 65, 76yellowpart, 18, 47–48, 84ypart, 18, 37, 47, 84yscaled, 35, 84yxpart, 37, 47, 84yypart, 37, 47, 85

z convention, 11, 19, 59zscaled, 35, 55, 85