0

I would like to center code listings when they are narrower than the full page, but wrap them when they are not.

I am using a table to do so, following the advice from this answer. As breaklines is turned on, these lines are wrapped, so the result is displaying properly. However, when a line needs wrapping, it is emitting the warning of an overfull hbox.

The same pre-listing/post-listing code needs to be used regardless of whether it will wrap or not.

This means that the output is correct, I would only like to avoid the overfull hbox warnings. How can I avoid these warnings?

\documentclass{article}
\usepackage{listings}

\begin{document}

\center\tabular{c}
\begin{lstlisting}[breaklines]
# narrow
# should be centered
\end{lstlisting}
\endtabular\endcenter

\center\tabular{c}
\begin{lstlisting}[breaklines]
1 abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc abc 2
\end{lstlisting}
\endtabular\endcenter
\end{document}

Current output (should not change)

Output

Current log (should be removed)

Overfull \hbox (141.00484pt too wide) in paragraph at lines 13--17

  • You shouldn't put such a listing in a c-type column. – Ulrike Fischer May 12 '20 at 06:59
  • @UlrikeFischer what method would you suggest for centring a listing then? – Charlie Harding May 12 '20 at 09:31
  • @CharlieHarding: Why do you place the lstlisting inside of the tabular? Just to horizontally center the lstlisting? If that's the case, a simplecenter` environment should be sufficient. However, please note that there is no point in centering something that is as wide as the textwidth anyways. Please clarify. – leandriis May 12 '20 at 17:00
  • @leandriis yes, to horizontally center it. Some of my listings are wide enough to need wrapping, whereas others are narrower and so need wrapping. Simply using \center doesn’t work as a narrower listing will still take up \textwidth. The answer I was following was this one: https://tex.stackexchange.com/questions/5818/how-to-center-a-listing/5822#5822 – Charlie Harding May 12 '20 at 18:11
  • @leandriis I have edited the question to hopefully clarify this – Charlie Harding May 12 '20 at 18:20

0 Answers0