# Put longtable caption in marginpar and keep compatibility with caption package

After some research I found a way to place the caption of a longtable (ltablex) into the left marginpar, aligned with the top of the table. Therefore, i adapted this solution stackexchange.com: longtable captions in marginpar

Here a MWE:

\documentclass[a4paper]{report}
\usepackage{longtable,caption,xcolor,lipsum}
% alter \LT@makecaption to move caption in top-left marginpar
\makeatletter
\def\LT@makecaption#1#2#3{%
\noalign{\vspace*{-0.4cm} % vertical adjustment to compensate for missing top caption
\smash{
\hbox{
\llap{
\parbox[t]{\marginparwidth}
{\vspace{0.5cm}\raggedleft#1{#2: }#3}
\kern\marginparsep
}
\kern\textwidth\
}
}
}
}
\makeatother

\begin{document}

\captionsetup{
labelfont={small,color={red}},
textfont={small,it}
}
\lipsum[8]
\begin{longtable}{rr}
\caption{This is a caption}\\
col1 & col2 \\
col1 & col2 \\
col1 & col2 \\
col1 & col2 \\
\end{longtable}
\lipsum[7]

\end{document}


Problem: This solution breaks compatibility with the caption package: While \captionsetup works flawlessly without this redefinition, it does not work afterwards.

Question: Is there a way to rewrite this code to either

• create/maintain compatibility with the caption package, or
• hardcode fontcolor/fontstyle of the caption into the code (if no other solution)
• or an alternative approach / solution with another package

Previous research: I experimented with the packages floatrow, sidecap, and caption, as well as the classes tufte-latex, and memoir, and the unofficial tufte sidenotes package.

The documentation of the caption package [2011/11/12] does suggest the following to move the caption type and number into the left margin (page 27f):

\DeclareCaptionFormat{llap}{\llap{#1#2}#3\par}


However, I wasn't able (lack the knowledge) to modify this code snippet, or other packages to achieve a similar result. The tufte sidenotes package looks particularly promising, but I don't know how to modify package code.

You may want either a caption with only the label in the margin, or the whole caption as a margin paragraph. I give a way of doing both:

\documentclass[a4paper]{report}
\usepackage{longtable,caption,xcolor,lipsum}

\usepackage{booktabs,ragged2e}
\DeclareCaptionFormat{marginlbl}{\llap{#1#2}#3\vskip-2\baselineskip}
\DeclareCaptionFormat{margin}{\hskip\dimexpr-\marginparwidth-\marginparsep\relax \setlength\fboxsep{0pt} \raisebox{\dimexpr-\height+0.45\baselineskip\relax}[0pt][0pt] {\parbox[0pt]{\marginparwidth}{\RaggedRight#1#2#3}} \vskip-1.5\baselineskip}

\captionsetup{
labelfont={small,color={red}},
textfont={small,it},singlelinecheck=no, format = margin
}

\begin{document}
\lipsum[8]
\begin{longtable}{rr}
\caption{This is a very, very, very long caption}\\
\midrule
col1 & col2 \\
col1 & col2 \\
col1 & col2 \\
col1 & col2
\end{longtable}
\lipsum[7]

\begin{longtable}{rr}\captionsetup{format=marginlbl}
\caption{This is a shorter caption}\\