[Tex/LaTex] Caption shifted left with `\captionof` in a list environment

captionshorizontal alignmentlists

I use the \captionof command from the caption package within a list environment. I would expect the caption to be centered with respect to the page, or to move right because of the indentation of the lists. However, the caption is shifted to the left (see example below, with four lists to exagerate the problem). How can this be fixed?

\documentclass{article}
\let\oldcaption\caption
\usepackage{caption}
\begin{document}
\begin{figure}
  Within a float:
  \oldcaption{Default \LaTeX's caption. OK.}
\end{figure}
\begin{figure}
  Within a float:
  \caption{\textsc{Caption}'s \texttt{\string\caption}. OK.}
\end{figure}
\noindent Outside of a float:
\bgroup
\captionof{figure}{\textsc{Caption}'s \texttt{\string\captionof}. OK.}
\egroup
\begin{itemize}
\item
  \begin{itemize}
  \item
    \begin{itemize}
    \item
      \begin{itemize}
      \item
        \begin{figure}[h]
          Within a float, within lists:
          \caption{\textsc{Caption}'s \texttt{\string\caption}. OK.}
        \end{figure}
        \noindent
        Outside of a float, within lists:
        \bgroup
        \captionof{figure}{\textsc{Caption}'s \texttt{\string\captionof}. Left shift.}
        \egroup
      \end{itemize}
    \end{itemize}
  \end{itemize}
\end{itemize}
\end{document}

Best Answer

I don't know the reason of this behavior, but if you put your \captionof inside a \parbox of width \linewidth

\parbox{\linewidth}{\captionof{figure}{\textsc{Caption}'s \texttt{\string\captionof}. Left shift.}}

the caption is centered in the remaining line width, that is, it is right-shifted as expected:

enter image description here

Full MWE:

\documentclass{article}
\let\oldcaption\caption
\usepackage{caption}
\begin{document}
\begin{figure}
  Within a float:
  \oldcaption{Default \LaTeX's caption. OK.}
\end{figure}
\begin{figure}
  Within a float:
  \caption{\textsc{Caption}'s \texttt{\string\caption}. OK.}
\end{figure}
\noindent Outside of a float:
\bgroup
\captionof{figure}{\textsc{Caption}'s \texttt{\string\captionof}. OK.}
\egroup
\begin{itemize}
\item
  \begin{itemize}
  \item
    \begin{itemize}
    \item
      \begin{itemize}
      \item
        \begin{figure}[h]
          Within a float, within lists:
          \caption{\textsc{Caption}'s \texttt{\string\caption}. OK.}
        \end{figure}
        \noindent
        Outside of a float, within lists:

        \vspace*{\baselineskip}
        \parbox{\linewidth}{\captionof{figure}{\textsc{Caption}'s \texttt{\string\captionof}. Left shift.}}
      \end{itemize}
    \end{itemize}
  \end{itemize}
\end{itemize}
\end{document} 

Also notice that the 4th caption is outside the list... That's probably why you don't encounter that strange behavior.