\textcolor 在 lstlisting 中吗?

\textcolor 在 lstlisting 中吗?

我有一些伪代码,我想用不同的颜色突出显示某些部分(原因是:在大学的作业中,我给出了一些代码并且必须对其进行调整。我想突出显示我为增强可读性而所做的更改)。

\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}

答案1

您应该提供 MWE。但是,我有以下答案:

\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}

在此处输入图片描述

相关内容