3

When using the packages algorithm2e (with figure option) and caption, together with a two-sided page layout, indentation of the caption is incorrect on every second page. Minimum example:

\documentclass{book}
\usepackage{caption}
\usepackage[english]{babel}
\usepackage[figure]{algorithm2e}
\begin{document}
test test test test test test test test test test test test test test test test
test test test test test test test test test test test test test test test test
\begin{algorithm}[bht]
\Return{$\epsilon$}\;
\caption{Example example example example example example example}
\end{algorithm}
\newpage
test test test test test test test test test test test test test test test test
test test test test test test test test test test test test test test test test
\begin{algorithm}[bht]
\Return{$\epsilon$}\;
\caption{Example example example example example example example}
\end{algorithm}
\end{document}

Does anyone know how to fix this?

Werner
  • 603,163
Martin
  • 33

1 Answers1

0

This is specific to algorithms that are set as figures appearing on verso (even) pages under the twoside option when caption is loaded. It seems the algorithm environment needs to reverse the default margin adjustment for these specific cases. You can do it manually:

enter image description here

\documentclass{book}

\usepackage{caption}
\usepackage[figure]{algorithm2e}

\begin{document}

\noindent X \dotfill X

\begin{algorithm}
  \caption{Example example example example example example example}
\end{algorithm}

\newpage

\noindent X \dotfill X

\begin{algorithm}
  \captionsetup{margin={\algomargin,-\algomargin}}
  \caption{Example example example example example example example}
\end{algorithm}

\end{document}

Alternatively, you can condition on whether the page is odd/even and set the margin automatically (see If Then Else for odd page/even page). Add the following to your preamble after loading algorithm2e:

\usepackage{changepage}
\strictpagecheck

\makeatletter
\let\old@algocf@init\@algocf@init
\renewcommand{\@algocf@init}{%
  \ifnum\pdfstrcmp{\algocf@float}{figure}=0
    \ifalgocf@figurecaption
      \checkoddpage
      \ifoddpage
        \captionsetup{margin={-\algomargin,\algomargin}}% Odd page
      \else
        \captionsetup{margin={\algomargin,-\algomargin}}% Even page
      \fi
    \fi
  \fi
  \old@algocf@init}
\makeatother
Werner
  • 603,163
  • Awesome, Werner, thank you so much! The second solution gives me the correct indentation only at the second compile run, but then I need to recompile the document because of undefined references, and afterwards indentation is wrong again. However, the first solution works fine, and it's already perfect for me. – Martin Sep 25 '16 at 17:21
  • @Martin: It would be interesting if you could provide a sample document that replicates your problem. I've reached out to the package author suggesting my solution as it seemed to work. However, if it doesn't, we'd need to find out why. – Werner Sep 25 '16 at 18:09