Apr 27
LaTeX Language definition for Patch Files (generated by diff)
As there is no lstlisting class for patches in LaTeX today I’ve had the problem to define a working definition to highlight diff files. If anyone else is having that problem, here are those 11 Lines of Code.
\definecolor{darkgreen}{cmyk}{0.7, 0, 1, 0.5}
\lstdefinelanguage{diff}
{
morekeywords={+, -},
sensitive=false,
morecomment=[l]{//},
morecomment=[s]{/*}{*/},
morecomment=[l][\color{darkgreen}]{+},
morecomment=[l][\color{red}]{-},
morestring=[b]",
}
After defining the diff format you can add the content by using the following code.
\lstset{language={diff}}
\begin{lstlisting}[captionpos=b, caption=text, label=src:patch]
- your content here -
\end{lstlisting}

3 Comments so far
Leave a comment
Thanks for that :) It was exactly what I needed
After googling like crazy, I finally found this post. Thank you!
I noticed problems with it, though: any line with a – or + character anywhere, that is not already highlighted, will be highlighted. Maybe you’re interested, maybe someone else will find this post — I wanted to share my version. I didn’t want the comment or string highlight support you used, since especially the strings and /* */ style comments sometimes breaks. I did want support for highlighting patch meta information, including the things git writes. The list of meta information keywords is incomplete.
The idea is this: all lines that aren’t changed starts with a space character, so use that as a “do nothing” keyword. Since this is the first option, this will be given the highest priority, and thus + or – after a space won’t do anything. Then I have your + and – code, and at the end I added a bunch of words that meta information lines may start with.
\definecolor{darkgreen}{cmyk}{0.7, 0, 1, 0.5}
\definecolor{darkblue}{rgb}{0.1, 0.1, 0.5}
\lstdefinelanguage{diff}
{
keywords={+, -, \ , @@, diff, index, new},
sensitive=false,
morecomment=[l][""]{\ },
morecomment=[l][\color{darkgreen}]{+},
morecomment=[l][\color{red}]{-},
morecomment=[l][\color{darkblue}]{@@},
morecomment=[l][\color{darkblue}]{diff},
morecomment=[l][\color{darkblue}]{index},
morecomment=[l][\color{darkblue}]{new},
morecomment=[l][\color{darkblue}]{similarity},
morecomment=[l][\color{darkblue}]{rename},
}
Thanks, working perfectly!