# Using varwidth within an environment definition with minted

I'm trying to create a new environment which holds a centered code snippet using minted. Firstly I came across to a minipage package, however it needs the width specification. I just want it to be dynamic according to it's content length. So I picked varwidth which seemed doing exactly what I need. But when I try to put it like:

\newenvironment{ra}[3][]{
\VerbatimEnvironment
\begin{listing}
\caption{#2}
\label{#3}
\begin{center}
\begin{varwidth}{15em}
\begin{minted}[escapeinside=||,
mathescape=true,
autogobble,
frame=single,
style=vs,
#1]{text}}
{
\end{minted}
\end{varwidth}
\end{center}
\end{listing}
}


It just behaves the same way as minipage does. Does not adjust at all. Usage:

\begin{ra}{some caption}{code:label}
Example
\end{ra}


Am I doing anything wrong? Thanks

You want to make Verbatim into BVerbatim:

\documentclass{article}
\usepackage{minted}

\newenvironment{ra}[3][]
{%
\VerbatimEnvironment
\begin{listing}%
\caption{#2}\label{#3}%
\centering
\RecustomVerbatimEnvironment{Verbatim}{BVerbatim}{}%
\begin{minted}[
escapeinside=||,
mathescape=true,
autogobble,
frame=single,
style=vs,
#1
]{text}%
}
{%
\end{minted}
\end{listing}
}

\begin{document}

\begin{ra}{some caption}{code:label}
Example
\end{ra}

\end{document}


The frame option is not honored by BVerbatim, though. The remedy is to frame manually.

\documentclass{article}
\usepackage{minted}

\newenvironment{ra}[3][]
{%
\VerbatimEnvironment
\begin{listing}%
\caption{#2}\label{#3}%
\centering
\RecustomVerbatimEnvironment{Verbatim}{BVerbatim}{}%
\begin{lrbox}{\rabox}%
\begin{minted}[
escapeinside=||,
mathescape=true,
autogobble,
frame=single,
style=vs,
#1
]{text}%
}
{%
\end{minted}
\end{lrbox}
\fbox{\usebox{\rabox}}
\end{listing}
}
\newsavebox{\rabox}
\begin{document}

\begin{ra}{some caption}{code:label}
Example
\end{ra}

\end{document}


• Awesome! Thanks. Just one detail, do you know why the frame does not show up? Mar 31 '19 at 7:16
• @marthin23 Hmm, I guess you need to add the frame in a different way. Mar 31 '19 at 7:27
• Thank you for your time! Greatly appreciated Mar 31 '19 at 8:42
• Is there any possibility redefine the default caption Listing 1 to anything else? Mar 31 '19 at 10:25