As a full-stack developer with over a decade of experience coding in languages like JavaScript, Python, C++, Rust, and Go, I rely heavily on LaTeX for writing technical documents covering everything from software architectures to cryptographic algorithms.
The ability to seamlessly integrate clean, well-formatted code blocks into LaTeX documents is an indispensable skill every professional coder should possess. Whether you are writing your Ph.D. thesis on neural networks or preparing an in-depth tutorial on building compilers, you absolutely need your code excerpts to stand out with clarity and precision.
In this guide, I will be leveraging my expertise as both a full-stack developer and LaTeX power user to suggest multiple methods for enhancing your code blocks. You will learn insider tips and little-known techniques to create gorgeous, publication-quality code listings worthy of any scientific journal or technical whitepaper.
Equip yourself with these advanced tools and radically transform the way you incorporate code into LaTeX projects!
Leveraging the Verbatim Environment – A Solid Building Block
Let‘s start by covering the simplest approach of using the inbuilt verbatim
environment. Here‘s a barebones example:
\begin{verbatim}
function sum(x, y) {
return x + y;
}
\end{verbatim}
This produces a plain code block rendering the contents in a mono-spaced font while ignoring any LaTeX commands:
Some key properties to note here:
- Contents render untouched without syntax highlighting
- Whitespace like newlines and tabs are preserved
- No need to escape special characters
This suffices for short code snippets but falls short when you want to:
- Highlight different logical blocks in color
- Number lines of code
- Enable line wrapping for readability
- Customize styles based on syntax
But verbatim serves as a useful baseline environment – one that‘s simple yet gets the job done. With more advanced packages, we can decorate the verbatim output to achieve professional-level results.
Before moving on, let‘s also check how inline code rendering works with verbatim:
You can call the \verb|sum()| function.
Gives:
With \verb| |
, you can drop code names and short snippets inline seamlessly thanks to verbatim.
Leveling Up Code Formatting with Listings
The listings
package brings much-needed enhancements for syntax highlighting, line numbering, rulers, breaks, and hyperlink integration among numerous other goodies.
Here‘s an example leveraging some of its capabilities:
\usepackage{listings}
\lstset{
language=Python,
tabsize=4,
caption={Factorial function in Python},
label=lst:factorial,
backgroundcolor=\color{blue!5},
frame=lines,
numbers=left,
numberstyle=\tiny,
breaklines=true
}
\begin{lstlisting}
def factorial(n):
result = 1
for x in range(1,n+1):
result *= x
return result
\end{lstlisting}
Output:
With around 150 configuration parameters at your disposal, the customization potential is practically endless.
Some examples of what you can tweak include:
- Numbering: 8 numbering styles like line numbers or relative offsets
- Theme: Color palettes, background styles
- Fonts: Alternate monospace fonts like PragmataPro
- Rules: Rulers, line highlighting, shadows, depth
- Spacing: Custom line spacing, indents
- Breaks: Intelligent line breaking rules
- Language: 130+ language definitions for syntax highlighting!
Let‘s see how we can utilize the language support in Listings:
\lstset{
language=JavaScript,
alsolanguage=HTML,
tabsize=2
}
\begin{lstlisting}
<script>
function greet() {
console.log("Hello!");
}
</script>
This automatically highlights both JavaScript and HTML appropriately:
Additionally, listings enable hyperlinking code objects to supplemental documentation with its identifier
tag:
\begin{lstlisting}[identifier=jsExample]
function increment(x) {
return x + 1;
}
\end{lstlisting}
...
Here the \lstinline[identifier=jsExample]!increment! function is shown.
This connection between code locations and external references is immensely useful when writing technical manuals.
Achieving Expert-Level Quality with Minted
If you want your code blocks to look like they came straight out of an official language documentation, minted is what you need!
It utilizes Pygments – a syntax highlighter that powers code styling across StackOverflow, GitHub, VSCode, Jupyter and many other platforms.
Let‘s see it add magic to a Python snippet:
\usepackage{minted}
\begin{minted}{python}
def bubble_sort(nums):
for i in range(len(nums)):
for j in range(len(nums) - i - 1):
if nums[j] > nums[j + 1]:
nums[j], nums[j+1] = nums[j+1], nums[j]
nums = [5, 3, 1, 2, 4]
bubble_sort(nums)
print(nums)
\end{minted}
Output:
With minted, you also have fine-grained control over styling elements like:
- Comments
- Functions
- Keywords
- Strings
- Numbers
- Variables
This enables true browser-grade code formatting that feels instantly familiar.
You can also customize:
- Tab spacing
- Break lines
- Rulers
- Captions
- Font sizes
- much more!
With 300+ supported languages and styles, minted eliminates the need to manually define language syntax rules. Its innate programming language intelligence automates the styling process – a capability that simply blows every other LaTeX package out of the water!
Comparison of Listings vs Minted
Now that you have seen listings and minted in action, you may wonder – which one is better?
In my experience minted wins hands down in terms of:
- Breadth of languages supported – 300+ vs 130+
- Intuitiveness of styling languages, no configuration needed
- Great looking default themes that blend well with most aesthetics
- Faithful representation of how code looks in IDEs and dev tools
- Active maintenance and updates
However, listings has some advantages in terms of:
- Integration with LaTeX counters and captions
- Hyperlink support between code locations and external documentation
- Granular control over all stylistic aspects beyond just coloring
My recommendation is to use minted for code blocks and listings for more advanced program listings that require tight LaTeX interlinking. This is the optimal combo I utilize in my own work.
Presenting Code Snippets Inline
In addition to dedicated code block environments, you will often need to mention small code fragments inline while discussing concepts in text.
Here‘s an example using minted:
\usepackage{minted}
\begin{document}
The \mintinline{python}|bubble_sort()| function
performs sorting in quadratic time.
\end{document}
This produces:
We can also use good old \texttt
without any special packages:
The \texttt{bubble\_sort()} function
performs sorting in quadratic time.
Output:
I recommend minted for inline code as well for automatic language recognition and formatting. The \texttt
alternative is better suited when language information is irrelevant.
Code Blocks for Data Analysis – Tables and Statistics
When writing analysis and reports on data science experiments, ML papers etc., presenting relevant metrics, statistics and evaluation data is crucial.
LaTeX offers stellar table construction facilities to insert beautifully formatted tabular numerical data seamlessly flowing with text:
\begin{table}[ht!]
\caption{Classification accuracy results}
\centering
\begin{tabular}{lcc}
\hline
& Precision & Recall \\ \hline
KNN & 0.94 & 0.96 \\
SVM & 0.98 & 0.97 \\
Neural Network & \textbf{0.99} & \textbf{0.98} \\ \hline
\end{tabular}
\end{table}
Output:
Coupled with floating placements, automatic numbering, multipage support and handy libraries like booktabs, LaTeX table construction is a breeze!
Here are some key table packages worth checking out:
- tabularx: Smart column sizing
- longtable: Multipage tables
- colortbl: Colorized tables
- multirow: Complex spanning
Showcasing Computational Notebooks
When dealing with exploratory data analysis and visualization-heavy machine learning workflows, Jupyter notebooks are ubiquitous.
Let‘s look at a simple example:
LaTeX enables converting these computational notebooks directly to publication quality PDF reports as is. No need to tediously copy paste images or data into a document.
The Jupyter-latex package handles the conversion seamlessly:
jupyter nbconvert my_analysis.ipynb --to pdfLatex
For BeakerX notebooks there‘s BeakerX-LaTeX.
These literate programming workflows combining code, visualizations and text narrations hugely boost scientific productivity. Integrating such computational notebooks directly within LaTeX documents grants immense flexibility when writing papers.
Final Recommendations and Best Practices
After going through numerous professional-grade options for enhancing code blocks across diverse LaTeX projects, I wanted to conclude by offering my top recommendations:
For everyday code blocks: Use minted without hesitation. It just works phenomenally well across the board.
For specialized program listings: Listings for its custom integrations with LaTeX internals.
For tables and data: Master LaTeX‘s built-in table construction facilities.
For notebooks: Utilize notebook specific converters like Jupyter-latex.
Additionally, adhere to the following best practices when working with code in LaTeX:
- Comment code appropriately for reader comprehension
- Number long code listings for easy reference
- Hyperlink code to external docs when suitable
- Reuse stylistic templates across documents for consistency
- Split long code blocks into coherent sections or files
- Show output snippets from key code locations
Adopting these suggestions coupled with the tips presented earlier will help you become a true LaTeX code virtuoso in no time!
Your coding creativity now has the perfect canvas to shine brightly within beautiful, publication-ready documents – so go forth and keep blowing minds with your phenomenal programming prowess fused seamlessly with LaTeX‘s aesthetics.
The sky is the limit my friend!