[Tex/LaTex] How to emphasize a part of a line in listing

emphasislistings

With the package listing I can use emph= to emphasize specific identifiers in the whole listing.

\begin{lstlisting}[style=towi, title=Functions,emph={add}]
void print(int arg) { /* ... */ }
int add(int a, int b) { return a + b; }
...
print(12);           // call function print
int sum = add(8, 4); // call function add
\end{lstlisting}

This will emphasize all instances of add in the listing.

But I want to emphasize only one specific instance, and not only the identifier, but want to choose freely, which part to emphasize, say add(8, 4);.

Best Answer

To achieve what you want, instead of adding emph=, define an escapechar and use the formatting of your emphstyle to emphasize that part of the line.

For example, let's suppose that you have

emphstyle=\underline

Then, defining

escapechar=ä

you can write

ä\underline{add(8, 4);}ä

to emphasize add(8, 4); and not the other occurrences of add.

MWE:

\documentclass{article}

\usepackage{listings}

\lstset{%
  basicstyle=\ttfamily,
  columns=fullflexible,
  emphstyle=\underline,
}

\begin{document}

\begin{lstlisting}[title=Functions,emph={add}]
void print(int arg) { /* ... */ }
int add(int a, int b) { return a + b; }
...
print(12);           // call function print
int sum = add(8, 4); // call function add
\end{lstlisting}

\begin{lstlisting}[title=Functions,escapechar=ä]
void print(int arg) { /* ... */ }
int add(int a, int b) { return a + b; }
...
print(12);           // call function print
int sum = ä\underline{add(8, 4);}ä // call function add
\end{lstlisting}

\end{document} 

Output:

enter image description here

Related Question