# Error when compiling a 'minted' listings inside a 'memoir' subfloat

I'm trying to compile the following minimal example:

\documentclass{memoir}

% Enable subfloats within figures
\newsubfloat{figure}

\usepackage{minted}

\begin{document}
\begin{figure}
\subbottom{%
\begin{minted}{c}
test;
\end{minted}
}
\end{figure}
\end{document}


but I get an error:

! Argument of \FV@BeginScanning has an extra }.
<inserted text>
\par
l.13 \end{minted}}


I've tried replacing the minted environment with a inputminted which reads the code from a file, but to no avail.

How do I fix this?

The minted environment can't work in the argument to another command, because the produced file which is input (and removed) uses the Verbatim environment.

A solution is to save the minted environment in a box and then use it:

\documentclass{memoir}

% Enable subfloats within figures
\newsubfloat{figure}
\newsavebox{\mintedbox}

\usepackage{minted}

\begin{document}
\begin{figure}
\begin{lrbox}{\mintedbox}
\begin{minipage}{\textwidth} % add here for the width
\begin{minted}{c}
test;
\end{minted}
\end{minipage}
\end{lrbox}
\subbottom{\usebox{\mintedbox}}
\end{figure}
\end{document}


A fancier solution is to do that without having to remember doing it, by defining a suitable environment. The width reserved for the listing is a mandatory argument, while the first and second optional arguments have the same meaning as for the \subbottom command.

\documentclass{memoir}
\usepackage{xparse}
% Enable subfloats within figures
\newsubfloat{figure}
\newsavebox{\mintedbox}

\NewDocumentEnvironment{mintedsubbottom}{oom}
{\begin{lrbox}{\mintedbox}\begin{minipage}{#3}}
{\end{minipage}\end{lrbox}%
\IfNoValueTF{#1}
{\subbottom{\usebox{\mintedbox}}}
{\IfNoValueTF{#2}
{\subbottom[#1]{\usebox{\mintedbox}}}
{\subbottom[#1][#2]{\usebox{\mintedbox}}}%
}%
}

\usepackage{minted}

\begin{document}
\begin{figure}
\begin{mintedsubbottom}[Caption]{\textwidth}
\begin{minted}{c}
test;
\end{minted}
\end{mintedsubbottom}
\end{figure}
\end{document}