5

I want to create a table with Tabular and put a minted environment into it, just like here: How to embed a minted environment inside a tabular environment?.

However, as shown in that post, the minted part has some spaces on top and below, so that it is not at the same height as the "testing" comment. Does one have a solution, how to remove the white spaces?

1 Answer 1

7

Package minted is based on package fancyvrb. Thus the first space can be removed by disabling \FV@ListVSpace. The space at the end is caused by the code of column p. A final strut, which only contains the depth of the usual tabular strut box, is added at the end of the cell, intended to go to the end of the last line. However the environment minted is already closed and thus is the paragraph mode. Back to vertical mode, the final strut adds a new paragraph with a new line.

The following example defines environment tabminted, based on minted. It should remove the space at the begin and end. Depending on the depth of the last line (\prevdepth), the final strut is added as \vspace to get the normal spacing behavior in the tabular. It avoids that the bottom line comes to close.

\documentclass{article}
\usepackage{minted}
\usepackage{booktabs}

\makeatletter
\newenvironment{tabminted}{%
  \let\FV@ListVSpace\relax  
  \minted
}{%
  \endminted
  \unskip   
  \aftergroup\@tabmintedend
}
\newcommand*{\tabminted@finalstrut}[1]{%
  \ifdim\prevdepth>0pt
    \ifdim\dp#1>\prevdepth
      \vskip\dimexpr(\dp#1)-\prevdepth\relax
    \fi
  \else
    \vskip\dimexpr(\dp#1)\relax
  \fi
}
\newcommand*{\@tabmintedend}{%
  \let\@finalstrut\tabminted@finalstrut
}
\makeatother

\begin{document}

\noindent\begin{tabular}{rp{0.5\textwidth}}
\toprule
A & B\\  
\midrule 
testing &
\begin{tabminted}{c}
int main() {
  printf("hello, world");
  return 0;
}
\end{tabminted}
\\
\bottomrule
\end{tabular}

\end{document}

Result

1
  • I'd like to note for the sake of the next person googling this: this issue also affects enumerate environments, and this solution fixes it too. Commented Jul 27, 2023 at 11:42

You must log in to answer this question.

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