I want to put the caption of my listing in the center but I can't do that. Do you have any idea how I could achieve this? The code:
\documentclass{report}
\usepackage{color}
\usepackage{xcolor}
\usepackage{listings}
\usepackage{caption}
\DeclareCaptionFont{white}{\color{white}}
\DeclareCaptionFormat{listing}{\colorbox{gray}{\parbox{\textwidth}{#1#2#3}}}
\captionsetup[lstlisting]{format=listing,labelfont=white,textfont=white}
% This concludes the preamble
\begin{document}
\begin{lstlisting}[label=some-code,caption=Some Code]
function <lhs_arguments>=<function_name><rhs_arguments>
<statements>
endfunction
\end{lstlisting}
\end{document}
Best Answer
The caption format will be used internally after applying the justification & font setting, and therefore the
\colorbox
will be centered but not the text inside the\colorbox
.One can fix that by applying the justification setting inside the colorbox (again) using the internal command
\caption@hj
:(Please note that I replaced
\textwidth
with\captionwidth
so the margin & width settings will be used here, too.)But a more naturally way of fixing this is changing the internal code which actually draws the box around the caption, i.e. redefining
\caption@parbox
:(Although both
\caption@hj
and\caption@parbox
are not documented this will work with future versions of thecaption
package, too.)When using version 3.3 of the
caption
package this can be realized without using internal commands at all:Addendum 2013-01-09: Since the version 3.3 of the
caption
package is available now the last solution is preferable.