
% (c) by Manuel Kauers 8.7.2001

% Example
%
%\begin{algo}%
%|procedure| 'test'
%	|begin|
%		|for| i = 1 |to| 100 |do|
%			x := x + 1;
%
%		|if| 'function'("variable") = 0 |then|
%			y = 7; // This is a comment
%
%		x^2+1;
%		|print| §do^2ne§;
%		|return| 'random'(1,\dots,15);
%	|end|%
% \end{algo}

% Macros to typeset keywords, functions, variables, text, and comments.
% Those do only do the fontifications.
\def\algo@keyword#1{\underline{\smash{\mathbf{#1}}}}
\def\algo@function#1{\mathop{\rm #1}}
\def\algo@var#1{\mathit{#1}}
\def\algo@text#1{\mathtt{\copy\algo@dq#1\copy\algo@dq}}
\def\algo@comment#1{\quad/\!/~\textrm{#1}}

% explicit space if the last item of the current list was not a kern and
% not a skip.
\def\algo@skip{\ifdim\lastkern=\z@ \ifdim\lastskip=\z@ \ \fi\fi}

% box register containing the typewriter double qoute sign
\newbox\algo@dq
{\catcode`\"=11
 \global\setbox\algo@dq=\hbox{\verb|"|}
}

% indenting amount
\newdimen\algo@indent
\algo@indent=1.5em

% macro to typeset line numbers
\def\algo@line#1{\textsc{\footnotesize #1}}

% counter for line numbers
\newcount\algo@linecnt

% change the catcodes to active
\def\algo@defcatcodes{%
 \catcode`\^^I=\active%
 \catcode`\^^M=\active%
 \catcode`\|=\active%
 \catcode`\'=\active%
 \catcode`\"=\active%
 \catcode`\§=\active%
 \catcode`/=\active%
}

% start a new line during the algorithm
\def\algo@startline{%
 \begin{math}\displaystyle\null\quad\llap{\algo@line{\the\algo@linecnt}}\quad%
 \global\advance\algo@linecnt by 1\relax%
}

\def\algo@slash{/}
% define the macro definition macro.
{\algo@defcatcodes%
\gdef\algo@defmacros{%
 \def^^I{\quad}%
 \def^^M{\@ifnextchar^^M\par{\end{math}\hfill\\\algo@startline}}%
 \let\par\smallskip%\smallskip\algo@startline}%
 \def|##1|{\algo@skip\algo@keyword{##1}\ }%
 \def'##1'{\algo@function{##1}}%
 \def"##1"{\algo@var{##1}}%
 \def§##1§{\algo@text{##1}}%
 \def//##1^^M{%
  \@ifnextchar^^M%
   {\algo@comment{##1}\par}%
   {\algo@comment{##1}^^M}%
 }%
}}

% define the environment
\newenvironment{algo}
{%
 \medskip\noindent
 \algo@defcatcodes%
 \algo@linecnt=1%
 \algo@defmacros%
 \algo@startline%
 \baselineskip1.1\baselineskip%
}{%
 \end{math}%
 \medskip%
}
