Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

latex and listings: highlighting some parts of the code

Tags:

latex

I'm using Latex and the listings package to display some C++ code (with syntax highlighting) inside a document.

I need to highlight some parts of the code. This specific highlight has nothing to do with syntax highlighting, it's just some parts of the code I'd like to highlight so that the reader can focus on it.

I wish I could make some variable name, for instance, displaying in bold, and on a yellow background. Here is something I did with MSWord I'd like to reproduce with Latex (of course, not the red and green underlining):

.

I haven't found a way to do it with the listings package. Is it possible?

like image 369
Jérôme Avatar asked May 05 '10 09:05

Jérôme


3 Answers

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.

like image 88
Ben Liblit Avatar answered Nov 07 '22 08:11

Ben Liblit


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.

like image 44
Konrad Rudolph Avatar answered Nov 07 '22 07:11

Konrad Rudolph


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.

like image 4
coanor Avatar answered Nov 07 '22 06:11

coanor