[Tex/LaTex] How to add color to source code under the listings environment

colorlistings

I would like to color a few keywords in my slides under the listings environment

In the following contrived example, I would like to color the __shared__
word with orange and WIDTH with blue. How would I modify this?

    \begin{frame}[fragile]
               \lstset{language=C++,
               basicstyle=\ttfamily\scriptsize,
               keywordstyle=\color{blue}\ttfamily,
               stringstyle=\color{red}\ttfamily,
               commentstyle=\color{green}\ttfamily,
               breakline=true
              }
      \begin{lstlisting}
    __global__ 
    void MatMulKernelFast(double* d_M,double* d_N,double* d_P,int WIDTH)
    {
     __shared__ double ds_M[TILE_WIDTH][TILE_WIDTH];
     __shared__ double ds_N[TILE_WIDTH][TILE_WIDTH];
     }
  \end{lstlisting} 

\end{frame}

Here is the output of the previous code
enter image description here

Best Answer

You can use keywords=[2]{...}, keywordstyle=[2] for a second group of keywords with different style (in this case, for the keywords in orange color); using otherkeywords= you can use the blue color for WIDTH:

\documentclass{beamer}
\usepackage{listings}

\lstset{language=C++,
               basicstyle=\ttfamily\scriptsize,
               keywordstyle=\color{blue}\ttfamily,
               otherkeywords={WIDTH},
               keywords=[2]{__shared__},
               keywordstyle=[2]\color{orange}\ttfamily,
               stringstyle=\color{red}\ttfamily,
               commentstyle=\color{green}\ttfamily,
               breaklines=true,
}

\begin{document}

\begin{frame}[fragile]
\begin{lstlisting}
__global__ 
void MatMulKernelFast(double* d_M,double* d_N,double* d_P,int WIDTH)
{
  __shared__ double ds_M[TILE_WIDTH][TILE_WIDTH];
  __shared__ double ds_N[TILE_WIDTH][TILE_WIDTH];
}
\end{lstlisting} 

\end{frame}

\end{document}

enter image description here

Related Question