Using the Verbatim Environment
LaTeX provides the verbatim environment for displaying code with monospaced font formatting. This enviroment preserves all whitespace and line breaks exactly as entered, while ignoring any LaTeX commands within it.
\documentclass{article}
\begin{document}
\begin{verbatim}
Code within the \texttt{verbatim} environment
appears exactly as typed,
with all LaTeX syntax ignored.
\end{verbatim}
\end{document}
The starred variant verbatim* displays spaces as visible characters:
\documentclass{article}
\begin{document}
\begin{verbatim*}
Spaces become visible: here
and LaTeX commands: \textbf{ignored}
\end{verbatim*}
\end{document}
Syntax Highlighting with Listings Package
Key Configuration Parameters
- Language and Formatting
language: Programming language (Python, Java, C++, etc.)basicstyle: Base font style and sizekeywordstyle: Keyword appearancecommentstyle: Comment stylingstringstyle: String formatting
- Borders and Background
frame: Border type (none, single, box, etc.)backgroundcolor: Background colorframerule: Border thicknessframesep: Padding between border and code
- Line Numbers and Wrapping
numbers: Line number positionnumberstyle: Line number appearancebreaklines: Enable automatic line wrappingbreakatwhitespace: Break only at whitespace
Sample Configuration Templates
Template 1: VS Code Light Theme
\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\definecolor{codebg}{RGB}{248,248,248}
\definecolor{codefg}{RGB}{0,0,0}
\definecolor{codecomment}{RGB}{0,128,0}
\definecolor{codekeyword}{RGB}{0,0,255}
\definecolor{codestring}{RGB}{163,21,21}
\lstset{
basicstyle=\ttfamily\small\color{codefg},
backgroundcolor=\color{codebg},
keywordstyle=\color{codekeyword},
commentstyle=\color{codecomment}\itshape,
stringstyle=\color{codestring},
numbers=left,
numberstyle=\tiny\color{gray},
frame=none,
breaklines=true,
tabsize=4
}
\begin{document}
\begin{lstlisting}[language=Python]
def calculate_primes(limit):
"""
Generate prime numbers up to specified limit
"""
primes = []
for num in range(2, limit+1):
if all(num % i != 0 for i in range(2, int(num**0.5)+1)):
primes.append(num)
return primes
# Example usage
prime_numbers = calculate_primes(50)
print(f"Primes: {prime_numbers}")
\end{lstlisting}
\end{document}
Template 2: Basic Highlighting
\lstset{
language=Python,
basicstyle=\ttfamily\small,
keywordstyle=\color{blue},
commentstyle=\color{green},
stringstyle=\color{red},
numbers=left,
numberstyle=\tiny\color{gray},
frame=single,
breaklines=true,
tabsize=4
}
Algorithm Pseudocode
Use the algorithmic and algorithm packages for pseudocode:
\usepackage{algorithm}
\usepackage{algorithmic}
\begin{algorithm}
\caption{Example Sorting Algorithm}
\begin{algorithmic}[1]
\REQUIRE Input array $A$ of $n$ elements
\ENSURE Sorted array
\FOR{$i \gets 0$ to $n-1$}
\FOR{$j \gets 0$ to $n-i-2$}
\IF{$A[j] > A[j+1]$}
\STATE Swap $A[j]$ and $A[j+1]$
\ENDIF
\ENDFOR
\ENDFOR
\RETURN $A$
\end{algorithmic}
\end{algorithm}