2

Is there a way to modify the code that minted uses to draw the background to have it up to the middle of the page, or a custom length? I think it should be done with a \newcommand or something like that since I want to keep the default style for large pieces of code, and the customized background length for small pieces of code.

\documentclass{article}

\usepackage{minted}
\usemintedstyle[c++]{manni}

\usepackage{xcolor}
\definecolor{codebackground}{RGB}{240, 240, 235}

\newlength{\msize}
\setlength{\msize}{\dimexpr(\paperwidth-\textwidth)/2\relax}

\begin{document} 
\hspace*{\msize} Stop background here?\par
\hspace*{\msize} $ \downarrow $
\begin{minted}[bgcolor=codebackground]{c} 
int main() {
  printf("hello, world");
  return 0;
}
\end{minted}
\end{document}

Here is the code that minted uses, taken from its documentation

\newenvironment{minted@colorbg}[1]{%
\setlength{\OuterFrameSep}{0pt}%
\colorlet{shadecolor}{#1}%
\let\minted@tmp\FV@NumberSep
\edef\FV@NumberSep{%
\the\numexpr\dimexpr\minted@tmp+\number\fboxsep\relax sp\relax}%
\medskip
\begin{snugshade*}}
{\end{snugshade*}%
\medskip\noindent}
1

1 Answer 1

3

If you want to box the minted environment, you can do

\documentclass{article}

\usepackage{minted}
\usepackage{xcolor}

\usemintedstyle[c++]{manni}
\definecolor{codebackground}{RGB}{240, 240, 235}

\newsavebox{\mintedbox}
\newenvironment{boxminted}
 {%
  \VerbatimEnvironment
  \RecustomVerbatimEnvironment{Verbatim}{BVerbatim}{}%
  \begin{lrbox}{\mintedbox}
  \begin{minted}%
 }
 {%
  \end{minted}%
  \end{lrbox}%
  \noindent\colorbox{codebackground}{\usebox{\mintedbox}}%
 }


\begin{document}

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

\end{document}

enter image description here

For a fixed size width,

\documentclass[a4paper]{article}

\usepackage{minted}
\usepackage{xcolor}

\usemintedstyle[c++]{manni}
\definecolor{codebackground}{RGB}{240, 240, 235}

\newlength{\msize}
\setlength{\msize}{\dimexpr\textwidth/2\relax}

\newsavebox{\mintedbox}
\newenvironment{boxminted}
 {%
  \VerbatimEnvironment
  \RecustomVerbatimEnvironment{Verbatim}{BVerbatim}{}%
  \begin{lrbox}{\mintedbox}
  \begin{minted}%
 }
 {%
  \end{minted}%
  \end{lrbox}%
  \noindent\colorbox{codebackground}{\makebox[\msize][l]{\usebox{\mintedbox}}}%
 }


\begin{document} 

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

\end{document}

enter image description here

2
  • 1
    Could you give some explanations ? I would like to remove the background color and auto-fit the box width with my text width. I have no idea how I can adapt your code to do that. Thanks.
    – Welgriv
    Aug 30, 2022 at 9:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .