Syntax highlighting and word wrapping code in LaTeX
For the longest time, I didn't think it was possible to syntax highlight code in LaTeX, but I was proven wrong a few months ago when I stumbled across the minted package, which uses pygments under-the-hood. Even better, it ships with texlive by default!
Recently, I had need to put it to use once more, and I encountered a bug in which my source code was too long for the line, but minted did not wrap it on to the following line. The solution was quite simple but definitely non-obvious, so I thought I'd make a quick post about it here.
To start with, minted works a lot like the lstlisting you might have used before:
An example block of syntax highlighted Javascript:
\begin{minted}{javascript}
"use strict";
export default async function(x, y) {
return x + y;
}
\end{minted}
Pretty easy, right? But if you have a really long line (or lots of indentation), then it might overflow the edge of the page without wrapping. Thankfully there's an easy way to fix it that I discovered after digging around for a bit:
\begin{minted}[breaklines,breakanywhere]{javascript}
"use strict";
export default async function(x, y) {
return x + y;
}
\end{minted}
....by adding [breaklines,breakanywhere] directly after \begin{minted}, we can get it to wrap onto the next line! Even better, we can use the same trick to also add line numbers for easy referencing later:
\begin{minted}[breaklines,breakanywhere,linenos]{javascript}
"use strict";
export default async function(x, y) {
return x + y;
}
\end{minted}
The linenos option here causes minted to draw line numbers before each line of code. This also respects wrapped lines too, so they don't get all out of sync. Here's a sample of all of these tricks put together in action:

I hope this helps someone out, because I know I find it very useful. I'll hopefully be posting another PhD update blog post soon for those who are eagerly await it - I know it's overdue!
Post a comment below if you have anything specific you'd like me to cover, and I'll do my best to make a post about it.