Master the art of including beautiful code listings in LaTeX documents. Learn syntax highlighting, line numbering, and advanced formatting with listings and minted packages.
Including source code in technical documents is an art form. Whether you’re writing software documentation, academic papers, or technical tutorials, LaTeX provides sophisticated tools for presenting code with professional formatting and syntax highlighting. This comprehensive guide will transform how you showcase code in your documents.
Traditional word processors struggle with code formatting. LaTeX excels by offering:
\usepackage{listings}
\usepackage{xcolor} % For syntax coloring
% Basic code inclusion
\begin{lstlisting}
def hello_world():
print("Hello, LaTeX!")
return True
\end{lstlisting}
% Python code with syntax highlighting
\begin{lstlisting}[language=Python]
def fibonacci(n):
"""Calculate Fibonacci sequence"""
if n <= 1:
return n
return fibonacci(n-1) + fibonacci(n-2)
# List comprehension example
squares = [x**2 for x in range(10)]
\end{lstlisting}
% JavaScript with highlighting
\begin{lstlisting}[language=JavaScript]
const fetchData = async (url) => {
try {
const response = await fetch(url);
const data = await response.json();
return data;
} catch (error) {
console.error('Error:', error);
}
};
\end{lstlisting}
\lstdefinestyle{mystyle}{
backgroundcolor=\color{gray!5},
commentstyle=\color{green!60!black},
keywordstyle=\color{blue},
numberstyle=\tiny\color{gray},
stringstyle=\color{orange},
basicstyle=\ttfamily\footnotesize,
breakatwhitespace=false,
breaklines=true,
captionpos=b,
keepspaces=true,
numbers=left,
numbersep=5pt,
showspaces=false,
showstringspaces=false,
showtabs=false,
tabsize=4,
frame=single,
rulecolor=\color{black!30},
xleftmargin=10pt,
framexleftmargin=10pt,
framexrightmargin=5pt,
framexbottommargin=5pt
}
\lstset{style=mystyle}
% C++ style
\lstdefinestyle{cpp}{
language=C++,
style=mystyle,
keywordstyle=\color{blue}\bfseries,
stringstyle=\color{red},
commentstyle=\color{green!50!black}\itshape,
morecomment=[l][\color{magenta}]{\#},
morekeywords={override, final, constexpr, nullptr}
}
% Usage
\begin{lstlisting}[style=cpp]
#include <iostream>
#include <vector>
template<typename T>
class SmartContainer {
private:
std::vector<T> data;
public:
void add(const T& item) {
data.push_back(item);
}
size_t size() const noexcept {
return data.size();
}
};
\end{lstlisting}
% Include entire file
\lstinputlisting[language=Python]{scripts/data_analysis.py}
% Include specific lines
\lstinputlisting[
language=Java,
firstline=10,
lastline=25
]{src/Main.java}
% Include with custom caption
\lstinputlisting[
language=C,
caption={Memory allocation function},
label={lst:malloc}
]{src/memory.c}
% Define file extensions
\lstset{
inputencoding=utf8,
extendedchars=true,
literate={á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1,
language=Python,
}
% Auto-detect from extension
\lstinputlisting[language={}]{script.py} % Uses Python
\lstinputlisting[language={}]{style.css} % Uses CSS
% Requires Python Pygments: pip install Pygments
% Compile with: pdflatex -shell-escape document.tex
\usepackage{minted}
% Basic usage
\begin{minted}{python}
import numpy as np
import matplotlib.pyplot as plt
def plot_function(f, x_range):
x = np.linspace(*x_range, 1000)
y = f(x)
plt.figure(figsize=(10, 6))
plt.plot(x, y, 'b-', linewidth=2)
plt.grid(True, alpha=0.3)
plt.show()
\end{minted}
% Custom styling
\usemintedstyle{monokai}
% With line numbers and highlighting
\begin{minted}[
linenos,
numbersep=5pt,
frame=lines,
framesep=2mm,
bgcolor=gray!5,
fontsize=\footnotesize,
highlightlines={3,5-7}
]{rust}
fn main() {
let mut vec = Vec::new();
vec.push(1);
vec.push(2);
for item in &vec {
println!("Value: {}", item);
}
}
\end{minted}
% Using listings
The function \lstinline{calculate_sum(a, b)} returns the sum.
% With custom style
\lstinline[style=mystyle]|vector<int> numbers;|
% Using minted
The \mintinline{python}{lambda x: x**2} function squares input.
\usepackage{multicol}
\begin{multicols}{2}
\begin{lstlisting}[language=Python, caption=Python Version]
def factorial(n):
if n <= 1:
return 1
return n * factorial(n-1)
\end{lstlisting}
\columnbreak
\begin{lstlisting}[language=C, caption=C Version]
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n-1);
}
\end{lstlisting}
\end{multicols}
\usepackage[ruled,vlined]{algorithm2e}
\begin{algorithm}[H]
\DontPrintSemicolon
\SetAlgoLined
\KwResult{Sorted array}
\SetKwFunction{FQuickSort}{QuickSort}
\SetKwProg{Fn}{Function}{:}{}
\Fn{\FQuickSort{$A, low, high$}}{
\If{$low < high$}{
$pivot \gets$ \texttt{Partition}$(A, low, high)$\;
\FQuickSort{$A, low, pivot-1$}\;
\FQuickSort{$A, pivot+1, high$}\;
}
}
\caption{QuickSort Algorithm}
\end{algorithm}
\usepackage{algorithm}
\usepackage{algpseudocode}
\begin{algorithm}
\caption{Binary Search}
\begin{algorithmic}[1]
\Procedure{BinarySearch}{$arr, target$}
\State $left \gets 0$
\State $right \gets \text{length}(arr) - 1$
\While{$left \leq right$}
\State $mid \gets \lfloor(left + right) / 2\rfloor$
\If{$arr[mid] = target$}
\State \Return $mid$
\ElsIf{$arr[mid] < target$}
\State $left \gets mid + 1$
\Else
\State $right \gets mid - 1$
\EndIf
\EndWhile
\State \Return $-1$
\EndProcedure
\end{algorithmic}
\end{algorithm}
\begin{lstlisting}[
caption={RESTful API endpoint implementation},
label={lst:api-endpoint}
]
@app.route('/api/users/<int:user_id>', methods=['GET'])
def get_user(user_id):
user = User.query.get_or_404(user_id)
return jsonify(user.to_dict())
\end{lstlisting}
% Reference in text
As shown in Listing~\ref{lst:api-endpoint}, the API endpoint...
% Add after \tableofcontents
\lstlistoflistings
% Custom title
\renewcommand{\lstlistlistingname}{Code Examples}
\lstdefinelanguage{Docker}{
keywords={FROM, RUN, CMD, LABEL, EXPOSE, ENV, WORKDIR, COPY, ADD, ENTRYPOINT, VOLUME, USER, ARG},
keywordstyle=\color{blue}\bfseries,
comment=[l]{\#},
commentstyle=\color{green!50!black},
stringstyle=\color{red},
string=[b]",
morestring=[b]',
sensitive=false,
morecomment=[l]{//},
}
\begin{lstlisting}[language=Docker]
FROM node:14-alpine
WORKDIR /app
COPY package*.json ./
RUN npm install --production
COPY . .
EXPOSE 3000
CMD ["node", "server.js"]
\end{lstlisting}
% Add keywords to Python
\lstdefinestyle{python-extended}{
language=Python,
morekeywords={async, await, yield, with, as},
morekeywords=[2]{self, cls},
keywordstyle=[2]\color{purple},
}
% Cache formatted listings
\usepackage{listings-ext}
\let\lst@InputListing\lstinputlisting
\renewcommand\lstinputlisting[2][]{%
\begingroup
\lstset{#1}%
\lst@InputListing{#2}%
\endgroup
}
% Conditional inclusion
\newif\ifincludecode
\includecodetrue % or \includecodefalse
\ifincludecode
\lstinputlisting{large-file.cpp}
\else
\texttt{[Code omitted for brevity]}
\fi
\lstset{
morecomment=[s][\color{blue}\bfseries]{@}{@}, % Highlight special comments
}
\begin{lstlisting}[language=Java]
public class DatabaseConnection {
@ Important: Always close connections @
private Connection conn;
// Regular comment
public void connect(String url) {
/* Multi-line comment
explaining the connection process */
conn = DriverManager.getConnection(url);
}
}
\end{lstlisting}
% Using line notes
\begin{lstlisting}[
language=Python,
escapechar=|
]
def process_data(data):
cleaned = data.strip() |\colorbox{yellow}{Step 1}|
validated = validate(cleaned) |\colorbox{orange}{Step 2}|
return transform(validated) |\colorbox{green}{Step 3}|
\end{lstlisting}
When documenting code with inscrive.io:
% Define team coding style
\lstdefinestyle{company-style}{
% Company-specific formatting
basicstyle=\ttfamily\small,
keywordstyle=\color{companyblue},
commentstyle=\color{companygreen},
% ... more settings
}
% Enforce consistent usage
\lstset{style=company-style}
\begin{lstlisting}[language=JavaScript]
class UserManager {
constructor() {
// ... constructor code ...
}
addUser(userData) {
// ... validation ...
// ... database operation ...
// ... logging ...
}
// ... more methods ...
}
\end{lstlisting}
\lstdefinestyle{diff}{
morecomment=[f][\color{red}]-,
morecomment=[f][\color{green}]+,
morecomment=[f][\color{gray}]{@@},
}
\begin{lstlisting}[style=diff]
@@ -10,7 +10,7 @@
function calculate(x, y) {
- return x + y;
+ return x * y;
}
\end{lstlisting}
% Fix UTF-8 issues
\lstset{
inputencoding=utf8,
extendedchars=true,
literate=
{á}{{\'a}}1 {é}{{\'e}}1 {í}{{\'i}}1
{ó}{{\'o}}1 {ú}{{\'u}}1 {ñ}{{\~n}}1
}
% Handle long lines
\lstset{
breaklines=true,
breakatwhitespace=true,
prebreak=\mbox{\textcolor{red}{$\searrow$}},
postbreak=\mbox{\textcolor{red}{$\hookrightarrow$}\space},
}
#!/bin/bash
# Extract code examples for LaTeX
find ./src -name "*.py" -exec echo "lstinputlisting[language=Python]{{}}" ; > code-listings.tex
# .github/workflows/docs.yml
- name: Generate Code Documentation
run: |
python scripts/extract_examples.py
pdflatex -shell-escape main.tex
% Provide alternative text
\begin{lstlisting}[
caption={[Function to calculate factorial]Recursive factorial implementation},
label={lst:factorial}
]
def factorial(n):
return 1 if n <= 1 else n * factorial(n-1)
\end{lstlisting}
Professional code presentation in LaTeX elevates technical documentation from merely functional to truly exceptional. Whether using listings for traditional formatting or minted for modern syntax highlighting, LaTeX provides the tools to showcase code with the respect it deserves.
Platforms like inscrive.io enhance this capability with collaborative features, making it easier to maintain consistent code documentation across teams. The combination of LaTeX’s powerful formatting and modern collaboration tools creates the perfect environment for technical documentation.
Remember: well-presented code is not just about aesthetics—it’s about communication, understanding, and professional pride in your work.
Ready to create beautiful code documentation? Try inscrive.io for collaborative LaTeX editing with instant code preview, syntax highlighting, and team review features. Make your code documentation as professional as your code.
Master the art of including beautiful code listings in LaTeX documents. Learn syntax highlighting, line numbering, and advanced formatting with listings and minted packages.
Read in 21 minutesMaster word counting in LaTeX documents with texcount and other tools. Learn accurate counting methods for theses, papers, and reports including handling of citations, captions, and mathematics.
Read in 17 minutesMaster figure placement, image inclusion, and advanced graphics in LaTeX. Learn professional techniques for scientific illustrations, diagrams, and visual content management.
Read in 24 minutesMaster the art of creating professional CVs and resumes with LaTeX. Explore modern templates, formatting tips, and collaborative editing with inscrive.io for impressive job applications.
Read in 18 minutesStay up to date with the roadmap progress, announcements and exclusive discounts feel free to sign up with your email.
We care about the protection of your data. Read our Privacy Policy.