ob-R: declare ess-current-process-name
[org-mode.git] / lisp / ob-R.el
blobea3303193006d69413b126a69c8391f318ccbeea
1 ;;; ob-R.el --- org-babel functions for R code evaluation
3 ;; Copyright (C) 2009-2014 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte
6 ;; Dan Davison
7 ;; Keywords: literate programming, reproducible research, R, statistics
8 ;; Homepage: http://orgmode.org
10 ;; This file is part of GNU Emacs.
12 ;; GNU Emacs is free software: you can redistribute it and/or modify
13 ;; it under the terms of the GNU General Public License as published by
14 ;; the Free Software Foundation, either version 3 of the License, or
15 ;; (at your option) any later version.
17 ;; GNU Emacs is distributed in the hope that it will be useful,
18 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
19 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 ;; GNU General Public License for more details.
22 ;; You should have received a copy of the GNU General Public License
23 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25 ;;; Commentary:
27 ;; Org-Babel support for evaluating R code
29 ;;; Code:
30 (require 'ob)
31 (eval-when-compile (require 'cl))
33 (declare-function orgtbl-to-tsv "org-table" (table params))
34 (declare-function R "ext:essd-r" (&optional start-args))
35 (declare-function inferior-ess-send-input "ext:ess-inf" ())
36 (declare-function ess-make-buffer-current "ext:ess-inf" ())
37 (declare-function ess-eval-buffer "ext:ess-inf" (vis))
38 (declare-function ess-wait-for-process "ext:ess-inf"
39 (proc &optional sec-prompt wait force-redisplay))
40 (declare-function org-number-sequence "org-compat" (from &optional to inc))
41 (declare-function org-remove-if-not "org" (predicate seq))
42 (declare-function org-every "org" (pred seq))
44 (defconst org-babel-header-args:R
45 '((width . :any)
46 (height . :any)
47 (bg . :any)
48 (units . :any)
49 (pointsize . :any)
50 (antialias . :any)
51 (quality . :any)
52 (compression . :any)
53 (res . :any)
54 (type . :any)
55 (family . :any)
56 (title . :any)
57 (fonts . :any)
58 (version . :any)
59 (paper . :any)
60 (encoding . :any)
61 (pagecentre . :any)
62 (colormodel . :any)
63 (useDingbats . :any)
64 (horizontal . :any)
65 (results . ((file list vector table scalar verbatim)
66 (raw org html latex code pp wrap)
67 (replace silent append prepend)
68 (output value graphics))))
69 "R-specific header arguments.")
71 (defconst ob-R-safe-header-args
72 (append org-babel-safe-header-args
73 '(:width :height :bg :units :pointsize :antialias :quality
74 :compression :res :type :family :title :fonts
75 :version :paper :encoding :pagecentre :colormodel
76 :useDingbats :horizontal))
77 "Header args which are safe for R babel blocks.
79 See `org-babel-safe-header-args' for documentation of the format of
80 this variable.")
82 (defvar org-babel-default-header-args:R '())
83 (put 'org-babel-default-header-args:R 'safe-local-variable
84 (org-babel-header-args-safe-fn ob-R-safe-header-args))
86 (defcustom org-babel-R-command "R --slave --no-save"
87 "Name of command to use for executing R code."
88 :group 'org-babel
89 :version "24.1"
90 :type 'string)
92 (defvar ess-current-process-name) ; dynamically scoped
93 (defvar ess-local-process-name) ; dynamically scoped
94 (defun org-babel-edit-prep:R (info)
95 (let ((session (cdr (assoc :session (nth 2 info)))))
96 (when (and session (string-match "^\\*\\(.+?\\)\\*$" session))
97 (save-match-data (org-babel-R-initiate-session session nil)))))
99 (defconst ob-R-transfer-variable-table-with-header
100 "%s <- local({
101 con <- textConnection(
104 res <- read.table(
105 con,
106 header = %s,
107 row.names = %s,
108 sep = \"\\t\",
109 as.is = TRUE
111 close(con)
114 "R code used to transfer a table defined as a variable from org to R.
115 This function is used when the table contains a header.")
117 (defconst ob-R-transfer-variable-table-without-header
118 "%s <- local({
119 con <- textConnection(
122 res <- read.table(
123 con,
124 header = %s,
125 row.names = %s,
126 sep = \"\\t\",
127 as.is = TRUE,
128 fill = TRUE,
129 col.names = paste(\"V\", seq_len(%d), sep =\"\")
131 close(con)
134 "R code used to transfer a table defined as a variable from org to R.
135 This function is used when the table does not contain a header.")
137 (defun org-babel-expand-body:R (body params &optional graphics-file)
138 "Expand BODY according to PARAMS, return the expanded body."
139 (mapconcat 'identity
140 (append
141 (when (cdr (assoc :prologue params))
142 (list (cdr (assoc :prologue params))))
143 (org-babel-variable-assignments:R params)
144 (list body)
145 (when (cdr (assoc :epilogue params))
146 (list (cdr (assoc :epilogue params)))))
147 "\n"))
149 (defun org-babel-execute:R (body params)
150 "Execute a block of R code.
151 This function is called by `org-babel-execute-src-block'."
152 (save-excursion
153 (let* ((result-params (cdr (assoc :result-params params)))
154 (result-type (cdr (assoc :result-type params)))
155 (session (org-babel-R-initiate-session
156 (cdr (assoc :session params)) params))
157 (colnames-p (cdr (assoc :colnames params)))
158 (rownames-p (cdr (assoc :rownames params)))
159 (graphics-file (and (member "graphics" (assq :result-params params))
160 (org-babel-graphical-output-file params)))
161 (full-body
162 (let ((inside
163 (list (org-babel-expand-body:R body params graphics-file))))
164 (mapconcat 'identity
165 (if graphics-file
166 (append
167 (list (org-babel-R-construct-graphics-device-call
168 graphics-file params))
169 inside
170 (list "},error=function(e){plot(x=-1:1, y=-1:1, type='n', xlab='', ylab='', axes=FALSE); text(x=0, y=0, labels=e$message, col='red'); paste('ERROR', e$message, sep=' : ')}); dev.off()"))
171 inside)
172 "\n")))
173 (result
174 (org-babel-R-evaluate
175 session full-body result-type result-params
176 (or (equal "yes" colnames-p)
177 (org-babel-pick-name
178 (cdr (assoc :colname-names params)) colnames-p))
179 (or (equal "yes" rownames-p)
180 (org-babel-pick-name
181 (cdr (assoc :rowname-names params)) rownames-p)))))
182 (if graphics-file nil result))))
184 (defun org-babel-prep-session:R (session params)
185 "Prepare SESSION according to the header arguments specified in PARAMS."
186 (let* ((session (org-babel-R-initiate-session session params))
187 (var-lines (org-babel-variable-assignments:R params)))
188 (org-babel-comint-in-buffer session
189 (mapc (lambda (var)
190 (end-of-line 1) (insert var) (comint-send-input nil t)
191 (org-babel-comint-wait-for-output session)) var-lines))
192 session))
194 (defun org-babel-load-session:R (session body params)
195 "Load BODY into SESSION."
196 (save-window-excursion
197 (let ((buffer (org-babel-prep-session:R session params)))
198 (with-current-buffer buffer
199 (goto-char (process-mark (get-buffer-process (current-buffer))))
200 (insert (org-babel-chomp body)))
201 buffer)))
203 ;; helper functions
205 (defun org-babel-variable-assignments:R (params)
206 "Return list of R statements assigning the block's variables."
207 (let ((vars (mapcar 'cdr (org-babel-get-header params :var))))
208 (mapcar
209 (lambda (pair)
210 (org-babel-R-assign-elisp
211 (car pair) (cdr pair)
212 (equal "yes" (cdr (assoc :colnames params)))
213 (equal "yes" (cdr (assoc :rownames params)))))
214 (mapcar
215 (lambda (i)
216 (cons (car (nth i vars))
217 (org-babel-reassemble-table
218 (cdr (nth i vars))
219 (cdr (nth i (cdr (assoc :colname-names params))))
220 (cdr (nth i (cdr (assoc :rowname-names params)))))))
221 (org-number-sequence 0 (1- (length vars)))))))
223 (defun org-babel-R-quote-tsv-field (s)
224 "Quote field S for export to R."
225 (if (stringp s)
226 (concat "\"" (mapconcat 'identity (split-string s "\"") "\"\"") "\"")
227 (format "%S" s)))
229 (defun org-babel-R-assign-elisp (name value colnames-p rownames-p)
230 "Construct R code assigning the elisp VALUE to a variable named NAME."
231 (if (listp value)
232 (let* ((lengths (mapcar 'length (org-remove-if-not 'sequencep value)))
233 (max (if lengths (apply 'max lengths) 0))
234 (min (if lengths (apply 'min lengths) 0)))
235 ;; Ensure VALUE has an orgtbl structure (depth of at least 2).
236 (unless (listp (car value)) (setq value (list value)))
237 (let ((file (orgtbl-to-tsv value '(:fmt org-babel-R-quote-tsv-field)))
238 (header (if (or (eq (nth 1 value) 'hline) colnames-p)
239 "TRUE" "FALSE"))
240 (row-names (if rownames-p "1" "NULL")))
241 (if (= max min)
242 (format ob-R-transfer-variable-table-with-header
243 name file header row-names)
244 (format ob-R-transfer-variable-table-without-header
245 name file header row-names max))))
246 (cond ((integerp value) (format "%s <- %s" name (concat (number-to-string value) "L")))
247 ((floatp value) (format "%s <- %s" name value))
248 ((stringp value) (format "%s <- %S" name (org-no-properties value)))
249 (t (format "%s <- %S" name (prin1-to-string value))))))
252 (defvar ess-ask-for-ess-directory) ; dynamically scoped
253 (defun org-babel-R-initiate-session (session params)
254 "If there is not a current R process then create one."
255 (unless (string= session "none")
256 (let ((session (or session "*R*"))
257 (ess-ask-for-ess-directory
258 (and (boundp 'ess-ask-for-ess-directory)
259 ess-ask-for-ess-directory
260 (not (cdr (assoc :dir params))))))
261 (if (org-babel-comint-buffer-livep session)
262 session
263 (save-window-excursion
264 (when (get-buffer session)
265 ;; Session buffer exists, but with dead process
266 (set-buffer session))
267 (require 'ess) (R)
268 (ess-wait-for-process
269 (get-process (or ess-local-process-name
270 ess-current-process-name)))
271 (rename-buffer
272 (if (bufferp session)
273 (buffer-name session)
274 (if (stringp session)
275 session
276 (buffer-name))))
277 (current-buffer))))))
279 (defun org-babel-R-associate-session (session)
280 "Associate R code buffer with an R session.
281 Make SESSION be the inferior ESS process associated with the
282 current code buffer."
283 (setq ess-local-process-name
284 (process-name (get-buffer-process session)))
285 (ess-make-buffer-current))
287 (defvar org-babel-R-graphics-devices
288 '((:bmp "bmp" "filename")
289 (:jpg "jpeg" "filename")
290 (:jpeg "jpeg" "filename")
291 (:tikz "tikz" "file")
292 (:tiff "tiff" "filename")
293 (:png "png" "filename")
294 (:svg "svg" "file")
295 (:pdf "pdf" "file")
296 (:ps "postscript" "file")
297 (:postscript "postscript" "file"))
298 "An alist mapping graphics file types to R functions.
300 Each member of this list is a list with three members:
301 1. the file extension of the graphics file, as an elisp :keyword
302 2. the R graphics device function to call to generate such a file
303 3. the name of the argument to this function which specifies the
304 file to write to (typically \"file\" or \"filename\")")
306 (defun org-babel-R-construct-graphics-device-call (out-file params)
307 "Construct the call to the graphics device."
308 (let* ((allowed-args '(:width :height :bg :units :pointsize
309 :antialias :quality :compression :res
310 :type :family :title :fonts :version
311 :paper :encoding :pagecentre :colormodel
312 :useDingbats :horizontal))
313 (device (and (string-match ".+\\.\\([^.]+\\)" out-file)
314 (match-string 1 out-file)))
315 (device-info (or (assq (intern (concat ":" device))
316 org-babel-R-graphics-devices)
317 (assq :png org-babel-R-graphics-devices)))
318 (extra-args (cdr (assq :R-dev-args params))) filearg args)
319 (setq device (nth 1 device-info))
320 (setq filearg (nth 2 device-info))
321 (setq args (mapconcat
322 (lambda (pair)
323 (if (member (car pair) allowed-args)
324 (format ",%s=%S"
325 (substring (symbol-name (car pair)) 1)
326 (cdr pair)) ""))
327 params ""))
328 (format "%s(%s=\"%s\"%s%s%s); tryCatch({"
329 device filearg out-file args
330 (if extra-args "," "") (or extra-args ""))))
332 (defvar org-babel-R-eoe-indicator "'org_babel_R_eoe'")
333 (defvar org-babel-R-eoe-output "[1] \"org_babel_R_eoe\"")
335 (defvar org-babel-R-write-object-command "{function(object,transfer.file){object;invisible(if(inherits(try({tfile<-tempfile();write.table(object,file=tfile,sep=\"\\t\",na=\"nil\",row.names=%s,col.names=%s,quote=FALSE);file.rename(tfile,transfer.file)},silent=TRUE),\"try-error\")){if(!file.exists(transfer.file))file.create(transfer.file)})}}(object=%s,transfer.file=\"%s\")")
337 (defun org-babel-R-evaluate
338 (session body result-type result-params column-names-p row-names-p)
339 "Evaluate R code in BODY."
340 (if session
341 (org-babel-R-evaluate-session
342 session body result-type result-params column-names-p row-names-p)
343 (org-babel-R-evaluate-external-process
344 body result-type result-params column-names-p row-names-p)))
346 (defun org-babel-R-evaluate-external-process
347 (body result-type result-params column-names-p row-names-p)
348 "Evaluate BODY in external R process.
349 If RESULT-TYPE equals 'output then return standard output as a
350 string. If RESULT-TYPE equals 'value then return the value of the
351 last statement in BODY, as elisp."
352 (case result-type
353 (value
354 (let ((tmp-file (org-babel-temp-file "R-")))
355 (org-babel-eval org-babel-R-command
356 (format org-babel-R-write-object-command
357 (if row-names-p "TRUE" "FALSE")
358 (if column-names-p
359 (if row-names-p "NA" "TRUE")
360 "FALSE")
361 (format "{function ()\n{\n%s\n}}()" body)
362 (org-babel-process-file-name tmp-file 'noquote)))
363 (org-babel-R-process-value-result
364 (org-babel-result-cond result-params
365 (with-temp-buffer
366 (insert-file-contents tmp-file)
367 (buffer-string))
368 (org-babel-import-elisp-from-file tmp-file '(16)))
369 column-names-p)))
370 (output (org-babel-eval org-babel-R-command body))))
372 (defvar ess-eval-visibly-p)
374 (defun org-babel-R-evaluate-session
375 (session body result-type result-params column-names-p row-names-p)
376 "Evaluate BODY in SESSION.
377 If RESULT-TYPE equals 'output then return standard output as a
378 string. If RESULT-TYPE equals 'value then return the value of the
379 last statement in BODY, as elisp."
380 (case result-type
381 (value
382 (with-temp-buffer
383 (insert (org-babel-chomp body))
384 (let ((ess-local-process-name
385 (process-name (get-buffer-process session)))
386 (ess-eval-visibly-p nil))
387 (ess-eval-buffer nil)))
388 (let ((tmp-file (org-babel-temp-file "R-")))
389 (org-babel-comint-eval-invisibly-and-wait-for-file
390 session tmp-file
391 (format org-babel-R-write-object-command
392 (if row-names-p "TRUE" "FALSE")
393 (if column-names-p
394 (if row-names-p "NA" "TRUE")
395 "FALSE")
396 ".Last.value" (org-babel-process-file-name tmp-file 'noquote)))
397 (org-babel-R-process-value-result
398 (org-babel-result-cond result-params
399 (with-temp-buffer
400 (insert-file-contents tmp-file)
401 (buffer-string))
402 (org-babel-import-elisp-from-file tmp-file '(16)))
403 column-names-p)))
404 (output
405 (mapconcat
406 'org-babel-chomp
407 (butlast
408 (delq nil
409 (mapcar
410 (lambda (line) (when (> (length line) 0) line))
411 (mapcar
412 (lambda (line) ;; cleanup extra prompts left in output
413 (if (string-match
414 "^\\([ ]*[>+\\.][ ]?\\)+\\([[0-9]+\\|[ ]\\)" line)
415 (substring line (match-end 1))
416 line))
417 (org-babel-comint-with-output (session org-babel-R-eoe-output)
418 (insert (mapconcat 'org-babel-chomp
419 (list body org-babel-R-eoe-indicator)
420 "\n"))
421 (inferior-ess-send-input)))))) "\n"))))
423 (defun org-babel-R-process-value-result (result column-names-p)
424 "R-specific processing of return value.
425 Insert hline if column names in output have been requested."
426 (if column-names-p
427 (cons (car result) (cons 'hline (cdr result)))
428 result))
430 (provide 'ob-R)
434 ;;; ob-R.el ends here