[Tex/LaTex] Emphasizing words within a string using the listings package in LaTeX

listings

I'm using the listings-package for LaTeX to format source-codes within my document. I can emphasize keywords using the emph-option of the listings package:

\lstset{
    emph={nerv},
    emphstyle={\color{red}\textbf}
}

\begin{lstlisting}[
    frame=trBL,
    caption={R-Code (test).},
    label={code:R_allee}
]
# comment
square <- function(x) {
    x^2
}

nerv = "Str ing "

x <- c(1:100)
y <- square(x)
\end{lstlisting}

This makes the "nerv" withing my source code bold and red. But, I want to highlight the "ing" withing the String "Str ing " using:

\lstset{
    emph={ing},
    emphstyle={\color{red}\textbf}
}

Unfortunately that does not work. I couldn't figure out what might solve the problem.

Does anyone of you have an idea?

Best Answer

I understand that this may be a moot point, since you only provide a minimal example. However, I also assume that highlighting the string ing in "Str ing " may be limited to only that specific instance in your code. For that, there is no need to define a style that is global to the entire listing. You could momentarily escape the listings environment (producing a local change), and typeset something using standard LaTeX by setting the mathescape=true flag:

\documentclass{article}
\usepackage{listings}
\usepackage{xcolor}
\begin{document}

\lstset{
    emph={ing},
    emphstyle={\color{red}\textit}
}

\begin{lstlisting}[
    frame=trBL,mathescape=true,
    caption={R-Code (test).},
    label={code:R_allee}
]
# comment
square <- function(x) {
    x^2
}

nerv = "Str $\color{blue}\textbf{ing}$ "
burn ing = hot

x <- c(1:100)
y <- square(x)
\end{lstlisting}

​\end{document}​

mathescape from within lstlisting

Another good example of such an illustration: Lstlistings: Getting pretty equations in display mode

Related Question