% $Id: mpman.tex 1098 2009-06-25 08:23:21Z taco $ % MetaPost manual, by John Hobby. License at end. \listfiles \RequirePackage{ifpdf} \ifpdf \ifnum\pdftexversion<140 \else \pdfminorversion=5 \pdfobjcompresslevel=1% Use compressed object streams. \fi \RequirePackage{cmap} \fi \documentclass{article} % article is NOT the original style \usepackage[nofancy]{svninfo}% Access VCS information. \svnInfo $Id: mpman.tex 1098 2009-06-25 08:23:21Z taco $ \newcommand*{\mpversion}{1.204} \usepackage[T1]{fontenc} \usepackage{lmodern} \usepackage{textcomp} \usepackage{mflogo} \usepackage{makeidx} \usepackage{fancyvrb} \usepackage{ctabbing} \RecustomVerbatimEnvironment {verbatim}{BVerbatim}{baseline=c} \usepackage{graphicx} \usepackage[latin1]{inputenc} \usepackage[textwidth=6in,textheight=8.65in]{geometry} \usepackage{tocloft} \setlength\cftbeforesecskip{1.3ex plus 0.3ex minus 0.3ex} \usepackage{ltxtable} \def\ttindex#1{{\tt #1}\index{#1?\texttt{#1}}} \def\ttt{\texttt} % I get tired of typing this out \def\ConTeXt{Con\TeX t} \newcommand\descr[1]{{\langle\hbox{#1}\rangle}} \newcommand\invisgap{\nobreak\hskip0pt\relax} \newcommand\tdescr[1]{$\langle$\invisgap#1\invisgap$\rangle$} \newcommand\pl{\dag} \newcommand\mathcenter[1]{\vcenter{\hbox{#1}}} \renewcommand{\topfraction}{.85} \renewcommand{\bottomfraction}{.7} \renewcommand{\textfraction}{.15} \renewcommand{\floatpagefraction}{.5} \renewcommand{\dbltopfraction}{.66} \renewcommand{\dblfloatpagefraction}{.66} \setcounter{topnumber}{9} \setcounter{bottomnumber}{9} \setcounter{totalnumber}{20} \setcounter{dbltopnumber}{9} \makeindex \usepackage{multicol} \usepackage[rgb,x11names]{xcolor}% Optimize for screen reading. \usepackage{hyperxmp} \usepackage{hyperref} \hypersetup{ pdftitle={MetaPost: A User's Manual}, pdfauthor={John D. Hobby and the MetaPost development team}, pdfkeywords={MetaPost, PostScript, SVG, vector graphics language, MetaFont, TeX} } \hypersetup{ pdfstartview={XYZ null null null},% Zoom factor is determined by viewer. colorlinks, linkcolor=RoyalBlue3, urlcolor=Chocolate4, citecolor=SpringGreen3 } \usepackage[all]{hypcap} \ifpdf \pdfmapfile{=cm2lm.map}% replace CM by LM in figures \else \DeclareGraphicsExtensions{.mps} \DeclareGraphicsRule{mps}{eps}{*}{} \usepackage{breakurl} \fi \begin{document} \VerbatimFootnotes %%% Title page layout documentation is missing. \begin{titlepage} \vbox to \textheight {% \vskip0pt \vfil \vfil \vfil \centerline{\resizebox{3.5in}{!}{\fontseries{b}\selectfont\MP}} \vskip10bp% actually 21bp (-11bp) \centerline{\includegraphics{mpman-60.mps}} \vskip15bp% actually 21bp (-6bp) \centerline{% \resizebox{3.5in}{!}{% \scshape% \fontsize{28bp}{28bp}\selectfont \strut\lowercase{A USER\kern-2bp\lower3bp\hbox{'}S MANUAL}% }% } \vskip-11bp \vfil \vfil \centerline{\large John D. Hobby} \vskip3bp \centerline{and the MetaPost development team} \vskip20.8bp% actually 31.8bp (-11bp) \centerline{\large documented version: \mpversion} \vskip3bp \centerline{\svnInfoMaxToday} \vfil \vfil \vfil } \end{titlepage} \setlength{\columnsep}{2.5em} \begin{multicols}{2} \tableofcontents \end{multicols} \section{Introduction} \label{intro} MetaPost is a programming language much like Knuth's \MF\footnote{\MF\ is a trademark of Addison Wesley Publishing company.}\index{metafont?\MF}~\cite{kn:c} except that it outputs vector graphics, either PostScript programs or SVG\index{SVG} graphics, instead of bitmaps. Borrowed from \MF\ are the basic tools for creating and manipulating pictures. These include numbers, coordinate pairs, cubic splines, affine transformations, text strings, and boolean quantities. Additional features facilitate integrating text and graphics and accessing special features of PostScript\footnote{PostScript is a trademark of Adobe Systems Inc.}\index{PostScript} such as clipping, shading, and dashed lines. Another feature borrowed from \MF\ is the ability to solve linear equations that are given implicitly, thus allowing many programs to be written in a largely declarative style. By building complex operations from simpler ones, MetaPost achieves both power and flexibility. MetaPost is particularly well-suited to generating figures for technical documents where some aspects of a picture may be controlled by mathematical or geometrical constraints that are best expressed symbolically. In other words, MetaPost is not meant to take the place of a freehand drawing tool or even an interactive graphics editor. It is really a programming language for generating graphics, especially figures for \TeX\footnote{\TeX\ is a trademark of the American Mathematical Society.}\index{TeX?\TeX} and troff\index{troff} documents. This document introduces the MetaPost language, beginning with the features that are easiest to use and most important for simple applications. The first few sections describe the language as it appears to the novice user with key parameters at their default values. Some features described in these sections are part of a predefined macro package called Plain. Later sections summarize the complete language and distinguish between primitives and preloaded macros from the Plain macro package\index{Plain macros}. Reading the manual and creating moderately complex graphics with MetaPost does not require knowledge of \MF\ or access to {\sl The \MF book} \cite{kn:c}. However, to really master MetaPost, both are beneficial, since the MetaPost language is based on Knuth's \MF\ to a large extent. Appendix~\ref{MPvsMF} gives a detailed comparison of MetaPost and \MF. MetaPost documentation is completed by ``Drawing Boxes with MetaPost'' and ``Drawing Graphs with MetaPost''---the manuals of the \texttt{boxes} and \texttt{graph} packages originally developed by John~D. Hobby. The MetaPost home page is \url{http://tug.org/metapost}. It has links to much additional information, including many articles that have been written about MetaPost. For general help, try the \url{metapost@tug.org} mailing list; you can subscribe to this list at \url{http://tug.org/mailman/listinfo/metapost}. The development is currently hosted at \url{https://foundry.supelec.fr/projects/metapost/}; visit this site for the current development team members, sources, and much else. Please report bugs and request enhancements either on the \url{metapost@tug.org} list, or through the address given above. (Please do not send reports directly to Dr.\ Hobby any more.) \section{Basic Drawing Statements} \label{basic} The simplest drawing statements are the ones that generate straight lines. Thus\index{draw?\texttt{draw}}\index{-{}-?\texttt{-{}-}} $$ \hbox{\verb|draw (20,20)--(0,0)|} $$ draws\index{draw?\texttt{draw}} a diagonal line and $$ \hbox{\verb|draw (20,20)--(0,0)--(0,30)--(30,0)--(0,0)|} $$ draws a polygonal line like this: $$ \includegraphics{mpman-1.mps} $$ \label{Ddrawdot}MetaPost also has a \ttt{drawdot} command to print a single point, as in \ttt{drawdot(30,0)}. What is meant by coordinates like \verb|(30,0)|? MetaPost uses the same default coordinate system that PostScript\index{PostScript!coordinate system} does. This means that \verb|(30,0)| is 30 units to the right of the origin, where a unit is $1\over72$ of an inch. We shall refer to this default unit as a {\sl PostScript point\/}\index{PostScript!point}\index{point!PostScript} to distinguish it from the standard printer's point\index{point!printer's} which is $1\over72.27$ inches. MetaPost uses the same names for units of measure that \TeX\ and \MF\ do. Thus \verb|bp|\index{bp?\texttt{bp}}\label{Dbp} refers to PostScript points (``big points'') and \verb|pt|\index{pt?\texttt{pt}}\label{Dpt} refers to printer's points. Other units of measure include \verb|in|\index{in?\texttt{in}}\label{Din} for inches, \verb|cm|\index{cm?\texttt{cm}}\label{Dcm} for centimeters, and \verb|mm|\index{mm?\texttt{mm}}\label{Dmm} for millimeters. For example, $$ \hbox{\verb|(2cm,2cm)--(0,0)--(0,3cm)--(3cm,0)--(0,0)|} $$ generates a larger version of the above diagram. It is OK to say \verb|0| instead \verb|0cm| because {\tt cm} is really just a conversion factor and {\tt 0cm} just multiplies the conversion factor by zero. (MetaPost understands constructions like {\tt 2cm}\index{multiplication, implicit} as shorthand for \verb|2*cm|). It is convenient to introduce your own scale factor, say $u$. Then you can define coordinates in terms of $u$ and decide later whether you want to begin with \verb|u=1cm| or \verb|u=0.5cm|. This gives you control over what gets scaled and what does not so that changing $u$ will not affect features such as line widths. There are many ways to affect the appearance of a line besides just changing its width, so the width-control mechanisms allow a lot of generality that we do not need yet. This leads to the strange looking statement\index{pickup?\texttt{pickup}}\index{pencircle?\texttt{pencircle}}% \index{scaled?\texttt{scaled}} $$ \hbox{\verb|pickup pencircle scaled 4pt|} $$ for setting the line width for subsequent \verb|draw| statements to 4 points. (This is about eight times the default line width). With such a wide line width, even a line of zero length comes out as a big bold dot\index{dots}. We can use this to make a grid of bold dots by having one \verb|drawdot| statement for each grid point. Such a repetitive sequence of \verb|draw| statements is best written as a pair of nested loops:\index{loops}% \index{for?\texttt{for}}\index{endfor?\texttt{endfor}} $$\begin{verbatim} for i=0 upto 2: for j=0 upto 2: drawdot (i*u,j*u); endfor endfor \end{verbatim} $$ The outer loop runs for $i=0,1,2$ and the inner loop runs for $j=0,1,2$. The result is a three-by-three grid of bold dots as shown in Figure~\ref{fig1}. The figure also includes a larger version of the polygonal line diagram that we saw before. \begin{figure}[htp] $$ \begin{verbatim} 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; \end{verbatim} \quad \mathcenter{\includegraphics{mpman-2.mps}} $$ \caption{MetaPost commands and the resulting output} \label{fig1} \end{figure} \section{The MetaPost workflow} \label{workflow} Before describing the MetaPost language in detail, let's have a look at how the MetaPost program is used for developing graphics: creating MetaPost source files, compiling sources, previewing MetaPost graphics, and finally including MetaPost graphics into third-party applications. This section also contains some technical details about MetaPost that are useful to know. If you're not interested in these basics right now you can savely skip those parts and only refer to them later. \subsection{Processing source files} \label{processing} To create graphics with MetaPost, you prepare a text file containing code in the MetaPost language and then invoke the compiler, usually by giving a command of the form\index{mpost?\texttt{mpost}} $$ {\tt mpost}\, \descr{filename} $$ on the command-line. The syntax and program name itself are system-dependent; sometimes it is named \texttt{mp}. MetaPost input files\index{files!input} normally have names ending \texttt{.mp}\index{mp file?{\tt mp} file}\index{files!mp?{\tt mp}} but this part of the name can be omitted when invoking MetaPost. The command-line options provided by MetaPost are summarized in appendix~\ref{refman:commandline}. \paragraph{Input file} \label{inputfile} A MetaPost input file normally contains a sequence of \verb|beginfig()|\index{beginfig?\texttt{beginfig}}, \verb|endfig|\index{endfig?\texttt{endfig}} pairs with an {\tt end}\index{end?\texttt{end}} statement after the last one. These are macros that perform various administrative functions and ensure that the results of all drawing operations get packaged up and translated into PostScript. The numeric argument to the \verb|beginfig| macro determines the name of the corresponding output file, whose name, by default, is of the form $\descr{jobname}{\tt.}\descr{n}$, where $\descr{jobname}$ is the base name of the graphics source file and $\descr{n}$ is the current argument to \verb|beginfig|. As an example, if a file is named {\tt fig.mp}, the output from drawing statements between \verb|beginfig(1)| and the next \verb|endfig| is written in a file {\tt fig.1}\index{files!output}. Statements can also appear outside \verb|beginfig/endfig|. Such statements are processed, but drawing operations generate no visible output. Typically, global configurations are put outside \verb|beginfig/endfig|, e.g., assignments to internal variables, such as \verb|outputtemplate| or \verb|prologues|, or a \LaTeX\ preamble declaration for enhanced text rendering. \paragraph{Log file and version number} \label{logfile} Any terminal I/O is summarized in a transcript\index{files!transcript}\index{transcript file} file called $\descr{filename}{\tt.log}$\index{log file?{\tt log} file}\index{files!log?{\tt log}}. This includes error messages and any MetaPost commands entered interactively.\footnote{A {\tt *}\index{*?\texttt{*}} prompt is used for interactive input and a {\tt **}\index{**?\texttt{**}} prompt indicates that an input file name is expected. This can be avoided by invoking MetaPost on a file that ends with an {\tt end}\index{end?\texttt{end}} command.} The transcript file starts with a banner line that identifies the version\index{version number} of MetaPost you are using. The version number is also written to the generated PostScript or SVG file as a comment (for PostScript output the \texttt{Creator}\index{Creator comment in PostScript output} line is used). You can also determine the current version from within a MetaPost program via the predefined constant string \texttt{mpversion}\index{mpversion?\texttt{mpversion}}\label{Dmpversion} (since version~0.9). For instance the following code $$\begin{verbatim} message "mp = " & mpversion; \end{verbatim} $$ writes $$\begin{verbatim}[commandchars=\\\{\}] mp = \mpversion \end{verbatim} $$ to the console and the transcript file. \paragraph{Output format} \label{outputformat} MetaPost can generate graphic in two output formats: Encapsulated PostScript\index{PostScript!structured} (EPSF\index{EPSF}), hence the name, and, since version~1.200, Scalable Vector Graphics (SVG\index{SVG}) following version~1.1 of the SVG specification~\cite{w3c:svg1.1}. By default, MetaPost outputs PostScript files. The output format can be changed to SVG by assigning the value \verb|"svg"| to the internal string variable\index{internal variables}\index{variables!internal} \ttindex{outputformat}\label{Doutputformat}: $$\begin{verbatim} outputformat := "svg"; \end{verbatim} $$ Any other value makes MetaPost fall back to PostScript output. Variable \verb|outputformat| is case-sensitive, so assigning it the string \verb|"SVG"| enables PostScript output, too. Default value of variable \verb|outputformat| is \verb|"eps"|. \paragraph{Output file names} \label{outputfilenames} As discussed earlier, by default, every \verb|beginfig/endfig| group in an input file corresponds to an output file that follows the naming scheme $\descr{jobname}{\tt.}\descr{n}$. That is, all files have varying numeric file extensions. MetaPost provides a template mechanism that allows for more flexible output file names. The template mechanism uses \ttt{printf}-style escape sequences that are re-evaluated at ship-out time, i.e., before each figure is written to disk. To configure the output file naming scheme a string containing the corresponding escape sequences has to be assigned to the internal string variable\index{internal variables}\index{variables!internal} \ttt{outputtemplate}% \index{outputtemplate?\texttt{outputtemplate}}\label{Doutputtemplate}. The escape sequences provided are listed in table~\ref{tab:fntmpl}. If this code is saved in a file \ttt{fig.mp}, $$\begin{verbatim} outputtemplate := "%j-%3c.mps"; beginfig(1); draw origin--(100,100); endfig; \end{verbatim} $$ it will create the output file \ttt{fig-001.mps} instead of \ttt{fig.1}. The file extension \texttt{.mps}\index{mps file?{\tt mps} file}\index{files!mps?{\tt mps}} is conventionally chosen for MetaPost's PostScript output (see section~\ref{teximport}). For SVG output one would want to use \texttt{.svg}\index{svg file?{\tt svg} file}\index{files!svg?{\tt svg}} instead. %\suppressfloats[t] \begin{table} \def\d{$\langle$0-9$\rangle$} \centering \begin{tabular}{|>{\ttfamily}l|>{\ttfamily}l|l|} \hline \multicolumn1{|c|}{Escape sequence} & \multicolumn1{c|}{Equivalent} & \multicolumn1{c|}{Meaning}\\\hline \%\%\index{\%\%?\texttt{\%\%}} & & percent sign\\ \%\d\{$\descr{internal variable}$\}\index{\%\{...\}?\texttt{\%\{\ldots\}}} & & evaluate internal variable\\ \%j\index{\%j?\texttt{\%j}} & \%\{jobname\} & current jobname\\ \%\d c\index{\%c?\texttt{\%c}} & \%\d\{charcode\} & charcode value (\verb|beginfig| argument)\\ \%\d y\index{\%y?\texttt{\%y}} & \%\d\{year\} & current year\\ \%\d m\index{\%m?\texttt{\%m}} & \%\d\{month\} & month (numeric)\\ \%\d d\index{\%d?\texttt{\%d}} & \%\d\{day\} & day of the month\\ \%\d H\index{\%H?\texttt{\%H}} & \%\d\{hour\} & hour\\ \%\d M\index{\%M?\texttt{\%M}} & \%\d\{minute\} & minute\\ \hline \end{tabular} \caption{Allowed escape sequences for \ttt{outputtemplate}} \label{tab:fntmpl} \end{table} The template mechanism can also be used for naming graphic files individually, yet keeping all sources in one file. E.\,g., collecting different diagram sources in a file \ttt{fig.mp} $$\begin{verbatim} outputtemplate := "fig-quality.mps"; beginfig(1); ... endfig; outputtemplate := "fig-cost-vs-productivity.mps"; beginfig(2); ... endfig; \end{verbatim} $$ it might be easier to recall the correct diagram names in a \TeX\ document than with numbered file names. Note, the argument to \verb|beginfig| is not relevant as long as there's no \ttt{\%c} pattern in the file name template string. To ensure compatibility with older files, the default value of \ttt{outputtemplate} is \verb|%j.%c|. If you assign an empty string, it will revert to that default. MetaPost versions~1.000 to~1.102 used a different template mechanism, see section~\ref{Dfilenametemplate} for more information. What does one do with all the graphic files? PostScript files are perfectly suitable for inclusion into documents created by \TeX\index{TeX?\TeX} or \emph{troff}\index{troff}. The SVG format, as an XML descendant (Extensible Meta Language), is more aiming at automated data processing/interchanging and is widely used for web applications. The next sections deal with the import of MetaPost graphics into third-party applications. At this point, it seems advisable to point out, that it is good style to create MetaPost graphics at nearly target size. While vector graphics \emph{can} be scaled without quality degradation, the visual character of a drawing might change unintentionally at large post-processing scale factors, because certain properties of a drawing do not scale proportionally, e.g., line width or arrow size. Additionally, while outline fonts do scale proportionally, this is not always desired, e.g., when a font is available in optical sizes, like the Computer Modern font family. \subsection{Previewing MetaPost graphics} \label{previewing} \index{previewing} \index{PostScript!previewing} \index{SVG!previewing} The PostScript output of MetaPost can be previewed with any decent PostScript viewer, e.\,g., GSview\index{GSview}. The situation becomes only a little bit fussy when PostScript graphics contain text. By default, MetaPost doesn't produce self-contained EPS files, e.\,g., font resources and encoding vectors are not stored in the output. For that reason MetaPost output containing text may be rendered with wrong fonts, wrong glyphs or with no text at all in a PostScript viewer. For a long time, the most reliable way for previewing was to prepare a test document that includes all MetaPost figures, process that with \TeX\ or \LaTeX\ and \ttindex{dvips} and display the resulting \ttt{ps} file in a PostScript viewer.\footnote{There are alternatives, though. \ttindex{mpstoeps} is a Perl script that automates the process outlined above. \ttindex{mptopdf} is another tools that converts MetaPost files to PDF.} However, with MetaPost version~1.000 the situation changed. Since that version MetaPost is able to produce self-contained EPS files, that can reliably be previewed, may they contain text or not. The new behaviour can be triggered by setting MetaPost's internal variable \ttt{prologues}\index{prologues?\texttt{prologues}} to~3. See section~\ref{Dbtex} for more information on \ttt{prologues}. Starting with version~1.200, MetaPost is also capable of producing SVG output. SVG files can be previewed with certain web browsers, for example Firefox~3\index{Firefox} or Konqueror~4.2\index{Konqueror}. \subsection{Importing MetaPost graphics in \TeX\ documents} \label{teximport} \index{TeX?\TeX!importing MetaPost files} \index{LaTeX?\LaTeX!importing MetaPost files} \index{pdfLaTeX?pdf\LaTeX!importing MetaPost files} \index{pdfTeX?pdf\TeX!importing MetaPost files} \index{ConTeXt?Con\TeX t!importing MetaPost files} MetaPost graphics in the PostScript format can be easily integreated into documents prepared with \TeX\ and friends. MetaPost's PostScript output is a low-featured dialect of the Postscript language, called \emph{purified EPS}, that can be converted into the Portable Document Format (PDF\index{PDF}) language on-the-fly. For that reason, MetaPost graphics can be handled by both engines, the traditional \TeX\ with an external output driver and the newer pdf\TeX, that contains a built-in PDF output driver. Figure~\ref{fig0} shows the process of including a MetaPost graphic into a plain \TeX\ or \LaTeX\ document. In the \TeX\ document a ``magic macro'' provided by the format or an external package is used for including a graphic file. During the typesetting stage, the macro only reads bounding box information off the PostScript file and reserves the required space on the page via an empty box. The file reference is passed-on to the output driver and only then, finally, the file is embedded into the document. The freely available program \ttindex{dvips} is used as an output driver in this example.\footnote{The C source for \ttt{dvips} comes with the web2c \TeX\ distribution. Similar programs are available from other sources.} The next paragraphs give brief information on some popular combinations of formats and engines. \begin{figure}[htp] $$ \includegraphics{mpman-0.mps} $$ \caption[A diagram of the processing for a document with MetaPost figures] {A diagram of the processing for a \TeX\ document with figures in MetaPost} \label{fig0} \end{figure} \paragraph{Plain \TeX\ with \TeX} For users of \TeX\ with traditional DVI output the \ttt{epsf}\index{epsf.tex?\texttt{epsf.tex}} package provides the ``magic macro'' $$ \verb|\epsfbox{|\descr{filename}\verb|}|% \index{epsfbox?\texttt{\string\epsfbox}} $$ for embedding graphics, e.g., \verb|\epsfbox{fig.1}|. \paragraph{Plain \TeX\ with pdf\TeX} Users of Plain \TeX\ and pdf\TeX\ should refer to the standalone macros of the \ttindex{mptopdf} bundle, that can be found at \url{http://context.aanhet.net/mptopdf.htm}. \paragraph{\LaTeX\ format} For \LaTeX\ documents the well-known \ttindex{graphics} (or \ttindex{graphicx}) package aids in external graphics inclusion. The package supports different engines and can handle several graphic formats. The ``magic macro'' is $$ \verb|\includegraphics{|\descr{filename}\verb|}|% \index{includegraphics?\texttt{\string\includegraphics}} $$ When the \ttt{dvips} driver is chosen, the \ttt{graphics} package assumes all files with an unknown file extension to be in the EPS format. MetaPost files with a numeric default file extension are therefore handled correctly -- even if only in a fall-back procedure (see~\cite{reckdahl:epslatex} for more information). For the pdf\TeX\ driver, the situation is a bit different. Only files with file extension \texttt{.mps}\index{mps file?{\tt mps} file}\index{files!mps?{\tt mps}} are recognized as purified EPS and can be converted to PDF\index{PDF} on-the-fly. The recommended procedure for including MetaPost graphics into \LaTeX\ documents compiled with the pdf\TeX\ engine should be obvious: change MetaPost's output file naming scheme to write files ending \texttt{.mps} via \verb|outputtemplate|\index{outputtemplate?\texttt{outputtemplate}} (see p.~\pageref{Doutputtemplate}). In the \LaTeX\ document include the graphic files with full name, e.g., $$\begin{verbatim} \includegraphics{fig-1.mps} \end{verbatim} $$ Note, the latter approach works with the \ttt{dvips} driver, too. Even though, again, this time \ttt{.mps} is an unknown file extension and triggers EPS file handling in the fall-back procedure. This property of the \ttt{graphics} package, that comes in handy for MetaPost files, is the reason many MetaPost source files start with the line $$\begin{verbatim} outputtemplate := "%j-%c.mps"; \end{verbatim} $$ \paragraph{Con\TeX t} In Con\TeX t\index{ConTeXt?Con\TeX t} support of MetaPost is integrated in the kernel. Apart from inline graphics (see MetaFun\index{MetaFun} manual), one can embed graphics explictely with the \verb+\externalfigure+% \index{externalfigure?\texttt{\string\externalfigure}} command. Numbered graphics are recognized automatically, as are graphics with the \ttt{mps} suffix. Special features like shading, transparency, image inclusion, color spaces and such are handled automatically. In practice Con\TeX t users will probably define MetaPost graphics in the document source which has some advantages, like a more natural interfacing with document properties, font support, and automatic processing. Support for MetaPost inclusion is present in the versions MkII as well as MkIV, but the used methods are slightly different. Future versions of MkIV will support an even more tight integration. \subsection{Importing MetaPost graphics in \emph{troff} documents} \label{troffimport} \index{troff!importing MetaPost files} It is also possible to include MetaPost output in a GNU \emph{troff} document. The procedure is similar to Figure~\ref{fig0}: the \ttt{grops} output processor includes PostScript files when they are requested via \emph{troff}'s \ttt{\string\X} command. The \ttt{-mpspic}\index{mpspic?\texttt{-mpspic}} macro package provides a command \verb|.PSPIC|\index{PSPIC?\texttt{.PSPIC}}, that does just that when including an encapsulated PostScript file in the source code. For instance, the \emph{troff} command $$ \hbox{\verb|.PSPIC fig.1|} $$ includes \ttt{fig.1}, using the natural height and width of the image as given in the file's bounding box. \subsection{Handling SVG files} \label{svgimport} \index{SVG!third-party applications} SVG graphics can be easily embedded into HTML\index{HTML} documents with the following code snippet: $$\begin{verbatim}
\end{verbatim} $$ SVG files can also be imported by various interactive graphics editing programs, for example GIMP\index{GIMP} or Inkscape\index{Inkscape}. See section~\ref{Dprologues} for information on font handling in SVG graphics. \section{Curves} \label{curves} MetaPost is perfectly happy to draw curved lines as well as straight ones. A \verb|draw| statement with the points separated by \verb|..|\index{..?\texttt{..}} draws a smooth curve through the points. For example consider the result of $$ \hbox{\verb|draw z0..z1..z2..z3..z4|} $$ after defining five points as follows: $$\begin{verbatim} z0 = (0,0); z1 = (60,40); z2 = (40,90); z3 = (10,70); z4 = (30,50); \end{verbatim} $$ Figure~\ref{fig2} shows the curve with points \verb|z0| through \verb|z4| labeled. \begin{figure}[htp] $$ \includegraphics{mpman-3.mps} $$ \caption[A curve through points 0, 1, 2, 3, and 4] {The result of {\tt draw z0..z1..z2..z3..z4}} \label{fig2} \end{figure} There are many other ways to draw a curved path through the same five points. To make a smooth closed curve, connect \verb|z4| back to the beginning by appending \verb|..cycle|\index{cycle?\texttt{cycle}} to the \verb|draw| statement as shown in Figure~\ref{fig3}a. It is also possible in a single \verb|draw| statement to mix curves and straight lines as shown in Figure~\ref{fig3}b. Just use \verb|--| where you want straight lines and \verb|..| where you want curves. Thus $$ \hbox{\verb|draw z0..z1..z2..z3--z4--cycle|} $$ produces a curve through points 0,~1, 2, and~3, then a polygonal line from point~3 to point~4 and back to point~0. The result is essentially the same as having two draw statements \begin{eqnarray*} \hbox{\verb|draw z0..z1..z2..z3|}\\ \noalign{\hbox{and}} \hbox{\verb|draw z3--z4--z0|} \end{eqnarray*} \begin{figure}[htp] $$ {\includegraphics{mpman-104.mps} \atop (a)} \qquad {\includegraphics{mpman-204.mps} \atop (b)} $$ \caption[Closed curves through five points] {(a)~The result of {\tt draw z0..\linebreak[0]z1..\linebreak[0]% z2..\linebreak[0]z3..\linebreak[0]z4..\linebreak[0]cycle}; (b)~the result of {\tt draw z0..\linebreak[0]z1..\linebreak[0]% z2..\linebreak[0]z3--\linebreak[0]z4--\linebreak[0]cycle}.} \label{fig3} \end{figure} \subsection{B\'ezier Cubic Curves} When MetaPost is asked to draw a smooth curve through a sequence of points, it constructs a piecewise cubic curve with continuous slope and approximately continuous curvature\index{curvature}. This means that a path specification such as $$ \hbox{\verb|z0..z1..z2..z3..z4..z5|} $$ results in a curve that can be defined parametrically\index{parameterization} as $(X(t),Y(t))$ for $0\le t\le5$, where $X(t)$ and $Y(t)$ are piecewise cubic functions. That is, there is a different pair of cubic functions for each integer-bounded $t$-interval. If ${\tt z0}=(x_0,y_0)$, ${\tt z1}=(x_1,y_1)$, ${\tt z2}=(x_2,y_2)$, \ldots, MetaPost selects B\'ezier control\index{control points} points $(x_0^+,y_0^+)$, $(x_1^-,y_1^-)$, $(x_1^+,y_1^+)$, \ldots, where \begin{eqnarray*} X(t+i) &=& (1-t)^3x_i + 3t(1-t)^2x_i^+ + 3t^2(1-t)x_{i+1}^- + t^3x_{i+1},\\ Y(t+i) &=& (1-t)^3y_i + 3t(1-t)^2y_i^+ + 3t^2(1-t)y_{i+1}^- + t^3y_{i+1} \end{eqnarray*} for $0\le t\le1$. The precise rules for choosing the B\'ezier control points are described in \cite{ho:splin} and in {\sl The \MF book\/}~\cite{kn:c}. In order for the path to have a continuous slope at $(x_i,y_i)$, the incoming and outgoing directions at $(X(i),Y(i))$ must match. Thus the vectors $$ (x_i-x_i^-,\,y_i-y_i^-) \qquad \hbox{and} \qquad (x_i^+-x_i,\,y_i^+-y_i) $$ must have the same direction; i.e., $(x_i,y_i)$ must be on the line segment between $(x_i^-,y_i^-)$ and $(x_i^+,y_i^+)$. This situation is illustrated in Figure~\ref{fig4} where the B\'ezier control points selected by MetaPost are connected by dashed lines. For those who are familiar with the interesting properties of this construction, MetaPost allows the control points to be specified directly in the following format:\index{controls?\texttt{controls}} $$ \begin{verbatim} 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); \end{verbatim} $$ \begin{figure}[htp] $$ \includegraphics{mpman-5.mps} $$ \caption[A curve and the control polygon] {The result of {\tt draw z0..z1..z2..z3..z4} with the automatically-selected B\'ezier control polygon illustrated by dashed lines.} \label{fig4} \end{figure} \subsection{Specifying Direction, Tension, and Curl} \label{tenscurl} MetaPost provides many ways of controlling the behavior of a curved path without actually specifying the control points. For instance, some points on the path may be selected as vertical or horizontal extrema. If \verb|z1| is to be a horizontal extreme and \verb|z2| is to be a vertical extreme, you can specify that $(X(t),Y(t))$ should go upward at \verb|z1| and to the left at \verb|z2|: $$ \hbox{\verb|draw z0..z1{up}..z2{left}..z3..z4;|} $$ The resulting shown in Figure~\ref{fig5} has the desired vertical and horizontal directions at \verb|z1| and \verb|z2|, but it does not look as smooth as the curve in Figure~\ref{fig2}. The reason is the large discontinuity in curvature\index{curvature} at \verb|z1|. If it were not for the specified direction at \verb|z1|, the MetaPost interpreter would have chosen a direction designed to make the curvature above \verb|z1| almost the same as the curvature below that point. \begin{figure}[htp] $$ \includegraphics{mpman-6.mps} $$ \caption[A curve and the control polygon] {The result of {\tt draw z0..z1\char`\{up\char`\}..z2\char`\{left\char`\}% ..z3..z4}.} \label{fig5} \end{figure} How can the choice of directions at given points on a curve determine whether the curvature will be continuous? The reason is that curves used in MetaPost come from a family where a path is determined by its endpoints and the directions there. Figures \ref{fig6} and~\ref{fig7} give a good idea of what this family of curves is like. \begin{figure}[htp] $$ \mathcenter{\includegraphics{mpman-7.mps}} \quad \begin{verbatim} beginfig(7) for a=0 upto 9: draw (0,0){dir 45}..{dir -10a}(6cm,0); endfor endfig; \end{verbatim} $$ \caption{A curve family and the MetaPost instructions for generating it} \label{fig6} \end{figure} \begin{figure}[htp] $$ \mathcenter{\includegraphics{mpman-8.mps}} \quad \begin{verbatim} beginfig(8) for a=0 upto 7: draw (0,0){dir 45}..{dir 10a}(6cm,0); endfor endfig; \end{verbatim} $$ \caption{Another curve family with the corresponding MetaPost instructions} \label{fig7} \end{figure} Figures \ref{fig6} and~\ref{fig7} illustrate a few new MetaPost features. The first is the {\tt dir}\index{dir?\texttt{dir}}\label{Ddirop} operator that takes an angle in degrees and generates a unit vector in that direction. Thus \verb|dir 0| is equivalent to {\tt right}\index{right?\texttt{right}}\label{Dright} and \verb|dir 90| is equivalent to {\tt up}\index{up?\texttt{up}}\label{Dup}. There are also predefined direction vectors {\tt left}\index{left?\texttt{left}}\label{Dleft} and {\tt down}\index{down?\texttt{down}}\label{Ddown} for {\tt dir 180} and {\tt dir 270}. The direction vectors given in \verb|{}| can be of any length, and they can come before a point as well as after one. It is even possible for a path specification to have directions given before and after a point. For example a path specification containing $$ \hbox{\verb|..{dir 60}(10,0){up}..|} $$ produces a curve with a corner at $(10,0)$. Note that some of the curves in Figure~\ref{fig6} have points of inflection\index{inflections}. This is necessary in order to produce smooth curves in situations like Figure~\ref{fig3}a, but it is probably not desirable when dealing with vertical and horizontal extreme points as in Figure~\ref{fig8}a. If \verb|z1| is supposed to be the topmost point on the curve, this can be achieved by using \verb|...|\index{...?\texttt{...}} instead of \verb|..| in the path specification as shown in Figure~\ref{fig8}b. The meaning of \verb|...| is ``choose an inflection-free path between these points unless the endpoint directions make this impossible.'' (It would be possible to avoid inflections in Figure~\ref{fig6}, but not in Figure~\ref{fig7}). \begin{figure}[htp] $$ {\mathcenter{\includegraphics{mpman-109.mps}} \atop \hbox{\verb|draw z0{up}..z1{right}..z2{down}|}} \quad {\mathcenter{\includegraphics{mpman-209.mps}} \atop \hbox{\verb|draw z0{up}...z1{right}...z2{down}|}} $$ \caption{Two {\tt draw} statements and the resulting curves.} \label{fig8} \end{figure} Another way to control a misbehaving path is to increase the ``tension''\index{tension} parameter. Using \verb|..| in a path specification sets the tension parameter to the default value~1. If this makes some part of a path a little too wild, we can selectively increase the tension. If Figure~\ref{fig9}a is considered ``too wild,'' a {\tt draw} statement of the following form increases the tension between {\tt z1} and {\tt z2}: $$ \hbox{\verb|draw z0..z1..tension 1.3..z2..z3|} $$ This produces Figure~\ref{fig9}b. For an asymmetrical effect like Figure~\ref{fig9}c, the \verb|draw| statement becomes $$ \hbox{\verb|draw z0..z1..tension 1.5 and 1..z2..z3|} $$ The tension parameter can be less than one, but it must be at least $3\over4$. \begin{figure}[htp] $$ {\mathcenter{\includegraphics{mpman-110.mps}} \atop (a)} \quad {\mathcenter{\includegraphics{mpman-210.mps}} \atop (b)} \quad {\mathcenter{\includegraphics{mpman-310.mps}} \atop (c)} $$ \caption[Effects of changing the tension parameter] {Results of {\tt draw z0..z1..tension} $\alpha$ {\tt and} $\beta$ {\tt ..z2..z3} for various $\alpha$ and $\beta$: (a)~$\alpha=\beta=1$; (b)~$\alpha=\beta=1.3$; (c)~$\alpha=1.5$, $\beta=1$.} \label{fig9} \end{figure} MetaPost paths also have a parameter called ``curl''\index{curl?\texttt{curl}} that affects the ends of a path. In the absence of any direction specifications, the first and last segments of a non-cyclic path are approximately circular arcs as in the $c=1$ case of Figure~\ref{fig10}. To use a different value for the curl parameter, specify \verb|{curl c}| for some other value of $c$. Thus $$ \hbox{\verb|draw z0{curl c}..z1..{curl c}z2|} $$ sets the curl parameter for \verb|z0| and \verb|z2|. Small values of the curl parameter reduce the curvature\index{curvature} at the indicated path endpoints, while large values increase the curvature as shown in Figure~\ref{fig10}. In particular, a curl value of zero makes the curvature approach zero. \begin{figure}[htp] $$ {\mathcenter{\includegraphics{mpman-111.mps}} \atop c=0} \qquad {\mathcenter{\includegraphics{mpman-211.mps}} \atop c=1} \qquad {\mathcenter{\includegraphics{mpman-311.mps}} \atop c=2} \qquad {\mathcenter{\includegraphics{mpman-411.mps}} \atop c=\infty} $$ \caption[Effects of changing the curl parameter] {Results of {\tt draw z0\char`\{curl c\char`\}..z1..% \char`\{curl c\char`\}z2} for various values of the curl parameter~$c$.} \label{fig10} \end{figure} \subsection{Summary of Path Syntax} There are a few other features of MetaPost path syntax, but they are relatively unimportant. Since \MF\ uses the same path syntax, interested readers can refer to \cite[chapter 14]{kn:c}. The summary of path syntax in Figure~\ref{sypath} includes everything discussed so far including the \verb|--| and \verb|...| constructions which \cite{kn:c} shows to be macros rather than primitives. A few comments on the semantics are in order here: If there is a non-empty $\descr{direction specifier}$ before a $\descr{path knot}$ but not after it, or vice versa, the specified direction (or curl amount) applies to both the incoming and outgoing path segments. A similar arrangement applies when a $\descr{controls}$ specification gives only one $\descr{pair primary}$. Thus $$ \hbox{\verb|..controls (30,20)..|} $$ is equivalent to $$ \hbox{\verb|...controls (30,20) and (30,20)..|} $$ \begin{figure}[htp] \begin{ctabbing} $\descr{path expression} \rightarrow \descr{path subexpression}$\\ \qquad \= ${}\mid \descr{path subexpression} \descr{direction specifier}$\\ \> ${}\mid \descr{path subexpression} \descr{path join}$ \verb|cycle|\\ $\descr{path subexpression} \rightarrow \descr{path knot}$\\ \> ${}\mid \descr{path expression} \descr{path join} \descr{path knot}$\\ $\descr{path join} \rightarrow \hbox{\verb|--|}$\\ \> ${}\mid \descr{direction specifier} \descr{basic path join} \descr{direction specifier}$\\ $\descr{direction specifier} \rightarrow \descr{empty}$\\ \> ${}\mid {}$\verb|{curl| $\descr{numeric expression}$\verb|}|\\ \> ${}\mid {}$\verb|{|$\descr{pair expression}$\verb|}|\\ \> ${}\mid {}$\verb|{|$\descr{numeric expression}$\verb|,|% $\descr{numeric expression}$\verb|}|\\ $\descr{basic path join} \rightarrow \hbox{\verb|..|} \mid \hbox{\verb|...|} \mid \hbox{\verb|..|}\descr{tension}\hbox{\verb|..|} \mid \hbox{\verb|..|}\descr{controls}\hbox{\verb|..|}$\\ $\descr{tension} \rightarrow \hbox{\verb|tension|}\descr{numeric primary}$\\ \> ${}\mid \hbox{\verb|tension|}\descr{numeric primary} \hbox{\verb|and|}\descr{numeric primary}$\\ $\descr{controls} \rightarrow \hbox{\verb|controls|}\descr{pair primary}$\\ \> ${}\mid \hbox{\verb|controls|}\descr{pair primary} \hbox{\verb|and|}\descr{pair primary}$ \end{ctabbing} \caption{The syntax for path construction} \label{sypath} \end{figure} A pair of coordinates like \verb|(30,20)| or a \verb|z| variable that represents a coordinate pair is what Figure~\ref{sypath} calls a $\descr{pair primary}$. A $\descr{path knot}$ is similar except that it can take on other forms such as a path expression in parentheses. Primaries and expressions of various types will be discussed in full generality in Section~\ref{exprs}. \section{Linear Equations} \label{lin.eq} An important feature taken from \MF\ is the ability to solve linear equations so that programs can be written in a partially declarative fashion. For example, the MetaPost interpreter can read $$ \hbox{\verb|a+b=3; 2a=b+3;|} $$ and deduce that $a=2$ and $b=1$. The same equations can be written slightly more compactly by stringing them together with multiple equal signs: $$ \hbox{\verb|a+b = 2a-b = 3;|} $$ Whichever way you give the equations, you can then give the command\index{show?\texttt{show}} $$ \hbox{\tt show a,b;} $$ to see the values of {\tt a} and {\tt b}. MetaPost responds by typing $$\begin{verbatim} >> 2 >> 1 \end{verbatim} $$ Note that {\tt =}\index{=?\texttt{=}} is not an assignment operator; it simply declares that the left-hand side equals the right-hand side. Thus {\tt a=a+1} produces an error message complaining about an ``inconsistent equation\index{Inconsistent equation?\texttt{Inconsistent equation}}.'' The way to increase the value of {\tt a} is to use the assignment\index{assignment} operator {\tt :=}\index{:=?\texttt{:=}} as follows: $$ \hbox{\tt a:=a+1;} $$ In other words, {\tt :=} is for changing existing values while {\tt =} is for giving linear equations to solve. There is no restriction against mixing equations and assignment operations as in the following example: $$ \hbox{\tt a = 2; b = a; a := 3; c = a;} $$ After the first two equations set {\tt a} and~{\tt b} equal to 2, the assignment operation changes {\tt a} to~3 without affecting {\tt b}. The final value of {\tt c} is 3 since it is equated to the new value of {\tt a}. In general, an assignment operation is interpreted by first computing the new value, then eliminating the old value from all existing equations before actually assigning the new value. \subsection{Equations and Coordinate Pairs} MetaPost can also solve linear equations involving coordinate pairs. We have already seen many trivial examples of this in the form of equations like $$ \hbox{\verb|z1=(0,.2in)|} $$ Each side of the equation must be formed by adding or subtracting coordinate pairs and multiplying or dividing them by known numeric quantities. Other ways of naming pair-valued variables will be discussed later, but the ${\tt z}\descr{number}$\index{z convention?{\tt z} convention} is convenient because it is an abbreviation for $$ \hbox{\tt (x}\descr{number} \hbox{\tt, y}\descr{number}\hbox{\tt)} $$ This makes it possible to give values to \verb|z| variables by giving equations involving their coordinates. For instance, points {\tt z1}, {\tt z2}, {\tt z3}, and~{\tt z6} in Figure~\ref{fig12} were initialized via the following equations: \begin{eqnarray*} &&\hbox{\verb|z1=-z2=(.2in,0);|} \\ &&\hbox{\verb|x3=-x6=.3in;|} \\ &&\hbox{\verb|x3+y3=x6+y6=1.1in;|} \end{eqnarray*} Exactly the same points could be obtained by setting their values directly: $$ \begin{verbatim} z1=(.2in,0); z2=(-.2in,0); z3=(.3in,.8in); z6=(-.3in,1.4in); \end{verbatim} $$ After reading the equations, the MetaPost interpreter knows the values of {\tt z1}, {\tt z2}, {\tt z3}, and~{\tt z6}. The next step in the construction of Figure~\ref{fig12} is to define points {\tt z4} and {\tt z5} equally spaced along the line from {\tt z3} to {\tt z6}. Since this operation comes up often, MetaPost has a special syntax for it. This mediation construction\index{mediation}\index{[]?\texttt{[]}!mediation} $$ \hbox{\verb|z4=1/3[z3,z6]|} $$ means that {\tt z4} is $1\over3$ of the way from $z3$ to $z6$; i.e., $$ {\tt z4}={\tt z3}+{1\over3}({\tt z6}-{\tt z3}). $$ Similarly $$ \hbox{\verb|z5=2/3[z3,z6]|} $$ makes {\tt z5} $2\over3$ of the way from $z3$ to $z6$. \begin{figure}[htp] $$ \begin{verbatim} 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; \end{verbatim} \quad \mathcenter{\includegraphics{mpman-13.mps}} $$ \caption[MetaPost code and figure using linear equations] {MetaPost commands and the resulting figure. Point labels have been added to the figure for clarity.} \label{fig12} \end{figure} Mediation can also be used to say that some point is at an unknown position along the line between two known points. For instance, we could a introduce new variable {\tt aa} and write something like $$ \hbox{\verb|z20=aa[z1,z3];|} $$ This says that {\tt z20} is some unknown fraction {\tt aa} of the way along the line between {\tt z1} and {\tt z3}. Another such equation involving a different line is sufficient to fix the value of {\tt z20}. To say that {\tt z20} is at the intersection of the {\tt z1}-{\tt z3} line and the {\tt z2}-{\tt z4} line, introduce another variable {\tt ab} and set $$ \hbox{\verb|z20=ab[z2,z4];|} $$ This allows MetaPost to solve for {\tt x20}, {\tt y20}, {\tt aa}, and {\tt ab}. It is a little painful to keep thinking up new names like {\tt aa} and {\tt ab}. This can be avoided by using a special feature called {\tt whatever}\index{whatever?\texttt{whatever}}\label{Dwhatev}. This macro generates a new anonymous variable each time it appears. Thus the statement $$ \hbox{\verb|z20=whatever[z1,z3]=whatever[z2,z4]|} $$ sets {\tt z20} as before, except it uses {\tt whatever} to generate two {\em different\/} anonymous variables instead of {\tt aa} and {\tt ab}. This is how Figure~\ref{fig12} sets {\tt z20}, {\tt z30}, and {\tt z40}. \subsection{Dealing with Unknowns} A system of equations such as those used in Figure~\ref{fig12} can be given in any order as long as all the equations are linear and all the variables can be determined before they are needed. This means that the equations \begin{eqnarray*} && \hbox{\verb|z1=-z2=(.2in,0);|}\\ && \hbox{\verb|x3=-x6=.3in;|}\\ && \hbox{\verb|x3+y3=x6+y6=1.1in;|}\\ && \hbox{\verb|z4=1/3[z3,z6];|}\\ && \hbox{\verb|z5=2/3[z3,z6];|} \end{eqnarray*} suffice to determine {\tt z1} through {\tt z6}, no matter what order the equations are given in. On the other hand $$ \hbox{\verb|z20=whatever[z1,z3]|} $$ is legal only when a known value has previously been specified for the difference ${\tt z3}-{\tt z1}$, because the equation is equivalent to\index{mediation} $$ \hbox{\verb|z20 = z1 + whatever*(z3-z1)|} $$ and the linearity requirement disallows multiplying unknown components of ${\tt z3}-{\tt z1}$ by the anonymous unknown result of {\tt whatever}. The general rule is that you cannot multiply two unknown quantities or divide by an unknown quantity, nor can an unknown quantity be used in a {\tt draw} statement. Since only linear equations are allowed, the MetaPost interpreter can easily solve the equations and keep track of what values are known. The most natural way to ensure that MetaPost can handle an expression like $$ \hbox{\verb|whatever[z1,z3]|} $$ is to ensure that {\tt z1} and {\tt z3} are both known. However this is not actually required since MetaPost may be able to deduce a known value for ${\tt z3}-{\tt z1}$ before either of {\tt z1} and {\tt z3} are known. For instance, MetaPost will accept the equations $$ \hbox{\verb|z3=z1+(.1in,.6in); z20=whatever[z1,z3];|} $$ but it will not be able to determine any of the components of {\tt z1}, {\tt z3}, or {\tt z20}. These equations do give partial information about {\tt z1}, {\tt z3}, and {\tt z20}. A good way to see this is to give another equation such as $$ \hbox{\verb|x20-x1=(y20-y1)/6;|} $$ This produces the error message ``{\tt ! Redundant equation}\index{Redundant equation?\texttt{Redundant equation}}.'' MetaPost assumes that you are trying to tell it something new, so it will usually warn you when you give a redundant equation. If the new equation had been $$ \hbox{\verb|(x20-x1)-(y20-y1)/6=1in;|} $$ the error message would have been\index{Inconsistent equation?\texttt{Inconsistent equation}} $$ \hbox{\verb|! Inconsistent equation (off by 71.99979).|} $$ This error message illustrates roundoff\index{roundoff error} error in MetaPost's linear equation solving mechanism. Roundoff error is normally not a serious problem, but it is likely to cause trouble if you are trying to do something like find the intersection of two lines that are almost parallel. \section{Expressions} \label{exprs} It is now time for a more systematic view of the MetaPost language. We have seen that there are numeric quantities and coordinate pairs, and that these can be combined to specify paths for {\tt draw} statements. We have also seen how variables can be used in linear equations, but we have not discussed all the operations and data types that can be used in equations. It is possible to experiment with expressions involving any of the data types mentioned below by using the statement\index{show?\texttt{show}}\label{Dshow} $$ {\tt show}\, \descr{expression} $$ to ask MetaPost to print a symbolic representation of the value of each expression. For known numeric values, each is printed on a new line preceded by ``\verb|>> |''. Other types of result are printed similarly, except that complicated values are sometimes not printed on standard output. This produces a reference to the transcript file\index{files!transcript} that looks like this: $$ \hbox{\verb|>> picture (see the transcript file)|} $$ If you want to the full results of {\tt show} statements to be printed on your terminal, assign a positive value to the internal\index{internal variables} variable\index{variables!internal} {\tt tracingonline}\index{tracingonline?\texttt{tracingonline}}\label{Dtonline}. \subsection{Data Types} MetaPost actually has ten basic data types\index{types}: numeric, pair, path, transform, (rgb)color, cmykcolor, string, boolean, picture, and pen. Let us consider these one at a time beginning with the numeric type. Numeric\index{numeric type} quantities in MetaPost are represented in fixed point arithmetic\index{arithmetic} as integer multiples of $1\over65536$. They must normally have absolute values less than 4096 but intermediate results can be eight times larger. This should not be a problem for distances or coordinate values since 4096 PostScript points is more than 1.4~meters. If you need to work with numbers of magnitude 4096 or more, setting the internal variable {\tt warningcheck}\index{warningcheck?\texttt{warningcheck}}\label{Dwarncheck} to zero suppresses the warning messages about large numeric quantities. The pair\index{pair type} type is represented as a pair of numeric quantities. We have seen that pairs are used to give coordinates in {\tt draw} statements. Pairs can be added, subtracted, used in mediation expressions, or multiplied or divided by numerics. Paths\index{path type} have already been discussed in the context of {\tt draw} statements, but that discussion did not mention that paths are first-class objects that can be stored and manipulated. A path represents a straight or curved line that is defined parametrically. Another data type represents an arbitrary affine transformation\index{transform type}. A {\em transform\/} can be any combination of rotating, scaling, slanting, and shifting. If ${\tt p}=(p_x,p_y)$ is a pair and {\tt T} is a transform,\index{transformed?\texttt{transformed}} $$ \hbox{\tt p transformed T} $$ is a pair of the form $$ (t_x+t_{xx}p_x+t_{xy}p_y, t_y+t_{yx}p_x+t_{yy}p_y), $$ where the six numeric quantities $(t_x,t_y,t_{xx},t_{xy},t_{yx},t_{yy})$ determine {\tt T}. Transforms can also be applied to paths, pictures, pens, and transforms. The color\index{color type} type is like the pair type, except that it has three components instead of two and each component is normally between 0 and 1. Like pairs, colors can be added, subtracted, used in mediation expressions, or multiplied or divided by numerics. Colors can be specified in terms of the predefined constants \ttindex{black}\label{Dblack}, \ttindex{white}\label{Dwhite}, \ttindex{red}\label{Dred}, \ttindex{green}\label{Dgreen}, \ttindex{blue}\label{Dblue}, or the red, green, and blue components can be given explicitly. Black is {\tt (0,0,0)} and white is {\tt (1,1,1)}. A level of gray such as {\tt (.4,.4,.4)} can also be specified as {\tt 0.4white}. Although color typed variables may be any ordered triplet, when adding an object to a picture, MetaPost will convert its color by clipping each component between 0 and 1. For example, MetaPost will output the color (1,2,3) as (1,1,1). MetaPost solves linear equations involving colors the same way it does for pairs. The type `rgbcolor' is an alias of type `color'. The cmykcolor\index{cmykcolor type} type is similar to the color type except that it has four components instead of three. This type is used to specify colors by their cyan, magenta, yellow, and black components explicitly. Because CMYK colors deal with pigments instead of light rays, the color white would be expressed as {\tt (0,0,0,0)} and black as {\tt (0,0,0,1)}. In theory, the colors {\tt ($c$,$m$,$y$,1)} and {\tt (1,1,1,$k$)} should result in black for any values of $c$, $m$, $y$ and~$k$, too. But in practice, this is avoided since it is a waste of colored ink and can lead to unsatisfactory results. A string\index{string type} represents a sequence of characters. String constants\index{string constants} are given in double quotes \hbox{\verb|"like this"|}. String constants cannot contain double quotes or newlines, but there is a way to construct a string containing any sequence of eight-bit characters. \label{Dscantokens} Conversion from strings to other types, notably numeric, can be accomplished by the {\tt scantokens}\index{scantokens?\texttt{scantokens}} primitive: \begin{center}\texttt{n := scantokens(}\textit{str}\texttt{);}\end{center} More generally, \texttt{scantokens} parses a string into a token sequence, as if MetaPost had read it as input. The boolean\index{boolean type} type has the constants {\tt true}\index{true?\texttt{true}}\label{Dtrue} and {\tt false}\index{false}\label{Dfalse} and the operators {\tt and}\index{and?\texttt{and}}\label{Dand}, {\tt or}\index{or?\texttt{or}}\label{Dor}, {\tt not}\index{not?\texttt{not}}\label{Dnot}. The relations \verb|=| and \verb|<>|\index{<>?\texttt{<>}}\label{Dcmpar} test objects of any type for equality and inequality\index{inequality}. Comparison\index{comparison} relations \verb|<|\index{\texttt{<}}, \verb|<=|\index{<=?\texttt{<=}}, \verb|>|\index{>?\texttt{>}}, and \verb|>=|\index{>=?\texttt{>=}} are defined lexicographically for strings and in the obvious way for numerics. Ordering relations are also defined for booleans, pairs, colors, and transforms, but the comparison rules are not worth discussing here. The picture\index{picture type} data type is just what the name implies. Anything that can be drawn in MetaPost can be stored in a picture variable. In fact, the {\tt draw}\index{draw?\texttt{draw}} statement actually stores its results in a special picture variable called {\tt currentpicture}\index{currentpicture?\texttt{currentpicture}}. Pictures can be added to other pictures and operated on by transforms. Finally, there is a data type called a pen\index{pen type}. The main function of pens in MetaPost is to determine line thickness, but they can also be used to achieve calligraphic effects. The statement\index{pickup?\texttt{pickup}}\label{Dpickup} $$ {\tt pickup\ }\descr{pen expression} $$ causes the given pen to be used in subsequent {\tt draw} statements. Normally, the pen expression is of the form $$ {\tt pencircle\ scaled\ }\descr{numeric primary}. $$ This defines a circular pen that produces lines of constant thickness. If calligraphic effects are desired, the pen expression can be adjusted to give an elliptical pen or a polygonal pen. \subsection{Operators} There are many different ways to make expressions of the ten basic types, but most of the operations fit into a fairly simple syntax with four levels of precedence as shown in Figure~\ref{syexpr}. There are primaries\index{primary?\tdescr{primary}}, secondaries\index{secondary?\tdescr{secondary}}, tertiaries\index{tertiary?\tdescr{tertiary}}, and expressions\index{expression?\tdescr{expression}} of each of the basic types, so the syntax rules could be specialized to deal with items such as \tdescr{numeric primary}, \tdescr{boolean tertiary}, etc. This allows the result type for an operation to depend on the choice of operator and the types of its operands. For example, the {\tt <} relation is a \tdescr{tertiary binary} that can be applied to a \tdescr{numeric expression} and a \tdescr{numeric tertiary} to give a \tdescr{boolean expression}. The same operator can accept other operand types such as \tdescr{string expression} and \tdescr{string tertiary}, but an error message results if the operand types do not match. \begin{figure}[htp] \begin{ctabbing} $\tt \descr{primary} \rightarrow \descr{variable}$\\ $\tt \qquad \;|\; \hbox{\tt (}\descr{expression}\hbox{\tt )}$\\ $\tt \qquad \;|\; \descr{nullary op}$\\ $\tt \qquad \;|\; \descr{of operator} \descr{expression} of \descr{primary}$\\ $\tt \qquad \;|\; \descr{unary op} \descr{primary}$\\ $\tt \descr{secondary} \rightarrow \descr{primary}$\\ $\tt \qquad \;|\; \descr{secondary} \descr{primary binop} \descr{primary}$\\ $\tt \descr{tertiary} \rightarrow \descr{secondary}$\\ $\tt \qquad \;|\; \descr{tertiary} \descr{secondary binop} \descr{secondary}$\\ $\tt \descr{expression} \rightarrow \descr{tertiary}$\\ $\tt \qquad \;|\; \descr{expression} \descr{tertiary binop} \descr{tertiary}$ \end{ctabbing} \caption{The overall syntax rules for expressions} \index{unary op?\tdescr{unary op}} \index{nullary op?\tdescr{nullary op}} \index{primary binop?\tdescr{primary binop}} \index{secondary binop?\tdescr{secondary binop}} \index{tertiary binop?\tdescr{tertiary binop}} \label{syexpr} \end{figure} The multiplication and division operators {\tt *}\label{Dmldiv} and~{\tt /} are examples of what Figure~\ref{syexpr} calls a \tdescr{primary binop}. Each can accept two numeric operands or one numeric operand and one operand of type pair or color. The exponentiation operator \verb|**|\index{**?\texttt{**}}\index{exponentiation}\label{Dpow} is a \tdescr{primary binop} that requires two numeric operands. Placing this at the same level of precedence as multiplication and division has the unfortunate consequence that \verb|3*a**2| means $(3a)^2$, not $3(a^2)$\index{parsing irregularities}. Since unary negation\label{Dneg} applies at the primary level, it also turns out that \verb|-a**2| means $(-a)^2$. Fortunately, subtraction has lower precedence so that \verb|a-b**2| does mean $a-(b^2)$ instead of $(a-b)^2$. Another \tdescr{primary binop} is the {\tt dotprod}\index{dotprod?\texttt{dotprod}}\label{Ddprod} operator that computes the vector dot product of two pairs. For example, {\tt z1 dotprod z2} is equivalent to {\tt x1*x2 + y1*y2}. The additive operators {\tt +} and {\tt -}\label{Dadd} are \tdescr{secondary binops} that operate on numerics, pairs, or colors and produce results of the same type. Other operators that fall in this category are ``Pythagorean addition'' \verb|++|\index{++?\texttt{++}}\label{Dpyadd} and ``Pythagorean subtraction'' \verb|+-+|\index{+-+?\texttt{+-+}}\label{Dpysub}: \verb|a++b| means $\sqrt{a^2+b^2}$ and \verb|a+-+b| means $\sqrt{a^2-b^2}$. There are too many other operators to list here, but some of the most important are the boolean operators {\tt and}\index{and?\texttt{and}} and {\tt or}\index{or?\texttt{or}}. The {\tt and} operator is a \tdescr{primary binop} and the {\tt or} operator is a \tdescr{secondary binop}. The basic operations on strings are concatenation\index{concatenation}, substring construction and calculating the length of a string. The \tdescr{tertiary binop} \verb|&|\index{&?\texttt{\&}}\label{Damp} implements concatenation; e.g., $$ \hbox{\verb|"abc" & "de"|} $$ produces the string \verb|"abcde"|. The {\tt length}\index{length?\texttt{length}}\label{DlengthString} operator returns the number of characters in a string if the argument is a \tdescr{string primary}; e.g., $$ \hbox{\verb|length "abcde"|} $$ returns \verb|5|. Another application of the {\tt length} operator is discussed on p.\ \pageref{Dlength}. For substring construction, the \tdescr{of operator} {\tt substring}\index{substring of?\texttt{substring of}}\label{Dsubstr} is used like this: $$ {\tt substring}\, \descr{pair expression} \,{\tt of}\, \descr{string primary} $$ The \tdescr{pair expression} determines what part of the string to select. For this purpose, the string is indexed\index{indexing} so that integer positions fall {\em between\/} characters. Pretend the string is written on a piece of graph paper so that the first character occupies $x$~coordinates between zero and one and the next character covers the range $1\le x\le2$, etc. Thus the string \verb|"abcde"| should be thought of like this $$ \includegraphics{mpman-14.mps} $$ and {\tt substring (2,4) of "abcde"} is {\tt "cd"}. This takes a little getting used to but it tends to avoid annoying ``off by one'' errors. Some operators take no arguments at all. An example of what Figure~\ref{syexpr} calls a \tdescr{nullary op} is {\tt nullpicture}\index{nullpicture?\texttt{nullpicture}}\label{Dnlpic} which returns a completely blank picture. The basic syntax in Figure~\ref{syexpr} only covers aspects of the expression syntax that are relatively type-independent. For instance, the complicated path syntax given in Figure~\ref{sypath} gives alternative rules for constructing a \tdescr{path expression}. An additional rule\index{path knot?\tdescr{path knot}} $$ \descr{path knot} \rightarrow \descr{pair tertiary} \;|\; \descr{path tertiary} $$ explains the meaning of \tdescr{path knot} in Figure~\ref{sypath}. This means that the path expression $$ \hbox{\verb|z1+(1,1){right}..z2|} $$ does not need parentheses around {\tt z1+(1,1)}. \subsection{Fractions, Mediation, and Unary Operators} Mediation\index{mediation} expressions do not appear in the basic expression syntax of Figure~\ref{syexpr}. Mediation expressions are parsed at the \tdescr{primary} level, so the general rule for constructing them is $$ \descr{primary} \rightarrow \descr{numeric atom} \hbox{\tt [} \descr{expression} \hbox{\tt ,} \descr{expression} \hbox{\tt ]} $$ where each \tdescr{expression} can be of type numeric, pair, or color. The \tdescr{numeric atom}\index{numeric atom?\tdescr{numeric atom}} in a mediation expression is an extra simple type of \tdescr{numeric primary} as shown in Figure~\ref{synprim}. The meaning of 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 fraction. For example,\index{parsing irregularities} $$ \hbox{\tt -1[a,b]} \quad {\rm and}\quad \hbox{\tt (-1)[a,b]} $$ are very different: the former is $-b$ since it is equivalent to {\tt -(1[a,b])}; the latter is $a-(b-a)$ or $2a-b$. \begin{figure}[htp] \begin{ctabbing} $\tt \descr{numeric primary} \rightarrow \descr{numeric atom}$\\ $\tt \qquad \;|\; \descr{numeric atom}\hbox{\tt [} \descr{numeric expression}\hbox{\tt ,}\descr{numeric expression}\hbox{\tt ]}$\\ $\tt \qquad \;|\; \descr{of operator} \descr{expression} of \descr{primary}$\\ $\tt \qquad \;|\; \descr{unary op} \descr{primary}$\\ $\tt \descr{numeric atom} \rightarrow \descr{numeric variable}$\\ $\tt \qquad \;|\; \descr{number or fraction}$\\ $\tt \qquad \;|\; \hbox{\tt (}\descr{numeric expression}\hbox{\tt )}$\\ $\tt \qquad \;|\; \descr{numeric nullary op}$\\ $\tt \descr{number or fraction} \rightarrow \descr{number} \hbox{\tt /}\descr{number}$\\ $\tt \qquad \;|\; \descr{number not followed by `$\hbox{\tt /}\descr{number}$'}$ \end{ctabbing} \caption{Syntax rules for numeric primaries} \label{synprim} \end{figure} A noteworthy feature of the syntax rules in Figure~\ref{synprim} is that the {\tt /}\index{fractions} operator binds most tightly when its operands are numbers. Thus {\tt 2/3} is a \tdescr{numeric atom}\index{numeric atom?\tdescr{numeric atom}}\index{parsing irregularities} while {\tt (1+1)/3} is only a \tdescr{numeric secondary}. Applying a \tdescr{unary op} such as {\tt sqrt}\index{sqrt?\texttt{sqrt}}\label{Dsqrt} makes the difference clear: $$ \hbox{\tt sqrt 2/3} $$ means $\sqrt{2\over3}$ while $$ \hbox{\tt sqrt(1+1)/3} $$ means $\sqrt 2/3$. Operators such as {\tt sqrt} can be written in standard functional notation, but it is often unnecessary to parenthesize the argument. This applies to any function that is parsed as a \tdescr{unary op}. For instance {\tt abs(x)}\index{abs?\texttt{abs}}\label{Dabs} and {\tt abs x} both compute the absolute value of {\tt x}. The same holds for the {\tt round}\index{round?\texttt{round}}\label{Dround}, {\tt floor}\index{floor?\texttt{floor}}\label{Dfloor}, {\tt ceiling}\index{ceiling?\texttt{ceiling}}\label{Dceil}, {\tt sind}\index{sind?\texttt{sind}}\label{Dsind}, and {\tt cosd}\index{cosd?\texttt{cosd}}\label{Dcosd} functions. The last two of these compute trigonometric functions of angles in degrees. Not all unary operators take numeric arguments and return numeric results. For instance, the {\tt abs}\index{abs?\texttt{abs}} operator can be applied to a pair to compute the Euclidean length of a vector. Applying the {\tt unitvector}\index{unitvector?\texttt{unitvector}}\label{Duvec} operator to a pair produces the same pair rescaled so that its Euclidean length is~1. The {\tt decimal}\index{decimal?\texttt{decimal}}\label{Ddecop} operator takes a number and returns the string representation. The {\tt angle}\index{angle?\texttt{angle}}\label{Dangle} operator takes a pair and computes the two-argument arctangent; i.e., {\tt angle} is the inverse of the {\tt dir} operator that was discussed in Section~\ref{tenscurl}. There is also an operator {\tt cycle}\index{cycle?\texttt{cycle}}\label{Dcycop} that takes a \tdescr{path primary} and returns a boolean result indicating whether the path is a closed curve. There is a whole class of other operators that classify expressions and return boolean results. A type name such as {\tt pair}\index{pair?\texttt{pair}} can operate on any type of \tdescr{primary} and return a boolean result indicating whether the argument is a {\tt pair}\label{Dpairop}. Similarly, each of the following can be used as a unary operator: {\tt numeric}\index{numeric?\texttt{numeric}}\label{Dnumop}, {\tt boolean}\index{boolean?\texttt{boolean}}\label{Dboolop}, {\tt cmykcolor}\index{cmykcolor?\texttt{cmykcolor}}\label{Dccolrop}, {\tt color}\index{color?\texttt{color}}\label{Dcolrop}, {\tt string}\index{string?\texttt{string}}\label{Dstrgop}, {\tt transform}\index{transform?\texttt{transform}}\label{Dtrnfop}, {\tt path}\index{path?\texttt{path}}\label{Dpathop}, {\tt pen}\index{pen?\texttt{pen}}\label{Dpenop}, {\tt picture}\index{picture?\texttt{picture}}\label{Dpictop}, and {\tt rgbcolor}\index{rgbcolor?\texttt{rgbcolor}}\label{Drcolrop}. Besides just testing the type of a \tdescr{primary}, you can use the {\tt known}\index{known?\texttt{known}}\label{Dknown} and {\tt unknown}\index{unknown?\texttt{unknown}}\label{Dunknwn} operators to test if it has a completely known value. Even a number can behave like an operator in some contexts. This refers to the trick that allows {\tt 3x}\index{multiplication, implicit} and {\tt 3cm} as alternatives to {\tt 3*x} and {\tt 3*cm}. The rule is that a \tdescr{number or fraction} that is not followed by {\tt +}, {\tt -}, or another \tdescr{number or fraction} can serve as a \tdescr{primary binop}. Thus {\tt 2/3x}\index{parsing irregularities} is two thirds of {\tt x} but {\tt (2)/3x} is $2\over3x$ and {\tt 3 3} is illegal. There are also operators for extracting numeric subfields from pairs, colors, cmykcolors, and even transforms. If {\tt p} is a \tdescr{pair primary}, {\tt xpart p}\index{xpart?\texttt{xpart}}\label{Dxprt} and {\tt ypart p}\index{ypart?\texttt{ypart}}\label{Dyprt} extract its components so that $$ \hbox{\tt (xpart p, ypart p)} $$ is equivalent to~{\tt p} even if {\tt p} is an unknown pair that is being used in a linear equation. Similarly, a color {\tt c} is equivalent to\index{redpart?\texttt{redpart}}% \index{greenpart?\texttt{greenpart}}% \index{bluepart?\texttt{bluepart}}\label{Drgbprt} $$ \hbox{\tt (redpart c, greenpart c, bluepart c)}. $$ For a cmykcolor {\tt c}, the components are% \index{cyanpart?\texttt{cyanpart}}% \index{magentapart?\texttt{magentapart}}% \index{yellowpart?\texttt{yellowpart}}% \index{blackpart?\texttt{blackpart}}\label{Dcmykprt} $$ \hbox{\tt (cyanpart c, magentapart c, yellowpart c, blackpart c)} $$ and for a greyscale color {\tt c}, there is only one component% \index{greypart?\texttt{greypart}}\label{Dgreyprt}% $$ \hbox{\tt greypart c}. $$ All color component operators are discussed in more detail in section~\ref{piccomp}. Part specifiers for transforms are discussed in section~\ref{transsec}. \section{Variables} \label{vars} MetaPost allows compound variable names such as {z.a}, {\tt x2r}, {\tt y2r}, and {\tt z2r}, where {\tt z2r} means {\tt (x2r,y2r)} and {\tt z.a} means {\tt (x.a,y.a)}. In fact there is a broad class of suffixes such that {\tt z}\tdescr{suffix}\index{suffix?\tdescr{suffix}} means $$ (x\descr{suffix},\, y\descr{suffix}). $$ Since a \tdescr{suffix} is composed of tokens, it is best to begin with a few comments about tokens. \subsection{Tokens} A MetaPost input file is treated as a sequence of numbers, string constants, and symbolic tokens\index{tokens}\index{tokens!symbolic}. A number consists of a sequence of digits possibly containing a decimal point. Technically, the minus sign in front of a negative number is a separate token. Since MetaPost uses fixed point arithmetic\index{arithmetic}, it does not understand exponential notation such as {\tt 6.02E23}. MetaPost would interpret this as the number 6.02, followed by the symbolic token {\tt E}, followed by the number~23. Anything between a pair of double quotes {\tt "} is a string constant\index{string constants}. It is illegal for a string constant to start on one line and end on a later line. Nor can a string constant contain double quotes {\tt "} or anything other than printable ASCII characters. Everything in a line of input other than numbers and string constants is broken into symbolic tokens\index{tokens!symbolic}. A symbolic token is a sequence of one or more similar characters, where characters are ``similar'' if they occur on the same row of Table~\ref{classes}. \begin{table} $$\begin{tabular}{c} \verb|ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz|\\ {\tt :<=>|}\\ \verb|#&@$|\\ \verb|/*\|\\ {\tt +-}\\ {\tt !?}\\ {\tt '`}\\ \verb|^~|\\ \verb|{}|\\ {\tt [}\\ {\tt ]}\\ \end{tabular} $$ \caption{Character classes for tokenization} \label{classes} \end{table} Thus \verb|A_alpha| and {\tt +-+} are symbolic tokens but {\tt !=} is interpreted as two tokens and {\tt x34} is a symbolic token followed by a number. Since the brackets {\tt [} and {\tt ]} are listed on lines by themselves, the only symbolic tokens involving them are {\tt [}, {\tt [[}, {\tt [[[}, etc.\ and {\tt ]}, {\tt ]]}, etc. Some characters are not listed in Table~\ref{classes} because they need special treatment. The four characters {\tt ,;()} are ``loners'': each comma, semicolon, or parenthesis is a separate token even when they occur consecutively. Thus {\tt (())} is four tokens, not one or two. The percent sign is very special because it introduces comments\index{comments}. The percent sign and everything after it up to the end of the line are ignored. Another special character is the period. Two or more periods together form a symbolic token, but a single period is ignored, and a period preceded or followed by digits is part of a number Thus {\tt ..} and {\tt ...} are symbolic tokens while {\tt a.b} is just two tokens {\tt a} and {\tt b}. It conventional to use periods to separate tokens in this fashion when naming a variable that is more than one token long. \subsection{Variable Declarations} \label{vardecl} A variable name is a symbolic token or a sequence of symbolic tokens. Most symbolic tokens are legitimate variable names, but anything with a predefined meaning like {\tt draw}, {\tt +}, or {\tt ..} is disallowed; i.e., variable names cannot be macros or MetaPost primitives. This minor restriction allows an amazingly broad class of variable names: {\tt alpha}, \verb|==>|, \verb|@$&|, and \verb|~~| are all legitimate variable names. Such symbolic tokens without special meanings are called {\em tags}\index{tags}. A variable name can be a sequence of tags like {\tt f.bot} or {\tt f.top}. The idea is to provide some of the functionality of Pascal records or C structures. It is also possible to simulate arrays by using variable names that contain numbers as well as symbolic tokens. For example, the variable name {\tt x2r} consists of the tag {\tt x}, the number 2, and the tag~{\tt r}. There can also be variables named {\tt x3r} and even {\tt x3.14r}. These variables can be treated as an array\index{arrays} via constructions like {\tt x[i]r}, where {\tt i} has an appropriate numeric value. The overall syntax for variable names is shown in Figure~\ref{syvar}. \begin{figure}[htp] \begin{ctabbing} $\tt \descr{variable} \rightarrow \descr{tag}\descr{suffix}$\\ $\tt \descr{suffix} \rightarrow \descr{empty} \;|\; \descr{suffix}\descr{subscript} \;|\; \descr{suffix}\descr{tag}$\\ $\tt \descr{subscript} \rightarrow \descr{number} \;|\; \hbox{\tt [}\descr{numeric expression}\hbox{\tt ]}$ \end{ctabbing} \caption{The syntax for variable names.} \index{suffix?\tdescr{suffix}}\index{subscript?\tdescr{subscript}} \label{syvar} \end{figure} Variables like {\tt x2} and {\tt y2} take on numeric values by default, so we can use the fact that {\tt z}\tdescr{suffix} is an abbreviation for\index{z convention?{\tt z} convention}\label{Dzconv} $$ (x\descr{suffix},\, y\descr{suffix}) $$ to generate pair-valued variables when needed. It turns out that the {\tt beginfig}\index{beginfig?\texttt{beginfig}} macro wipes out pre-existing values variables that begin with the tags {\tt x} or {\tt y} so that {\tt beginfig} \ldots\ {\tt endfig} blocks do not interfere with each other when this naming scheme is used. In other words, variables that start with {\tt x}, {\tt y}, {\tt z} are local\index{variables!local}\index{locality} to the figure they are used in. General mechanisms for making variables local will be discussed in Section~\ref{grsec}. Type declarations\index{declarations}\index{type declarations} make it possible to use almost any naming scheme while still wiping out any previous value that might cause interference. For example, the declaration $$ \hbox{\tt pair pp, a.b;} $$ makes {\tt pp} and {\tt a.b} unknown pairs. Such a declaration is not strictly local since {\tt pp} and {\tt a.b} are not automatically restored to their previous values at the end of the current figure. Of course, they are restored to unknown pairs if the declaration is repeated. Declarations work the same way for any of the other nine types: numeric, path, transform, color, cmykcolor, string, boolean, picture, and pen. The only restriction is that you cannot give explicit numeric subscripts in a variable declaration. Do not give the illegal declaration $$ \hbox{\tt numeric q1, q2, q3;} $$ use the generic subscript\index{subscript!generic} symbol {\tt []}\index{arrays}\index{[]?\texttt{[]}!array} instead, to declare the whole array: $$ \hbox{\tt numeric q[];} $$ You can also declare ``multidimensional'' arrays\index{arrays!multidimensional}. After the declaration $$ \hbox{\tt path p[]q[], pq[][];} $$ {\tt p2q3} and {\tt pq1.4 5} are both paths. Internal\index{internal variables}\index{variables!internal} variables like {\tt tracingonline} cannot be declared in the normal fashion. All the internal variables discussed in this manual are predefined and do not have to be declared at all, but there is a way to declare that a variable should behave like a newly-created internal variable. The declaration is {\tt newinternal}\index{newinternal?\texttt{newinternal}}\label{Dnewint} followed by an optional type specifier \texttt{numeric}\index{internal variables!\texttt{numeric}}\index{variables!internal!\texttt{numeric}} or \texttt{string}\index{internal variables!\texttt{string}}\index{variables!internal!\texttt{string}} and a list of symbolic tokens. For example, $$\begin{verbatim} newinternal numeric n, m; newinternal string s, t; newinternal num; \end{verbatim} $$ are valid declarations that declare three internal numeric variables \texttt{n}, \texttt{m}, and~\texttt{num} and two internal string variables \texttt{s} and~\texttt{t}. Internal variables always have known values, and these values can only be changed by using the assignment\index{assignment} operator {\tt:=}\index{:=?\texttt{:=}}. Internal numeric variables are initially zero and internal string variables are initially the empty string~\verb|""|, except that the Plain\index{Plain macros} macro package gives some of the variables different initial values. (The Plain macros are normally preloaded automatically as explained in Section~\ref{intro}.) Internal string variables have been introduced in MetaPost version~1.200. For backwards compatibility, if the type specifier is missing, internal variables default to a \texttt{numeric}\index{internal variables!\texttt{numeric}}\index{variables!internal!\texttt{numeric}} type, as in the last example. The declarations \texttt{newinternal numeric;} and \texttt{newinternal string;} are invalid and throw an error. \section{Integrating Text and Graphics} \label{text} MetaPost has a number of features for including labels and other text\index{text and graphics} in the figures it generates. The simplest way to do this is to use the {\tt label}\index{label?\texttt{label}}\label{Dlabel} statement\index{label suffix?\tdescr{label suffix}} $$ {\tt label}\descr{label suffix} \hbox{\tt (} \descr{string or picture expression} \hbox{\tt,}\, \descr{pair expression} \hbox{\tt );} $$ The \tdescr{string or picture expression} gives the label and the \tdescr{pair expression} says where to put it. The \tdescr{label suffix} can be \tdescr{empty} in which case the label is just centered on the given coordinates. If you are labeling some feature of a diagram you probably want to offset the label slightly to avoid overlapping. This is illustrated in Figure~\ref{fig16} where the {\tt "a"} label is placed above the midpoint of the line it refers to and the {\tt "b"} label is to the left of the midpoint of its line. This is achieved by using {\tt label.top}\index{top?\texttt{top}} for the {\tt "a"} label and {\tt label.lft}\index{lft?\texttt{lft}} for the {\tt "b"} label as shown in the figure. The \tdescr{label suffix} specifies the position of the label relative to the specified coordinates. The complete set of possibilities is\index{rt?\texttt{rt}}\index{bot?\texttt{bot}}% \index{ulft?\texttt{ulft}}\index{urt?\texttt{urt}}\index{llft?\texttt{llft}}\index{lrt?\texttt{lrt}} $$ \tt \descr{label suffix} \rightarrow \descr{empty} \;|\; lft \;|\; rt \;|\; top \;|\; bot \;|\; ulft \;|\;urt \;|\; llft \;|\; lrt $$ where {\tt lft} and {\tt rt} mean left and right and {\tt llft}, {\tt ulft}, etc.\ mean lower left, upper left, etc. The actual amount by which the label is offset in whatever direction is determined by the internal variable\index{internal variables}\index{variables!internal} {\tt labeloffset}\index{labeloffset?\texttt{labeloffset}}\label{Dlaboff}. \begin{figure}[htp] $$ \begin{verbatim} 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; \end{verbatim} \qquad \mathcenter{\includegraphics{mpman-17.mps}} $$ \caption{MetaPost code and the resulting output} \label{fig16} \end{figure} Figure~\ref{fig16} also illustrates the {\tt dotlabel}\index{dotlabel?\texttt{dotlabel}}\label{Ddotlab} statement. This is effectively like a {\tt label} statement followed by a statement drawing a dot at the indicated coordinates. For example $$ \hbox{\tt dotlabel.bot("(0,0)", z0)} $$ places a dot at {\tt z0} and then puts the label ``(0,0)'' just below the dot. Another alternative is the macro {\tt thelabel}\index{thelabel?\texttt{thelabel}}\label{Dthelab}. This has the same syntax as the {\tt label} and {\tt dotlabel} statements except that it returns the label as a \tdescr{picture primary} instead of actually drawing it. Thus $$ \hbox{\tt label.bot("(0,0)", z0)} $$ is equivalent to $$ \hbox{\tt draw thelabel.bot("(0,0)", z0)} $$ For simple applications of labeled figures, you can normally get by with just {\tt label} and {\tt dotlabel}. In fact, you may be able to use a short form of the {\tt dotlabel} statement that saves a lot of typing when you have many points {\tt z0}, {\tt z1}, {\tt z.a}, {\tt z.b}, etc.\ and you want to use the {\tt z} suffixes as labels. The statement\index{dotlabels?\texttt{dotlabels}}\label{Ddotlbs} $$ \hbox{\tt dotlabels.rt(0, 1, a);} $$ is equivalent to $$ \hbox{\tt dotlabel.rt("0",z0); dotlabel.rt("1",z1); dotlabel.rt("a",z.a);} $$ Thus the argument to {\tt dotlabels} is a list of suffixes for which {\tt z} variables are known, and the \tdescr{label suffix} given with {\tt dotlabels} is used to position all the labels. There is also a {\tt labels}\index{labels?\texttt{labels}}\label{Dlabels} statement that is analogous to {\tt dotlabels} but its use is discouraged because it presents compatibility problems with \MF\index{metafont?\MF}. Some versions of the preloaded Plain\index{Plain macros} macro package define {\tt labels} to be synonymous with {\tt dotlabels}. For labeling statements such as {\tt label} and {\tt dotlabel} that use a string expression for the label text, the string gets typeset in a default font as determined by the string variable {\tt defaultfont}\index{defaultfont?\texttt{defaultfont}}\label{Ddffont}. The initial value of {\tt defaultfont} is likely to be {\tt "cmr10"}, but it can be changed to a different font name by giving an assignment such as $$ \hbox{\tt defaultfont:="ptmr8r"} $$ \ttt{ptmr8r} is a typical way to refer to the Times-Roman font in \TeX. The discussion of font names on p.\ \pageref{fontname} explains further. There is also a numeric quantity called {\tt defaultscale}\index{defaultscale?\texttt{defaultscale}}\label{Ddfscale} that determines the type size. When {\tt default\-scale} is 1, you get the ``normal size'' which is usually 10 point, but this can also be changed. For instance $$ \hbox{\tt defaultscale := 1.2} $$ makes labels come out twenty percent larger. If you do not know the normal size and you want to be sure the text comes out at some specific size, say 12 points, you can use the {\tt fontsize}\index{fontsize?\texttt{fontsize}}\label{Dfntsiz} operator to determine the normal size: e.g., $$ \hbox{\tt defaultscale := 12pt/fontsize defaultfont;} $$ \label{fontname} When you change {\tt defaultfont}, the new font name should be something that \TeX\ would understand since MetaPost gets height and width information by reading a {\tt tfm}\index{tfm file?{\tt tfm} file}\index{files!tfm?{\tt tfm}} file. (This is explained in {\sl The \TeX book\/} \cite{kn:a}.) It should be possible to use built-in PostScript\index{PostScript!fonts} fonts, but the names for them are system-dependent. Some typical ones are {\tt ptmr8r} for Times-Roman\index{Times-Roman}, \ttt{pplr8r} for Palatino\index{Palatino}, and \ttt{phvr} for Helvetica\index{Helvetica}. The Fontname document, available at \url{http://tug.org/fontname}, has much more information about font names and \TeX. A \TeX\index{TeX?\TeX!fonts} font such as {\tt cmr10} is a little dangerous because it does not have a space character or certain ASCII symbols. MetaPost does not use the ligatures\index{ligatures} and kerning\index{kerning} information that comes with a \TeX\ font. Further, MetaPost itself does not interpret virtual fonts. \subsection{Typesetting Your Labels} \label{Dbtex} \index{labels, typesetting} \TeX\index{TeX?\TeX} may be used to format complex labels. If you say\index{btex?\texttt{btex}}\index{etex?\texttt{etex}} $$ {\tt btex}\, \descr{typesetting commands}\, {\tt etex} $$ in a MetaPost input file, the \tdescr{typesetting commands} get processed by \TeX\ and translated into a picture expression (actually a \tdescr{picture primary}) that can be used in a {\tt label} or {\tt dotlabel} statement. Any spaces after {\tt btex} or before {\tt etex} are ignored. For instance, the statement $$ \hbox{\verb|label.lrt(btex $\sqrt x$ etex, (3,sqrt 3)*u)|} $$ in Figure~\ref{fig17} places the label $\sqrt x$ at the lower right of the point {\tt (3,sqrt 3)*u}. \begin{figure}[htp] $$ \begin{verbatim} 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; \end{verbatim} \qquad \mathcenter{\includegraphics{mpman-18.mps}} $$ \caption{Arbitrary \TeX\ as labels} \label{fig17} \end{figure} Figure~\ref{fig18} illustrates some of the more complicated things that can be done with labels. Since the result of {\tt btex} \ldots {\tt etex} is a picture, it can be operated on like a picture. In particular, it is possible to apply transformations to pictures. We have not discussed the syntax for this yet, but a \tdescr{picture secondary} can be\index{rotated text}\index{rotated?\texttt{rotated}} $$ \descr{picture secondary}\, {\tt rotated}\, \descr{numeric primary} $$ This is used in Figure~\ref{fig18} to rotate the label ``$y$ axis'' so that it runs vertically. \begin{figure}[htp] $$ \begin{verbatim} 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; \end{verbatim} \qquad \mathcenter{\includegraphics{mpman-19.mps}} $$ \caption{\TeX\ labels with display math, and rotated by MetaPost} \label{fig18} \end{figure} Another complication in Figure~\ref{fig18} is the use of the displayed equation $$y={2\over 1+\cos x}$$ as a label. It would be more natural to code this as $$ \hbox{\verb|$$y={2\over 1+\cos x}$$|} $$ but this would not work because \TeX\ typesets the labels in ``horizontal mode.'' For a way to typeset \emph{variable} text as labels, see the \texttt{TEX} utility routine described on p.\ \pageref{dTEX}. Here is how \TeX\ material gets translated into a form MetaPost understands: MetaPost stores all {\tt btex}\index{btex?\texttt{btex}} \ldots\ {\tt etex}\index{etex?\texttt{etex}} blocks in a temporary file and then runs \TeX\ on that file. If the environment variable \ttindex{MPTEXPRE} is set to the name of an existing file, its content will be prepended to the output file for processing by \TeX. You can use this to include \LaTeX\ preambles, for instance. The \ttt{TEX} macro described on p.\ \pageref{dTEX} provides another way to handle this. Once the \TeX\ run is finished, MetaPost translates the resulting DVI\index{dvi file?{\tt dvi} file}\index{files!dvi?{\tt dvi}} file into low level MetaPost commands that are then read instead of the {\tt btex} \ldots\ {\tt etex} blocks. If the main file is {\tt fig.mp}, the translated \TeX\ material is placed in a file named {\tt fig.mpx}\index{mpx file?{\tt mpx} file}\index{files!mpx?{\tt mpx}}. The conversion normally runs silently without any user intervention but it could fail, for instance if one of the {\tt btex} \ldots {\tt etex} blocks contains an erroneous \TeX\index{TeX?\TeX!errors} command. In that case, the \TeX\ input is saved in the file {\tt mpxerr.tex}\index{mpxerr.tex?\texttt{mpxerr.tex}} and the \TeX\ error messages appear in {\tt mpxerr.log}\index{mpxerr.log?\texttt{mpxerr.log}}\index{log file?{\tt log} file}\index{files!log?{\tt log}}. The DVI to MetaPost conversion route {\it does\/} understand virtual fonts, so you can use your normal \TeX\ font switching commands inside the label. \label{Dmakempx} In MetaPost versions before 1.100, the \TeX\ label preprocessing was handled by an external program that was called upon automatically by MetaPost. On Web2C-based systems, the preprocessor was normally named \ttindex{makempx}, which called the utility \ttindex{mpto} for the creation of the \TeX\ input file and the utility \ttindex{dvitomp} for the conversion to low level MetaPost. In the current MetaPost version, the work of this program is now done internally. However, if the environment variable \ttindex{MPXCOMMAND} is set, the whole label conversion mechanism will be delegated to the command given in that variable. \label{Dverbatimtex} \TeX\ macro definitions or any other auxiliary \TeX\ commands can be enclosed in a {\tt verbatimtex}\index{verbatimtex?\texttt{verbatimtex}} \ldots\ {\tt etex}\index{etex?\texttt{etex}} block. The difference between {\tt btex} and {\tt verbatimtex} is that the former generates a picture expression while the latter only adds material for \TeX\ to process. For instance, if you want \TeX\ to typeset labels using macros defined in {\tt mymac.tex}, your MetaPost input file would look something like this: \begin{eqnarray*} && \verb|verbatimtex \input mymac etex|\\ && \verb|beginfig(1);|\\ && \qquad \dots\\ && \verb|label(btex|\, \descr{\TeX\ material using \hbox{\tt mymac.tex}}\, \verb|etex, | \descr{some coordinates} \hbox{\tt );}\\ && \qquad \dots \end{eqnarray*} \label{Dtroffmode} On Unix\footnote{Unix is a registered trademark of Unix Systems Laboratories.}\index{Unix} and other Web2C-based systems, the option {\tt -troff} to MetaPost tells the preprocessor that {\tt btex} $\ldots$ {\tt etex} and {\tt verbatimtex} $\ldots$ {\tt etex} blocks are in troff\index{troff} instead of \TeX. When using this option, MetaPost sets the internal variable \ttindex{troffmode} to~1\index{prologues?\texttt{prologues}}. \label{Dprologues} Setting \ttt{prologues} can be useful with \TeX, too, not just troff. Here is some explanation: \begin{itemize} \item In PostScript output mode, when \ttt{prologues} is 0, which is the default, the MetaPost output files do not have embedded fonts. Fonts in the resulting output will probably render as Courier\index{Courier} or Times-Roman\index{Times-Roman}. In SVG mode, the text will probably render in a generic sans serif font. There may very well be problems with the encoding of non-ASCII characters: the font model of SVG is totally different from the model used by MetaPost. \item In PostScript output mode, when \ttt{prologues} is 1, the MetaPost output claims to be ``structured PostScript''\index{PostScript!structured} (EPSF\index{EPSF}), but it is not completely conformant. This variant is kept for backward compatibility with old (troff) documents, but its use is deprecated. MetaPost sets \ttt{prologues} to~1 when the {\tt -troff} option is given on the command line. A \ttt{prologues:=1} setting is currently ignored in SVG output mode. The value is reserved for future use (possibly for mapping to \ttt{font-family}, \ttt{font-weight}, etc. properties). \item In PostScript output mode, when \ttt{prologues} is 2, the MetaPost output is EPSF and assumes that the text comes from PostScript\index{PostScript!fonts} fonts provided by the ``environment'', such as the document viewer or embedded application using the output. MetaPost will attempt to set up the font encodings correctly, based on \ttt{fontmapfile} and \ttt{fontmapline} commands. A \ttt{prologues:=2} setting is currently ignored in SVG output mode. The value is reserved for future use (possibly for external \ttt{font-face} definitions). \item In PostScript output mode, when \ttt{prologues} is 3, the MetaPost output will be EPSF but will contain the PostScript font(s) (or a subset) used based on the \ttt{fontmapfile} and \ttt{fontmapline} commands. This value is useful for generating stand-alone PostScript graphics. In SVG mode, the font glyphs are converted to path definitions that are included at the top of the output file. This method is currently the only reliable way to export text objects to SVG. \end{itemize} It is worth noting that the default value \ttt{prologues:=0} is sufficient for graphics included in \TeX-based documents. Also, the \ttt{prologues} variable is irrelevant when processing MetaPost files through the \ttindex{mptopdf} utility (part of the \ConTeXt\ distribution), because PDF files are, by nature, stand-alone. Moreover, the value of \ttt{prologues} has no effect on \MF\ fonts in your MetaPost files, i.\,e., MetaPost never embeds such fonts. Only output drivers, e.\,g., \ttt{dvips} or pdf\LaTeX\ will handle those. The details on how to include PostScript figures in a paper done in \TeX\ or troff are system-dependent. They can generally be found in manual pages and other on-line documentation, but have a look at section~\ref{teximport} of this manual for some brief instructions that in many cases should work. The manual for the widely-used Dvips processor is in a file \ttt{dvips.texi}, included in most distributions, and is available online at \url{http://tug.org/texinfohtml/dvips.html}, among many other places and formats. \subsection{Font map files} \label{fontmap} If \ttt{prologues} is set to~2, any used fonts in the output file are automatically re-encoded, and the encoding vector file specified in the fontmap entry will be embedded in the output file. If \ttt{prologues} is set to~3, MetaPost will also attempt to include (a subset of) the used PostScript\index{PostScript!fonts} fonts. For this to work, it needs to acquire font map information. The code is based on the font library used by pdf\TeX. Following in the footsteps of pdf\TeX, there are two new associated primitives: \ttindex{fontmapfile}\label{Dfontmapfile} and \ttindex{fontmapline}\label{Dfontmapline}. Here is a simple example, specifying the map file for Latin Modern fonts in YandY (\LaTeX\ LY1) encoding: \begin{center}\begin{tabular}{l} \verb|prologues:=2;|\\ \verb|fontmapfile "texnansi-lm.map";|\\ \verb|beginfig(1);|\\ \verb| draw "Helló, világ" infont "texnansi-lmr10";|\\ \verb|endfig;| \end{tabular}\end{center} Using \ttt{fontmapline}, you can specify font mapping information inside the figure: \begin{center}\begin{tabular}{l} \verb|prologues:=2;|\\ \verb|fontmapline "pplbo8r URWPalladioL-Bold "&ditto&|\\ \verb| ".167 SlantFont"&ditto&" <8r.enc