LaTeX for TiddlyWiki – A MathJax Plugin

Update: The MathJax Plugin for TiddlyWiki has a new home: https://github.com/guyru/tiddlywiki-mathjax
Some time ago I came across MathJax, a nifty, Javascript based engine for displaying TeX and LaTeX equations. It works by “translating” the equation to MathML or HTML+CSS, so it works on all modern browsers. The result isn’t a raster image, like in most LaTeX solutions (e.g. MediaWiki), so it’s scales with the text around it. Furthermore, it’s quite easy to integrate as it doesn’t require any real installation, and you could always use MathJax’s own CDN, which makes things even simpler.

TiddlyWiki with the MathJaxPlugin
A tiddler with LaTeX equations.

I quickly realized MathJax will be a perfect fit for TiddlyWiki which is also based on pure Javascript. It will allow me to enter complex formulas in tiddlers and still be able to carry my wiki anywhere with me, independent of a real TeX installation. I searched the web for an existing MathJaX plugin for TiddlyWiki but I came up empty handed (I did find some links, but they referenced pages that no longer exist). So I regarded it as a nice opportunity to begin writing some plugins for TiddlyWiki and created the MathJaxPlugin which integrates MathJax with TiddlyWiki.

As I don’t have an online TiddlyWiki, you’ll won’t be able to import the plugin, instead you’ll have to install it manually (which is pretty simple).

Start by creating a new tiddler named MathJaxPlugin, and tag with systemConfig (this tag will tell TiddlyWiki to execute the JS code in the tiddler, thus making it a plugin. Now copy the following code to the tiddler content:

/***
|''Name:''|MathJaxPlugin|
|''Description:''|Enable LaTeX formulas for TiddlyWiki|
|''Version:''|1.0.1|
|''Date:''|Feb 11, 2012|
|''Source:''|http://www.guyrutenberg.com/2011/06/25/latex-for-tiddlywiki-a-mathjax-plugin|
|''Author:''|Guy Rutenberg|
|''License:''|[[BSD open source license]]|
|''~CoreVersion:''|2.5.0|

!! Changelog
!!! 1.0.1 Feb 11, 2012
* Fixed interoperability with TiddlerBarPlugin
!! How to Use
Currently the plugin supports the following delemiters:
* """\(""".."""\)""" - Inline equations
* """$$""".."""$$""" - Displayed equations
* """\[""".."""\]""" - Displayed equations
!! Demo
This is an inline equation \(P(E)   = {n \choose k} p^k (1-p)^{ n-k}\) and this is a displayed equation:
\[J_\alpha(x) = \sum_{m=0}^\infty \frac{(-1)^m}{m! \, \Gamma(m + \alpha + 1)}{\left({\frac{x}{2}}\right)}^{2 m + \alpha}\]
This is another displayed equation $$e=mc^2$$
!! Code
***/
//{{{
config.extensions.MathJax = {
  mathJaxScript : "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
  // uncomment the following line if you want to access MathJax using SSL
  // mathJaxScript : "https://d3eoax9i5htok0.cloudfront.net/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
  displayTiddler: function(TiddlerName) {
    config.extensions.MathJax.displayTiddler_old.apply(this, arguments);
    MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
  }
};
 
jQuery.getScript(config.extensions.MathJax.mathJaxScript, function(){
    MathJax.Hub.Config({
      extensions: ["tex2jax.js"],
      "HTML-CSS": { scale: 100 }
    });
 
    MathJax.Hub.Startup.onload();
    config.extensions.MathJax.displayTiddler_old = story.displayTiddler;
    story.displayTiddler = config.extensions.MathJax.displayTiddler;
});
 
config.formatters.push({
	name: "mathJaxFormula",
	match: "\\\\\\[|\\$\\$|\\\\\\(",
	//lookaheadRegExp: /(?:\\\[|\$\$)((?:.|\n)*?)(?:\\\]|$$)/mg,
	handler: function(w)
	{
		switch(w.matchText) {
		case "\\[": // displayed equations
			this.lookaheadRegExp = /\\\[((?:.|\n)*?)(\\\])/mg;
			break;
		case "$$": // inline equations
			this.lookaheadRegExp = /\$\$((?:.|\n)*?)(\$\$)/mg;
			break;
		case "\\(": // inline equations
			this.lookaheadRegExp = /\\\(((?:.|\n)*?)(\\\))/mg;
			break;
		default:
			break;
		}
		this.lookaheadRegExp.lastIndex = w.matchStart;
		var lookaheadMatch = this.lookaheadRegExp.exec(w.source);
		if(lookaheadMatch && lookaheadMatch.index == w.matchStart) {
			createTiddlyElement(w.output,"span",null,null,lookaheadMatch[0]);
			w.nextMatch = this.lookaheadRegExp.lastIndex;
		}
	}
});
//}}}

After saving the tiddler, reload the wiki and the MathJaxPlugin should be active. You can test it by creating a new tiddler with some equations in it:

This is an inline equation $$P(E)   = {n \choose k} p^k (1-p)^{ n-k}$$ and this is a displayed equation:
\[J_\alpha(x) = \sum_{m=0}^\infty \frac{(-1)^m}{m! \, \Gamma(m + \alpha + 1)}{\left({\frac{x}{2}}\right)}^{2 m + \alpha}\]

Which should result in the tiddler that appears in the above image.

Update 2011-08-19: Removed debugging code from the plugin.

Changelog 1.0.1 (Feb 11, 2012

  • Applied Winter Young’s fix for interoperability with other plugins (mainly TiddlerBarPlugin

60 thoughts on “LaTeX for TiddlyWiki – A MathJax Plugin”

  1. Guy, I tweaked your script a little bit and so far it seems to be working ok.

    Basically I removed the whole “config.formatters.push” section, and edited the config.extension.MathJax section.

    config.extensions.MathJax = {
      mathJaxScript : "http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML-full",
      // uncomment the following line if you want to access MathJax using SSL
      // mathJaxScript : "https://d3eoax9i5htok0.cloudfront.net/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML",
      displayTiddler: function(TiddlerName) {
        config.extensions.MathJax.displayTiddler_old.apply(this, arguments);
        MathJax.Hub.Queue(["Typeset", MathJax.Hub]);
      }
    };
     
    jQuery.getScript(config.extensions.MathJax.mathJaxScript, function(){
        MathJax.Hub.Config({
          extensions: ["tex2jax.js"],
          "HTML-CSS": { scale: 100 },
          tex2jax: {
            inlineMath: [ ['\\(','\\)'], ['&&','&&'] ],
            displayMath: [ ['$$','$$'], ['\\[','\\]'] ],
            processEscapes: true
          },
          asciimath2jax: {
            delimiters: [ ['@@', '@@'], ['`','`'] ]
          },
          styles: { ".MathJax": { color: "blue" } }
        });
     
        MathJax.Hub.Startup.onload();
        config.extensions.MathJax.displayTiddler_old = story.displayTiddler;
        story.displayTiddler = config.extensions.MathJax.displayTiddler;
    });
    
  2. Well done! Works very well.
    There is a bug in the example above
    “This is an inline equation $$P(E) = {n \choose k} p^k (1-p)^{ n-k}$$ and this is a displayed equation:
    \[J_\alpha(x) = \sum_{m=0}^\infty \frac{(-1)^m}{m! \, \Gamma(m + \alpha + 1)}{\left({\frac{x}{2}}\right)}^{2 m + \alpha}\]”

    should be

    “This is an inline equation \(P(E) = {n \choose k} p^k (1-p)^{ n-k}\) and this is a displayed equation:
    \[J_\alpha(x) = \sum_{m=0}^\infty \frac{(-1)^m}{m! \, \Gamma(m + \alpha + 1)}{\left({\frac{x}{2}}\right)}^{2 m + \alpha}\]”

    Changed ‘$$’ to ‘\(‘ and ‘\)’ to enable inline equation formatting.

  3. Excellent! Very easy to install and use, thanks!

    Is there any way to tell if I’m using web fonts or installed STIX fonts?

    Thanks again! — David

  4. Any chance of supporting single-dollar ($) for inline equations? I tried to add them manually to switch, but it still doesn’t recognize them.

  5. Hello,

    Thank you for this very useful plugin.
    I noticed some problem to see equations when I am offline. This is certainly due to the activation of distant js in
    mathJaxScript : “http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML”
    Is there is a way to keep a correct equation viewing even when network is lost?
    Thank in advance
    Brindy

Leave a Reply

Your email address will not be published. Required fields are marked *