2

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?

3
  • Are you specifically referring to inline listings?
    – Werner
    Commented Sep 15, 2015 at 20:18
  • 1
    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!)
    – cgnieder
    Commented Sep 15, 2015 at 20:19
  • For those coming across this question: color - Colored background in inline listings - TeX - LaTeX Stack Exchange might be useful.
    – user202729
    Commented May 7 at 21:21

2 Answers 2

3

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

2

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}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .