0

I have the following MWE, where I use the package algorithm2e to print algorithms. However, I like the captions of the algorithms to be placed on the top (how to do this was already answered in this question). The placement of the caption works fine.

Unfortunately, the hyperref anchor is placed in the wrong place. When I click the link, the page jumps to the bottom line "Return" of the algorithm. How can I make it jump such that the caption is the first line on the display?

\documentclass{article}

\usepackage[boxed]{algorithm2e}

% https://tex.stackexchange.com/questions/147747/algorithm2e-caption-above-code
\makeatletter
\renewcommand{\@algocf@capt@boxed}{above} % formerly {bottom}
\makeatother

\usepackage[linkcolor=red]{hyperref}    

\begin{document}

Algorithm~\ref{algo:myalgo}.

\begin{algorithm}
    Do something.\\
    Calculate something.\\
    Erase something.\\
    Return.
    \caption{The caption}
    \label{algo:myalgo}
\end{algorithm}

\end{document}

1 Answer 1

0

You could try something like this:

\documentclass{article}

\usepackage[boxed]{algorithm2e}
\usepackage{etoolbox}
% https://tex.stackexchange.com/questions/147747/algorithm2e-caption-above-code
\makeatletter
\renewcommand{\@algocf@capt@boxed}{above} % formerly {bottom}
\renewcommand{\algocf@caption@boxed}{\vskip\AlCapSkip\MakeLinkTarget[topalgocf]{algocf}\box\algocf@capbox}%
\patchcmd\algocf@caption@algo
    {\hyper@refstepcounter{algocf}}
    {\hyper@refstepcounter{algocf}\xdef\@currentHref{top\@currentHref}}{}{\fail}
\makeatother

\usepackage[linkcolor=red]{hyperref}    

\begin{document}

Algorithm~\ref{algo:myalgo}.


\begin{algorithm}
    Do something.\\
    Calculate something.\\
    Erase something.\\
    Return.
    \caption{The caption}\label{algo:myalgo}    
\end{algorithm}

\end{document}
3
  • I get the error "Undefined control sequence. \end{algorithm}"
    – KennyH
    Commented Jun 8, 2023 at 14:08
  • you should look into the log-file to get the real error, don't rely on the summary of your editor. But if I should guess I would say your texsystem is not up-to-date. Commented Jun 8, 2023 at 14:18
  • Yes, indeed, that solved the issue.
    – KennyH
    Commented Jun 8, 2023 at 20:32

You must log in to answer this question.

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