Beautiful math in Javadoc

A formula like a picture is often worth a thousand words. Working on software for mathematical optimization, I've been wondering how can I embed math in my API documentation generated by Javadoc. Recently I had some time to explore this problem and this post is devoted to my findings.

As Javadoc generates output in HTML format, MathML is the obvious candidate for embedded math. However, I am not paid for the number of lines of code I write, so MathML doesn't really appeal to me. For example here's a MathML snippet for \(ax^2 + bx + c\):

<math>
    <apply>
        <plus></plus>
        <apply>
            <times></times>
            <ci>a</ci>
            <apply>
                <power></power>
                <ci>x</ci>
                <cn>2</cn>
            </apply>
        </apply>
        <apply>
            <times></times>
            <ci>b</ci>
            <ci>x</ci>
        </apply>
        <ci>c</ci>
    </apply>
</math>

What really appeals to me is LaTeX especially considering that it will allow me to copy existing formulas to and from my LaTeX documents. The above example in LaTeX is just ax^2 + bx + c. Besides, browser support for MathML is patchy at best.

Fortunately, there are at least two Javascript libraries, MathJax and jsMath, that can render LaTeX formulas. To link MathJax to the generated HTML pages add the -header option providing the necessary code to the javadoc command as follows:

$ javadoc -header \
    '' ...

Or, if you are using Maven, you can pass the Javadoc parameter via additionalparam as in the following POM extract:

<build>
  <plugins>
    <plugin>
      <groupid>org.apache.maven.plugins</groupid>
      <artifactid>maven-javadoc-plugin</artifactid>
      <version>2.8</version>
      <configuration>
        <additionalparam>-header &apos;&lt;script type=&quot;text/javascript&quot; src=&quot;http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML&quot;&gt;&lt;/script&gt;&apos;</additionalparam>
      </configuration>
    </plugin>
    ...
  </plugins>
</build>
...

Note that substantial amount of escaping is needed in this case.

Now you should be able to use LaTeX in your Javadoc:

/**
 * This class implements a very sophisticated algorithm which
 * has something to do with polynomial \(ax^2 + bx + c\).
 */
public class Poly {
    ...
}

and get nice rendering of formulas:

This class implements a very sophisticated algorithm which has something to do with polynomial \(ax^2 + bx + c\) .
comments powered by Disqus