Running MetaPost

This page just gives the most basic introduction to getting output from MetaPost. For tutorials, references, and much more, see the MetaPost home page.

Contents: Running standalone - SVG output; filename extensions - Running inside ConTeXt - MetaFun

Running standalone

The basic method for running MetaPost is to create a plain text file with extension .mp and run MetaPost directly on the command line:

mpost ourfile.mp

Inside the .mp file, the code for drawing the graphics is enclosed within beginfig ... endfig. The % character starts a comment. Here's a complete example:

beginfig (1);
  % draw a line
  draw (1cm,2cm) -- (3cm,5cm);
endfig;
end.

The default output from running mpost is a PostScript file, with the file extension being the figure number. With this example, the output would be a file ourfile.1.

SVG output; filename extensions

If you add a line outputformat:="svg"; at the very beginning of the file, the output will be in SVG format. However, the resulting file will still be named ourfile.1. Most likely, you will need to rename it to ourfile.svg for it to be recognized. Alternatively, you can tell MetaPost to use .svg in the first place, like this:

outputtemplate := "%j-%c.svg";
outputformat   := "svg";

The %j is replaced with the main filename and the %c the figure number, so the output files here would be named ourfile-1.svg, ourfile-2.svg, etc.

You can also have MetaPost use a different extension for its normal PostScript output. Commonly, .mps is used for this (“MetaPost PostScript”), because that extension is already known to (La)TeX and can be handled without any further conversion. Thus:

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

This will create output files with names like ourfile-1.mps.

Running inside ConTeXt

Another method is to run MetaPost inside a ConTeXt document. In this case, the file extension is the usual .tex, and the MetaPost code (the same MetaPost code as when running standalone) is enclosed inside \startMPpage ... \stopMPpage, like this:

\startMPpage
  % draw a line
  draw (1cm,2cm) -- (3cm,5cm);
\stopMPpage

The usual command line invocation with ConTeXt would be:

context ourfile.tex

The output from ConTeXt is (by default) a PDF file, ourfile.pdf in this case. (Naturally, you can have both normal document text and MetaPost code in one and the same ConTeXt file.)

MetaFun

The MetaFun add-on package to MetaPost provides much additional functionality, e.g., an xsized command to easily scale an image.

MetaFun is loaded by default in ConTeXt, but needs to be explicitly loaded when using standalone plain MetaPost documents, like this:

mpost --mem=metafun ourfile.mp

Have fun.


(Credits: This page is an edited version of text from Mari Voipio's article, Entry-level MetaPost: On the grid, published in TUGboat 34:1. It seemed worth having on the web as a standalone page.)


$Date: 2019/07/23 22:39:01 $;
TUG home page; webmaster; facebook; twitter; mastodon;   (via DuckDuckGo)