MathJax in Markdown :: 20 Jul 2011

I had some issues getting MathJax running smoothly alongside Markdown. The main issue stemmed from Markdown not providing a way to temporarily escape from its text transformations, so some LATEX would get interpreted as Markdown.

The only way I know of to prevent text transformations in Markdown is through the code block (prefix with 4+ spaces) and inline code (surround with `) features. However, both of those wrap the result in some HTML tag (<pre> for the first, <code> for the second). I decided to use the inline code feature as the basis for inserting my math.

I can insert math by typing, for example `\( \del \cdot \vec{B} = 0 \)`. To make this work, I had to use the following MathJax configuration:

MathJax.Hub.Config({
    tex2jax: {
        skipTags: ['script', 'noscript', 'style', 'textarea', 'pre']
    }
});

This prevents MathJax from skipping <code> tags. This could potentially cause issues if I used the sequences \(, \[, or $$ in a normal (non-math) code block, but I think it's safe to say that those sequences won't show up in most of my code.

The next step was to make sure MathJax <code> tags weren't actually styled like "normal" <code> tags. To do this, I added this to my MathJax configuration:

MathJax.Hub.Queue(function() {
    // Fix <code> tags after MathJax finishes running. This is a
    // hack to overcome a shortcoming of Markdown. Discussion at
    // https://github.com/mojombo/jekyll/issues/199
    var all = MathJax.Hub.getAllJax(), i;
    for(i = 0; i < all.length; i += 1) {
        all[i].SourceElement().parentNode.className += ' has-jax';
    }
});

with this in my CSS:

code.has-jax {font: inherit; font-size: 100%; background: inherit; border: inherit;}

Comments

blog comments powered by Disqus