[Tex/LaTex] Typesetting algorithms in LaTeX like Knuth

algorithmstypography

Is there any LaTeX package for typesetting algorithms in the style Donald Knuth uses in The Art of Computer Programming?

I know about the algorithm2e package, but I am looking for something that produces output like this:

1. [Check for lower bound.] If X < lower_bound, go to 3.

2. [Check for upper bound.] If X > upper_bound, go to 4.

I suppose I can use \newcommand and define my own macro, but I was hoping for something with more intelligence.

Best Answer

You can use the listings package, which has support for typesetting literate code. You need to set the replacement parameters first using \lstset{literate=}. This will replace for example := with $\gets$ etc.

\documentclass{article}
\usepackage{graphicx}
\usepackage{listings}
\begin{document}
\lstset{literate={:=}{{$\gets$}}1 {<=}{{$\leq$}}1 {>=}{{$\geq$}}1 {<>}{{$\neq$}}1}
\begin{lstlisting}
var i:integer;
if (i<=0) i := 1;
if (i>=0) i := 0;
if (i<>0) i := 0;
\end{lstlisting}
\end{document}

The setting is a bit tedious and the details can be found on page 48 of the listings package (just texdoc listings) from a command prompt interface.

Related Question