# Listing background broken by \colorbox and \framebox

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{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.

-

If you want to highlight entire lines, you can exploit the features of the lstlinebgrd package.

Here's an example:

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

\begin{document}

\begin{frame}[fragile]
\frametitle{Background broken}
\begin{lstlisting}[escapechar=$,linebackgroundcolor={\ifnum\value{lstnumber}=2\color{green}\else\color{lightgray}\fi}] int a = 0; int b = 0; int c = 0; int d = 0; int e = 0; int f = 0; int g = 0; \end{lstlisting} \end{frame} \end{document}  - You can set \fboxsep to a suitable value. \fboxsep=1.5pt seems to work fine. \documentclass{beamer} \usetheme{Montpellier} \usepackage{listings} \usepackage{xcolor} \fboxsep=1.5pt %% adjust \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}


With basicstyle=\footnotesize\ttfamily:

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

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

\end{frame}

\end{document}


-
this does not work if we use the ttfamily font (basicstyle={\footnotesize\ttfamily}) – An Cong Tran Feb 10 '14 at 6:32
@AnCongTran Is it? See the edit. – Harish Kumar Feb 10 '14 at 7:22
If you replace "int d = 0;" by "int g = 0;" you will see the problem. – An Cong Tran Feb 10 '14 at 8:13
@AnCongTran Sorry, but what is the problem? – Harish Kumar Feb 10 '14 at 8:23
It is so weird. If I replace "int d = 0;" by "int g = 0;", a gap appears between "int g" and "int d" (as in my question). I do not know how to attach the figure in this section. – An Cong Tran Feb 10 '14 at 10:04