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

1 Answer 1

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

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

You must log in to answer this question.

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