Tuesday, January 7, 2014

Evaluate Mathematica code in emacs org-mode

This is yet another attempt of running Mathematica in emacs. For the previous one, see
http://cosmosimple.blogspot.co.uk/2013/12/run-mathematica-commands-in-emacs.html

However, in org-mode, there are greater expectations -- we would like emacs not only to be able to run the Mathematica code, but also "knows" which are code blocks, which are results. Such knowledge enables clever things like calling a Mathematica function from emacs lisp, or other org-supported language. Also, one can easily export the org output to pdf or html, with code and result in the desired styles.

I didn't find org support for Mathematica. Thus I created it myself:

https://github.com/tririver/wy-els/blob/master/ob-mathematica.el

In principle, I could do better by using sessions. However, it's beyond my current need thus I leave it for (possible) future work.

Note that the rather complicated structure of org code blocks can be simplified by yasnippet of emacs.

Example: working on a org-table
(Note that the lines above "#+RESULTS:" are inputs. After pressing C-c C-c inside the SRC block, the result emerges.)

#+NAME: example-table
          | 1 | 4 |
          | 2 | 4 |
          | 3 | 6 |
          | 4 | 8 |
          | 7 | 0 |

#+BEGIN_SRC mathematica :var x=example-table :exports both
1+Transpose@x
#+END_SRC

#+RESULTS:
| 2 | 3 | 4 | 5 | 8 |
| 5 | 5 | 7 | 9 | 1 |

Example: call Mathematica function from org-mode

#+NAME: add-one
#+BEGIN_SRC mathematica :var x=1
  x+1
#+END_SRC

#+RESULTS: add-one
: 2

#+CALL: add-one(x='(1 2 3 4))

#+RESULTS:
| 2 | 3 | 4 | 5 |

No comments:

Post a Comment