[Tex/LaTex] Using package minted inside a multicol (multicol package)

mintedmulticol

I'm trying to list some code (package minted) inside a multicol (package multicol).

Example Code:

\documentclass{article}

\usepackage{minted}
\usepackage{multicol}

\begin{document}

  \begin{multicols}{2}
    This is a listing inside a multicolom:
    \begin{listing}
      \begin{minted}{sql}
        SELECT * FROM table1
      \end{minted}
      \caption{Some random SQL Query}
      \label{lst:sql}
    \end{listing}
  \end{multicols}

  This is a listing outside the multicolums:
  \begin{listing}
    \begin{minted}{sql}
      SELECT * FROM table2
    \end{minted}
    \caption{Some other random SQL Query}
    \label{lst:sql2}
  \end{listing}

\end{document}

Output:

output

Question:

The first listing is missing, as you can see. When not using minted inside the listing environment the code shows up, but without the needed chaption/label.

How can I use the minted listing environment inside a multicol with labels and chaptions?

Best Answer

The problem is that a listing is a float, like table or figure, and floats aren't allowed inside the multicol environment. If you're happy to place the listing where you want it by hand, you can achieve the effect you're after by removing the listing environment, using the caption package, and changing \caption to \captionof:

\documentclass{article}

\usepackage{minted, caption}
\usepackage{multicol}

\begin{document}

\begin{multicols}{2}
  This is a listing inside a multicolumn:
  \begin{minted}{sql}
    SELECT * FROM table1
  \end{minted}
  \captionof{listing}{Some random SQL Query}
  \label{lst:sql}
\end{multicols}

\end{document}

Alternatively, if you need the float facility, another option is to use the listing* environment instead. This, however, will set the listing across the whole page rather than in a single column, and also means that it will never appear on the page being typeset when the command is read (always on some subsequent page).