DocC for Math

Quickly resurrecting this thread to give a shout-out to MathML as an alternative to LaTeX that can already be embedded in DocC. The trick is that, since MathML and SVG are both web standards, the following is a perfectly legal SVG file (that can be inserted into your DocC like any other image):

<svg:svg xmlns:svg="http://www.w3.org/2000/svg" viewBox="0 0 130 50" version="1.1">
    <svg:foreignObject width="130" height="50">
        <math xmlns="http://www.w3.org/1998/Math/MathML">
            <mfrac>
                <mn>1</mn>
                <mrow>
                    <mi>n</mi>
                    <mo>-</mo>
                    <mn>1</mn>
                </mrow>
            </mfrac>
            <mspace width="5px"/>
            <munderover displaystyle="true">
                <mo>∑</mo>
                <mrow>
                    <mi>i</mi>
                    <mo>=</mo>
                    <mn>1</mn>
                </mrow>
                <mi>n</mi>
            </munderover>
            <msup>
                <mrow>
                    <mo>‖</mo>
                    <msub>
                        <mi>x</mi>
                        <mi>i</mi>
                    </msub>
                    <mo>-</mo>
                    <mi>μ</mi>
                    <mo>‖</mo>
                </mrow>
                <mn>2</mn>
            </msup>
        </math>
    </svg:foreignObject>
</svg:svg>

I recommend saving the above to a .svg file and seeing what it looks like. To support dark mode, just make an exact copy and

  1. Add style="color: white" to the copy's <math> tag.
  2. Add ~dark to the copy's filename.

This MathML+SVG trick is how I typeset math in my documentation; in fact, the SVG above is copied verbatim from a Swift package I'm working on.

This trick is, of course, not ideal. We need to:

  1. Keep two separate files (one for light mode and one for dark) in sync
  2. Wrap the MathML in a bunch of SVG nonsense
  3. Manually size the svg viewBox and the foreignObject

And the image on the documentation webpage will be an <img> of a .svg containing MathML, not an <svg> and certainly not a <math> (which would be ideal, especially for accessibility; alt texts are no replacement for being able to navigate an equation). So I do agree that first-class support for mathematical typesetting would be a welcome addition to DocC. But I believe that MathML would be a much better choice than LaTeX.

7 Likes