[Tex/LaTex] Colored background in inline listings

colorlistingssourcecodeverbatim

I would like to make inline code more distinguishable from the text surrounding it, and I thought that using a background might work (like it is done on the stackexchange pages.)

Since I use the listings package for my other code samples, I tried the inline version of listings, but the key=value pairs seem not to work in the inline version (although the documentation seems to indicate that they should).

Full example:

\documentclass{article}
\usepackage{color}
\usepackage{listings}
\begin{document}
This is a test where \lstinline[backgroundcolor=\color{yellow}]{A=1} should have a yellow background.

This, on the other hand, actually works:
  \begin{lstlisting}[backgroundcolor=\color{yellow}]
    A = 1
  \end{lstlisting}
\end{document}

Questions:

  1. Can it be done with listings? And how?
  2. What other ways to
    increase the distinguishability of inline verbatim do you use?

Best Answer

I'm not familiar with most of the color- and highlighting-related options of the lstlistings package. However, the \colorbox macro, which is defined in the color package and takes two arguments (the color and the item to be placed in the colored box), will do a nice job of highlighting a piece of inline text. The following MWE builds directly on your code:

\documentclass{article}
\usepackage{color,listings}
\begin{document}
This is to test whether \colorbox{yellow}{\lstinline{A=1}} 
has a yellow background.
\end{document}

enter image description here

Addendum: As MartinScharrer has pointed out, the \colorbox command won't get the job done if the argument of your \lstinline command contains "real" verbatim material -- which may well feature some TeX "special" characters such as %, _, &, and so on. For that contingency, you should load the realboxes package and employ its \Colorbox macro:

This is to test whether \Colorbox{yellow}{\lstinline{A=@#$%^&*()1}} has a yellow background.

enter image description here