diff options
Diffstat (limited to 'Master/texmf-dist/doc/metapost/base/source-manual/mpman.tex')
-rw-r--r-- | Master/texmf-dist/doc/metapost/base/source-manual/mpman.tex | 1363 |
1 files changed, 915 insertions, 448 deletions
diff --git a/Master/texmf-dist/doc/metapost/base/source-manual/mpman.tex b/Master/texmf-dist/doc/metapost/base/source-manual/mpman.tex index c4a38d43a2c..6889d586176 100644 --- a/Master/texmf-dist/doc/metapost/base/source-manual/mpman.tex +++ b/Master/texmf-dist/doc/metapost/base/source-manual/mpman.tex @@ -1,4 +1,4 @@ -% $Id: mpman.tex 1219 2010-04-01 09:05:51Z taco $ +% $Id: mpman.tex 1432 2010-10-22 12:02:13Z stephanhennig $ % MetaPost manual, by John Hobby. License at end. \listfiles \RequirePackage{ifpdf} @@ -12,8 +12,8 @@ \fi \documentclass{article} % article is NOT the original style \usepackage[nofancy]{svninfo}% Access VCS information. -\svnInfo $Id: mpman.tex 1219 2010-04-01 09:05:51Z taco $ -\newcommand*{\mpversion}{1.211} +\svnInfo $Id: mpman.tex 1432 2010-10-22 12:02:13Z stephanhennig $ +\newcommand*{\mpversion}{1.503} \usepackage[T1]{fontenc} \usepackage{lmodern} @@ -29,6 +29,7 @@ \usepackage[textwidth=6in,textheight=8.65in]{geometry} \usepackage{tocloft} \setlength\cftbeforesecskip{1.3ex plus 0.3ex minus 0.3ex} + \setcounter{tocdepth}{2} \usepackage{ltxtable} @@ -39,7 +40,7 @@ \newcommand\descr[1]{{\langle\hbox{#1}\rangle}} \newcommand\invisgap{\nobreak\hskip0pt\relax} -\newcommand\tdescr[1]{$\langle$\invisgap#1\invisgap$\rangle$} +\newcommand\tdescr[1]{{\normalfont$\langle$\invisgap#1\invisgap$\rangle$}} \newcommand\pl{\dag} @@ -178,8 +179,8 @@ written about MetaPost. For general help, try the \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. +\url{http://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. @@ -197,8 +198,10 @@ $$ \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)}. +MetaPost also has a +\verb|drawdot|\index{drawdot?\texttt{drawdot}}\label{Ddrawdot} command +to draw a single point with the current pen, as in +\verb|drawdot (30,0)|. What is meant by coordinates like \verb|(30,0)|? MetaPost uses the same default coordinate system that PostScript\index{PostScript!coordinate @@ -237,20 +240,21 @@ 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 setting the line width (actually the pen size) for subsequent +\verb|draw| or \verb|drawdot| statements to 4 points. (This is about +eight times the default pen size). + +With such a large pen size, the \verb|drawdot| statement draws rather +bold dots. We can use this to make a grid of dots by nesting +\verb|drawdot| in a pair of loops:\index{loops}% +$$ +\begin{verbatim} for i=0 upto 2: for j=0 upto 2: drawdot (i*u,j*u); endfor endfor \end{verbatim} +\index{for?\texttt{for}} +\index{endfor?\texttt{endfor}} $$ 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}. @@ -275,393 +279,143 @@ $$ \end{figure} -\section{The MetaPost workflow} +\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 +MetaPost's graphic design workflow. This section also contains a few +technical details about MetaPost's compilation process, just enough to +get you started. Section~\ref{workflow2} is more elaborate on this +topic. + +In this manual, we'll assume a stand-alone command-line executable of +the MetaPost compiler is used, which is usually called +\texttt{mpost}\index{mpost?\texttt{mpost}}. The syntax and program name +itself are system-dependent; sometimes it is named \texttt{mp}. The +executable is actually a small wrapper program around +\emph{mplib}\index{mplib?\emph{mplib}}, a library containing the +MetaPost compiler. The library can as well be embedded into third-party +applications.\footnote{C~API\index{mplib?\emph{mplib}!C~API} and Lua + bindings\index{mplib?\emph{mplib}!Lua bindings} are described in file + \verb|manual/mplibapi.pdf|\index{mplib?\emph{mplib}!mplibapi.pdf?\texttt{mplibapi.pdf}} + as part of the MetaPost distribution.} Section~\ref{mpimport} has +some brief information on how to use the MetaPost compiler built-into +Lua\TeX. For more information, please refer to the documentation of the +embedding application. + +The basic MetaPost workflow\index{workflow} is depicted in +figure~\ref{fig:mpworkflow}. Being a graphics description language, +creating graphics with MetaPost follows the +\emph{edit-compile-debug}\index{edit}\index{compile}\index{debug} +paradigm known from other programming languages. + +\begin{figure}[tbp] +$$ \includegraphics{mpman-charts-2.mps} $$ +\caption{The basic MetaPost workflow} +\label{fig:mpworkflow} +\end{figure} -$$\begin{verbatim} -message "mp = " & mpversion; -\end{verbatim} +To create graphics with MetaPost, you prepare\index{edit} a text file +containing code in the MetaPost language and then invoke the +compiler\index{compile}, usually by giving a command of the form $$ -writes -$$\begin{verbatim}[commandchars=\\\{\}] -mp = \mpversion +\begin{verbatim}[commandchars=\\\{\}] +mpost \tdescr{input file} \end{verbatim} +\index{mpost?\texttt{mpost}} $$ -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}: +on the command-line. 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. A complete description of the +command-line syntax can be found in Section~\ref{refman:commandline}. + +Any terminal I/O during the compilation process is summarized in a +transcript\index{files!transcript}\index{transcript file|see{files, + transcript}} file called \texttt{\tdescr{jobname}.log}\index{log + file?{\tt log} file}\index{files!log?{\tt log}}, where +\tdescr{jobname} is the base name of the input file. This includes +error messages and any MetaPost commands entered in interactive mode. + +If all goes well during compilation, MetaPost outputs one or more +graphic files in a variant of the PostScript format, by default. +PostScript output can be previewed\index{preview} with any decent +PostScript viewer, e.g., GSview\index{GSview} or +PS\_View\index{PSView?PS\_View}. Section~\ref{preview} has some tips +and discusses several more elaborate ways for previewing PostScript +output. Particularly, if graphics contain text labels, some more work +might be required to get robust results in a PostScript viewer. +Starting with version~1.200, MetaPost is also capable of generating +graphics in the SVG\index{SVG} format. SVG files can be previewed with +certain web browsers, for example Firefox~3\index{Firefox} or +Konqueror~4.2\index{Konqueror}. -$$\begin{verbatim} -outputformat := "svg"; -\end{verbatim} +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 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. +Section~\ref{mpimport} deals with the import of MetaPost graphics into +external applications. + +A MetaPost input file\index{files!input}\index{edit}\index{edit} +normally contains a sequence of +\verb|beginfig()|\index{beginfig?\texttt{beginfig}}, +\verb|endfig|\index{endfig?\texttt{endfig}} pairs with an +\verb|end|\index{end?\texttt{end}} statement after the last +one.\footnote{Omitting the final \verb|end| statement causes MetaPost to + enter interactive mode\index{interactive mode} after processing the + input file.} These are macros that perform various administrative +functions and ensure that the results of all drawing operations get +packaged up and translated into PostScript or SVG format. The numeric +argument to the \verb|beginfig| macro determines the name of the +corresponding output file, whose name, by default, is of the form +\texttt{\tdescr{jobname}.\tdescr{n}}, where \tdescr{n} is the current +argument to \verb|beginfig| rounded to the nearest integer. As an +example, if a file is named \texttt{fig.mp} and contains the lines $$ - -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"; +\begin{verbatim}[commandchars=\\\{\}] beginfig(1); - draw origin--(100,100); + \tdescr{drawing statements} endfig; +end \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} +the output from statements between \verb|beginfig(1)| and the next +\verb|endfig| is written in a file \texttt{fig.1}\index{files!output}. + +Statements can also appear outside \verb|beginfig| \ldots\ +\verb|endfig|. Such statements are processed, but drawing operations +generate no visible output. Typically, global configurations are put +outside \verb|beginfig| \ldots\ \verb|endfig|, e.g., assignments to +internal variables, such as \texttt{outputtemplate}, or a \LaTeX\ +preamble declaration for enhanced text rendering. +Comments\index{comments} in MetaPost code are introduced by the percent +sign~\verb|%|\index{\%?\texttt{\%}}, which causes the remainder of the +current line to be ignored. + +The remainder of this section briefly introduces three assignments to +internal variables, each one useful by itself, that can often be found +in MetaPost input files: $$ -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} -<p> - <object data="foo.svg" type="image/svg+xml" width="300" height="200"> - </object> -</p> +\begin{verbatim}[commandchars=\\\{\}] +prologues := 3; \smallskip +outputtemplate := "%j-%c.mps"; \smallskip +outputformat := "svg"; \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. +If your graphics contain text labels, you might want to set variable +\texttt{prologues} to~3 to make sure the correct fonts are used under +all possible circumstances. The second assignment changes the output +file naming scheme to the form \texttt{\tdescr{jobname}-\tdescr{n}.mps}. +That way, instead of a numeric index, all output files get a uniform +file extension \texttt{mps}\index{mps file?{\tt mps} + file}\index{files!mps?{\tt mps}}, which is typically used for +MetaPost's PostScript output. The last assignment lets MetaPost write +output files in the SVG format rather than in the PostScript format. +More information can be found in Sections~\ref{Dprologues} +and~\ref{workflow2}. \section{Curves} @@ -761,6 +515,9 @@ draw (0,0)..controls (26.8,-1.8) and (51.4,14.6) \end{verbatim} $$ +For a way to extract the control points of a path, given by the user or +calculated by MetaPost, see section~\ref{Dprepostctrl}. + \begin{figure}[htp] $$ \includegraphics{mpman-5.mps} $$ @@ -1317,8 +1074,10 @@ 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 +causes the given pen to be used in subsequent +\verb|draw|\index{draw?\texttt{draw}} or +\verb|drawdot|\index{drawdot?\texttt{drawdot}} 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 @@ -1829,7 +1588,11 @@ 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. +places a dot at {\tt z0} and then puts the label ``(0,0)'' just below +the dot. The diameter of the dot drawn by the {\tt dotlabel} statement +is determined by the value of the internal variable {\tt + dotlabeldiam}\index{dotlabeldiam?\texttt{dotlabeldiam}}\label{Ddotlabdiam}. +Default value is 3bp. Another alternative is the macro {\tt thelabel}\index{thelabel?\texttt{thelabel}}\label{Dthelab}. This has @@ -2024,7 +1787,7 @@ 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 +creation of the \TeX\ input file and the utility \texttt{dvitomp}\index{dvitomp?\texttt{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 @@ -2102,17 +1865,50 @@ will contain the PostScript font(s) (or a subset) used based on the 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. +are included at the top of the output file. \end{itemize} +The correct setting for variable \texttt{prologues} depends on how +MetaPost graphics are post-processed. Here are recommendations for some +popular use-cases: + +\begin{description} + +\item[\normalfont\itshape Previewing:] Section~\ref{preview} discusses + previewing PostScript output. + +\item[\normalfont\itshape \TeX\ and dvips:] When including PostScript + figures into a \TeX\ document that is processed by \TeX\ and a DVI + output processer, e.g., dvips\index{dvips}, variable + \texttt{prologues} should \emph{not} be set to the value~1, unless the + used fonts are known to be resident in the PostScript interpreter. + Make sure that variable \texttt{prologues} is set to either~0 (font + inclusion handled by dvips, but without re-encoding support), 2 (font + inclusion by dvips, with font re-encoding if necessary), or~3 (font + inclusion and re-encoding by MetaPost). Value~3 is safest, but may + result in slightly larger output. + +\item[\normalfont\itshape pdf\TeX:] When generating PDF files with + pdf\TeX\ (and the mptopdf\index{mptopdf} bundle), variable + \texttt{prologues} is not relevant. + +\item[\normalfont\itshape PostScript in external applications:] Some + text\index{text processor} processors or graphics applications can + directly import EPSF files, while for others MetaPost's PostScript + output has to be converted to a different vector or even a bitmap + format first. In any case, as soon as PostScript graphics generated + by MetaPost are leaving the \TeX\ ecosystem, variable + \texttt{prologues} should be set to~3, so that all needed fonts are + embedded (as a subset). + +\item[\normalfont\itshape SVG output:] Converting font glyphs to paths + by setting variable \texttt{prologues} to~3 is currently the only + reliable way to export text objects to SVG. + +\end{description} -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 +It is worth noting that 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. @@ -2120,14 +1916,14 @@ 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 +section~\ref{mpimport} 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} +\subsection{Font Map Files} \label{fontmap} If \ttt{prologues} is set to~2, any used fonts in the output file are @@ -2193,18 +1989,18 @@ pdftex.map}, depending on whether or not troff mode is enabled. If statement. Again, this is for backward compatibility only. -\subsection{The \texttt{infont} operator} +\subsection{The \texttt{infont} Operator} \label{Sinfont} Regardless of whether you use \TeX\ or troff, all the real work of adding text to pictures is done by a MetaPost primitive operator called {\tt infont}\index{infont?\texttt{infont}}. It is a \tdescr{primary -binop}\index{primary binop?\tdescr{primary binop}} that takes a + binop}\index{primary binop?\tdescr{primary binop}} that takes a \tdescr{string secondary} as its left argument and a \tdescr{string -primary} as its right argument. The left argument is text, and the + primary} as its right argument. The left argument is text, and the right argument is a font name. The result of the operation is a -\tdescr{picture secondary} that can then be transformed in various ways. -One possibility is enlargement by a given factor via the +\tdescr{picture secondary}, which can then be transformed in various +ways. One possibility is enlargement by a given factor via the syntax\index{scaled?\texttt{scaled}} $$ \descr{picture secondary}\, \hbox{\tt scaled}\, \descr{numeric primary} $$ Thus {\tt label("text",z0)} is equivalent to @@ -2674,6 +2470,31 @@ Thus $$ p_1\ {\tt cutafter}\ p_2 $$ tries to cut off the part of $p_1$ after its last intersection with $p_2$. +The control points of a path can be requested by the two operators +\index{precontrol of?\texttt{precontrol of}} +\index{postcontrol of?\texttt{postcontrol of}} +\label{Dprepostctrl} +\begin{eqnarray*} + {\tt precontrol}\, \descr{numeric expression}\, {\tt of}\, \descr{path primary},\\ + {\tt postcontrol}\, \descr{numeric expression}\, {\tt of}\, \descr{path primary}. +\end{eqnarray*} + +For integer time values~$t$, these operators return the control points +before and after a cardinal point of a path. A segment +$z_{t-1}\verb|..|z_t$ of a path~$p$ has therefore control points +$$ {\tt postcontrol}\ t-1\ {\tt of}\ p +$$ +and +$$ {\tt precontrol}\ t\ {\tt of}\ p. +$$ + +For decimal time values, {\tt precontrol of} returns the last control +point of sub-path $(0, t)$ and {\tt postcontrol of} returns the first +control point of sub-path $(t, \infty)$ of a path. In other words, the +control points at fractional time values correspond to a virtual +cardinal point inserted at the given time value without modifying path +shape. + Another operator\index{direction of?\texttt{direction of}}\label{Ddirof} $$ {\tt direction}\, \descr{numeric expression}\, {\tt of}\, \descr{path primary} $$ @@ -3544,7 +3365,7 @@ $$ {\tt shipout}\, \descr{picture expression} $$ writes out a picture as a PostScript\index{PostScript} file whose file name is determined by {\tt outputtemplate}\index{outputtemplate?\texttt{outputtemplate}} -(see section~\ref{outputfilenames}). By default, the file name ends +(see Section~\ref{Doutputtemplate}). By default, the file name ends {\tt.}{\it nnn}, where {\tt nnn} is the decimal representation of the value of the internal variable\index{internal variables}\index{variables!internal} {\tt @@ -3781,23 +3602,25 @@ To summarize the discussion of mismatching part operators: \index{greypart?\texttt{greypart}|)} -\subsection{Decomposing the glyphs of a font} +\subsection{Decomposing the Glyphs of a Font} \label{glyphs} -MetaPost provides a primitive to convert a glyph of a font in the Adobe -Type~1 Font\index{PostScript!fonts}\index{font!PostScript}\index{Adobe - Type~1 Font}\index{font!Adobe Type~1} format into its constituent -filled paths---the strokes---and store them in a picture variable. A -glyph\index{font!glyph} is the visual representation of a character in a -font. A character\index{character}\index{font!character} is a certain -slot\index{slot} (index) in a font with an associated meaning, e.g., the -capital letter~``M'' or the exclamation mark. The meaning of a slot is -defined by the font encoding\index{encoding}\index{font!encoding}. In -general, the same character is represented by different glyphs in -different fonts. Figure~\ref{glyphsample} shows some glyphs for the -character at slot~103 in the T1 encoding, i.e., the lower-case -letter~``g''. All glyphs are at the same nominal size. Note, how -glyphs may extend beyond their bounding box. +MetaPost provides a primitive to convert a +glyph\index{glyph}\index{font!glyph} of a font in the Adobe Type~1 +Font\index{PostScript!fonts}\index{font!PostScript}\index{Adobe Type~1 + Font}\index{font!Adobe Type~1} format into its constituent filled +paths---the strokes---and store them in a picture variable. A glyph is +the visual representation of a character in a font. A +character\index{character}\index{font!character} is a certain +slot\index{slot}\index{font!slot} (index) in a font with an associated +meaning, e.g., the capital letter~``M'' or the exclamation mark. The +meaning of a slot is defined by the font +encoding\index{encoding}\index{font!encoding}. In general, the same +character is represented by different glyphs in different fonts. +Figure~\ref{glyphsample} shows some glyphs for the character at slot~103 +in the T1 encoding, i.e., the lower-case letter~``g''. All glyphs are +at the same nominal size. Note, how glyphs may extend beyond their +bounding box. \begin{figure}[htp] \centering \setlength{\fboxsep}{0pt} @@ -3819,8 +3642,8 @@ glyphs may extend beyond their bounding box. \label{glyphsample} \end{figure} -The glyphs of an Adobe Type~1 font -\index{PostScript!fonts}\index{font!PostScript}\index{Adobe Type~1 +The glyphs of an Adobe Type~1 +font\index{PostScript!fonts}\index{font!PostScript}\index{Adobe Type~1 Font}\index{font!Adobe Type~1} are composed of two types of contours: Clockwise oriented contours add to the shape of a glyph and are filled with black ink. Counter-clockwise oriented contours @@ -3862,17 +3685,19 @@ glyph visually\footnote{Plain contours already carry enough information fonts\index{PostScript!fonts}\index{font!PostScript}\index{Adobe Type~1 Font}\index{font!Adobe Type~1} use a generalized variant of the non-zero winding number fill rule\index{non-zero fill rule}\index{fill - rule!non-zero}\index{PostScript!fill rule}, that MetaPost doesn't + rule!non-zero}\index{PostScript!fill rule}, which MetaPost doesn't implement (MetaPost cannot handle non-contiguous paths). As a side effect, the interiors of the erasing\index{erasing} contours are an opaque white in the returned picture, while they were transparent in the original glyph. One can think of erasing contours to be unfilled (see p.~\pageref{Dunfill}). For instance, the following code saves the contours of the lower case letter~``g'', bound to slot~103 in the OT1 -encoding\index{OT1 encoding}\index{encoding!OT1}, in the Computer Modern -Roman\index{Computer Modern Roman} font in a picture variable: +encoding\index{OT1 encoding}\index{encoding!OT1}, in the +Computer\index{Computer Modern Roman} Modern Roman font in a picture +variable: -$$\begin{verbatim} +$$ +\begin{verbatim} fontmapline "cmr10 CMR10 <cmr10.pfb"; picture g; g := glyph 103 of "cmr10"; @@ -3893,7 +3718,7 @@ is mandatory for the font in question, given either by section~\ref{Dfontmapline}). In Figure~\ref{fig56}, the contours of the upper case letter~``\v{D}'' -in the Latin Modern Roman\index{Latin Modern Roman} font are saved in a +in the Latin\index{Latin Modern Roman} Modern Roman font are saved in a picture variable. The glyph is identified by its CharString name ``Dcaron''\index{Dcaron}. The code then iterates over all contours and draws them together with their cardinal (black) and control points @@ -3901,7 +3726,8 @@ draws them together with their cardinal (black) and control points cardinal points in this glyph. \begin{figure}[htb] -$$\begin{verbatim} +$$ +\begin{verbatim} fontmapfile "=lm-ec.map"; beginfig(56); picture q; @@ -3945,13 +3771,13 @@ negative). Second, in an Adobe Type~1 font\index{PostScript!fonts}\index{font!PostScript}\index{Adobe Type~1 Font}\index{font!Adobe Type~1}, contours are in general closed by repeating the starting point before applying the \verb|closepath| -operator\index{PostScript!\texttt{closepath} operator}. The MetaPost -representation of such a path would be: +operator\index{PostScript!closepath operator?\texttt{closepath} + operator}. The MetaPost representation of such a path would be: $$ z_0\verb|..|\mbox{\itshape controls}\verb|..|z_1\verb|..| \cdots \verb|..|z_n\verb|..|\mbox{\itshape controls}\verb|..|z_0\verb|--cycle| $$ -A more natural MetaPost representation of this path would be: +However, a more natural MetaPost representation of that path would be: $$ z_0\verb|..|\mbox{\itshape controls}\verb|..|z_1\verb|..| \cdots \verb|..|z_n\verb|..|\mbox{\itshape controls}\verb|..cycle| @@ -3959,20 +3785,20 @@ $$ The \verb|glyph| operator transforms all paths into the latter representation, i.e., the last point is removed, whenever it matches the starting point. Finally, the picture returned by the \verb|glyph| -operator is scaled such that one font design unit\index{font!design +operator is scaled, such that one font design unit\index{font!design unit} equals one PostScript point\index{point!PostScript}\index{PostScript!point} (bp). A usual font design unit is a thousandth part of the font design -size\index{font!design size}. The returned picture will therefore -typically have a height of around 1000\,bp. +size\index{font!design size}. Therefore, the returned picture will +typically have a height of around 1000bp. Converting a text into plain curves is part of a process oftentimes -called ``flattening\index{flattening} a document.'' When flattening -text, all hinting information in fonts are lost. Hinting information -aid a rendering application in aligning certain parts of a glyph on a +called ``flattening\index{flattening}'' a document. During flattening, +all hinting information in fonts are lost. Hinting information aid a +rendering application in aligning certain parts of a glyph on a low-resolution output device. A flattened text may therefore look distorted on screen. In SVG output, all text is automatically -flattened, when the internal variable +flattened, if the internal variable \verb|prologues|\index{prologues?\texttt{prologues}} is set to~3 (see section~\ref{Dprologues}). @@ -4981,7 +4807,7 @@ Explanation: \begin{itemize} \item -The \texttt{\%\&latex} causes \LaTeX\ to be invoked instead of \TeX. +The \texttt{\%\&latex}\index{\%\&?\texttt{\%\&}} causes \LaTeX\ to be invoked instead of \TeX. (See below, also.) Web2C- and MiKTeX-based \TeX\ implementations, at least, understand this \texttt{\%\&} specification; see, e.g., the Web2C documentation for details, \url{http://tug.org/web2c}. (Information on @@ -5027,18 +4853,424 @@ whatever processor, of course). This might be useful from a Makefile, or just a one-off run. \end{itemize} -\subsection{\texttt{mproof.tex}} -\index{mproof.tex?\texttt{mproof.tex}} +\section{Another Look at the MetaPost Workflow} +\label{workflow2} + +\index{workflow} + +In Section~\ref{workflow} we already had a brief look at how MetaPost +compiles input files and generates output files. This section contains +some more information and discusses internal variables that can be used +to control MetaPost's run-time behavior, previewing PostScript output, +debugging MetaPost code, and importing MetaPost graphics into +third-party applications. + +\subsection{Customizing Run-Time Behavior} + +\index{runtime behavior!customize} + +MetaPost knows and obeys a number of internal\index{internal + variables}\index{variables!internal} variables that have no direct +impact on drawing commands, but can be used to customize the way the +MetaPost compiler processes input files. The following paragraphs +describe those variables (in no particular order). + +\paragraph{Date and Time} + +MetaPost provides a number of internal numeric variables that store the +date and time a job was started, i.e., the MetaPost executable was +called on the command-line. Variables +\texttt{year}\index{year?\texttt{year}}\label{Dyear}, +\texttt{month}\index{month?\texttt{month}}\label{Dmonth}, +\texttt{day}\index{day?\texttt{day}}\label{Dday}, +\texttt{hour}\index{hour?\texttt{hour}}\label{Dhour}, and +\texttt{minute}\index{minute?\texttt{minute}}\label{Dminute} should be +self-explanatory. Variable +\texttt{time}\index{time?\texttt{time}}\label{Dtime} returns the number +of minutes past midnight, since the job was started, i.e., +$\texttt{time} = 60*\texttt{hour} + \texttt{minute}$. + +\paragraph{Output File Names} + +As discussed in Section~\ref{workflow}, by default, every +\verb|beginfig| \ldots\ \verb|endfig| group in an input file corresponds +to an output file that follows the naming scheme +\texttt{\tdescr{jobname}.\tdescr{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 +\texttt{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 +\verb|outputtemplate|\index{outputtemplate?\texttt{outputtemplate}}\label{Doutputtemplate}. +The escape sequences provided are listed in +table~\ref{tab:outputtemplate}. As an example, if this code is saved in +a file \texttt{fig.mp}, +$$ +\begin{verbatim} +outputtemplate := "%j-%c.mps"; +beginfig(1); + drawdot origin; +endfig; +end +\end{verbatim} +$$ +it will create the output file \texttt{fig-1.mps} instead of +\texttt{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{mpimport}). For SVG +output one would want to use \texttt{svg}\index{svg file?{\tt svg} + file}\index{files!svg?{\tt svg}} instead. + +\begin{table} + \newcommand*{\otesc}[3]{\%#1\index{\%#1?\texttt{\%#1}} & #2 & \%\{#3\}} + \centering + \begin{tabular}{|>{\ttfamily}l|l|>{\ttfamily}l|} + \hline + \multicolumn1{|c|}{Escape sequence} & \multicolumn1{c|}{Meaning} & \multicolumn1{c|}{Alternative}\\\hline + \%\%\index{\%\%?\texttt{\%\%}} & percent sign &\\ + \%\{\tdescr{internal variable}\}\index{\%\{...\}?\texttt{\%\{\tdescr{internal variable}\}}} & evaluate internal variable &\\ + \%j\index{\%j?\texttt{\%j}} & current jobname & \%\{jobname\} \\ + \otesc{c}{charcode value (\texttt{beginfig} argument)}{charcode}\\ + \otesc{y}{current year}{year}\\ + \otesc{m}{month (numeric)}{month}\\ + \otesc{d}{day of the month}{day}\\ + \otesc{H}{hour}{hour}\\ + \otesc{M}{minute}{minute}\\ + \hline + \end{tabular} + \caption{Allowed escape sequences for \ttt{outputtemplate}} + \label{tab:outputtemplate} +\end{table} -\texttt{mproof.tex} is a (plain) \TeX\ routine, not MetaPost at all. It -writes a proof sheet for MetaPost output. Call it like this: +In single-letter escape sequences referring to internal numerics, the +corresponding value is rounded to the nearest integer before it is +converted to a string expression. In such escape sequences, there can +be an optional number (0--99) following \verb|%| that determines the +minimum number of digits in the resulting string expression, like +\verb|%2m|. If the decimal representation of the internal variable +requires more digits, actual string length exceeds the requested length. +If less digits are required, the string is padded to the requested +length with zeros from left. + +In the \verb|%{...}| escape sequence no rounding takes place. +Additionally, neither this nor single-letter escape sequences referring +to internal string variables can be zero-padded. + +For backwards compatibility, the \verb|%c|\index{\%c?\texttt{\%c}} +escape sequence is handled special. If the result of rounding the +charcode value is negative, \verb|%c| evaluates to the string \verb|ps|. +This transformation can be bypassed by using \verb|%{charcode}| instead +of \verb|%c| (bypassing the rounding, too). -$$\hbox{\tt tex mproof {\sl MetaPost-output-filename}}$$ +The template mechanism can also be used for naming graphic files +individually, yet keeping all sources in one file. Collecting, e.g., +different diagram sources in a single file \texttt{fig.mp}, 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 \verb|%c| pattern in the file name +template string. +$$ +\begin{verbatim} +outputtemplate := "fig-quality.mps"; +beginfig(1); + ... +endfig; + +outputtemplate := "fig-cost-vs-productivity.mps"; +beginfig(2); + ... +endfig; +\end{verbatim} +$$ + +To ensure compatibility with older files, the default value of +\verb|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. + +\paragraph{Output Format} + +MetaPost can generate graphics in two output formats: Encapsulated +PostScript\index{PostScript!structured} (EPSF\index{EPSF}) 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---hence the name MetaPost. 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} +\verb|outputformat|\index{outputformat?\texttt{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{PostScript Dictionary} + +For PostScript output, MetaPost can define a dictionary of abbreviations +of the PostScript commands, e.g., \verb|l| instead of \verb|lineto|, to +reduce the size of output files. Setting the internal variable +\texttt{mpprocset}\index{mpprocset?\texttt{mpprocset}}\label{Dmpprocset} +to~1 makes MetaPost create an extended preamble setting-up the +dictionary. Default value of variable \texttt{mpprocset} is~0, that is, +no dictionary is used. For SVG output, variable \texttt{mpprocset} is +not relevant. + +\paragraph{Version Number} + +The version number of the MetaPost compiler can be determined 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. Variable \texttt{mpversion} can +be used to execute code depending on the MetaPost version like this: +$$ +\begin{verbatim}[commandchars=\\\{\}] +if unknown mpversion: string mpversion; mpversion := "0.000"; fi +if scantokens(mpversion) < 1.200: + errmessage "MetaPost v1.200 or later required (found v" & mpversion & ")"; +else: + \tdescr{code} +fi +\end{verbatim} +$$ +The first line is optional and only added to handle ancient MetaPost +versions gracefully that don't even know about variable +\textrm{mpversion} (prior to v0.9). The second test does the actual +work. + +The version number is also written to output files and the transcript +file. For PostScript output the version number can be found in the +\texttt{Creator}\index{Creator comment in PostScript + output?\texttt{Creator} comment in PostScript output|see{PostScript, + \texttt{Creator} comment}}\index{PostScript!Creator + comment?\texttt{Creator} comment} comment. SVG files contain a simple +comment line near the beginning of the file. The +transcript\index{files!transcript} file starts with a banner line that +identifies the version\index{version number} of the MetaPost compiler. + +\subsection{Previewing PostScript Output} +\label{preview} +\index{preview!PostScript} + +Previewing MetaPost's PostScript output is not difficult, but there are +some catches that one should know about. This section deals with the +following questions: How can graphics be clipped to their true bounding +box in the PostScript viewer application? Why are my text labels +rendered with an ugly font (or not at all) and how to avoid that? How +can several graphics be combined into a multi-page document that can be +previewed within one instance of the viewer application? + +\subsubsection{Bounding Box} +\index{bounding box} +\index{PostScript!bounding box} + +With default settings, MetaPost writes very much stripped-down +PostScript code, containing only the bare graphics code, but no other +ressources, like fonts etc. The PostScript code is somewhat deficient, +because it fails to correctly identify as Encapsulated PostScript +(EPSF\index{EPSF}) in the header. Note, Encapsulated PostScript files +don't have an associated page size, but provide bounding box +information, because they are meant for inclusion into other documents. +Instead MetaPost output wrongly pretends to be full PostScript +(PS\index{PS}), which it is not. + +This is just fine for including MetaPost graphics in, say, \TeX\ +documents (see Section~\ref{mpimport}), but some PostScript viewers have +difficulties rendering those PostScript files correctly. As an example, +because of the wrong ``PS'' header, GSview\index{GSview}---not knowing +better---ignores bounding box information and then clips all contents to +a (configurable) page size. Graphic elements laying outside those fixed +page boundaries are therefore not visible, e.g., when they have negative +coordinates. + +To avoid such situations, the first rule when previewing MetaPost's +PostScript output is to put the line +$$ +\begin{verbatim} +prologues := 2; +\end{verbatim} +\index{prologues?\texttt{prologues}} +$$ +before the first \verb|beginfig| in MetaPost input files (see the +discussion about \texttt{prologues} in Section~\ref{Dprologues}). That +way, MetaPost's PostScript output correctly identifies as Encapsulated +PostScript and viewer applications should always obey the file's +bounding box for on-screen rendering. + +A workaround for MetaPost's deficient default PostScript code that can +sometimes be seen is to move the lower left corner of a figure to the +origin as a last operation by saying +$$ +\begin{verbatim}[commandchars=\\\{\}] +\color{gray}currentpicture := currentpicture shifted -llcorner currentpicture; +\end{verbatim} +\index{currentpicture?\texttt{currentpicture}} +\index{llcorner?\texttt{llcorner}} +$$ +before \verb|endfig|. But this doesn't prevent from clipping on the +right and upper page boundaries. Additionally, the line is required for +all figures, cluttering source code, and it alters all coordinates in +PostScript output, which might complicate debugging. Applying such a +manual transformation is therefore not recommended (which is why the +line is grayed out). Instead, users are advised to adjust +\texttt{prologues} once in the preamble of the input file and enable +clipping to the bounding box in the PostScript viewer. For +GSview\index{GSview}, that can be done by activating \texttt{Options} +$\rightarrow$ \texttt{EPS Clip} and optionally \texttt{Options} +$\rightarrow$ \texttt{Show Bounding Box} for verification. + +\subsubsection{Text Labels} + +Another popular previewing issue concerns graphics that contain text +labels. An observation MetaPost users can often make is that text +labels in graphics are rendered with wrong fonts, wrong glyphs, and +sometimes even not at all. The reason is that with default settings, +again, MetaPost's PostScript output is deficient, in that it uses a +simple, non-standard way to declare what fonts are used in a graphic. +Setting variable \texttt{prologues} to~2, as shown in the previous +section, makes MetaPost generate more complex PostScript code to declare +all needed PostScript\index{PostScript!fonts} fonts and embed the +necessary encoding information. If the PostScript viewer can provide +the requested fonts, this might be sufficient to get text labels +rendered correctly. If you still observe wrong or missing glyphs you +should put the line +$$ +\begin{verbatim} +prologues := 3; +\end{verbatim} +\index{prologues?\texttt{prologues}} +$$ +into the preamble of the input file. That way, MetaPost embeds the used +PostScript\index{PostScript!fonts} fonts into the output file so that +they are always available (see the discussion about \texttt{prologues} +in Section~\ref{Dprologues}). Note, this might enlarge the size of +output files considerably. Additionally, fonts might be embedded +multiple times when several graphics using the same fonts are included +into a document. For that reason, it is recommended to reset variable +\texttt{prologues} to~0 before finally including MetaPost graphics into +external documents. + +\subsubsection{Proof Sheets} +\index{proof sheets} + +If you have lots of figures in a source file and need to preview many of +them at the same time, opening every graphic in a new instance of the +viewer application and switching between them back and forth can get +cumbersom. An alternative is to collect all graphics generated from a +MetaPost input file in a proof sheet, a multi-page document, that can be +previewed and navigated in a single instance of the viewer application. +The MetaPost distribution contains two (plain) \TeX\ scripts, +\texttt{mproof.tex} and \texttt{mpsproof.tex}, that help with the latter +approach. + +\paragraph{\texttt{mproof.tex}} +\index{mproof.tex?\texttt{mproof.tex}} + +To write a proof sheet for MetaPost output, call \texttt{mproof.tex} as +$$ +\begin{verbatim}[commandchars=\\\{\}] +tex mproof \tdescr{MetaPost output files} +\end{verbatim} +$$ Then process the resulting \texttt{.dvi}\index{dvi file?{\tt dvi} - file}\index{files!dvi?{\tt dvi}} file as usual. + file}\index{files!dvi?{\tt dvi}} file as usual. That way, there's no +need to care about different settings of variable +\texttt{prologues}\index{prologues?\texttt{prologues}}, since in proof +sheets MetaPost graphics are already embedded. + +Note, the parameters after \texttt{mproof} are an explicit list of +MetaPost output files, possibly generated from different input files. +On shells that support POSIX\index{shell patterns}\index{POSIX!shell + patterns} shell patterns, these can be used to avoid typing a long +list of files. As an example, for a file \texttt{fig.mp} containing +three figures with charcodes 1, 2, and~3, the proof sheet can be +generated by calling +$$ +\begin{verbatim} +tex mproof fig.? +\end{verbatim} +$$ +The pattern \texttt{fig.?} is automatically expanded to \texttt{fig.1 + fig.2 fig.3} by the shell (but not necessarily in numerically +increasing order) before \TeX\ is run. If there were an output file +\texttt{fig.10}, using patterns \texttt{fig.??} or \texttt{fig.*} to +cover two-digit indices would fail, since those covered the source file +\texttt{fig.mp} as well. To avoid that, output file names have to be +made more significant, e.g., by setting variable \texttt{outputtemplate} +to \verb|%j-%c.mps| (see Section~\ref{Doutputtemplate}). The proof sheet +can then be generated with +$$ +\begin{verbatim} +tex mproof *.mps +\end{verbatim} +$$ -\section{Debugging} +\paragraph{\texttt{mpsproof.tex}} +\index{mpsproof.tex?\texttt{mpsproof.tex}} + +An alternative to \texttt{mproof.tex} is the script +\texttt{mpsproof.tex}, which is similar, but more powerful. While the +former script only runs with \TeX\ and requires a DVI output driver to +generate PostScript files, \texttt{mpsproof.tex} can as well be run +through pdf\TeX\ to directly generate PDF files. Additionally, it +provides some command-line options. + +With the +\verb|\noheaders|\index{mpsproof.tex?\texttt{mpsproof.tex}!noheaders?\texttt{\textbackslash + noheaders}} option, file names, date stamps, and page numbers are +omitted from the proof sheet. Use it like +$$ +\begin{verbatim}[commandchars=\|\{\}] +tex mpsproof \noheaders |tdescr{MetaPost output files} +\end{verbatim} +$$ + +The +\verb|\bbox|\index{mpsproof.tex?\texttt{mpsproof.tex}!bbox?\texttt{\textbackslash + bbox}} option can be used to generate an output file that has +exactly the same page size as a figure's bounding box (\verb|\bbox| is +actually an alias for the longer +\verb|\encapsulate|\index{mpsproof.tex?\texttt{mpsproof.tex}!encapsulate?\texttt{\textbackslash + encapsulate}}). With this option only one figure can be processed +at a time, e.g., +$$ +\begin{verbatim} +pdftex mpsproof \bbox fig.1 +\end{verbatim} +$$ + +\paragraph{Alternatives} Other alternatives for previewing MetaPost +figures, which are not part of the MetaPost distribution, are the +mptopdf\index{mptopdf} bundle or the Perl script \ttindex{mpstoeps.pl}. +There is also an online compiler and viewer for MetaPost code at +\url{http://tlhiv.org/mppreview/}. + +\subsection{Debugging} +\label{debug} + +\index{debug} MetaPost inherits from \MF\index{metafont?\MF} numerous facilities for interactive debugging, most of which can only be mentioned briefly here. @@ -5232,6 +5464,241 @@ shows in the transcript file at the end of the job how many of the MetaPost interpreter's limited resources were used. \end{description} +\subsection{Importing MetaPost Graphics into External Applications} +\label{mpimport} + +MetaPost is very well suited for creating graphics that are to be +included into third-party applications, such as text documents, +presentations or web pages, because MetaPost outputs graphics in vector +formats, which can be scaled without quality degradation. However, +practice shows, that vector graphics, too, are best created with a rough +target size already in mind. Scaling a vector graphic calls for +non-proportional scaling of certain technical parameters, such as line +width, arrow size or fonts. Otherwise, with growing scale factors +scalable graphics tend to change their visual character. Additionally, +during import into a main document, they'll likely fail to match, e.g., +stroke width of the document. To circumvent this, it is advisable to +apply only small post-processing scale factors to vector graphics. The +following sections briefly discuss how to import MetaPost graphics into +documents with selected applications. + +\subsubsection{\TeX\ and Friends} +\label{teximport} +\index{TeX?\TeX!and friends} + +MetaPost graphics in the PostScript\index{PostScript} format can be +easily integrated into documents prepared with \TeX\ and friends. +MetaPost's PostScript output is a low-featured dialect of the Postscript +language, called \emph{purified EPS}\index{EPS!purified}, which can be +converted into the Portable Document Format (PDF\index{PDF}) language +on-the-fly. For that reason, external MetaPost graphics can be used on +both routes: a) using the traditional \TeX\ engine together with an +external PostScript output driver and b) using newer \TeX\ engines, like +pdf\TeX\ or its successor Lua\TeX, which contain a built-in PDF output +driver. Lua\TeX\ can additionally process embedded MetaPost code +natively, falling back to the built-in \emph{mplib} library. + +Figure~\ref{fig:teximport} shows the process of including an external +MetaPost graphic into a \TeX\ document using the PostScript route. In +the \TeX\ source 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 more detailed information on some +popular combinations of \TeX\ formats and engines. + +\begin{figure} +$$ \includegraphics{mpman-charts-1.mps} $$ +\caption{A diagram of the processing for a \TeX\ document embedding + MetaPost figures} +\label{fig:teximport} +\end{figure} + +\paragraph{Plain \TeX\ Format} +\label{plaintexformat} +\index{TeX?\TeX!format, plain!importing MetaPost files} + +For users of the Plain \TeX\ format and the traditional \TeX\ +engine\index{TeX?\TeX!engine} with Device Independend output +(DVI\index{dvi file?{\tt dvi} file}) 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}|. + +Users of the pdf\TeX\ engine\index{pdfTeX?pdf\TeX!engine} should refer +to the standalone macros of the mptopdf\index{mptopdf} bundle, which can +be found at \url{http://context.aanhet.net/mptopdf.htm}. + +With the Lua\TeX\ engine\index{LuaTeX?Lua\TeX!engine}, embedding +external graphics works the same as with pdf\TeX. Additionally, +Lua\TeX\ users can inline MetaPost code directly into Plain \TeX\ +documents. Lua\TeX\ is able to process such MetaPost code snippets, +falling back to the built-in \emph{mplib}\index{mplib?\emph{mplib}} +library. Note, \emph{mplib} doesn't support +\verb|verbatimtex|\slash\verb|btex| \ldots\ \verb|etex| constructs, +currently. Here is an example of a MetaPost graphic inlined into a +Plain \TeX\ document. For more information, please refer to the +Lua\TeX~\cite[chap.~4.8]{luatex:manual} and +\ttindex{luamplib}~\cite{hagen:luamplib} documentation. + +$$\begin{verbatim} +\input luamplib.sty +\mplibcode +beginfig(1); + ... +endfig; +\endmplibcode +\bye +\end{verbatim} +$$ + +\paragraph{\LaTeX\ Format} +\label{latexformat} +\index{LaTeX?\LaTeX!format!importing MetaPost files} +\index{TeX?\TeX!engine} +\index{pdfTeX?pdf\TeX!engine} + +For users of the \LaTeX\ format and the traditional \TeX\ engine with +Device Independent output (DVI\index{dvi file?{\tt dvi} file}) the +well-known \ttindex{graphics} (or \ttindex{graphicx}) package aids in +external graphics inclusion. The package supports different engines, +guessing the correct output driver automatically, and can handle several +graphic formats. The ``magic macro'' is +$$ \verb|\includegraphics{|\descr{filename}\verb|}|% +\index{includegraphics?\texttt{\string\includegraphics}} $$ + +In DVI output driver mode the \ttt{graphics} package assumes all files +with an unknown file extension, such as \texttt{.1} etc., to be in the +EPS\index{EPS} format. It therefore handles MetaPost files with a +numeric default file extension correctly (see~\cite{reckdahl:epslatex} +for more information). + +When using the pdf\TeX\ engine with a built-in PDF output 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\index{EPS!purified} and can be converted +to PDF\index{PDF} on-the-fly. The recommended procedure for embedding +MetaPost graphics into \LaTeX\ documents compiled with pdf\TeX\ is +therefore to change MetaPost's output file name extension 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 \ttindex{dvips} driver, too. +Even though, again, this time \ttt{.mps} is an unknown file extension, +triggering EPS file handling in a fall-back procedure. This property of +the \ttt{graphics} package, which 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} +$$ + +With the Lua\TeX\ engine\index{LuaTeX?Lua\TeX!engine}, embedding +external graphics works the same as with pdf\TeX. Additionally, +Lua\TeX\ users can inline MetaPost code directly into La\TeX\ documents. +Lua\TeX\ is able to process such MetaPost code snippets, falling back to +the built-in \emph{mplib}\index{mplib?\emph{mplib}} library. Note, +\emph{mplib} doesn't support \verb|verbatimtex|\slash\verb|btex| \ldots\ +\verb|etex| constructs, currently. Here is an example of a MetaPost +graphic inlined into a \LaTeX\ document. For more information, please +refer to the Lua\TeX~\cite[chap.~4.8]{luatex:manual} and +\ttindex{luamplib}~\cite{hagen:luamplib} documentation. +$$\begin{verbatim} +\documentclass{article} +\usepackage{luamplib} +\begin{document} +\begin{mplibcode} +beginfig(1); + ... +endfig; +\end{mplibcode} +\end{document} +\end{verbatim} +$$ + +\paragraph{Con\TeX t Format} +\label{contextformat} +\index{ConTeXt?Con\TeX t!format!importing MetaPost files} + +In Con\TeX t\index{ConTeXt?Con\TeX t} graphics support is integrated in +the kernel, covering advanced features like shading, transparency, color +spaces or image inclusion. The ``magic macro'' for embedding external +graphics is +$$ \verb|\externalfigure[|\descr{filename}\verb|]|% +\index{externalfigure?\texttt{\string\externalfigure}} $$ +% +The macro can handle numbered files as well as files with the \ttt{mps} +suffix. + +Alternatively, Con\TeX t users can inline MetaPost code in the document +source, which allows for more natural interfacing with document +properties, font support, and automatic processing~\cite{hagen:metafun}. +Here is an example of a MetaPost graphic inlined into a Con\TeX t +document. +$$\begin{verbatim}[commandchars=|\[\]] +\starttext +\startuseMPgraphic{|tdescr[name]} + ... +\stopuseMPgraphic +\useMPgraphic{|tdescr[name]} +\stoptext +\end{verbatim} +$$ + +Con\TeX t MkIV, being based on the Lua\TeX\ engine, provides a much +tighter integration of MetaPost than older versions, since it can +fall-back to the built-in \emph{mplib}\index{mplib?\emph{mplib}} +library. + +\subsubsection{Troff} +\label{troffimport} +\index{troff!importing MetaPost files} + +It is also possible to include MetaPost output in a GNU +troff\index{troff} document. The procedure is similar to +Figure~\ref{fig:teximport}: the \ttindex{grops} output processor +includes PostScript files when they are requested via troff's +\ttt{\string\X}\index{X?\texttt{\string\X}} command. The +\ttt{-mpspic}\index{mpspic?\texttt{-mpspic}} macro package provides a +command \verb|.PSPIC|\index{PSPIC?\texttt{.PSPIC}}, which does just that +when including an encapsulated PostScript file in the source code. For +instance, the 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. + +\subsubsection{Web Applications} +\label{webimport} +\index{SVG!files} + +An SVG\index{svg file?{\tt svg} file}\index{files!svg?{\tt svg}} file +\texttt{fig.svg} can be easily embedded into HTML\index{HTML} documents +with the following code snippet: +$$\begin{verbatim} +<p> + <object data="fig.svg" type="image/svg+xml" width="300" height="200"> + </object> +</p> +\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*{Acknowledgement} |