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