3

I'm trying to make an environment for python code using minted, but I always get FancyVerb error. Here is my code:

\documentclass{article}
\usepackage[utf8]{inputenc}

\usepackage{minted}
\usepackage{color, colortbl}
\definecolor{Gray}{gray}{0.9}

\newenvironment{code}[1][python]
{
    \begin{table}[ht]
            \begin{tabular}{p{0.8\textwidth}}
                \rowcolor{Gray}
                \begin{minted}{#1}
}
{
                \end{minted}
            \end{tabular}
    \end{table}
}



\begin{document}

\begin{code}
print("This is some code example") 
\end{code}

\end{document}

I read in this this answer that this is a problem with this kind of package, which cannot be used with \newenvironment. Is there any way around this? I don't mind changing the approach completely, but the result I want is to be able to have a code environment that formats the text according to the desired language (in my case python, but preferably I would like to be able to reuse this for other languages too).

1 Answer 1

3

I suggest a different method, namely to use tcolorbox.

\documentclass{article}

\usepackage[many]{tcolorbox}
\tcbuselibrary{minted,skins}
%\usepackage{minted}

\definecolor{Gray}{gray}{0.9}

\newtcblisting{code}[1][python]{
  colback=Gray,
  listing engine=minted,
  minted language=#1,
  listing only,
  skin=tile,
  width=0.8\textwidth
 }
\BeforeBeginEnvironment{code}{\begin{table}[htp]}
\AfterEndEnvironment{code}{\end{table}}


\begin{document}

\begin{code}
print("This is some code example") 
\end{code}

\begin{code}[C]
print("This is some code example") 
\end{code}

\end{document}

enter image description here

It's not difficult to make the box tighter around the code, see the extensive manual of tcolorbox.

For instance, if I change the code to

\newtcblisting{code}[1][python]{
  colback=Gray,
  listing engine=minted,
  minted language=#1,
  listing only,
  skin=tile,
  sharp corners,
  width=0.8\textwidth,
  top=2pt,bottom=2pt,left=2pt,right=2pt,
 }
\BeforeBeginEnvironment{code}{\begin{table}[htp]}
\AfterEndEnvironment{code}{\end{table}}

the result is

enter image description here

You must log in to answer this question.

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