[Tex/LaTex] How to space before and after a `minted` code block with bgcolor

mintedspacing

I'm using minted to format code samples in my document, and I have set a bgcolor option to make them stand out. By default (as in Harish's answer below) the code block will naturally have some margins above and below to separate the code from the paragraphs. However, when I set a bgcolor, that goes away. The question is: how can I get the colored background while also getting normal whitespace above and below the code block? (Question has been edited since I narrowed down the problem to the case where bgcolor is set.)

Sample code:

\documentclass{article}
\usepackage{minted}
\usepackage{lipsum}

\usepackage{color}
\definecolor{light-gray}{rgb}{0.9,0.9,0.9}
\setminted{bgcolor=light-gray}  % this line causes the problem

\begin{document}
\lipsum*[1] Some text

\begin{minted}{c}
int main() {
printf("hello, world");
return 0;
}
\end{minted}

Some text \lipsum*[2]
\end{document}

The result:
enter image description here

Best Answer

I believe it's a bug in minted, because the internal minted@colorbg environment, used when the bgcolor option has been given, doesn't add vertical space above and below.

Here's a proposed fix:

\documentclass{article}
\usepackage{minted}
\usepackage{etoolbox}

\usepackage{color}

\usepackage{lipsum}

\definecolor{light-gray}{rgb}{0.9,0.9,0.9}
\setminted{bgcolor=light-gray}  % this line causes the problem

\makeatletter
\patchcmd{\minted@colorbg}{\noindent}{\medskip\noindent}{}{}
\apptocmd{\endminted@colorbg}{\par\medskip}{}{}
\makeatother

\begin{document}
\lipsum*[1] Some text

\begin{minted}{c}
int main() {
printf("hello, world");
return 0;
}
\end{minted}

Some text \lipsum*[2]
\end{document}

enter image description here

Related Question