Latex Inspired Rendering of Algorithms in HTML

I recently updated the code for my blog (yes, this one) to render, in classic latex style, algorithms as pseudocode. This style has been so extensively used from the 80's and continues to be used as a standard format for rendering algorithms as pseudocode. Below is an example of what I'm talking about, its the Quicksort algorithm rendered using this style.

% This quicksort algorithm is extracted from Chapter 7, Introduction to Algorithms (3rd edition)
\begin{algorithm}
\caption{Quicksort}
\begin{algorithmic}
\PROCEDURE{Quicksort}{$A, p, r$}
  \IF{$p < r$}
    \STATE $q = $ \CALL{Partition}{$A, p, r$}
    \STATE \CALL{Quicksort}{$A, p, q - 1$}
    \STATE \CALL{Quicksort}{$A, q + 1, r$}
  \ENDIF
\ENDPROCEDURE
\PROCEDURE{Partition}{$A, p, r$}
  \STATE $x = A[r]$
  \STATE $i = p - 1$
  \FOR{$j = p$ \TO $r - 1$}
    \IF{$A[j] < x$}
      \STATE $i = i + 1$
      \STATE exchange
      $A[i]$ with     $A[j]$
    \ENDIF
    \STATE exchange $A[i]$ with $A[r]$
  \ENDFOR
\ENDPROCEDURE
\end{algorithmic}
\end{algorithm}

If you'd like to use it yourself then it isn't too hard. You can get most of the magic from a nice little java script library that you can find on github called pseudocode.js. The problem is that you will only get half way there using the javascript alone. The parts that are there work great, but it won't search your html for you and render anything, you have to write that yourself. For that if you put the following block of code at the end of your page's source, and make sure the project I linked earlier is already installed, then it will solve that problem for you.

  var blocks = document.getElementsByClassName("pseudocode");
  for(var blockId = 0; blockId < blocks.length; blockId++) {
    var block = blocks[blockId];

    var code = block.textContent;
    var options = {
      lineNumber: true
    };

    var outputEl = document.createElement('div');
    outputEl.className += " pseudocode-out";
    block.parentNode.insertBefore(outputEl, block.nextSibling);

    pseudocode.render(code, outputEl, options);
  }

  while( blocks[0]) {
    blocks[0].parentNode.removeChild(blocks[0]);
  }
  

Now all you have to do is add any element with a class of "pseudocode" and write the actual psueudocode inside the element, following the format specified in the pseudocode project. I prefer to define this as a "pre" element so if javascript is turned off it will still produce a human readable block. So other then that I didn't have to do anything too special to get it working.