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