开发者

latex and listings: highlighting some parts of the code

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 r开发者_StackOverflow社区ed and green underlining):

latex and listings: highlighting some parts of the code

.

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


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜