[Tex/LaTex] captionof in longtable gives Misplaced \noalign

captionslongtable

Trying to make a multi-page figure panel, with 50 same-sized figures in a 2-by-5 arrangement on 5 pages, a Figure caption for the entire thing at the top of the first page, and everything placed onto pages where the margin has been reduced.

With subfigure, subfig, subcaption I only got errors about "Too many unprocessed floats.", and although \usepackage{morefloats} removed the error, it also removed the figures. Switching to simple 'tabular's caused other problems, similar as with 'minipage's, where the figure panel would have to be split into one panel per page and then other floats would appear between the panels, despite many earlier \clearpage's.

With 'longtable' it almost works. But the table is not counted under Figures.

\documentclass{article}
\usepackage{longtable}
\usepackage{capt-of}
\begin{document}

\begin{longtable}{cc}
    \captionof{figure}{This gives a Misplaced noalign error \label{fig:dummy1}} \\
     %\caption[This]{Works} \\
    Test & test 2 \\
    Test & test 2 \\
% later need to include this: \addtocounter{table}{-1} %
\end{longtable}

\end{document}

How to get captionof to work…?

Best Answer

longtable has its own definition of \caption which makes using \captionof doubly difficult: Even if you circumvent the Misplaced \noalign, you'll notice that the floattype table is hardcoded...

As \captionof will always call \caption it's a bit hard to patch it in a way which will work inside and outside of longtable without completely rewriting longtables version of \caption. Here's an idea based on \multicolumn:

\documentclass{article}
\usepackage{longtable}
\usepackage{etoolbox}

\makeatletter
\let\o@caption\caption
\newcommand\LT@captionof[2]
{%
  \multicolumn{\LT@cols}{p{\textwidth}}{\def\@captype{#1}\o@caption{#2}}%
}
\patchcmd\LT@array{\let\caption\LT@caption}
{\let\caption\LT@caption\let\captionof\LT@captionof}{}{}
\makeatother

\begin{document}

\listoffigures

\begin{longtable}{cc}
    \captionof{figure}{This gives a Misplaced noalign error \label{fig:dummy1}} \\
     %\caption[This]{Works} \\
    Test & test 2 \\
    Test & test 2 \\
% later need to include this: \addtocounter{table}{-1} %
\end{longtable}

reference to figure \ref{fig:dummy1}.

\end{document}

enter image description here

Related Question