[Tex/LaTex] \textcolor within lstlisting

colorlistings

I have some pseudo-code where I want to highlight some sections in a different color (this is why: in an assignment at university, I have some code given and have to adapt it. I want to highlight what I changed for enhanced readability).

\documentclass[english, a4paper, 11pt]{article}
\usepackage{xcolor}
\usepackage{listings}
lstset(language=C)  //best for pseudo-code IMHO

\begin{document}
\begin{lstlisting}[frame=single]
   public class A<T> extends B<T> {
      \textcolor{red} {Stack stack};  //how can I achive this? Nothing should change, except for the textcolor. This code just prints the \textcolor command though.

       //ctor
       public A() {};
   }
\end{lstlisting}
\end{document}

Best Answer

You should provide a MWE. However, I have the following answer:

\documentclass{article}
\usepackage{listings}

\usepackage{xcolor}

\lstdefinestyle{base}{
  language=C,
  emptylines=1,
  breaklines=true,
  basicstyle=\ttfamily\color{black},
  moredelim=**[is][\color{red}]{@}{@},
}

\begin{document}

\begin{lstlisting}[frame=single,style=base]
   public class A<T> extends B<T> {
      @Stack stack@;  //how can I achive this? Nothing should change, except for the textcolor. This code just prints the \textcolor command though.

       //ctor
       public A() {};
   }
\end{lstlisting}

\end{document}

enter image description here

Related Question