Displaying minted code line numbers from within preview environment

The problem is that \parindent is zero when you evaluate it.

\documentclass{memoir}

\usepackage[active,pdftex,tightpage,psfixbb]{preview}
\usepackage{xcolor}
\usepackage{minted}

\pagestyle{empty}

\begin{document}
\begin{preview}
\begin{minted}[xleftmargin=20pt,linenos]{cpp}
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

unsigned short i;

int main() {
  for (i = 0; i <= 5; i++) {
    // whatever
  }  
  return 0;  
}
\end{minted}
\end{preview}
\end{document}

enter image description here

You might want to look at the standalone class:

\documentclass[
  class=memoir,
  varwidth,
  border={20 0 2 2},
]{standalone}

\usepackage{xcolor}
\usepackage{minted}

\begin{document}
\begin{minted}[linenos]{cpp}
#include <cstdio>
#include <cstdlib>
#include <iostream>

using namespace std;

unsigned short i;

int main() {
  for (i = 0; i <= 5; i++) {
    // whatever
  }  
  return 0;  
}
\end{minted}

\end{document}

enter image description here


In the meantime, I have myself found a simple workaround which makes sense in the overall context where my post came from. It is not in the strict sense an answer to my post because it involves wrapping the minted environment within a tikzpicture environment, but it works for me. I'll leave my "answer" unchecked for some time to see if somebody comes up with another not involving such a wrapping.

You can find below the pertinent lines to be added within my original MWE (I have also adjusted the value of the xleftmargin key).

\begin{preview}
\begin{tikzpicture}
  \node {
  \begin{minipage}{\textwidth}
  \begin{minted}[xleftmargin=1em,linenos]{cpp}
    // Whatever C++ code to be displayed 
  \end{minted}
  \end{minipage}      
  };
\end{tikzpicture}
\end{preview}

Tags:

Preview

Minted