Using the minted package
The LaTeX package Minted
allows to use the syntax highlighter pygment
to display code in a LaTeX document. It is extremely versatile,
and in our latest paper,
my coauthors and I used it extensively.
To use minted
in a LaTeX project, one (NO LONGER, see edit)
has to modify a standard LaTeX compiler workflow
in two ways.
- The LaTeX compiler must be passed the
--shell-escape
command, and - The package
minted
must be told where the LaTeX auxiliary files are.
In my workflow (described here), these two things are done respectively by
- passing the argument
--latex-args=--shell-escape
tolatexrun
, and - importing
minted
with the optionoutputdir=latex.out
, as\usepackage[outputdir=latex.out]{minted}
.
Usage
Using Minted is relatively straightforward: to display code by itself,
one uses the minted
environment as follows:
\begin{minted}{julia}
"""
my_function(x, y, z)
This is the docstring of my function
"""
function my_function(x, y, z)
# this is a complicated function
sleep(5)
return x + y - z
end
\end{minted}
To display code inline, one writes something like
\mintinline{julia}{my_function(1, 2, 3) == 0}
.
If necessary, one can escape minted and execute LaTeX code inside a minted
environment,
by passing a symbol to the escapeinside
keyword. This looks like the following:
\begin{minted}[escapeinside=||]{julia}
"""
my_function(x, y, z)
This is the docstring of my function
"""
function my_function(x, y, z)
# this is a complicated function
sleep(5)
|\textrm{Here I display latex code inside minted!}|
|$\int_{0}^{\infty} f(x)dx = 0$ - It even handles mathmode.|
return x + y - z
end
\end{minted}
EDIT
The first draft of this post was quite old.
The latest version of minted
does not need the --shell-escape
argument,
and it finds the auxiliary files automatically, so it is no longer necessary to modify
one’s latex workflow in any way: one just needs to have pygmentize
installed.