Base.show() for displaying MathJax formulas in Jupyter / IJulia?

I’d like to override Base.show() for a custom type I defined, to displayed an object of the type as a math formula (MathJax / LaTeX) when using Jupyter notebook. How can this be done? I already know how to override Base.show() for the command line interface, but want to know how to exploit Jupyter’s math rendering capabilities.

1 Like

Along those lines, defining Julia code with inline Latex math strings like \frac and rendering them as such in Jupyter would be nice too.

You can use text/latex:

Base.show(io::IO, ::MIME"text/latex", x::MyObject) =
    print(io, "\\frac{1}{1+2+3+4}")

or you can use markdown (either text/markdown or via the Markdown stdlib) with embedded equations if you need more flexible formatting.

You can put LaTeX in the docstrings of your Julia code and then it will render as equations in the Jupyter help.

1 Like

Unfortunately this doesn’t seems to work for the latest versions of Julia (1.5.4) and Jupyter. Here’s my screenshot (click to enlarge).

I suspect there is some API change.

I think you need $s.

1 Like

You’re right, this worked (using $$ display environment):

Base.show(io::IO, ::MIME"text/latex", x::MyObject) =
    print(io, "\$\$\\frac{1}{1+2+3+4}\$\$")

If it’s a more complicated pattern, and you want it to be a bit more explicit, you can use Latexify and define a latexrecipe for your type. This will also be recursive:

@latexrecipe function f(m::MyType)
    return :(1/(3+4a+5b))
end

julia> latexify(:(x=$(MyType()))
L"$x = \frac{1}{3 + 4a + 5b}$" 

(I’m on my phone, take everything with a dash of cayenne)

1 Like