How can I center a Sweave verbatim chunk?

I have a very simple sweave chunk with two lines, like this:

<<results=verbatim>>==
quantile(foo\$bar)
@


How can I center this element? I've tried embracing the chunk with \begin{center} to no avail.

A verbatim environment by default has the width equal to the text width. Thus you cannot center it: the trailing whitespace is included in the line.

Fortunately, Sweave.sty uses fancyvrb package internally. Sweave defines three environments, for the input, output and code, using fancyvrb in the following way:

\DefineVerbatimEnvironment{Sinput}{Verbatim}{fontshape=sl}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{}
\DefineVerbatimEnvironment{Scode}{Verbatim}{fontshape=sl}


Now fancyvrb has several environments. One which is helpful in your case is BVerbatim: the text is put into a box with the width by default equal to the width of the longest line of the text. The resulting box can be centered.

Thus the following works:

\documentclass{article}
\usepackage{Sweave}
\pagestyle{empty}
\DefineVerbatimEnvironment{Soutput}{BVerbatim}{}
\begin{document}
\noindent\rule{\textwidth}{.1pt} % To show centering
\begin{center}
<<>>==
2+3
@
\end{center}
\end{document}


We redefined Soutput as BVerbatim, and the output is now centered:

Note that only the output is centered in this example. To center input, redefine Sinput as well.

• Really nice answer! – Alan Munn Aug 2 '13 at 21:42
• @Boris, I've just noticed one problem with that configuration. At the end of the file, I insert another verbatim chunk which is just a print of part of a data frame. However, \DefineVerbatimEnvironment{Soutput}{Verbatim}{} prevents page breaking, so that last chunk will never fit the page (it has 129 rows and 3 cols). How can I prevent this? – Waldir Leoncio Aug 6 '13 at 22:43
• Well, BVerbatim is a box, so it is not splittable. Redefine the Soutput back to Verbatim just before this large chunk. – Boris Aug 7 '13 at 2:39