1

I would like to make my listings environnements more readable by coloring the background of some keywords with a specific color. Like this :

enter image description here

I thought using the \colorbox function from xcolor package but It only work with an argument (not as \color) and doesn't work with listings.

Is there another way to get colored text background working with listings environnement?

  • Are you specifically referring to inline listings? – Werner Sep 15 '15 at 20:18
  • this is surely possible since listings allows for setting keywordstyles and also has a mechanism for escaping to LaTeX. However, it is rather unclear to me how you want to use it. (E.g., the picture you posted doesn't look at at like a listing!) – clemens Sep 15 '15 at 20:19
2

It's possible to use keywordstyle, identifierstyle etc. and set them to a specific colour or use a specific colour background with \colorbox{colorname} -- The relevant 2nd argument to \colorbox will be inserted by listings automatically. Please note, that this might look not as well as desired, see the example in the C - language with the descenders of the # - symbol:

\documentclass{article}

\usepackage{xcolor}

\usepackage{listings}


\begin{document}

\lstset{ keywordstyle={\colorbox{yellow}},identifierstyle={\colorbox{green}}}

\begin{lstlisting}[language=C]
#include <stdio.h>

int main(int argc, char** argv)
{
  printf("Hello World\n");
  return EXIT_SUCCESS;
}
\end{lstlisting}

\end{document}

enter image description here

1

Adding to Christian's answer, you might want to fix height of colorboxes and set their padding to zero, so that they don't change layout of your code.

print screen of result

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}

\newcommand{\myColorBox}[3][0pt]{{\fboxsep#1\colorbox{#2}{\strut #3}}}

\begin{document}

\lstset{columns=fullflexible,basicstyle=\ttfamily,keepspaces,language=C}

\begin{lstlisting}
#include <stdio.h>

int main(int argc, char** argv)
{
  printf("Hello World\n");
  return EXIT_SUCCESS;
}
\end{lstlisting}

\begin{lstlisting}[
  keywordstyle={\myColorBox{yellow}},
  identifierstyle={\myColorBox{green}}
]
#include <stdio.h>

int main(int argc, char** argv)
{
  printf("Hello World\n");
  return EXIT_SUCCESS;
}
\end{lstlisting}

\end{document}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.