[Tex/LaTex] Listing background broken by \colorbox and \framebox

backgroundsboxeslistings

I am using listing environment (listings package) with the background parameter. I want to highlight some lines of code and I am using the \colorbox, \makebox and \framebox to achieve this. However, a problem with my solution is that the background is broken (space without background in the listing environment).

Would you please to help me to solve out this problem.

\documentclass{beamer}
\usetheme{Montpellier}
\usepackage{listings}
\usepackage{xcolor}

\begin{document}

\begin{frame}[fragile]
\frametitle{Background broken}
\begin{lstlisting}[escapechar=$, backgroundcolor=\color{lightgray}]
int a = 0;
$\colorbox{green}{int b = 0;}$
int c = 0;
$\framebox{int d = 0;}$
int e = 0;
int f = 0;
int g = 0;
\end{lstlisting}

\end{frame}

\end{document}

enter image description here

Best Answer

You can use the very powerful tcolorbox package, so the background is colored on a global basis, rather than line by line:

\documentclass{beamer}
\usetheme{Montpellier}
\usepackage{tcolorbox}
\tcbuselibrary{listings}
\newcommand{\lcolorbox}[2]{%
  \hspace*{-\fboxsep}\colorbox{#1}{#2}%
}
\newcommand{\lfbox}[1]{%
  \hspace*{-\fboxsep}\hspace*{-\fboxrule}\fbox{#1}%
}

\usepackage{xcolor}

\begin{document}

\begin{frame}[fragile]
\frametitle{Background broken}
\lstset{escapechar=$}
\begin{tcblisting}{
  listing only,
  colback=lightgray,
}
int a = 0;
$\lcolorbox{green}{int b = 0;}$
int c = 0;
$\lfbox{int d = 0;}$
int e = 0;
int f = 0;
int g = 0;
\end{tcblisting}

\end{frame}

\end{document}

I have also provided some commands for adjusting the horizontal position of the boxes.

enter image description here