Monday, March 26, 2012

Run mathematica commands in emacs

I would like the following feature: When writing a document in emacs (say, a LaTeX paper), I can write the original expression in a comment line, then execute and get the answer. The idea is to send a string from emacs to a shell script, which runs Mathematica kernel

Here is the realisation:
I wrote a shell script to run math (Meval.sh):
#!/bin/bash
echo "$1" | sed 's/^[%#;]//g' > /tmp/Meval.tmp.m
math -noprompt < /tmp/Meval.tmp.m | sed '/^$/d'
Then I put the following functions in Emacs settings (The region-or-line-start / end function is taken from Claus Brunzema's ll-debug.el):
(defun region-or-line-start ()
  (save-excursion
    (if (and transient-mark-mode mark-active)
        (progn
          (goto-char (region-beginning))
          (point-at-bol))
      (if (= (current-column) (current-indentation))
          (point)
        (point-at-bol)))))

(defun region-or-line-end ()
  (save-excursion
    (if (and transient-mark-mode mark-active)
        (progn
          (goto-char (region-end))
          (unless (bolp)
            (forward-line))
          (point))
      (progn
        (forward-line)
        (point)))))

(defun math-eval ()
  "Evaluate Mathematica command"
  (interactive)
  (let* ((start (region-or-line-start))
         (end (region-or-line-end))
         (code (concat "Meval.sh '" (buffer-substring-no-properties start end) "'")))
    (shell-command code)
  )

2 comments:

  1. Cool~ I will use LyX for LaTeX writing. One day, I realized that Lyx was just a surface, so why couldn't it be a surface for mathematica? After several tests, it works well.

    ReplyDelete