ob-octave.el 9.44 KB
Newer Older
Rasmus's avatar
Rasmus committed
1
;;; ob-octave.el --- Babel Functions for Octave and Matlab -*- lexical-binding: t; -*-
2

Paul Eggert's avatar
Paul Eggert committed
3
;; Copyright (C) 2010-2020 Free Software Foundation, Inc.
4 5 6

;; Author: Dan Davison
;; Keywords: literate programming, reproducible research
Rasmus's avatar
Rasmus committed
7
;; Homepage: https://orgmode.org
8 9 10 11 12 13 14 15 16 17 18 19 20 21

;; This file is part of GNU Emacs.

;; GNU Emacs is free software: you can redistribute it and/or modify
;; it under the terms of the GNU General Public License as published by
;; the Free Software Foundation, either version 3 of the License, or
;; (at your option) any later version.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY; without even the implied warranty of
;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
;; GNU General Public License for more details.

;; You should have received a copy of the GNU General Public License
22
;; along with GNU Emacs.  If not, see <https://www.gnu.org/licenses/>.
23 24 25 26 27 28 29 30 31 32

;;; Commentary:

;;; Requirements:

;; octave
;; octave-mode.el and octave-inf.el come with GNU emacs

;;; Code:
(require 'ob)
Bastien's avatar
Bastien committed
33
(require 'org-macs)
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51

(declare-function matlab-shell "ext:matlab-mode")
(declare-function matlab-shell-run-region "ext:matlab-mode")

(defvar org-babel-default-header-args:matlab '())
(defvar org-babel-default-header-args:octave '())

(defvar org-babel-matlab-shell-command "matlab -nosplash"
  "Shell command to run matlab as an external process.")
(defvar org-babel-octave-shell-command "octave -q"
  "Shell command to run octave as an external process.")

(defvar org-babel-matlab-with-emacs-link nil
  "If non-nil use matlab-shell-run-region for session evaluation.
  This will use EmacsLink if (matlab-with-emacs-link) evaluates
  to a non-nil value.")

(defvar org-babel-matlab-emacs-link-wrapper-method
52
  "%s
53 54 55 56 57 58 59 60
if ischar(ans), fid = fopen('%s', 'w'); fprintf(fid, '%%s\\n', ans); fclose(fid);
else, save -ascii %s ans
end
delete('%s')
")
(defvar org-babel-octave-wrapper-method
  "%s
if ischar(ans), fid = fopen('%s', 'w'); fprintf(fid, '%%s\\n', ans); fclose(fid);
Carsten Dominik's avatar
Carsten Dominik committed
61
else, dlmwrite('%s', ans, '\\t')
62 63
end")

64
(defvar org-babel-octave-eoe-indicator "'org_babel_eoe'")
65 66 67 68 69 70

(defvar org-babel-octave-eoe-output "ans = org_babel_eoe")

(defun org-babel-execute:matlab (body params)
  "Execute a block of matlab code with Babel."
  (org-babel-execute:octave body params 'matlab))
Carsten Dominik's avatar
Carsten Dominik committed
71

72 73
(defun org-babel-execute:octave (body params &optional matlabp)
  "Execute a block of octave code with Babel."
Carsten Dominik's avatar
Carsten Dominik committed
74
  (let* ((session
75 76
	  (funcall (intern (format "org-babel-%s-initiate-session"
				   (if matlabp "matlab" "octave")))
Rasmus's avatar
Rasmus committed
77 78
		   (cdr (assq :session params)) params))
         (result-type (cdr (assq :result-type params)))
Carsten Dominik's avatar
Carsten Dominik committed
79 80 81
	 (full-body
	  (org-babel-expand-body:generic
	   body params (org-babel-variable-assignments:octave params)))
Rasmus's avatar
Rasmus committed
82
	 (gfx-file (ignore-errors (org-babel-graphical-output-file params)))
83
	 (result (org-babel-octave-evaluate
Bastien Guerry's avatar
Bastien Guerry committed
84
		  session
Rasmus's avatar
Rasmus committed
85
		  (if gfx-file
Bastien Guerry's avatar
Bastien Guerry committed
86 87 88 89
		      (mapconcat 'identity
				 (list
				  "set (0, \"defaultfigurevisible\", \"off\");"
				  full-body
Rasmus's avatar
Rasmus committed
90
				  (format "print -dpng %s" gfx-file))
Bastien Guerry's avatar
Bastien Guerry committed
91 92 93
				 "\n")
		    full-body)
		  result-type matlabp)))
Rasmus's avatar
Rasmus committed
94
    (if gfx-file
Bastien Guerry's avatar
Bastien Guerry committed
95 96 97 98
	nil
      (org-babel-reassemble-table
       result
       (org-babel-pick-name
Rasmus's avatar
Rasmus committed
99
	(cdr (assq :colname-names params)) (cdr (assq :colnames params)))
Bastien Guerry's avatar
Bastien Guerry committed
100
       (org-babel-pick-name
Rasmus's avatar
Rasmus committed
101
	(cdr (assq :rowname-names params)) (cdr (assq :rownames params)))))))
102 103 104 105

(defun org-babel-prep-session:matlab (session params)
  "Prepare SESSION according to PARAMS."
  (org-babel-prep-session:octave session params 'matlab))
Carsten Dominik's avatar
Carsten Dominik committed
106 107

(defun org-babel-variable-assignments:octave (params)
108
  "Return list of octave statements assigning the block's variables."
Carsten Dominik's avatar
Carsten Dominik committed
109 110
  (mapcar
   (lambda (pair)
111
     (format "%s=%s;"
Carsten Dominik's avatar
Carsten Dominik committed
112 113
	     (car pair)
	     (org-babel-octave-var-to-octave (cdr pair))))
Rasmus's avatar
Rasmus committed
114
   (org-babel--get-vars params)))
Carsten Dominik's avatar
Carsten Dominik committed
115 116 117 118

(defalias 'org-babel-variable-assignments:matlab
  'org-babel-variable-assignments:octave)

119 120 121 122 123
(defun org-babel-octave-var-to-octave (var)
  "Convert an emacs-lisp value into an octave variable.
Converts an emacs-lisp variable into a string of octave code
specifying a variable of the same value."
  (if (listp var)
Carsten Dominik's avatar
Carsten Dominik committed
124 125
      (concat "[" (mapconcat #'org-babel-octave-var-to-octave var
			     (if (listp (car var)) "; " ",")) "]")
Bastien Guerry's avatar
Bastien Guerry committed
126 127
    (cond
     ((stringp var)
128
      (format "'%s'" var))
Bastien Guerry's avatar
Bastien Guerry committed
129 130
     (t
      (format "%s" var)))))
131 132 133 134

(defun org-babel-prep-session:octave (session params &optional matlabp)
  "Prepare SESSION according to the header arguments specified in PARAMS."
  (let* ((session (org-babel-octave-initiate-session session params matlabp))
Carsten Dominik's avatar
Carsten Dominik committed
135
	 (var-lines (org-babel-variable-assignments:octave params)))
136 137 138 139 140 141 142 143 144
    (org-babel-comint-in-buffer session
      (mapc (lambda (var)
              (end-of-line 1) (insert var) (comint-send-input nil t)
              (org-babel-comint-wait-for-output session)) var-lines))
    session))

(defun org-babel-matlab-initiate-session (&optional session params)
  "Create a matlab inferior process buffer.
If there is not a current inferior-process-buffer in SESSION then
145
create.  Return the initialized session."
146
  (org-babel-octave-initiate-session session params 'matlab))
Carsten Dominik's avatar
Carsten Dominik committed
147

Rasmus's avatar
Rasmus committed
148
(defun org-babel-octave-initiate-session (&optional session _params matlabp)
149 150
  "Create an octave inferior process buffer.
If there is not a current inferior-process-buffer in SESSION then
151
create.  Return the initialized session."
Bastien Guerry's avatar
Bastien Guerry committed
152 153
  (if matlabp (require 'matlab) (or (require 'octave-inf nil 'noerror)
				    (require 'octave)))
154 155 156 157 158 159 160 161 162 163 164 165
  (unless (string= session "none")
    (let ((session (or session
		       (if matlabp "*Inferior Matlab*" "*Inferior Octave*"))))
      (if (org-babel-comint-buffer-livep session) session
	(save-window-excursion
	  (if matlabp (unless org-babel-matlab-with-emacs-link (matlab-shell))
	    (run-octave))
	  (rename-buffer (if (bufferp session) (buffer-name session)
			   (if (stringp session) session (buffer-name))))
	  (current-buffer))))))

(defun org-babel-octave-evaluate
Carsten Dominik's avatar
Carsten Dominik committed
166
  (session body result-type &optional matlabp)
167
  "Pass BODY to the octave process in SESSION.
Rasmus's avatar
Rasmus committed
168 169
If RESULT-TYPE equals `output' then return the outputs of the
statements in BODY, if RESULT-TYPE equals `value' then return the
170 171 172 173 174 175 176 177 178 179
value of the last statement in BODY, as elisp."
  (if session
      (org-babel-octave-evaluate-session session body result-type matlabp)
    (org-babel-octave-evaluate-external-process body result-type matlabp)))

(defun org-babel-octave-evaluate-external-process (body result-type matlabp)
  "Evaluate BODY in an external octave process."
  (let ((cmd (if matlabp
		 org-babel-matlab-shell-command
	       org-babel-octave-shell-command)))
Rasmus's avatar
Rasmus committed
180 181 182
    (pcase result-type
      (`output (org-babel-eval cmd body))
      (`value (let ((tmp-file (org-babel-temp-file "octave-")))
183 184
	       (org-babel-eval
		cmd
Carsten Dominik's avatar
Carsten Dominik committed
185 186 187 188
		(format org-babel-octave-wrapper-method body
			(org-babel-process-file-name tmp-file 'noquote)
			(org-babel-process-file-name tmp-file 'noquote)))
	       (org-babel-octave-import-elisp-from-file tmp-file))))))
189 190

(defun org-babel-octave-evaluate-session
Rasmus's avatar
Rasmus committed
191
    (session body result-type &optional matlabp)
192
  "Evaluate BODY in SESSION."
Carsten Dominik's avatar
Carsten Dominik committed
193 194
  (let* ((tmp-file (org-babel-temp-file (if matlabp "matlab-" "octave-")))
	 (wait-file (org-babel-temp-file "matlab-emacs-link-wait-signal-"))
195
	 (full-body
Rasmus's avatar
Rasmus committed
196 197
	  (pcase result-type
	    (`output
198 199 200
	     (mapconcat
	      #'org-babel-chomp
	      (list body org-babel-octave-eoe-indicator) "\n"))
Rasmus's avatar
Rasmus committed
201
	    (`value
202 203 204
	     (if (and matlabp org-babel-matlab-with-emacs-link)
		 (concat
		  (format org-babel-matlab-emacs-link-wrapper-method
Carsten Dominik's avatar
Carsten Dominik committed
205 206 207
			  body
			  (org-babel-process-file-name tmp-file 'noquote)
			  (org-babel-process-file-name tmp-file 'noquote) wait-file) "\n")
208 209 210
	       (mapconcat
		#'org-babel-chomp
		(list (format org-babel-octave-wrapper-method
Carsten Dominik's avatar
Carsten Dominik committed
211 212 213
			      body
			      (org-babel-process-file-name tmp-file 'noquote)
			      (org-babel-process-file-name tmp-file 'noquote))
214 215 216 217 218 219 220 221 222 223
		      org-babel-octave-eoe-indicator) "\n")))))
	 (raw (if (and matlabp org-babel-matlab-with-emacs-link)
		  (save-window-excursion
		    (with-temp-buffer
		      (insert full-body)
		      (write-region "" 'ignored wait-file nil nil nil 'excl)
		      (matlab-shell-run-region (point-min) (point-max))
		      (message "Waiting for Matlab Emacs Link")
		      (while (file-exists-p wait-file) (sit-for 0.01))
		      "")) ;; matlab-shell-run-region doesn't seem to
224 225 226
		;; make *matlab* buffer contents easily
		;; available, so :results output currently
		;; won't work
227 228 229 230 231 232 233
		(org-babel-comint-with-output
		    (session
		     (if matlabp
			 org-babel-octave-eoe-indicator
		       org-babel-octave-eoe-output)
		     t full-body)
		  (insert full-body) (comint-send-input nil t)))) results)
Rasmus's avatar
Rasmus committed
234 235
    (pcase result-type
      (`value
Carsten Dominik's avatar
Carsten Dominik committed
236
       (org-babel-octave-import-elisp-from-file tmp-file))
Rasmus's avatar
Rasmus committed
237 238 239
      (`output
       (setq results
	     (if matlabp
Bastien's avatar
Bastien committed
240 241
		 (cdr (reverse (delq "" (mapcar #'org-strip-quotes
						(mapcar #'org-trim raw)))))
Rasmus's avatar
Rasmus committed
242
	       (cdr (member org-babel-octave-eoe-output
Bastien's avatar
Bastien committed
243 244
			    (reverse (mapcar #'org-strip-quotes
					     (mapcar #'org-trim raw)))))))
Rasmus's avatar
Rasmus committed
245
       (mapconcat #'identity (reverse results) "\n")))))
246 247 248 249 250

(defun org-babel-octave-import-elisp-from-file (file-name)
  "Import data from FILE-NAME.
This removes initial blank and comment lines and then calls
`org-babel-import-elisp-from-file'."
Carsten Dominik's avatar
Carsten Dominik committed
251
  (let ((temp-file (org-babel-temp-file "octave-matlab-")) beg end)
252 253 254
    (with-temp-file temp-file
      (insert-file-contents file-name)
      (re-search-forward "^[ \t]*[^# \t]" nil t)
Bastien's avatar
Bastien committed
255 256 257
      (when (< (setq beg (point-min))
	       (setq end (point-at-bol)))
	(delete-region beg end)))
Carsten Dominik's avatar
Carsten Dominik committed
258
    (org-babel-import-elisp-from-file temp-file '(16))))
259 260 261

(provide 'ob-octave)

262

263 264

;;; ob-octave.el ends here