When I searched how to generate pictures in org-mode on the Internet,
Metapost is surprisingly missing.
If you never tried Metapost, I think you should really take a look at
this gem.
This article will simply provide an example how I could create an
emacs package (not yet distributed) to use Metapost in my org-mode
documents.
The script
One of the main issue with Metapost is that, like
,
it generates a bunch of temporary files and clutter your current
directory with them. There is also a notion that Metapost is done to
generate not a single, but multiple files.
For our use case, we just want a program to generate a single
image.
This is why I wrote a very simple mp2png
script. It is
inspired by mp2png.sh
I could find in bsdowl.
In short, this script move a Metapost single figure code into a
temporary directory. We prepare enclose the figure description into a
Metapost template. We perform the compilation in that temporary
directory.
If you remove all the ceremony this is simply:
# Generate a temporary directory
tmpdir="$(mktemp -d)"
# Name the temporary metapost
tmpmp="${tmpdir}/tmp.mp"
# Provide a prelude
cat > "$tmpmp" <<EOF
prologues:=3;
outputtemplate:="tmp-1.eps";
EOF
# copy the content of your metapost code
cat "$src" >> "$tmpmp"
# close the metapost file
cat >> "$tmpmp" <<EOF
end.
EOF
# Move to the temporary directory
pushd "$tmpdir" || err "ERROR: pushd \"${tmpdir}\""
# Compile the metapost file
mpost "tmp.mp"
# Convert the EPS file to PNG
gm convert -density "$density" "tmp-1.eps" "tmp-1.png"
# Return to the original directory
popd || err "ERROR: popd (tmpdir= \"${tmpdir}\")"
With all the details this become a bit more complex because I would
like to be able to pass the code from stdin
as this will ease to write the org babel
code. Here is the full script:
#!/usr/bin/env zsh
# dependencies:
# - metapost
# - graphicsmagick
set -e
cmd=${0:t}
showhelp() {
echo "$cmd SRC [DEST]"
echo ""
echo "SRC could be any file if - is provided read from stdin"
echo " if - is provided the default file name will be result.png"
echo "DEST could be any file if - is provided read from stdin"
}
if (( $# == 0 )); then
showhelp
fi
src="$1"
density=1200
tmpdir="$(mktemp -d)"
if (( $# > 1 )); then
maindst="$2"
elif [[ "$src" = "-" ]]; then
maindst="result.png"
else
maindst="${src%.*}.png"
fi
err() {
local msg="$1"
echo "$msg" >&2
exit 1
}
dst="$maindst"
# i=0
# while [[ -e $dst ]]; do
# dst="${maindst%.*}-$((++i)).png"
# done
tmpmp="${tmpdir}/tmp.mp"
cat > "$tmpmp" <<EOF
prologues:=3;
outputtemplate:="tmp-1.eps";
% TEX macro is short enough to be copied
string preverbatimtex_, postverbatimtex_;
vardef TEXPRE text s = preverbatimtex_ := s; enddef;
vardef TEXPOST text s = postverbatimtex_ := s; enddef;
vardef TEX primary s =
if known preverbatimtex_:
write "verbatimtex "&preverbatimtex_&" etex" to "mptextmp.mp";
fi
write "btex "&s&" etex" to "mptextmp.mp";
if known postverbatimtex_:
write "verbatimtex "&postverbatimtex_&" etex" to "mptextmp.mp";
fi
write EOF to "mptextmp.mp";
scantokens "input mptextmp"
enddef;
beginfig(1);
EOF
if [[ "$src" = "-" ]]; then
cat >> "$tmpmp"
else
cat "$src" >> "$tmpmp"
fi
cat >> "$tmpmp" <<EOF
endfig;
end.
EOF
pushd "$tmpdir" || err "ERROR: pushd \"${tmpdir}\""
mpost "tmp.mp"
gm convert -density "$density" "tmp-1.eps" "tmp-1.png"
popd || err "ERROR: popd (tmpdir= \"${tmpdir}\")"
cp "${tmpdir}/tmp-1.png" "$dst"
echo "File: $dst"
And now for the code in emacs, inspired by ob-ditaa
:
;;; ob-metapost.el --- Babel Functions for metapost -*- lexical-binding: t; -*-
;; Copyright (C) 2024 Free Software Foundation, Inc.
;; Author: Yann Esposito
;; Keywords: literate programming, reproducible research
;; Homepage: https://orgmode.org
;; This file is part of GNU Emacs.
;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.
;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
;; GNU General Public License for more details.
;; You should have received a copy of the GNU General Public License
;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
;;; Commentary:
;; Org-Babel support for evaluating metapost source code.
;;
;; This differs from most standard languages in that
;;
;; 1) there is no such thing as a "session" in metapost
;;
;; 2) we are generally only going to return results of type "file"
;;
;; 3) we are adding the "file" and "cmdline" header arguments
;;
;; 4) there are no variables (at least for now)
;;; Code:
(require 'ob)
(require 'org-compat)
(defvar org-babel-default-header-args:metapost
'((:results . "file")
(:exports . "results"))
"Default arguments for evaluating a metapost source block.")
(defcustom org-babel-metapost-cmd "mp2png"
"Metapost to png command"
:group 'org-babel
:type 'string)
(defun org-babel-execute:metapost (body params)
"Execute a block of Metapost code with org-babel.
This function is called by `org-babel-execute-src-block'."
(let* ((out-file (or (cdr (assq :file params))
(error "Metapost code block requires :file header argument")))
(cmdline (cdr (assq :cmdline params)))
(in-file (org-babel-temp-file "metapost-"))
(cmd (concat org-babel-metapost-cmd
" " cmdline
" " (org-babel-process-file-name in-file)
" " (org-babel-process-file-name out-file))))
(with-temp-file in-file (insert body))
(message cmd)
(shell-command cmd)
nil)) ;; signal that output has already been written to file
(defun org-babel-prep-session:metapost (_session _params)
"Return an error because metapost does not support sessions."
(error "Metapost does not support sessions"))
(provide 'ob-metapost)
;;; ob-metapost.el ends here
And that's it. That was a lot easier than I expected. And now, I can
generate image like this:
u := 0.2cm;
z0 = (0,0);
z1 = (sqrt(3)*cm,0);
z2 = (sqrt(3)*cm,1cm);
draw z0--z1--z2--cycle;
label.bot(btex $\sqrt{3}$ etex, 1/2[z0,z1]);
label.rt(btex 1 etex, 1/2[z1,z2]);
label.top(btex 2 etex, 1/2[z0,z2]);
z3 = z1 - (u,0);
z4 = z1 + (-u,u);
z5 = z1 + (0,u);
draw z3--z4--z5;
or this:
numeric r, theta; r = sqrt 1/2; theta = 45;
vardef dragon(expr a, b) =
if abs(a-b) > 8:
save p; pair p;
p = r[a, b] rotatedabout(a, theta);
dragon(a, p) & reverse dragon(b, p)
else:
a .. b
fi
enddef;
vardef rounded_corners expr p =
save r, n; numeric r, n; r = 1/4; n = length p;
subpath (0, 1-r) of p
for t=1 upto n-1:
.. subpath (t+r, t+1-r) of p
endfor .. subpath (n-r, n) of p
enddef;
draw rounded_corners dragon(origin,240 right) withcolor (.6,.2,.7);
I hope it will help people to find the resources to write org babel
integrations as well as help people use Metapost more.