latex and listings: highlighting some parts of the code

Unfortunately @Konrad's approach truly escapes from listings formatting entirely. If the highlighted text contains any program keywords, then those keywords will not be highlighted by the listings package as they would be on non-highlighted lines. The ideal might be to use \highlight{\lstinline{...}}, but it seems you cannot nest a \lstinline macro inside a listings environment.

The TeX StackExchange site has essentially the same question, with a nice answer based on the tikz package and a further refinement thereof. It overlays highlighting while still letting listings automatically format highlighted text.

This whole tikz-based approach took on a life of its own, eventually leading to a good, robust solution. That is currently the best known (to me) approach to highlighting selected listings lines while keeping automatic syntax highlighting. It will actually work just as well for stroking highlights between any pair of locations on a given page.


You can enable arbitrary LaTeX commands inside your listings region:

\begin{listings}[escapeinside=\{\}]
{\highlight{Colonnes[3] = 9}}
\end{listings}

\highlight is your highlighting macro (you need to write it yourself). See the listings documentation, section 4.14 (“Escaping to LaTeX”) for further details. Notice that you now need to escape every other occurrence of the special characters in your code – so for C++ code, {} is probably a bad choice.


In C or C++ code, I think the character ` is free to be the escape character.

lstset {
...
escapeinside=\`\`,
...
}

then, you can use it like

\begin{lstlisting}
const_cast<T>(`\it{exception}`)
\end{lstlisting}

the word exception then become exception. BTW, character ` is the Markdown format character for code, so its very easy to use it in C or C++ like code listing.

Tags:

Latex