Apr 27

LaTeX Language definition for Patch Files (generated by diff)

Category: Informatics

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}


Screenshot of the PDF file

3 comments

3 Comments so far

  1. andrew May 8th, 2009 3:41

    Thanks for that :) It was exactly what I needed

  2. Robin Sonefors January 15th, 2010 6:00

    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},
    }

  3. Phlogi April 25th, 2010 14:08

    Thanks, working perfectly!

Leave a comment