Search code examples
rlatextexsweave

Getting Sweave code chunks to stay inside page margins?


Sometimes I get to make an R code chunk (in Sweave) which is longer then the margins of the page. Is there a way to force it to "go to the next line" once that happens?

Here is a simple example of that happening:

\documentclass[a4paper]{article}

\usepackage{Sweave}

\DefineVerbatimEnvironment{Sinput}{Verbatim} {xleftmargin=2em,
                                              frame=single}
\DefineVerbatimEnvironment{Soutput}{Verbatim}{xleftmargin=2em,
                                              frame=single}
\title{Sweave with boxes}

\begin{document}
\maketitle

<<echo=FALSE>>=
options(width=60)
@

Here is an example of a code chunk followed by an output chunk,
both enclosed in boxes.

<<>>=
print(rnorm(99))
@


<<>>=
print("aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa")
@


\end{document}

Solution

  • This is a difficult and extreme case, because you do not have spaces among those a's, so LaTeX may not be able to wrap the words. If you do have spaces, knitr will be able to produce the output with the long lines wrapped with tidy=TRUE, highlight=TRUE (so will Sweave, I think, if you set keep.source=FALSE).