8

Out of pure laziness, I decided to create lstlisting floats with the option offered by the package:

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[float,caption={Test}]
  void a() {
    foo();
  }
\end{lstlisting}
\end{document}

This creates a float in which the code is left aligned:

enter image description here

This looks just silly on a page with text if code lines are short.

Of course, it's easy to center by creating "regular" figures (maybe with a custom type for listings), but this approach here has the appeal of brevity.

Is there a way to get the code centered in this setup?

Raphael
  • 5,983
  • Not a solution, but a suggestion: if you frame those listings, they will look less silly, as you put it. – jub0bs May 21 '14 at 12:28

1 Answers1

13

It's not so easy to automatically centre without modifying more listings internals than seems wise, but it easy to centre any specific example by adjusting the left margin:

enter image description here

\documentclass{article}
\usepackage[utf8]{inputenc}
\usepackage{listings}

\begin{document}
\begin{lstlisting}[float,caption={Test},xleftmargin=.4\textwidth]
  void a() {
    foo();
  }
\end{lstlisting}
\end{document}
David Carlisle
  • 757,742
  • Oh, I almost forgot about this; thanks for your reply! Given that the listing itself seems to get a "fitting" box, is it possible to determine its width and adjust the margin automatically? I guess not inside the options of lstlisting. – Raphael Nov 05 '14 at 11:19
  • 1
    @Raphael yes sorry about disturbing your sleep:-) I was just doing a sweep of the "unanswered" questions doing a bit of cleanup answering ones that looked like they could have an answer. Clearly it must be possible but a quick look at the source seemed to imply that you'd have to modify several internals to get the centering in, and I don't know that code that well so doing that without breaking other uses in the document that don't have exactly the same options might be tricky (too tricky to do in this pass of easy unanswered questions at least:-) – David Carlisle Nov 05 '14 at 11:28