読み書きプログラミング

日常のプログラミングで気づいたことを綴っています

Maxima on WebへのMathJax導入

MathJaxはHTML内のTeXなどを数式に変換してくれる表示エンジンです。
Maxima on Webでは数式表示にlatex.codecogs.comを利用していましたが、GUI化の第一歩としてMathJaxを導入してみました。

<html>
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>Maxima on Web</title>
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({ tex2jax: { inlineMath: [['$','$'], ["\\(","\\)"]] } });
</script>
<script type="text/javascript" src="http://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS_HTML"></script>
<meta http-equiv="X-UA-Compatible" CONTENT="IE=EmulateIE7" />

<script type="text/javascript" src="prototype.js"></script>
<script type="text/javascript"><!--
function execute() {
  if ($('command').value.length > 0) {
    var xmlHttp = new Ajax.Request(
      'cgi-bin/maxima.rb?',
      {method: 'post',
      postBody: $('command').value,
      onSuccess: function(request) {
        $('result').innerHTML = request.responseText;
	MathJax.Hub.Queue(["Typeset", MathJax.Hub, $('result')]);
        },
      onFailure: function(request) {
        alert('failure');
      },
      onException: function(request) {
        alert('exception');
      }
    });
  }
}
// --></script>
</head>
<body>
<h1>Maxima on Web</h1>
<form>
<textarea id="command" rows="4" cols="80"></textarea>
<input type="button" value="Evaluate!" onClick="execute()" />
</form>
<div id="result"></div>
</body>
</html>

最初のおまじないの部分は他の解説記事にお任せします。
ここでのポイントは、非同期で式を更新したい場合には更新タスクをキューにいれる必要があるというところです。onSuccessの中身に注意してください。

#!/usr/bin/ruby
# -*- coding: utf-8 -*-
ENV['PATH'] = '/opt/local/bin:' + ENV['PATH'] # gnuplot用パスを追加
texfile = 'maxima.tex'
graphfile = 'images/maxima.png'
graphrelative = '../' + graphfile
# Maximaのtexコマンドはファイルに追加していくので最初にファイルを消しておく。
`rm #{texfile}` 
`rm #{graphrelative}` 

print "Content-Type: text/plain\n\n"

cmd = $stdin.gets
if /^\s*$/ =~ cmd then
  exit
end
if /[;$]$/ !~ cmd then
  cmd = cmd + '$' #cmdの最後に$や;がなければ$を追加する。
end
cmd = 'set_plot_option([gnuplot_term, png]);\n' \
"set_plot_option([gnuplot_out_file, \\\"#{graphrelative}\\\"]);\n" \
+ cmd + '\ntex(%, \\"' + texfile + '\\");'
`echo "#{cmd}" | /Applications/Maxima.app/Contents/Resources/maxima.sh`

f = open(texfile)
result = f.read
if result.length > '$$$$'.length then #'$$$$'は空っぽの結果
  puts result
end
f.close
if File.exist?(graphrelative) then
  puts '<div align="center">'
  puts "<img src=\"#{graphfile}\" />"
  puts '</div>'
end

CGI側からは、数式に関しては、ただMaximatex出力を返すだけになりました。

参考文献

  1. MathJax v1.1 documentation, "Modifying Math on the Page"