Package framed

Default LaTeX style in knitr

By default, knitr uses a LaTeX package named framed for typesetting; the most obvious feature is the light gray shading. In this page, we introduce some tricks and known problems.

As listed in FAQ's, you may see the output overflow the shading box, and you can set options('width') to a smaller value in this case.

Overflow of elements

Besides text overflow, figures may also exceed the margin of the shading. If a figure is too wide, LaTeX may complain there is something wrong with the kframe environment, which is what knitr uses to wrap up the chunk output. A known case is about PNG graphics in #154. To make sure your figures do not exceed the page margin, knitr uses the following command in the LaTeX preamble:

%% maxwidth is the original width if it's less than linewidth
%% otherwise use linewidth (to make sure the graphics do not exceed the margin)
\makeatletter
\def\maxwidth{ %
  \ifdim\Gin@nat@width>\linewidth
    \linewidth
  \else
    \Gin@nat@width
  \fi
}
\makeatother

The chunk option out.width is set to '\\maxwidth' by default if the output format is LaTeX.

Padding of the shading box

This LaTeX command sets the padding to be 5mm if you feel the default layout is too parsimonious (no padding at all).

\setlength\fboxsep{5mm}

If you do not like this default style with the framed package, you are free to switch to other styles like listings or even define your own output hooks.

Incompatible environments with framed

It does not work well with the figure* environment in two-column documents; see knitr-twocolumn.pdf for one approach to deal with this situation.

If you use the Tufte handout/book classes, the fullwidth environment does not work well with the framed package either; see discussion in #222 for possible solutions.

It does not work with the lineno package; see Michael's post in the mailing list.