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

Kalaschnik
  • 178
  • 10

1 Answers1

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}
BR123
  • 307
  • 2
  • 10
  • 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 Feb 15 '17 at 17:02