6

My goal is to use the Colorbox macro from the realboxes package to highlight inline code with the lstinline command from the listings package. The Colorbox command works great for this purpose, except that I find the amount of padding around the box to be a little too big for my tastes. Below I present a MWE and show the compiled example, and then show a comparison of what I would like it to look like (the modified version was created using image manipulation software).

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}
\usepackage{realboxes}

\begin{document}
Some inline code \Colorbox{gray!20}{\lstinline{@#$%^&*()}} here
\end{document}

Actual:

enter image description here

Desired:

enter image description here

6

You can locally set a different value for \fboxsep; in order to have all those backgrounds the same height, a phantom seems the best solution. You can also reduce the padding on the sides by using kerns.

\documentclass{article}
\usepackage{xpatch}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{realboxes}

\definecolor{mygray}{rgb}{0.8,0.8,0.8}

\lstset{
  basicstyle=\ttfamily,
  backgroundcolor=\color{mygray},
}

\makeatletter
\xpretocmd\lstinline
  {%
   \bgroup\fboxsep=1.5pt
   \Colorbox{mygray}\bgroup\kern-\fboxsep\vphantom{\ttfamily\char`\\y}%
   \appto\lst@DeInit{\kern-\fboxsep\egroup\egroup}%
  }{}{}
\makeatother

\begin{document}

\noindent\lstinline[language=TeX]|\my code| \lstinline|axe| \lstinline|lll|

\begin{lstlisting}[language=TeX,columns=fullflexible]
\my code
\end{lstlisting}

\end{document}

enter image description here

2
  • When I use this code with the microtype package, I've discovered that text in the inline blocks starting with a + or - shifts horizontally left slightly out of the background box. In other words, an entry such as \lstnline{-n} will result in the box surrounding the -n text to be in the correct place, but the -n itself moves left. Is there anything that can be done to fix this? – dpritch Feb 22 '18 at 5:17
  • Very nice. I found that inserting \let\Scalebox\relax right before \usepackage{realboxes} fixed an error I was getting, probably caused by some other package (re)defining Scalebox. – PatrickT Jun 14 '18 at 14:14
7

It uses the same \fboxsep parameter as the standard \colorbox

enter image description here

\documentclass{article}

\usepackage{xcolor}
\usepackage{listings}
\usepackage{realboxes}

\begin{document}
Some inline code \Colorbox{gray!20}{\lstinline{@#$%^&*()}} here

\setlength\fboxsep{0pt}
Some inline code \Colorbox{gray!20}{\lstinline{@#$%^&*()}} here
\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.