Release 7.4
[org-mode/org-jambu.git] / lisp / ob.el
blob1c9f9fdbc12e059a385cf2286b58fc4b4d7716ad
1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 7.4
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 ;; See the online documentation for more information
29 ;; http://orgmode.org/worg/org-contrib/babel/
31 ;;; Code:
32 (eval-when-compile
33 (require 'org-list)
34 (require 'cl))
35 (require 'ob-eval)
36 (require 'org-macs)
38 (defvar org-babel-call-process-region-original)
39 (declare-function show-all "outline" ())
40 (declare-function tramp-compat-make-temp-file "tramp-compat"
41 (filename &optional dir-flag))
42 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
43 (declare-function tramp-file-name-user "tramp" (vec))
44 (declare-function tramp-file-name-host "tramp" (vec))
45 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
46 (declare-function org-icompleting-read "org" (&rest args))
47 (declare-function org-edit-src-code "org-src"
48 (&optional context code edit-buffer-name quietp))
49 (declare-function org-edit-src-exit "org-src" (&optional context))
50 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
51 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
52 (declare-function org-outline-overlay-data "org" (&optional use-markers))
53 (declare-function org-set-outline-overlay-data "org" (data))
54 (declare-function org-narrow-to-subtree "org" ())
55 (declare-function org-entry-get "org"
56 (pom property &optional inherit literal-nil))
57 (declare-function org-make-options-regexp "org" (kwds &optional extra))
58 (declare-function org-do-remove-indentation "org" (&optional n))
59 (declare-function org-show-context "org" (&optional key))
60 (declare-function org-at-table-p "org" (&optional table-type))
61 (declare-function org-cycle "org" (&optional arg))
62 (declare-function org-uniquify "org" (list))
63 (declare-function org-current-level "org" ())
64 (declare-function org-table-import "org-table" (file arg))
65 (declare-function org-add-hook "org-compat"
66 (hook function &optional append local))
67 (declare-function org-table-align "org-table" ())
68 (declare-function org-table-end "org-table" (&optional table-type))
69 (declare-function orgtbl-to-generic "org-table" (table params))
70 (declare-function orgtbl-to-orgtbl "org-table" (table params))
71 (declare-function org-babel-lob-get-info "ob-lob" nil)
72 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
73 (declare-function org-babel-ref-parse "ob-ref" (assignment))
74 (declare-function org-babel-ref-resolve "ob-ref" (ref))
75 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
76 (declare-function org-number-sequence "org-compat" (from &optional to inc))
77 (declare-function org-in-item-p "org-list" ())
78 (declare-function org-list-parse-list "org-list" (&optional delete))
79 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
80 (declare-function org-list-bottom-point "org-list" ())
82 (defgroup org-babel nil
83 "Code block evaluation and management in `org-mode' documents."
84 :tag "Babel"
85 :group 'org)
87 (defcustom org-confirm-babel-evaluate t
88 "Confirm before evaluation.
89 Require confirmation before interactively evaluating code
90 blocks in Org-mode buffers. The default value of this variable
91 is t, meaning confirmation is required for any code block
92 evaluation. This variable can be set to nil to inhibit any
93 future confirmation requests. This variable can also be set to a
94 function which takes two arguments the language of the code block
95 and the body of the code block. Such a function should then
96 return a non-nil value if the user should be prompted for
97 execution or nil if no prompt is required.
99 Warning: Disabling confirmation may result in accidental
100 evaluation of potentially harmful code. It may be advisable
101 remove code block execution from C-c C-c as further protection
102 against accidental code block evaluation. The
103 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
104 remove code block execution from the C-c C-c keybinding."
105 :group 'org-babel
106 :type '(choice boolean function))
107 ;; don't allow this variable to be changed through file settings
108 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
110 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
111 "Remove code block evaluation from the C-c C-c key binding."
112 :group 'org-babel
113 :type 'boolean)
115 (defvar org-babel-src-name-regexp
116 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
117 "Regular expression used to match a source name line.")
119 (defvar org-babel-multi-line-header-regexp
120 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
121 "Regular expression used to match multi-line header arguments.")
123 (defvar org-babel-src-name-w-name-regexp
124 (concat org-babel-src-name-regexp
125 "\\("
126 org-babel-multi-line-header-regexp
127 "\\)*"
128 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
129 "Regular expression matching source name lines with a name.")
131 (defvar org-babel-src-block-regexp
132 (concat
133 ;; (1) indentation (2) lang
134 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
135 ;; (3) switches
136 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
137 ;; (4) header arguments
138 "\\([^\n]*\\)\n"
139 ;; (5) body
140 "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
141 "Regexp used to identify code blocks.")
143 (defvar org-babel-inline-src-block-regexp
144 (concat
145 ;; (1) replacement target (2) lang
146 "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
147 ;; (3,4) (unused, headers)
148 "\\(\\|\\[\\(.*?\\)\\]\\)"
149 ;; (5) body
150 "{\\([^\f\n\r\v]+?\\)}\\)")
151 "Regexp used to identify inline src-blocks.")
153 (defun org-babel-get-header (params key &optional others)
154 "Select only header argument of type KEY from a list.
155 Optional argument OTHERS indicates that only the header that do
156 not match KEY should be returned."
157 (delq nil
158 (mapcar
159 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
160 params)))
162 (defun org-babel-get-src-block-info (&optional light)
163 "Get information on the current source block.
165 Optional argument LIGHT does not resolve remote variable
166 references; a process which could likely result in the execution
167 of other code blocks.
169 Returns a list
170 (language body header-arguments-alist switches name indent)."
171 (let ((case-fold-search t) head info name indent)
172 ;; full code block
173 (if (setq head (org-babel-where-is-src-block-head))
174 (save-excursion
175 (goto-char head)
176 (setq info (org-babel-parse-src-block-match))
177 (setq indent (car (last info)))
178 (setq info (butlast info))
179 (while (and (forward-line -1)
180 (looking-at org-babel-multi-line-header-regexp))
181 (setf (nth 2 info)
182 (org-babel-merge-params
183 (org-babel-parse-header-arguments (match-string 1))
184 (nth 2 info))))
185 (when (looking-at org-babel-src-name-w-name-regexp)
186 (setq name (org-babel-clean-text-properties (match-string 4)))
187 (when (match-string 6)
188 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
189 (org-babel-merge-params
190 (mapcar (lambda (ref) (cons :var ref))
191 (org-babel-ref-split-args (match-string 6)))
192 (nth 2 info))))))
193 ;; inline source block
194 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
195 (looking-at org-babel-inline-src-block-regexp))
196 (setq info (org-babel-parse-inline-src-block-match))))
197 ;; resolve variable references and add summary parameters
198 (when (and info (not light))
199 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
200 (when info (append info (list name indent)))))
202 (defun org-babel-confirm-evaluate (info)
203 "Confirm evaluation of the code block INFO.
204 This behavior can be suppressed by setting the value of
205 `org-confirm-babel-evaluate' to nil, in which case all future
206 interactive code block evaluations will proceed without any
207 confirmation from the user.
209 Note disabling confirmation may result in accidental evaluation
210 of potentially harmful code."
211 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
212 (when (assoc :noeval (nth 2 info)) "no")))
213 (query (or (equal eval "query")
214 (if (functionp org-confirm-babel-evaluate)
215 (funcall org-confirm-babel-evaluate
216 (nth 0 info) (nth 1 info))
217 org-confirm-babel-evaluate))))
218 (if (or (equal eval "never") (equal eval "no")
219 (and query
220 (not (yes-or-no-p
221 (format "Evaluate this%scode block%son your system? "
222 (if info (format " %s " (nth 0 info)) " ")
223 (if (nth 4 info)
224 (format " (%s) " (nth 4 info)) " "))))))
225 (prog1 nil (message "Evaluation %s"
226 (if (or (equal eval "never") (equal eval "no"))
227 "Disabled" "Aborted")))
228 t)))
230 ;;;###autoload
231 (defun org-babel-execute-safely-maybe ()
232 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
233 (org-babel-execute-maybe)))
235 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
237 ;;;###autoload
238 (defun org-babel-execute-maybe ()
239 (interactive)
240 (or (org-babel-execute-src-block-maybe)
241 (org-babel-lob-execute-maybe)))
243 (defun org-babel-execute-src-block-maybe ()
244 "Conditionally execute a source block.
245 Detect if this is context for a Babel src-block and if so
246 then run `org-babel-execute-src-block'."
247 (interactive)
248 (let ((info (org-babel-get-src-block-info)))
249 (if info
250 (progn (org-babel-eval-wipe-error-buffer)
251 (org-babel-execute-src-block current-prefix-arg info) t) nil)))
253 ;;;###autoload
254 (defun org-babel-expand-src-block-maybe ()
255 "Conditionally expand a source block.
256 Detect if this is context for a org-babel src-block and if so
257 then run `org-babel-expand-src-block'."
258 (interactive)
259 (let ((info (org-babel-get-src-block-info)))
260 (if info
261 (progn (org-babel-expand-src-block current-prefix-arg info) t)
262 nil)))
264 ;;;###autoload
265 (defun org-babel-load-in-session-maybe ()
266 "Conditionally load a source block in a session.
267 Detect if this is context for a org-babel src-block and if so
268 then run `org-babel-load-in-session'."
269 (interactive)
270 (let ((info (org-babel-get-src-block-info)))
271 (if info
272 (progn (org-babel-load-in-session current-prefix-arg info) t)
273 nil)))
275 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
277 ;;;###autoload
278 (defun org-babel-pop-to-session-maybe ()
279 "Conditionally pop to a session.
280 Detect if this is context for a org-babel src-block and if so
281 then run `org-babel-pop-to-session'."
282 (interactive)
283 (let ((info (org-babel-get-src-block-info)))
284 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
286 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
288 (defconst org-babel-header-arg-names
289 '(cache cmdline colnames dir exports file noweb results
290 session tangle var eval noeval comments)
291 "Common header arguments used by org-babel.
292 Note that individual languages may define their own language
293 specific header arguments as well.")
295 (defvar org-babel-default-header-args
296 '((:session . "none") (:results . "replace") (:exports . "code")
297 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
298 "Default arguments to use when evaluating a source block.")
300 (defvar org-babel-default-inline-header-args
301 '((:session . "none") (:results . "silent") (:exports . "results"))
302 "Default arguments to use when evaluating an inline source block.")
304 (defvar org-babel-current-buffer-properties nil
305 "Local cache for buffer properties.")
306 (make-variable-buffer-local 'org-babel-current-buffer-properties)
308 (defvar org-babel-result-regexp
309 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
310 "Regular expression used to match result lines.
311 If the results are associated with a hash key then the hash will
312 be saved in the second match data.")
314 (defvar org-babel-result-w-name-regexp
315 (concat org-babel-result-regexp
316 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
318 (defvar org-babel-min-lines-for-block-output 10
319 "The minimum number of lines for block output.
320 If number of lines of output is equal to or exceeds this
321 value, the output is placed in a #+begin_example...#+end_example
322 block. Otherwise the output is marked as literal by inserting
323 colons at the starts of the lines. This variable only takes
324 effect if the :results output option is in effect.")
326 (defvar org-babel-noweb-error-langs nil
327 "Languages for which Babel will raise literate programming errors.
328 List of languages for which errors should be raised when the
329 source code block satisfying a noweb reference in this language
330 can not be resolved.")
332 (defvar org-babel-hash-show 4
333 "Number of initial characters to show of a hidden results hash.")
335 (defvar org-babel-after-execute-hook nil
336 "Hook for functions to be called after `org-babel-execute-src-block'")
337 (defun org-babel-named-src-block-regexp-for-name (name)
338 "This generates a regexp used to match a src block named NAME."
339 (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
340 (substring org-babel-src-block-regexp 1)))
342 ;;; functions
343 (defvar call-process-region)
344 ;;;###autoload
346 (defun org-babel-execute-src-block (&optional arg info params)
347 "Execute the current source code block.
348 Insert the results of execution into the buffer. Source code
349 execution and the collection and formatting of results can be
350 controlled through a variety of header arguments.
352 With prefix argument ARG, force re-execution even if a an
353 existing result cached in the buffer would otherwise have been
354 returned.
356 Optionally supply a value for INFO in the form returned by
357 `org-babel-get-src-block-info'.
359 Optionally supply a value for PARAMS which will be merged with
360 the header arguments specified at the front of the source code
361 block."
362 (interactive)
363 (let ((info (or info (org-babel-get-src-block-info))))
364 (when (org-babel-confirm-evaluate info)
365 (let* ((lang (nth 0 info))
366 (params (if params
367 (org-babel-process-params
368 (org-babel-merge-params (nth 2 info) params))
369 (nth 2 info)))
370 (cache? (and (not arg) (cdr (assoc :cache params))
371 (string= "yes" (cdr (assoc :cache params)))))
372 (result-params (cdr (assoc :result-params params)))
373 (new-hash (when cache? (org-babel-sha1-hash info)))
374 (old-hash (when cache? (org-babel-result-hash info)))
375 (body (setf (nth 1 info)
376 (let ((noweb (cdr (assoc :noweb params))))
377 (if (and noweb
378 (or (string= "yes" noweb)
379 (string= "tangle" noweb)))
380 (org-babel-expand-noweb-references info)
381 (nth 1 info)))))
382 (cmd (intern (concat "org-babel-execute:" lang)))
383 (dir (cdr (assoc :dir params)))
384 (default-directory
385 (or (and dir (file-name-as-directory dir)) default-directory))
386 (org-babel-call-process-region-original
387 (if (boundp 'org-babel-call-process-region-original)
388 org-babel-call-process-region-original
389 (symbol-function 'call-process-region)))
390 (indent (car (last info)))
391 result)
392 (unwind-protect
393 (flet ((call-process-region (&rest args)
394 (apply 'org-babel-tramp-handle-call-process-region args)))
395 (unless (fboundp cmd)
396 (error "No org-babel-execute function for %s!" lang))
397 (if (and (not arg) new-hash (equal new-hash old-hash))
398 (save-excursion ;; return cached result
399 (goto-char (org-babel-where-is-src-block-result nil info))
400 (end-of-line 1) (forward-char 1)
401 (setq result (org-babel-read-result))
402 (message (replace-regexp-in-string
403 "%" "%%" (format "%S" result))) result)
404 (message "executing %s code block%s..."
405 (capitalize lang)
406 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
407 (setq result
408 ((lambda (result)
409 (cond
410 ((member "file" result-params)
411 (cdr (assoc :file params)))
412 ((and (eq (cdr (assoc :result-type params)) 'value)
413 (or (member "vector" result-params)
414 (member "table" result-params))
415 (not (listp result)))
416 (list (list result)))
417 (t result)))
418 (funcall cmd body params)))
419 (org-babel-insert-result
420 result result-params info new-hash indent lang)
421 (run-hooks 'org-babel-after-execute-hook)
422 result))
423 (setq call-process-region 'org-babel-call-process-region-original))))))
425 (defun org-babel-expand-body:generic (body params &optional var-lines)
426 "Expand BODY with PARAMS.
427 Expand a block of code with org-babel according to it's header
428 arguments. This generic implementation of body expansion is
429 called for languages which have not defined their own specific
430 org-babel-expand-body:lang function."
431 (mapconcat #'identity (append var-lines (list body)) "\n"))
433 ;;;###autoload
434 (defun org-babel-expand-src-block (&optional arg info params)
435 "Expand the current source code block.
436 Expand according to the source code block's header
437 arguments and pop open the results in a preview buffer."
438 (interactive)
439 (let* ((info (or info (org-babel-get-src-block-info)))
440 (lang (nth 0 info))
441 (params (setf (nth 2 info)
442 (sort (org-babel-merge-params (nth 2 info) params)
443 (lambda (el1 el2) (string< (symbol-name (car el1))
444 (symbol-name (car el2)))))))
445 (body (setf (nth 1 info)
446 (if (and (cdr (assoc :noweb params))
447 (string= "yes" (cdr (assoc :noweb params))))
448 (org-babel-expand-noweb-references info) (nth 1 info))))
449 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
450 (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
451 (expanded
452 (if (fboundp expand-cmd) (funcall expand-cmd body params)
453 (org-babel-expand-body:generic
454 body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
455 (org-edit-src-code
456 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
458 ;;;###autoload
459 (defun org-babel-load-in-session (&optional arg info)
460 "Load the body of the current source-code block.
461 Evaluate the header arguments for the source block before
462 entering the session. After loading the body this pops open the
463 session."
464 (interactive)
465 (let* ((info (or info (org-babel-get-src-block-info)))
466 (lang (nth 0 info))
467 (params (nth 2 info))
468 (body (setf (nth 1 info)
469 (if (and (cdr (assoc :noweb params))
470 (string= "yes" (cdr (assoc :noweb params))))
471 (org-babel-expand-noweb-references info)
472 (nth 1 info))))
473 (session (cdr (assoc :session params)))
474 (dir (cdr (assoc :dir params)))
475 (default-directory
476 (or (and dir (file-name-as-directory dir)) default-directory))
477 (cmd (intern (concat "org-babel-load-session:" lang))))
478 (unless (fboundp cmd)
479 (error "No org-babel-load-session function for %s!" lang))
480 (pop-to-buffer (funcall cmd session body params))
481 (end-of-line 1)))
483 ;;;###autoload
484 (defun org-babel-initiate-session (&optional arg info)
485 "Initiate session for current code block.
486 If called with a prefix argument then resolve any variable
487 references in the header arguments and assign these variables in
488 the session. Copy the body of the code block to the kill ring."
489 (interactive "P")
490 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
491 (lang (nth 0 info))
492 (body (nth 1 info))
493 (params (nth 2 info))
494 (session (cdr (assoc :session params)))
495 (dir (cdr (assoc :dir params)))
496 (default-directory
497 (or (and dir (file-name-as-directory dir)) default-directory))
498 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
499 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
500 (if (and (stringp session) (string= session "none"))
501 (error "This block is not using a session!"))
502 (unless (fboundp init-cmd)
503 (error "No org-babel-initiate-session function for %s!" lang))
504 (with-temp-buffer (insert (org-babel-trim body))
505 (copy-region-as-kill (point-min) (point-max)))
506 (when arg
507 (unless (fboundp prep-cmd)
508 (error "No org-babel-prep-session function for %s!" lang))
509 (funcall prep-cmd session params))
510 (funcall init-cmd session params)))
512 ;;;###autoload
513 (defun org-babel-switch-to-session (&optional arg info)
514 "Switch to the session of the current code block.
515 Uses `org-babel-initiate-session' to start the session. If called
516 with a prefix argument then this is passed on to
517 `org-babel-initiate-session'."
518 (interactive "P")
519 (pop-to-buffer (org-babel-initiate-session arg info))
520 (end-of-line 1))
522 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
524 ;;;###autoload
525 (defun org-babel-switch-to-session-with-code (&optional arg info)
526 "Switch to code buffer and display session."
527 (interactive "P")
528 (flet ((swap-windows
530 (let ((other-window-buffer (window-buffer (next-window))))
531 (set-window-buffer (next-window) (current-buffer))
532 (set-window-buffer (selected-window) other-window-buffer))
533 (other-window 1)))
534 (let ((info (org-babel-get-src-block-info))
535 (org-src-window-setup 'reorganize-frame))
536 (save-excursion
537 (org-babel-switch-to-session arg info))
538 (org-edit-src-code))
539 (swap-windows)))
541 (defmacro org-babel-do-in-edit-buffer (&rest body)
542 "Evaluate BODY in edit buffer if there is a code block at point.
543 Return t if a code block was found at point, nil otherwise."
544 `(let ((org-src-window-setup 'switch-invisibly))
545 (when (and (org-babel-where-is-src-block-head)
546 (org-edit-src-code nil nil nil 'quietly))
547 (unwind-protect (progn ,@body)
548 (if (org-bound-and-true-p org-edit-src-from-org-mode)
549 (org-edit-src-exit)))
550 t)))
552 (defun org-babel-do-key-sequence-in-edit-buffer (key)
553 "Read key sequence and execute the command in edit buffer.
554 Enter a key sequence to be executed in the language major-mode
555 edit buffer. For example, TAB will alter the contents of the
556 Org-mode code block according to the effect of TAB in the
557 language major-mode buffer. For languages that support
558 interactive sessions, this can be used to send code from the Org
559 buffer to the session for evaluation using the native major-mode
560 evaluation mechanisms."
561 (interactive "kEnter key-sequence to execute in edit buffer: ")
562 (org-babel-do-in-edit-buffer
563 (call-interactively
564 (key-binding (or key (read-key-sequence nil))))))
566 (defvar org-bracket-link-regexp)
567 ;;;###autoload
568 (defun org-babel-open-src-block-result (&optional re-run)
569 "If `point' is on a src block then open the results of the
570 source code block, otherwise return nil. With optional prefix
571 argument RE-RUN the source-code block is evaluated even if
572 results already exist."
573 (interactive "P")
574 (when (org-babel-get-src-block-info)
575 (save-excursion
576 ;; go to the results, if there aren't any then run the block
577 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
578 (progn (org-babel-execute-src-block)
579 (org-babel-where-is-src-block-result))))
580 (end-of-line 1)
581 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
582 ;; open the results
583 (if (looking-at org-bracket-link-regexp)
584 ;; file results
585 (org-open-at-point)
586 (let ((results (org-babel-read-result)))
587 (flet ((echo-res (result)
588 (if (stringp result) result (format "%S" result))))
589 (pop-to-buffer (get-buffer-create "org-babel-results"))
590 (delete-region (point-min) (point-max))
591 (if (listp results)
592 ;; table result
593 (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
594 ;; scalar result
595 (insert (echo-res results))))))
596 t)))
598 ;;;###autoload
599 (defmacro org-babel-map-src-blocks (file &rest body)
600 "Evaluate BODY forms on each source-block in FILE.
601 If FILE is nil evaluate BODY forms on source blocks in current
602 buffer. During evaluation of BODY the following local variables
603 are set relative to the currently matched code block.
605 full-block ------- string holding the entirety of the code block
606 beg-block -------- point at the beginning of the code block
607 end-block -------- point at the end of the matched code block
608 lang ------------- string holding the language of the code block
609 beg-lang --------- point at the beginning of the lang
610 end-lang --------- point at the end of the lang
611 switches --------- string holding the switches
612 beg-switches ----- point at the beginning of the switches
613 end-switches ----- point at the end of the switches
614 header-args ------ string holding the header-args
615 beg-header-args -- point at the beginning of the header-args
616 end-header-args -- point at the end of the header-args
617 body ------------- string holding the body of the code block
618 beg-body --------- point at the beginning of the body
619 end-body --------- point at the end of the body"
620 (declare (indent 1))
621 (let ((tempvar (make-symbol "file")))
622 `(let* ((,tempvar ,file)
623 (visited-p (or (null ,tempvar)
624 (get-file-buffer (expand-file-name ,tempvar))))
625 (point (point)) to-be-removed)
626 (save-window-excursion
627 (when ,tempvar (find-file ,tempvar))
628 (setq to-be-removed (current-buffer))
629 (goto-char (point-min))
630 (while (re-search-forward org-babel-src-block-regexp nil t)
631 (goto-char (match-beginning 0))
632 (let ((full-block (match-string 0))
633 (beg-block (match-beginning 0))
634 (end-block (match-end 0))
635 (lang (match-string 2))
636 (beg-lang (match-beginning 2))
637 (end-lang (match-end 2))
638 (switches (match-string 3))
639 (beg-switches (match-beginning 3))
640 (end-switches (match-end 3))
641 (header-args (match-string 4))
642 (beg-header-args (match-beginning 4))
643 (end-header-args (match-end 4))
644 (body (match-string 5))
645 (beg-body (match-beginning 5))
646 (end-body (match-end 5)))
647 ,@body
648 (goto-char end-block))))
649 (unless visited-p (kill-buffer to-be-removed))
650 (goto-char point))))
652 ;;;###autoload
653 (defun org-babel-execute-buffer (&optional arg)
654 "Execute source code blocks in a buffer.
655 Call `org-babel-execute-src-block' on every source block in
656 the current buffer."
657 (interactive "P")
658 (org-save-outline-visibility t
659 (org-babel-map-src-blocks nil
660 (org-babel-execute-src-block arg))))
662 ;;;###autoload
663 (defun org-babel-execute-subtree (&optional arg)
664 "Execute source code blocks in a subtree.
665 Call `org-babel-execute-src-block' on every source block in
666 the current subtree."
667 (interactive "P")
668 (save-restriction
669 (save-excursion
670 (org-narrow-to-subtree)
671 (org-babel-execute-buffer arg)
672 (widen))))
674 ;;;###autoload
675 (defun org-babel-sha1-hash (&optional info)
676 "Generate an sha1 hash based on the value of info."
677 (interactive)
678 (let ((print-level nil)
679 (info (or info (org-babel-get-src-block-info))))
680 (setf (nth 2 info)
681 (sort (copy-sequence (nth 2 info))
682 (lambda (a b) (string< (car a) (car b)))))
683 (let ((hash (sha1
684 (format "%s-%s"
685 (mapconcat
686 #'identity
687 (delq nil
688 (mapcar
689 (lambda (arg)
690 (let ((v (cdr arg)))
691 (when (and v (not (and (sequencep v)
692 (not (consp v))
693 (= (length v) 0))))
694 (format "%S" v))))
695 (nth 2 info))) ":")
696 (nth 1 info)))))
697 (when (interactive-p) (message hash))
698 hash)))
700 (defun org-babel-result-hash (&optional info)
701 "Return the in-buffer hash associated with INFO."
702 (org-babel-where-is-src-block-result nil info)
703 (org-babel-clean-text-properties (match-string 3)))
705 (defun org-babel-hide-hash ()
706 "Hide the hash in the current results line.
707 Only the initial `org-babel-hash-show' characters of the hash
708 will remain visible."
709 (add-to-invisibility-spec '(org-babel-hide-hash . t))
710 (save-excursion
711 (when (and (re-search-forward org-babel-result-regexp nil t)
712 (match-string 3))
713 (let* ((start (match-beginning 3))
714 (hide-start (+ org-babel-hash-show start))
715 (end (match-end 3))
716 (hash (match-string 3))
717 ov1 ov2)
718 (setq ov1 (make-overlay start hide-start))
719 (setq ov2 (make-overlay hide-start end))
720 (overlay-put ov2 'invisible 'org-babel-hide-hash)
721 (overlay-put ov1 'babel-hash hash)))))
723 (defun org-babel-hide-all-hashes ()
724 "Hide the hash in the current buffer.
725 Only the initial `org-babel-hash-show' characters of each hash
726 will remain visible. This function should be called as part of
727 the `org-mode-hook'."
728 (save-excursion
729 (while (re-search-forward org-babel-result-regexp nil t)
730 (goto-char (match-beginning 0))
731 (org-babel-hide-hash)
732 (goto-char (match-end 0)))))
733 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
735 (defun org-babel-hash-at-point (&optional point)
736 "Return the value of the hash at POINT.
737 The hash is also added as the last element of the kill ring.
738 This can be called with C-c C-c."
739 (interactive)
740 (let ((hash (car (delq nil (mapcar
741 (lambda (ol) (overlay-get ol 'babel-hash))
742 (overlays-at (or point (point))))))))
743 (when hash (kill-new hash) (message hash))))
744 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
746 (defun org-babel-result-hide-spec ()
747 "Hide portions of results lines.
748 Add `org-babel-hide-result' as an invisibility spec for hiding
749 portions of results lines."
750 (add-to-invisibility-spec '(org-babel-hide-result . t)))
751 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
753 (defvar org-babel-hide-result-overlays nil
754 "Overlays hiding results.")
756 (defun org-babel-result-hide-all ()
757 "Fold all results in the current buffer."
758 (interactive)
759 (org-babel-show-result-all)
760 (save-excursion
761 (while (re-search-forward org-babel-result-regexp nil t)
762 (save-excursion (goto-char (match-beginning 0))
763 (org-babel-hide-result-toggle-maybe)))))
765 (defun org-babel-show-result-all ()
766 "Unfold all results in the current buffer."
767 (mapc 'delete-overlay org-babel-hide-result-overlays)
768 (setq org-babel-hide-result-overlays nil))
770 ;;;###autoload
771 (defun org-babel-hide-result-toggle-maybe ()
772 "Toggle visibility of result at point."
773 (interactive)
774 (let ((case-fold-search t))
775 (if (save-excursion
776 (beginning-of-line 1)
777 (looking-at org-babel-result-regexp))
778 (progn (org-babel-hide-result-toggle)
779 t) ;; to signal that we took action
780 nil))) ;; to signal that we did not
782 (defun org-babel-hide-result-toggle (&optional force)
783 "Toggle the visibility of the current result."
784 (interactive)
785 (save-excursion
786 (beginning-of-line)
787 (if (re-search-forward org-babel-result-regexp nil t)
788 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
789 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
791 (if (memq t (mapcar (lambda (overlay)
792 (eq (overlay-get overlay 'invisible)
793 'org-babel-hide-result))
794 (overlays-at start)))
795 (if (or (not force) (eq force 'off))
796 (mapc (lambda (ov)
797 (when (member ov org-babel-hide-result-overlays)
798 (setq org-babel-hide-result-overlays
799 (delq ov org-babel-hide-result-overlays)))
800 (when (eq (overlay-get ov 'invisible)
801 'org-babel-hide-result)
802 (delete-overlay ov)))
803 (overlays-at start)))
804 (setq ov (make-overlay start end))
805 (overlay-put ov 'invisible 'org-babel-hide-result)
806 ;; make the block accessible to isearch
807 (overlay-put
808 ov 'isearch-open-invisible
809 (lambda (ov)
810 (when (member ov org-babel-hide-result-overlays)
811 (setq org-babel-hide-result-overlays
812 (delq ov org-babel-hide-result-overlays)))
813 (when (eq (overlay-get ov 'invisible)
814 'org-babel-hide-result)
815 (delete-overlay ov))))
816 (push ov org-babel-hide-result-overlays)))
817 (error "Not looking at a result line"))))
819 ;; org-tab-after-check-for-cycling-hook
820 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
821 ;; Remove overlays when changing major mode
822 (add-hook 'org-mode-hook
823 (lambda () (org-add-hook 'change-major-mode-hook
824 'org-babel-show-result-all 'append 'local)))
826 (defvar org-file-properties)
827 (defun org-babel-params-from-properties (&optional lang)
828 "Retrieve parameters specified as properties.
829 Return an association list of any source block params which
830 may be specified in the properties of the current outline entry."
831 (save-match-data
832 (let (val sym)
833 (delq nil
834 (mapcar
835 (lambda (header-arg)
836 (and (setq val
837 (or (condition-case nil
838 (org-entry-get (point) header-arg t)
839 (error nil))
840 (cdr (assoc header-arg org-file-properties))))
841 (cons (intern (concat ":" header-arg))
842 (org-babel-read val))))
843 (mapcar
844 'symbol-name
845 (append
846 org-babel-header-arg-names
847 (progn
848 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
849 (and (boundp sym) (eval sym))))))))))
851 (defun org-babel-params-from-buffer ()
852 "Retrieve per-buffer parameters.
853 Return an association list of any source block params which
854 may be specified at the top of the current buffer."
855 (or org-babel-current-buffer-properties
856 (setq org-babel-current-buffer-properties
857 (save-match-data
858 (save-excursion
859 (save-restriction
860 (widen)
861 (goto-char (point-min))
862 (when (re-search-forward
863 (org-make-options-regexp (list "BABEL")) nil t)
864 (org-babel-parse-header-arguments
865 (org-match-string-no-properties 2)))))))))
867 (defvar org-src-preserve-indentation)
868 (defun org-babel-parse-src-block-match ()
869 "Parse the results from a match of the `org-babel-src-block-regexp'."
870 (let* ((block-indentation (length (match-string 1)))
871 (lang (org-babel-clean-text-properties (match-string 2)))
872 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
873 (switches (match-string 3))
874 (body (org-babel-clean-text-properties (match-string 5)))
875 (preserve-indentation (or org-src-preserve-indentation
876 (string-match "-i\\>" switches))))
877 (list lang
878 ;; get block body less properties, protective commas, and indentation
879 (with-temp-buffer
880 (save-match-data
881 (insert (org-babel-strip-protective-commas body))
882 (unless preserve-indentation (org-do-remove-indentation))
883 (buffer-string)))
884 (org-babel-merge-params
885 org-babel-default-header-args
886 (org-babel-params-from-buffer)
887 (org-babel-params-from-properties lang)
888 (if (boundp lang-headers) (eval lang-headers) nil)
889 (org-babel-parse-header-arguments
890 (org-babel-clean-text-properties (or (match-string 4) ""))))
891 switches
892 block-indentation)))
894 (defun org-babel-parse-inline-src-block-match ()
895 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
896 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
897 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
898 (list lang
899 (org-babel-strip-protective-commas
900 (org-babel-clean-text-properties (match-string 5)))
901 (org-babel-merge-params
902 org-babel-default-inline-header-args
903 (org-babel-params-from-buffer)
904 (org-babel-params-from-properties lang)
905 (if (boundp lang-headers) (eval lang-headers) nil)
906 (org-babel-parse-header-arguments
907 (org-babel-clean-text-properties (or (match-string 4) "")))))))
909 (defun org-babel-parse-header-arguments (arg-string)
910 "Parse a string of header arguments returning an alist."
911 (when (> (length arg-string) 0)
912 (delq nil
913 (mapcar
914 (lambda (arg)
915 (if (string-match
916 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
917 arg)
918 (cons (intern (match-string 1 arg))
919 (org-babel-read (org-babel-chomp (match-string 2 arg))))
920 (cons (intern (org-babel-chomp arg)) nil)))
921 (let ((balance 0) (partial nil) (lst nil) (last 0))
922 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
923 (setq balance (+ balance
924 (cond ((equal 91 ch) 1)
925 ((equal 93 ch) -1)
926 (t 0))))
927 (setq partial (cons ch partial))
928 (when (and (= ch 58) (= balance 0)
929 (or (= last 32) (= last 9)))
930 (setq lst (cons (apply #'string (nreverse (cddr partial)))
931 lst))
932 (setq partial (list ch)))
933 (setq last ch))
934 (string-to-list arg-string))
935 (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
937 (defun org-babel-process-params (params)
938 "Expand variables in PARAMS and add summary parameters."
939 (let* ((vars-and-names (org-babel-disassemble-tables
940 (mapcar (lambda (el)
941 (if (consp (cdr el))
942 (cdr el) (org-babel-ref-parse (cdr el))))
943 (org-babel-get-header params :var))
944 (cdr (assoc :hlines params))
945 (cdr (assoc :colnames params))
946 (cdr (assoc :rownames params))))
947 (result-params (append
948 (split-string (or (cdr (assoc :results params)) ""))
949 (cdr (assoc :result-params params)))))
950 (append
951 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
952 (list
953 (cons :colname-names (cadr vars-and-names))
954 (cons :rowname-names (caddr vars-and-names))
955 (cons :result-params result-params)
956 (cons :result-type (cond ((member "output" result-params) 'output)
957 ((member "value" result-params) 'value)
958 (t 'value))))
959 (org-babel-get-header params :var 'other))))
961 ;; row and column names
962 (defun org-babel-del-hlines (table)
963 "Remove all 'hlines from TABLE."
964 (remove 'hline table))
966 (defun org-babel-get-colnames (table)
967 "Return the column names of TABLE.
968 Return a cons cell, the `car' of which contains the TABLE less
969 colnames, and the `cdr' of which contains a list of the column
970 names."
971 (if (equal 'hline (nth 1 table))
972 (cons (cddr table) (car table))
973 (cons (cdr table) (car table))))
975 (defun org-babel-get-rownames (table)
976 "Return the row names of TABLE.
977 Return a cons cell, the `car' of which contains the TABLE less
978 colnames, and the `cdr' of which contains a list of the column
979 names. Note: this function removes any hlines in TABLE."
980 (flet ((trans (table) (apply #'mapcar* #'list table)))
981 (let* ((width (apply 'max
982 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
983 (table (trans (mapcar (lambda (row)
984 (if (not (equal row 'hline))
986 (setq row '())
987 (dotimes (n width)
988 (setq row (cons 'hline row)))
989 row))
990 table))))
991 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
992 (trans (cdr table)))
993 (remove 'hline (car table))))))
995 (defun org-babel-put-colnames (table colnames)
996 "Add COLNAMES to TABLE if they exist."
997 (if colnames (apply 'list colnames 'hline table) table))
999 (defun org-babel-put-rownames (table rownames)
1000 "Add ROWNAMES to TABLE if they exist."
1001 (if rownames
1002 (mapcar (lambda (row)
1003 (if (listp row)
1004 (cons (or (pop rownames) "") row)
1005 row)) table)
1006 table))
1008 (defun org-babel-pick-name (names selector)
1009 "Select one out of an alist of row or column names.
1010 SELECTOR can be either a list of names in which case those names
1011 will be returned directly, or an index into the list NAMES in
1012 which case the indexed names will be return."
1013 (if (listp selector)
1014 selector
1015 (when names
1016 (if (and selector (symbolp selector) (not (equal t selector)))
1017 (cdr (assoc selector names))
1018 (if (integerp selector)
1019 (nth (- selector 1) names)
1020 (cdr (car (last names))))))))
1022 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1023 "Parse tables for further processing.
1024 Process the variables in VARS according to the HLINES,
1025 ROWNAMES and COLNAMES header arguments. Return a list consisting
1026 of the vars, cnames and rnames."
1027 (let (cnames rnames)
1028 (list
1029 (mapcar
1030 (lambda (var)
1031 (when (listp (cdr var))
1032 (when (and (not (equal colnames "no"))
1033 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1034 (not (member 'hline (cddr (cdr var)))))))
1035 (let ((both (org-babel-get-colnames (cdr var))))
1036 (setq cnames (cons (cons (car var) (cdr both))
1037 cnames))
1038 (setq var (cons (car var) (car both)))))
1039 (when (and rownames (not (equal rownames "no")))
1040 (let ((both (org-babel-get-rownames (cdr var))))
1041 (setq rnames (cons (cons (car var) (cdr both))
1042 rnames))
1043 (setq var (cons (car var) (car both)))))
1044 (when (and hlines (not (equal hlines "yes")))
1045 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1046 var)
1047 vars)
1048 cnames rnames)))
1050 (defun org-babel-reassemble-table (table colnames rownames)
1051 "Add column and row names to a table.
1052 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1053 to the table for reinsertion to org-mode."
1054 (if (listp table)
1055 ((lambda (table)
1056 (if (and colnames (listp (car table)) (= (length (car table))
1057 (length colnames)))
1058 (org-babel-put-colnames table colnames) table))
1059 (if (and rownames (= (length table) (length rownames)))
1060 (org-babel-put-rownames table rownames) table))
1061 table))
1063 (defun org-babel-where-is-src-block-head ()
1064 "Find where the current source block begins.
1065 Return the point at the beginning of the current source
1066 block. Specifically at the beginning of the #+BEGIN_SRC line.
1067 If the point is not on a source block then return nil."
1068 (let ((initial (point)) top bottom)
1070 (save-excursion ;; on a source name line
1071 (beginning-of-line 1)
1072 (and (looking-at org-babel-src-name-regexp) (forward-line 1)
1073 (looking-at org-babel-src-block-regexp)
1074 (point)))
1075 (save-excursion ;; on a #+begin_src line
1076 (beginning-of-line 1)
1077 (and (looking-at org-babel-src-block-regexp)
1078 (point)))
1079 (save-excursion ;; inside a src block
1080 (and
1081 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1082 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1083 (< top initial) (< initial bottom)
1084 (progn (goto-char top) (beginning-of-line 1)
1085 (looking-at org-babel-src-block-regexp))
1086 (point))))))
1088 ;;;###autoload
1089 (defun org-babel-goto-src-block-head ()
1090 "Go to the beginning of the current code block."
1091 (interactive)
1092 ((lambda (head)
1093 (if head (goto-char head) (error "not currently in a code block")))
1094 (org-babel-where-is-src-block-head)))
1096 ;;;###autoload
1097 (defun org-babel-goto-named-src-block (name)
1098 "Go to a named source-code block."
1099 (interactive
1100 (let ((completion-ignore-case t))
1101 (list (org-icompleting-read "source-block name: "
1102 (org-babel-src-block-names) nil t))))
1103 (let ((point (org-babel-find-named-block name)))
1104 (if point
1105 ;; taken from `org-open-at-point'
1106 (progn (goto-char point) (org-show-context))
1107 (message "source-code block '%s' not found in this buffer" name))))
1109 (defun org-babel-find-named-block (name)
1110 "Find a named source-code block.
1111 Return the location of the source block identified by source
1112 NAME, or nil if no such block exists. Set match data according to
1113 org-babel-named-src-block-regexp."
1114 (save-excursion
1115 (let ((case-fold-search t)
1116 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1117 (goto-char (point-min))
1118 (when (or (re-search-forward regexp nil t)
1119 (re-search-backward regexp nil t))
1120 (match-beginning 0)))))
1122 (defun org-babel-src-block-names (&optional file)
1123 "Returns the names of source blocks in FILE or the current buffer."
1124 (save-excursion
1125 (when file (find-file file)) (goto-char (point-min))
1126 (let (names)
1127 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1128 (setq names (cons (org-babel-clean-text-properties (match-string 3))
1129 names)))
1130 names)))
1132 ;;;###autoload
1133 (defun org-babel-goto-named-result (name)
1134 "Go to a named result."
1135 (interactive
1136 (let ((completion-ignore-case t))
1137 (list (org-icompleting-read "source-block name: "
1138 (org-babel-result-names) nil t))))
1139 (let ((point (org-babel-find-named-result name)))
1140 (if point
1141 ;; taken from `org-open-at-point'
1142 (progn (goto-char point) (org-show-context))
1143 (message "result '%s' not found in this buffer" name))))
1145 (defun org-babel-find-named-result (name)
1146 "Find a named result.
1147 Return the location of the result named NAME in the current
1148 buffer or nil if no such result exists."
1149 (save-excursion
1150 (goto-char (point-min))
1151 (when (re-search-forward
1152 (concat org-babel-result-regexp
1153 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1154 (beginning-of-line 0) (point))))
1156 (defun org-babel-result-names (&optional file)
1157 "Returns the names of results in FILE or the current buffer."
1158 (save-excursion
1159 (when file (find-file file)) (goto-char (point-min))
1160 (let (names)
1161 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1162 (setq names (cons (org-babel-clean-text-properties (match-string 4))
1163 names)))
1164 names)))
1166 ;;;###autoload
1167 (defun org-babel-next-src-block (&optional arg)
1168 "Jump to the next source block.
1169 With optional prefix argument ARG, jump forward ARG many source blocks."
1170 (interactive "P")
1171 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1172 (condition-case nil
1173 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1174 (error (error "No further code blocks")))
1175 (goto-char (match-beginning 0)) (org-show-context))
1177 ;;;###autoload
1178 (defun org-babel-previous-src-block (&optional arg)
1179 "Jump to the previous source block.
1180 With optional prefix argument ARG, jump backward ARG many source blocks."
1181 (interactive "P")
1182 (condition-case nil
1183 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1184 (error (error "No previous code blocks")))
1185 (goto-char (match-beginning 0)) (org-show-context))
1187 (defvar org-babel-load-languages)
1189 ;;;###autoload
1190 (defun org-babel-mark-block ()
1191 "Mark current src block"
1192 (interactive)
1193 ((lambda (head)
1194 (when head
1195 (save-excursion
1196 (goto-char head)
1197 (looking-at org-babel-src-block-regexp))
1198 (push-mark (match-end 5) nil t)
1199 (goto-char (match-beginning 5))))
1200 (org-babel-where-is-src-block-head)))
1202 (defun org-babel-demarcate-block (&optional arg)
1203 "Wrap or split the code in the region or on the point.
1204 When called from inside of a code block the current block is
1205 split. When called from outside of a code block a new code block
1206 is created. In both cases if the region is demarcated and if the
1207 region is not active then the point is demarcated."
1208 (interactive "P")
1209 (let ((info (org-babel-get-src-block-info 'light))
1210 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1211 (if info
1212 (mapc
1213 (lambda (place)
1214 (save-excursion
1215 (goto-char place)
1216 (let ((lang (nth 0 info))
1217 (indent (make-string (nth 5 info) ? )))
1218 (when (string-match "^[[:space:]]*$"
1219 (buffer-substring (point-at-bol)
1220 (point-at-eol)))
1221 (delete-region (point-at-bol) (point-at-eol)))
1222 (insert (concat (if (looking-at "^") "" "\n")
1223 indent "#+end_src\n"
1224 (if arg stars indent) "\n"
1225 indent "#+begin_src " lang
1226 (if (looking-at "[\n\r]") "" "\n")))))
1227 (move-end-of-line 2))
1228 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1229 (let ((start (point))
1230 (lang (org-icompleting-read "Lang: "
1231 (mapcar (lambda (el) (symbol-name (car el)))
1232 org-babel-load-languages)))
1233 (body (delete-and-extract-region
1234 (if (region-active-p) (mark) (point)) (point))))
1235 (insert (concat (if (looking-at "^") "" "\n")
1236 (if arg (concat stars "\n") "")
1237 "#+begin_src " lang "\n"
1238 body
1239 (if (or (= (length body) 0)
1240 (string-match "[\r\n]$" body)) "" "\n")
1241 "#+end_src\n"))
1242 (goto-char start) (move-end-of-line 1)))))
1244 (defvar org-babel-lob-one-liner-regexp)
1245 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1246 "Find where the current source block results begin.
1247 Return the point at the beginning of the result of the current
1248 source block. Specifically at the beginning of the results line.
1249 If no result exists for this block then create a results line
1250 following the source block."
1251 (save-excursion
1252 (let* ((on-lob-line (progn (beginning-of-line 1)
1253 (looking-at org-babel-lob-one-liner-regexp)))
1254 (name (if on-lob-line
1255 (nth 0 (org-babel-lob-get-info))
1256 (nth 4 (or info (org-babel-get-src-block-info)))))
1257 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1258 found beg end)
1259 (when head (goto-char head))
1260 (setq
1261 found ;; was there a result (before we potentially insert one)
1263 (and
1264 ;; named results:
1265 ;; - return t if it is found, else return nil
1266 ;; - if it does not need to be rebuilt, then don't set end
1267 ;; - if it does need to be rebuilt then do set end
1268 name (setq beg (org-babel-find-named-result name))
1269 (prog1 beg
1270 (when (and hash (not (string= hash (match-string 3))))
1271 (goto-char beg) (setq end beg) ;; beginning of result
1272 (forward-line 1)
1273 (delete-region end (org-babel-result-end)) nil)))
1274 (and
1275 ;; unnamed results:
1276 ;; - return t if it is found, else return nil
1277 ;; - if it is found, and the hash doesn't match, delete and set end
1278 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1279 (progn (end-of-line 1)
1280 (if (eobp) (insert "\n") (forward-char 1))
1281 (setq end (point))
1282 (or (and (not name)
1283 (progn ;; unnamed results line already exists
1284 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1285 (beginning-of-line 1)
1286 (looking-at
1287 (concat org-babel-result-regexp "\n")))
1288 (prog1 (point)
1289 ;; must remove and rebuild if hash!=old-hash
1290 (if (and hash (not (string= hash (match-string 3))))
1291 (prog1 nil
1292 (forward-line 1)
1293 (delete-region
1294 end (org-babel-result-end)))
1295 (setq end nil)))))))))
1296 (if (and insert end)
1297 (progn
1298 (goto-char end)
1299 (unless beg
1300 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1301 (insert (concat
1302 (if indent
1303 (mapconcat
1304 (lambda (el) " ")
1305 (org-number-sequence 1 indent) "")
1307 "#+results"
1308 (when hash (concat "["hash"]"))
1310 (when name (concat " " name)) "\n"))
1311 (unless beg (insert "\n") (backward-char))
1312 (beginning-of-line 0)
1313 (if hash (org-babel-hide-hash))
1314 (point))
1315 found))))
1317 (defvar org-block-regexp)
1318 (defun org-babel-read-result ()
1319 "Read the result at `point' into emacs-lisp."
1320 (let ((case-fold-search t) result-string)
1321 (cond
1322 ((org-at-table-p) (org-babel-read-table))
1323 ((org-in-item-p) (org-babel-read-list))
1324 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1325 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1326 ((looking-at "^[ \t]*: ")
1327 (setq result-string
1328 (org-babel-trim
1329 (mapconcat (lambda (line)
1330 (if (and (> (length line) 1)
1331 (string-match "^[ \t]*: \\(.+\\)" line))
1332 (match-string 1 line)
1333 line))
1334 (split-string
1335 (buffer-substring
1336 (point) (org-babel-result-end)) "[\r\n]+")
1337 "\n")))
1338 (or (org-babel-number-p result-string) result-string))
1339 ((looking-at org-babel-result-regexp)
1340 (save-excursion (forward-line 1) (org-babel-read-result))))))
1342 (defun org-babel-read-table ()
1343 "Read the table at `point' into emacs-lisp."
1344 (mapcar (lambda (row)
1345 (if (and (symbolp row) (equal row 'hline)) row
1346 (mapcar #'org-babel-read row)))
1347 (org-table-to-lisp)))
1349 (defun org-babel-read-list ()
1350 "Read the list at `point' into emacs-lisp."
1351 (mapcar #'org-babel-read (cdr (org-list-parse-list))))
1353 (defvar org-link-types-re)
1354 (defun org-babel-read-link ()
1355 "Read the link at `point' into emacs-lisp.
1356 If the path of the link is a file path it is expanded using
1357 `expand-file-name'."
1358 (let* ((case-fold-search t)
1359 (raw (and (looking-at org-bracket-link-regexp)
1360 (org-babel-clean-text-properties (match-string 1))))
1361 (type (and (string-match org-link-types-re raw)
1362 (match-string 1 raw))))
1363 (cond
1364 ((not type) (expand-file-name raw))
1365 ((string= type "file")
1366 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1367 (expand-file-name (match-string 2 raw))))
1368 (t raw))))
1370 (defun org-babel-insert-result
1371 (result &optional result-params info hash indent lang)
1372 "Insert RESULT into the current buffer.
1373 By default RESULT is inserted after the end of the
1374 current source block. With optional argument RESULT-PARAMS
1375 controls insertion of results in the org-mode file.
1376 RESULT-PARAMS can take the following values...
1378 replace - (default option) insert results after the source block
1379 replacing any previously inserted results
1381 silent -- no results are inserted
1383 file ---- the results are interpreted as a file path, and are
1384 inserted into the buffer using the Org-mode file syntax
1386 list ---- the results are interpreted as an Org-mode list.
1388 raw ----- results are added directly to the Org-mode file. This
1389 is a good option if you code block will output org-mode
1390 formatted text.
1392 org ----- similar in effect to raw, only the results are wrapped
1393 in an org code block. Similar to the raw option, on
1394 export the results will be interpreted as org-formatted
1395 text, however by wrapping the results in an org code
1396 block they can be replaced upon re-execution of the
1397 code block.
1399 html ---- results are added inside of a #+BEGIN_HTML block. This
1400 is a good option if you code block will output html
1401 formatted text.
1403 latex --- results are added inside of a #+BEGIN_LATEX block.
1404 This is a good option if you code block will output
1405 latex formatted text.
1407 code ---- the results are extracted in the syntax of the source
1408 code of the language being evaluated and are added
1409 inside of a #+BEGIN_SRC block with the source-code
1410 language set appropriately. Note this relies on the
1411 optional LANG argument."
1412 (if (stringp result)
1413 (progn
1414 (setq result (org-babel-clean-text-properties result))
1415 (when (member "file" result-params)
1416 (setq result (org-babel-result-to-file result))))
1417 (unless (listp result) (setq result (format "%S" result))))
1418 (if (and result-params (member "silent" result-params))
1419 (progn
1420 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1421 result)
1422 (when (and (stringp result) ;; ensure results end in a newline
1423 (> (length result) 0)
1424 (not (or (string-equal (substring result -1) "\n")
1425 (string-equal (substring result -1) "\r"))))
1426 (setq result (concat result "\n")))
1427 (save-excursion
1428 (let ((existing-result (org-babel-where-is-src-block-result
1429 t info hash indent))
1430 (results-switches
1431 (cdr (assoc :results_switches (nth 2 info))))
1432 beg end)
1433 (if (not existing-result)
1434 (setq beg (point))
1435 (goto-char existing-result)
1436 (save-excursion
1437 (re-search-forward "#" nil t)
1438 (setq indent (- (current-column) 1)))
1439 (forward-line 1)
1440 (setq beg (point))
1441 (cond
1442 ((member "replace" result-params)
1443 (delete-region (point) (org-babel-result-end)))
1444 ((member "append" result-params)
1445 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1446 ((member "prepend" result-params)))) ; already there
1447 (setq results-switches
1448 (if results-switches (concat " " results-switches) ""))
1449 ;; insert results based on type
1450 (cond
1451 ;; do nothing for an empty result
1452 ((= (length result) 0))
1453 ;; insert a list if preferred
1454 ((member "list" result-params)
1455 (insert
1456 (org-babel-trim
1457 (org-list-to-generic (cons 'unordered
1458 (if (listp result) result (list result)))
1459 '(:splicep nil :istart "- " :iend "\n")))))
1460 ;; assume the result is a table if it's not a string
1461 ((not (stringp result))
1462 (goto-char beg)
1463 (insert (concat (orgtbl-to-orgtbl
1464 (if (or (eq 'hline (car result))
1465 (and (listp (car result))
1466 (listp (cdr (car result)))))
1467 result (list result))
1468 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1469 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1470 ((member "file" result-params)
1471 (insert result))
1472 (t (goto-char beg) (insert result)))
1473 (when (listp result) (goto-char (org-table-end)))
1474 (setq end (point-marker))
1475 ;; possibly wrap result
1476 (flet ((wrap (start finish)
1477 (goto-char beg) (insert start)
1478 (goto-char end) (insert finish)
1479 (setq end (point-marker))))
1480 (cond
1481 ((member "html" result-params)
1482 (wrap "#+BEGIN_HTML\n" "#+END_HTML"))
1483 ((member "latex" result-params)
1484 (wrap "#+BEGIN_LaTeX\n" "#+END_LaTeX"))
1485 ((member "code" result-params)
1486 (wrap (format "#+BEGIN_SRC %s%s\n" (or lang "none") results-switches)
1487 "#+END_SRC"))
1488 ((member "org" result-params)
1489 (wrap "#+BEGIN_ORG\n" "#+END_ORG"))
1490 ((member "raw" result-params)
1491 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1492 ((member "wrap" result-params)
1493 (when (and (stringp result) (not (member "file" result-params)))
1494 (org-babel-examplize-region beg end results-switches))
1495 (wrap "#+BEGIN_RESULT\n" "#+END_RESULT"))
1496 ((and (stringp result) (not (member "file" result-params)))
1497 (org-babel-examplize-region beg end results-switches)
1498 (setq end (point)))))
1499 ;; possibly indent the results to match the #+results line
1500 (when (and indent (> indent 0)
1501 ;; in this case `table-align' does the work for us
1502 (not (and (listp result)
1503 (member "append" result-params))))
1504 (indent-rigidly beg end indent))))
1505 (if (= (length result) 0)
1506 (if (member "value" result-params)
1507 (message "Code block returned no value.")
1508 (message "Code block produced no output."))
1509 (message "Code block evaluation complete."))))
1511 (defun org-babel-remove-result (&optional info)
1512 "Remove the result of the current source block."
1513 (interactive)
1514 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1515 (when location
1516 (save-excursion
1517 (goto-char location) (setq start (point)) (forward-line 1)
1518 (delete-region start (org-babel-result-end))))))
1520 (defun org-babel-result-end ()
1521 "Return the point at the end of the current set of results"
1522 (save-excursion
1523 (cond
1524 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1525 ((org-in-item-p) (- (org-list-bottom-point) 1))
1527 (let ((case-fold-search t)
1528 (blocks-re (regexp-opt
1529 (list "latex" "html" "example" "src" "result"))))
1530 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1531 (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1532 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1533 (forward-line 1))))
1534 (point)))))
1536 (defun org-babel-result-to-file (result)
1537 "Convert RESULT into an `org-mode' link.
1538 If the `default-directory' is different from the containing
1539 file's directory then expand relative links."
1540 (format
1541 "[[file:%s]]"
1542 (if (and default-directory
1543 buffer-file-name
1544 (not (string= (expand-file-name default-directory)
1545 (expand-file-name
1546 (file-name-directory buffer-file-name)))))
1547 (expand-file-name result default-directory)
1548 result)))
1550 (defun org-babel-examplize-region (beg end &optional results-switches)
1551 "Comment out region using the ': ' org example quote."
1552 (interactive "*r")
1553 (let ((size (count-lines beg end)))
1554 (save-excursion
1555 (cond ((= size 0)) ; do nothing for an empty result
1556 ((< size org-babel-min-lines-for-block-output)
1557 (goto-char beg)
1558 (dotimes (n size)
1559 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1561 (goto-char beg)
1562 (insert (if results-switches
1563 (format "#+begin_example%s\n" results-switches)
1564 "#+begin_example\n"))
1565 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1566 (insert "#+end_example\n"))))))
1568 (defun org-babel-update-block-body (new-body)
1569 "Update the body of the current code block to NEW-BODY."
1570 (if (not (org-babel-where-is-src-block-head))
1571 (error "not in source block")
1572 (save-match-data
1573 (replace-match (concat (org-babel-trim new-body) "\n") nil nil nil 5))
1574 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1576 (defun org-babel-merge-params (&rest plists)
1577 "Combine all parameter association lists in PLISTS.
1578 Later elements of PLISTS override the values of previous element.
1579 This takes into account some special considerations for certain
1580 parameters when merging lists."
1581 (let ((results-exclusive-groups
1582 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1583 "html" "latex" "code" "pp" "wrap")
1584 ("replace" "silent" "append" "prepend")
1585 ("output" "value")))
1586 (exports-exclusive-groups
1587 '(("code" "results" "both" "none")))
1588 params results exports tangle noweb cache vars shebang comments)
1589 (flet ((e-merge (exclusive-groups &rest result-params)
1590 ;; maintain exclusivity of mutually exclusive parameters
1591 (let (output)
1592 (mapc (lambda (new-params)
1593 (mapc (lambda (new-param)
1594 (mapc (lambda (exclusive-group)
1595 (when (member new-param exclusive-group)
1596 (mapcar (lambda (excluded-param)
1597 (setq output
1598 (delete
1599 excluded-param
1600 output)))
1601 exclusive-group)))
1602 exclusive-groups)
1603 (setq output (org-uniquify
1604 (cons new-param output))))
1605 new-params))
1606 result-params)
1607 output)))
1608 (mapc
1609 (lambda (plist)
1610 (mapc
1611 (lambda (pair)
1612 (case (car pair)
1613 (:var
1614 (let ((name (if (listp (cdr pair))
1615 (cadr pair)
1616 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1617 (cdr pair))
1618 (intern (match-string 1 (cdr pair)))))))
1619 (when name
1620 (setq vars
1621 (cons (cons name pair)
1622 (if (member name (mapcar #'car vars))
1623 (delq nil
1624 (mapcar
1625 (lambda (p) (unless (equal (car p) name) p))
1626 vars))
1627 vars))))))
1628 (:results
1629 (setq results (e-merge results-exclusive-groups
1630 results (split-string (cdr pair)))))
1631 (:file
1632 (when (cdr pair)
1633 (setq results (e-merge results-exclusive-groups
1634 results '("file")))
1635 (unless (or (member "both" exports)
1636 (member "none" exports)
1637 (member "code" exports))
1638 (setq exports (e-merge exports-exclusive-groups
1639 exports '("results"))))
1640 (setq params (cons pair (assq-delete-all (car pair) params)))))
1641 (:exports
1642 (setq exports (e-merge exports-exclusive-groups
1643 exports (split-string (cdr pair)))))
1644 (:tangle ;; take the latest -- always overwrite
1645 (setq tangle (or (list (cdr pair)) tangle)))
1646 (:noweb
1647 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1648 (split-string (or (cdr pair) "")))))
1649 (:cache
1650 (setq cache (e-merge '(("yes" "no")) cache
1651 (split-string (or (cdr pair) "")))))
1652 (:shebang ;; take the latest -- always overwrite
1653 (setq shebang (or (list (cdr pair)) shebang)))
1654 (:comments
1655 (setq comments (e-merge '(("yes" "no")) comments
1656 (split-string (or (cdr pair) "")))))
1657 (t ;; replace: this covers e.g. :session
1658 (setq params (cons pair (assq-delete-all (car pair) params))))))
1659 plist))
1660 plists))
1661 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1662 (cons (cons :comments (mapconcat 'identity comments " "))
1663 (cons (cons :shebang (mapconcat 'identity shebang " "))
1664 (cons (cons :cache (mapconcat 'identity cache " "))
1665 (cons (cons :noweb (mapconcat 'identity noweb " "))
1666 (cons (cons :tangle (mapconcat 'identity tangle " "))
1667 (cons (cons :exports
1668 (mapconcat 'identity exports " "))
1669 (cons
1670 (cons :results
1671 (mapconcat 'identity results " "))
1672 params)))))))))
1674 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1675 "Expand Noweb references in the body of the current source code block.
1677 For example the following reference would be replaced with the
1678 body of the source-code block named 'example-block'.
1680 <<example-block>>
1682 Note that any text preceding the <<foo>> construct on a line will
1683 be interposed between the lines of the replacement text. So for
1684 example if <<foo>> is placed behind a comment, then the entire
1685 replacement text will also be commented.
1687 This function must be called from inside of the buffer containing
1688 the source-code block which holds BODY.
1690 In addition the following syntax can be used to insert the
1691 results of evaluating the source-code block named 'example-block'.
1693 <<example-block()>>
1695 Any optional arguments can be passed to example-block by placing
1696 the arguments inside the parenthesis following the convention
1697 defined by `org-babel-lob'. For example
1699 <<example-block(a=9)>>
1701 would set the value of argument \"a\" equal to \"9\". Note that
1702 these arguments are not evaluated in the current source-code
1703 block but are passed literally to the \"example-block\"."
1704 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1705 (info (or info (org-babel-get-src-block-info)))
1706 (lang (nth 0 info))
1707 (body (nth 1 info))
1708 (new-body "") index source-name evaluate prefix)
1709 (flet ((nb-add (text)
1710 (setq new-body (concat new-body text))))
1711 (with-temp-buffer
1712 (insert body) (goto-char (point-min))
1713 (setq index (point))
1714 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1715 (save-match-data (setf source-name (match-string 1)))
1716 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1717 (save-match-data
1718 (setq prefix
1719 (buffer-substring (match-beginning 0)
1720 (save-excursion
1721 (beginning-of-line 1) (point)))))
1722 ;; add interval to new-body (removing noweb reference)
1723 (goto-char (match-beginning 0))
1724 (nb-add (buffer-substring index (point)))
1725 (goto-char (match-end 0))
1726 (setq index (point))
1727 (nb-add (with-current-buffer parent-buffer
1728 (mapconcat ;; interpose PREFIX between every line
1729 #'identity
1730 (split-string
1731 (if evaluate
1732 (let ((raw (org-babel-ref-resolve source-name)))
1733 (if (stringp raw) raw (format "%S" raw)))
1734 (save-restriction
1735 (widen)
1736 (let ((point (org-babel-find-named-block
1737 source-name)))
1738 (if point
1739 (save-excursion
1740 (goto-char point)
1741 (org-babel-trim
1742 (org-babel-expand-noweb-references
1743 (org-babel-get-src-block-info))))
1744 ;; optionally raise an error if named
1745 ;; source-block doesn't exist
1746 (if (member lang org-babel-noweb-error-langs)
1747 (error "%s"
1748 (concat
1749 "<<" source-name ">> "
1750 "could not be resolved (see "
1751 "`org-babel-noweb-error-langs')"))
1752 "")))))
1753 "[\n\r]") (concat "\n" prefix)))))
1754 (nb-add (buffer-substring index (point-max)))))
1755 new-body))
1757 (defun org-babel-clean-text-properties (text)
1758 "Strip all properties from text return."
1759 (when text
1760 (set-text-properties 0 (length text) nil text) text))
1762 (defun org-babel-strip-protective-commas (body)
1763 "Strip protective commas from bodies of source blocks."
1764 (replace-regexp-in-string "^,#" "#" body))
1766 (defun org-babel-script-escape (str)
1767 "Safely convert tables into elisp lists."
1768 (let (in-single in-double out)
1769 (org-babel-read
1770 (if (and (stringp str) (string-match "^\\[.+\\]$" str))
1771 (org-babel-read
1772 (concat
1774 (progn
1775 (mapc
1776 (lambda (ch)
1777 (setq
1779 (case ch
1780 (91 (if (or in-double in-single) ; [
1781 (cons 91 out)
1782 (cons 40 out)))
1783 (93 (if (or in-double in-single) ; ]
1784 (cons 93 out)
1785 (cons 41 out)))
1786 (44 (if (or in-double in-single) (cons 44 out) out)) ; ,
1787 (39 (if in-double ; '
1788 (cons 39 out)
1789 (setq in-single (not in-single)) (cons 34 out)))
1790 (34 (if in-single ; "
1791 (append (list 34 32) out)
1792 (setq in-double (not in-double)) (cons 34 out)))
1793 (t (cons ch out)))))
1794 (string-to-list str))
1795 (apply #'string (reverse out)))))
1796 str))))
1798 (defun org-babel-read (cell)
1799 "Convert the string value of CELL to a number if appropriate.
1800 Otherwise if cell looks like lisp (meaning it starts with a
1801 \"(\" or a \"'\") then read it as lisp, otherwise return it
1802 unmodified as a string.
1804 This is taken almost directly from `org-read-prop'."
1805 (if (and (stringp cell) (not (equal cell "")))
1806 (or (org-babel-number-p cell)
1807 (if (or (equal "(" (substring cell 0 1))
1808 (equal "'" (substring cell 0 1))
1809 (equal "`" (substring cell 0 1)))
1810 (eval (read cell))
1811 (progn (set-text-properties 0 (length cell) nil cell) cell)))
1812 cell))
1814 (defun org-babel-number-p (string)
1815 "If STRING represents a number return it's value."
1816 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1817 (= (length (substring string (match-beginning 0)
1818 (match-end 0)))
1819 (length string)))
1820 (string-to-number string)))
1822 (defun org-babel-import-elisp-from-file (file-name &optional separator)
1823 "Read the results located at FILE-NAME into an elisp table.
1824 If the table is trivial, then return it as a scalar."
1825 (let (result)
1826 (save-window-excursion
1827 (with-temp-buffer
1828 (condition-case nil
1829 (progn
1830 (org-table-import file-name separator)
1831 (delete-file file-name)
1832 (setq result (mapcar (lambda (row)
1833 (mapcar #'org-babel-string-read row))
1834 (org-table-to-lisp))))
1835 (error nil)))
1836 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
1837 (if (consp (car result))
1838 (if (null (cdr (car result)))
1839 (caar result)
1840 result)
1841 (car result))
1842 result))))
1844 (defun org-babel-string-read (cell)
1845 "Strip nested \"s from around strings."
1846 (org-babel-read (or (and (stringp cell)
1847 (string-match "\\\"\\(.+\\)\\\"" cell)
1848 (match-string 1 cell))
1849 cell)))
1851 (defun org-babel-reverse-string (string)
1852 "Return the reverse of STRING."
1853 (apply 'string (reverse (string-to-list string))))
1855 (defun org-babel-chomp (string &optional regexp)
1856 "Strip trailing spaces and carriage returns from STRING.
1857 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1858 overwritten by specifying a regexp as a second argument."
1859 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
1860 (while (and (> (length string) 0)
1861 (string-match regexp (substring string -1)))
1862 (setq string (substring string 0 -1)))
1863 string))
1865 (defun org-babel-trim (string &optional regexp)
1866 "Strip leading and trailing spaces and carriage returns from STRING.
1867 Like `org-babel-chomp' only it runs on both the front and back
1868 of the string."
1869 (org-babel-chomp (org-babel-reverse-string
1870 (org-babel-chomp (org-babel-reverse-string string) regexp))
1871 regexp))
1873 (defvar org-babel-org-babel-call-process-region-original nil)
1874 (defun org-babel-tramp-handle-call-process-region
1875 (start end program &optional delete buffer display &rest args)
1876 "Use tramp to handle call-process-region.
1877 Fixes a bug in `tramp-handle-call-process-region'."
1878 (if (and (featurep 'tramp) (file-remote-p default-directory))
1879 (let ((tmpfile (tramp-compat-make-temp-file "")))
1880 (write-region start end tmpfile)
1881 (when delete (delete-region start end))
1882 (unwind-protect
1883 ;; (apply 'call-process program tmpfile buffer display args)
1884 ;; bug in tramp
1885 (apply 'process-file program tmpfile buffer display args)
1886 (delete-file tmpfile)))
1887 ;; org-babel-call-process-region-original is the original emacs
1888 ;; definition. It is in scope from the let binding in
1889 ;; org-babel-execute-src-block
1890 (apply org-babel-call-process-region-original
1891 start end program delete buffer display args)))
1893 (defun org-babel-local-file-name (file)
1894 "Return the local name component of FILE."
1895 (if (file-remote-p file)
1896 (let (localname)
1897 (with-parsed-tramp-file-name file nil
1898 localname))
1899 file))
1901 (defun org-babel-process-file-name (name &optional no-quote-p)
1902 "Prepare NAME to be used in an external process.
1903 If NAME specifies a remote location, the remote portion of the
1904 name is removed, since in that case the process will be executing
1905 remotely. The file name is then processed by
1906 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
1907 the file name is additionally processed by
1908 `shell-quote-argument'"
1909 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
1910 (expand-file-name (org-babel-local-file-name name))))
1912 (defvar org-babel-temporary-directory)
1913 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
1914 (defvar org-babel-temporary-directory
1915 (or (and (boundp 'org-babel-temporary-directory)
1916 (file-exists-p org-babel-temporary-directory)
1917 org-babel-temporary-directory)
1918 (make-temp-file "babel-" t))
1919 "Directory to hold temporary files created to execute code blocks.
1920 Used by `org-babel-temp-file'. This directory will be removed on
1921 Emacs shutdown."))
1923 (defun org-babel-temp-file (prefix &optional suffix)
1924 "Create a temporary file in the `org-babel-temporary-directory'.
1925 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
1926 value of `temporary-file-directory' temporarily set to the value
1927 of `org-babel-temporary-directory'."
1928 (if (file-remote-p default-directory)
1929 (make-temp-file
1930 (concat (file-remote-p default-directory)
1931 (expand-file-name
1932 prefix temporary-file-directory)
1933 nil suffix))
1934 (let ((temporary-file-directory
1935 (or (and (file-exists-p org-babel-temporary-directory)
1936 org-babel-temporary-directory)
1937 temporary-file-directory)))
1938 (make-temp-file prefix nil suffix))))
1940 (defun org-babel-remove-temporary-directory ()
1941 "Remove `org-babel-temporary-directory' on Emacs shutdown."
1942 (when (and (boundp 'org-babel-temporary-directory)
1943 (file-exists-p org-babel-temporary-directory))
1944 ;; taken from `delete-directory' in files.el
1945 (condition-case nil
1946 (progn
1947 (mapc (lambda (file)
1948 ;; This test is equivalent to
1949 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
1950 ;; but more efficient
1951 (if (eq t (car (file-attributes file)))
1952 (delete-directory file)
1953 (delete-file file)))
1954 ;; We do not want to delete "." and "..".
1955 (directory-files org-babel-temporary-directory 'full
1956 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
1957 (delete-directory org-babel-temporary-directory))
1958 (error
1959 (message "Failed to remove temporary Org-babel directory %s"
1960 org-babel-temporary-directory)))))
1962 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
1964 (provide 'ob)
1966 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
1968 ;;; ob.el ends here