[Tex/LaTex] Using Beamer to step through an algorithm written in pseudocode.

beamerpseudocode

I am trying to create a beamer presentation in which I would step through an algorithm, highlighting the current line in the algorithm on each slide. I know it is possible to do with the semiverbatim environment, however, my algorithm has to be written in pseudocode. I am trying to match the pseudocode format that is used by the textbook I am using, and for that the algpseudocode package that is a part of the algorithmicx package seems to do an excellent work.

However, I cannot figure out how to highlight the current line in the algorithmic environment. I tried to do this:

\documentclass[ignorenonframetext]{beamer}
\usepackage{algpseudocode}

\begin{document}
\section{Blah}
\begin{frame}
   \frametitle{Blah}
   \begin{columns}
 \begin{column}{.4\hsize}
    \begin{algorithmic}
       \alert<1>{\State $z \gets 1$}
       \alert<2>{\For{$i = 1 \to n$}}
       \alert<3>{\State $z \gets z + \frac{1}{i}$}
       \alert<4>{\EndFor}
    \end{algorithmic}
 \end{column}%
 \begin{column}{.6\hsize}
    Some text discussing the current line.
 \end{column}
   \end{columns}
\end{frame}
\end{document}

however that gives me an error about missing \endcsname. Does anybody have any suggestion on how to achieve this?

Best Answer

The problem seems to be that the algorithmic environment needs to be able to "see" the commands \State, \For, \EndFor at the top level. It doesn't like having them in the \alert environments. One way around this is to simulate the alerting by merely changing the text colour on each line. Here's a way to do it:

\documentclass[ignorenonframetext]{beamer}
\usepackage{algpseudocode}

\newcommand{\alertline}{%
 \usebeamercolor[fg]{normal text}%
 \only{\usebeamercolor[fg]{alerted text}}}

\begin{document}
\section{Blah}
\begin{frame}
   \frametitle{Blah}
   \begin{columns}
 \begin{column}{.4\hsize}
    \begin{algorithmic}
\alertline<1>\State  $z \gets 1$
\alertline<2>\For    {$i = 1 \to n$}
\alertline<3>\State  $z \gets z + \frac{1}{i}$
\alertline<4>\EndFor
    \end{algorithmic}
 \end{column}%
 \begin{column}{.6\hsize}
    Some text discussing the current line.
 \end{column}
   \end{columns}
\end{frame}
\end{document}

This approach doesn't work if you want the background to be highlighted as that puts the text in a \colorbox which seems to hide it from the algorithmic environment.

(Note: my suppositions about what's happening are based purely on observation and not on any knowledge of what's going on under the bonnet.)

Related Question