Introduction to Syntax Highlighting with Minted
When writing technical documents, research papers, or programming tutorials in LaTeX, displaying code snippets is a frequent requirement. While the standard listings package is a common choice, the minted package is widely considered the gold standard for high-quality syntax highlighting.
minted utilizes the powerful Pygments library (written in Python) to provide superior color schemes and support for over 300 programming and markup languages. This guide will walk you through the setup, basic usage, and advanced customization of the minted package.
Setting Up the Environment
Unlike most LaTeX packages, minted requires an external program to handle the highlighting logic. Because it relies on Python, there are a few extra steps to get it running.
1. Requirements
Before using minted, ensure you have the following installed on your system:
- Python: Most modern operating systems come with Python.
- Pygments: This is the engine that does the highlighting. You can install it via your terminal or command prompt using:
pip install Pygments
2. The --shell-escape Flag
LaTeX is usually restricted from running external programs for security reasons. Because minted needs to "talk" to Pygments, you must enable a feature called shell escape.
When compiling your document, you need to add the -shell-escape flag to your command:
pdflatex -shell-escape your_document.texNote for Editor Users: If you use an editor like Typevia, TeXstudio, or VS Code, you must enable shell escape in the settings. On Typevia, this is enabled by default, making it the easiest place for beginners to start with
minted.
Basic Usage
To start using the package, add \usepackage{minted} to your document preamble.
The minted Environment
The primary way to display a block of code is using the minted environment. You must specify the language as a mandatory argument.
\documentclass{article}
\usepackage{minted}
\begin{document}
Here is a simple Python function:
\begin{minted}{python}
def greet(name):
if name == "World":
print("Hello, World!")
else:
print(f"Hi, {name}!")
\end{minted}
\end{document}Inline Code
If you need to mention a variable or a short snippet within a sentence, use the \mintinline command.
To print a message in Python, use the \mintinline{python}{print()} function.Customizing Code Appearance
One of the greatest strengths of minted is its high level of customization. Options are passed in square brackets [] immediately following the language name.
Common Options
linenos: Adds line numbers to the left of the code.frame=lines: Adds horizontal rules above and below the code block. Other options includesingle,topline, etc.framesep=2mm: Controls the distance between the frame and the code.fontsize=\footnotesize: Adjusts the size of the text.breaklines: Automatically wraps long lines of code.
Example: A Styled Code Block
\begin{minted}[
frame=single,
framesep=3mm,
linenos,
fontsize=\small,
breaklines
]{cpp}
#include <iostream>
int main() {
// This is a very long comment that would normally go off the edge of the page without the breaklines option enabled.
std::cout << "Hello LaTeX enthusiasts!" << std::endl;
return 0;
}
\end{minted}Changing Highlight Styles
Pygments comes with many built-in color schemes (styles) like monokai, friendly, colorful, and manni. You can set the global style in your preamble:
\usemintedstyle{monokai}Working with External Files
For larger projects, it is often better to keep your source code in separate files rather than cluttering your .tex document. minted makes it easy to import these files directly.
The command \inputminted allows you to pull in an external code file and apply highlighting.
Example: Importing a Java file
\section{Implementation}
Below is the main logic of our application:
\inputminted[linenos, frame=single, firstline=10, lastline=25]{java}{src/Main.java}In this example, minted will only import lines 10 through 25 of Main.java, which is extremely helpful for focusing on specific logic sections without copying and pasting code.
Defining Custom Shortcuts
If you find yourself using the same options repeatedly (e.g., always using linenos and frame=single for Python), you can define a custom environment to keep your code clean.
Place this in your preamble:
\newminted{python}{frame=single, linenos, tabsize=4}Now, you can use a new environment named pythoncode:
\begin{pythoncode}
import math
print(math.sqrt(16))
\end{pythoncode}Tip: The command
\newminted{lang}{options}automatically creates an environment namedlangcode. For example,\newminted{cpp}{...}creates\begin{cppcode}.
Common Mistakes and Troubleshooting
1. "Package minted Error: You must have 'pygmentize' installed"
This is the most common error. It means either Pygments isn't installed or you forgot the -shell-escape flag. Double-check your installation and compiler settings.
2. Tab Characters
LaTeX can sometimes be picky about literal tab characters. If your indentation looks strange, try using the obeytabs option or converting your tabs to spaces in your source code.
3. Performance Issues
Because minted calls an external Python script every time you compile, it can be slower than listings.
Best Practice: Use the cache option to speed up compilation:
\usepackage[cache=true]{minted}This stores the highlighted snippets in a folder (usually named _minted-filename), so they don't have to be re-processed unless the code changes.
4. Mathematical Symbols inside Code
If you want to use LaTeX math symbols inside your code comments, use the mathescape option:
\begin{minted}[mathescape]{python}
# This calculates $\pi \cdot r^2$
area = math.pi * r**2
\end{minted}By following these guidelines, you can create professional-looking technical documents with beautiful, readable code snippets that enhance the quality of your LaTeX projects.
