1

in regards to this: How to center a lstlisting

This approach works like a charm. The only problem is that when using the caption of the lstlisting it is not centered, yet the caption of the figure is centered. But I still want to use my list of code.

Is there maybe a way to change the type of the figure caption? So that the figure caption acts as if it’s a lstlistings caption?

Or any other ideas?

Best, McTell

2
  • 2
    Use package caption or make a MWE. Commented Feb 15, 2017 at 12:37
  • As far as I know the captions for lstlisting are centered by default
    – user31729
    Commented Feb 15, 2017 at 14:17

1 Answer 1

2

You can define your own environment for a floating listing. I reused the code that was provided in How to center a lstlisting for centering the listing:

\documentclass{scrartcl}

\usepackage{float}% http://ctan.org/pkg/float
\usepackage{listings}
\usepackage{fancybox}

\makeatletter
\newenvironment{CenteredBox}{% 
\begin{Sbox}}{% Save the content in a box
\end{Sbox}\centerline{\parbox{\wd\@Sbox}{\TheSbox}}}% And output it centered
\makeatother

% Create new "listing" float, we do not use the "float" option of lstlisting, because we want to use our custom caption 
\newfloat{lstfloat}{htbp}{lop}%[section]
\floatname{lstfloat}{Listing}
\newcommand{\mylistoflistings}{\listof{lstfloat}{List of Listings}}

\begin{document}

\begin{lstfloat}
\begin{CenteredBox}
\begin{lstlisting}
#include <iostream.h>

main()
{
    cout << "Hello World!";
    return 0;
}
\end{lstlisting}
\end{CenteredBox}
\caption{blubb}
\end{lstfloat}
\mylistoflistings

\end{document}
1
  • Thats a good approach, but I need to redefine a lot of things I guess, and also \autoref needs some fixes when code labels are used...
    – Kalaschnik
    Commented Feb 15, 2017 at 17:02

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .