Highlight source code keeping spacing intact

codecolorboxlistingsspacing

I try to highlight some lines of a code using colorbox in listings.

\documentclass[12pt,a4paper]{report}
\usepackage{xcolor}
\usepackage{listings}

\begin{document}

\lstdefinestyle{data}{
  backgroundcolor=\color{yellow},
  basicstyle=\ttfamily\small,
  escapechar=\%
}
\lstset{style=data}

\begin{lstlisting}
1       2       3       4
%\colorbox{gray}{1       2       3       4}%
5       6       7       8
\end{lstlisting}

\end{document}

mwe

As seen in the example, there seem to be four problems:

  1. all spacing is ignored;
  2. there is a thin blank line above;
  3. the font is a bit smaller;
  4. there is some indentation.

I can easily address the fourth one (adding a negative space), but I have no luck with the rest. Adding a \hspace in between can address the first problem, but it is very cumbersome.

Best Answer

\documentclass{article}
\usepackage{listings,mdframed,xcolor}

\NewDocumentCommand{\hl}{v}{\hspace{-\fboxsep}\colorbox{gray}{#1}}

\lstset{
  basicstyle=\ttfamily\small,
  escapechar=\%,
  columns=fullflexible,
  keepspaces,
}

\mdfsetup{backgroundcolor=yellow,linewidth=0pt}

\begin{document}

\begin{mdframed}
\begin{lstlisting}
1       2       3       4
%\hl{1       2       3       4}%
5       6       7       8
\end{lstlisting}
\end{mdframed}

\end{document}

enter image description here