Friday, March 26, 2010

setting up blogger to format latex expressions

I want to be able to post mathematical expressions and have them formatted nicely.

After some searching I found yourequations.com which had a nice little script to do the job, and did some digging on how Google Docs was doing the rendering of the expressions.

From there I found Google Chart Tools.

After gathering all that information I wrote up a script block to add to the blog template.

To install this just add it to a Blogger layout block after the Blog Posts layout block.

<script type="text/javascript">
var tags = [ "pre", "code" ];
for(var i = 0; i < tags.length; i++) {
  var eqn = document.getElementsByTagName(tags[i]);
  for (var j = 0; j < eqn.length; j++) {
    var e = eqn[j];
    if (e.getAttribute("lang") != "eq.latex") { 
      continue;
    }
    if (e.innerHTML.match(/<img.*?>/i)) {
      continue;
    }

    var str = e.innerHTML.
      replace(/<br>/gi,"").
      replace(/<br \/>/gi,"").
      replace(/&lt;/gi,"<").
      replace(/&gt;/gi,">").
      replace(/&amp;/gi,"&");

    var url_str = escape(str).
      replace(/\+/g, "%2B");

    e.innerHTML = "<img " +
      "src=\"http://chart.apis.google.com/chart" +
      "?cht=tx&chf=bg,s,ffffff00" +
      "&chl=" + url_str + "\" " +
      "title=\"" + str + "\" alt=\"" + str + "\" " +
      "class=\"eq_latex\" align=\"middle\" " +
      "border=\"0\" />";
  }
}
</script>
After installing the layout block just enclose the expressions in <pre lang="eq.latex"> and </pre>, or <code lang="eq.latex"> and </code>. For example, <code lang="eq.latex">\int_{0}^{1}xdx</code> renders as \int_{0}^{1}xdx.

No comments:

Post a Comment