2

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

2

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}

enter image description here

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}

enter image description here

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.