[Tex/LaTex] Problems customizing listings captions

captionscolorlistings

I'm trying to "decorate" source code with listings, but I'm getting some warnings and bad boxes when I compile my document. However the document compiles and looks like I want.

I noticed the warning is due to some } and { symbols in the code.

Overfull \hbox (6.0pt too wide) in paragraph at lines 31–31
[][][][][][][] []

LaTeX Font Info: Try loading font information for OMS+cmss on input
line 32.

LaTeX Font Info: No file OMScmss.fd. on input line 32.

LaTeX Font Warning: Font shape OMS/cmss/m/n' undefined (Font)
using
OMS/cmsy/m/n' instead (Font) for symbol
`textbraceleft' on input line 32.

\documentclass[a4paper]{article}

\usepackage[spanish,activeacute]{babel}
\usepackage{amsmath}
\usepackage{listings}
\usepackage{color}
\usepackage{xcolor}
\usepackage{caption}

\lstset{
basicstyle=\footnotesize,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}


\renewcommand{\familydefault}{\sfdefault}  %this is because default font looks blurry

\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{black}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

\begin{document}

Some Code:
\begin{lstlisting}
public void hello() {
    aaaa();
}
\end{lstlisting}

\end{document}

Best Answer

Use the Cork encoding:

\documentclass[a4paper]{article}
\usepackage[T1]{fontenc}
\usepackage[spanish,activeacute]{babel}
\usepackage{amsmath}
\usepackage{listings}
\usepackage{color}
\usepackage{xcolor}
\usepackage{caption}

\lstset{
basicstyle=\footnotesize,
numbers=left,
numberstyle=\tiny,
frame=tb,
columns=fullflexible,
showstringspaces=false
}


\renewcommand{\familydefault}{\sfdefault}  %this is because default font looks blurry

\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{black}{\parbox{\dimexpr\textwidth-2\fboxsep\relax}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}

\begin{document}

Some Code:
\begin{lstlisting}[caption=some code, label=source, language=java]
public void hello() {
    aaaa();
}
\end{lstlisting}

\end{document}

I also fixed an overfull box (you didn't have into account the \fboxsep lengths introduced by the \colorbox).

enter image description here

Perhaps you could be interested in this answer from Axel Sommerfeldt (the author of caption) about \DeclareCaptionBox.

Related Question