Background colour with minted package: code misplaced

minted uses the following macro internally if a background colour is selected:

\newsavebox{\minted@bgbox}

\newenvironment{minted@colorbg}[1]{
  \def\minted@bgcol{#1}
  \noindent
  \begin{lrbox}{\minted@bgbox}
  \begin{minipage}{\linewidth-2\fboxsep}}
 {\end{minipage}
  \end{lrbox}%
  \colorbox{\minted@bgcol}{\usebox{\minted@bgbox}}}

Without further testing I’m assuming that the use of a minipage doesn’t introduce a new paragraph. If so, a simple \par command before the box should correct the problem.

This seems like something that would have been noticed as a bug,

It should have. The fact is, the documentation minted.pdf pretty much serves as the only test case at the moment and in the documentation the bgcolor option is only used in a single example without surrounding text, so the lack of a paragraph break makes no difference.


You can solve this issue by making use of mdframed package (\usepackage{mdframed}), this way:

\definecolor{bg}{rgb}{0.95,0.95,0.95}
...

\begin{mdframed}[backgroundcolor=bg]
    \begin{minted}{latex}
        your code
    \end{minted}
\end{mdframed}

To update the previous answers, this is what the manual says about it as 2016:

This option will prevent breaklines from working with \mintinline. A \colorbox cannot break across lines.

This option will prevent environments from breaking across pages. If you want support for page breaks and advanced options, you should consider a framing package such as framed, mdframed, or tcolorbox. It is easy to add framing to minted commands and environments using the etoolbox package. For example, using mdframed:

\BeforeBeginEnvironment{minted}{\begin{mdframed}}
\AfterEndEnvironment{minted}{\end{mdframed}}

Some framing packages also provide built-in commands for such purposes. For example, mdframed provides a \surroundwithmdframed command, which could be used to add a frame to all minted environments:

\surroundwithmdframed{minted} 

tcolorbox even provides a built-in framing environment with minted support.

Tags:

Minted