ob: allow passing elisp vectors through to code blocks
[org-mode/org-jambu.git] / lisp / ob.el
blobb0b5fb6d7569a1445661ace919b55b0b8b85ef3d
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 (defvar org-src-lang-modes)
39 (declare-function show-all "outline" ())
40 (declare-function tramp-compat-make-temp-file "tramp-compat"
41 (filename &optional dir-flag))
42 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
43 (declare-function tramp-file-name-user "tramp" (vec))
44 (declare-function tramp-file-name-host "tramp" (vec))
45 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
46 (declare-function org-icompleting-read "org" (&rest args))
47 (declare-function org-edit-src-code "org-src"
48 (&optional context code edit-buffer-name quietp))
49 (declare-function org-edit-src-exit "org-src" (&optional context))
50 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
51 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
52 (declare-function org-outline-overlay-data "org" (&optional use-markers))
53 (declare-function org-set-outline-overlay-data "org" (data))
54 (declare-function org-narrow-to-subtree "org" ())
55 (declare-function org-entry-get "org"
56 (pom property &optional inherit literal-nil))
57 (declare-function org-make-options-regexp "org" (kwds &optional extra))
58 (declare-function org-do-remove-indentation "org" (&optional n))
59 (declare-function org-show-context "org" (&optional key))
60 (declare-function org-at-table-p "org" (&optional table-type))
61 (declare-function org-cycle "org" (&optional arg))
62 (declare-function org-uniquify "org" (list))
63 (declare-function org-current-level "org" ())
64 (declare-function org-table-import "org-table" (file arg))
65 (declare-function org-add-hook "org-compat"
66 (hook function &optional append local))
67 (declare-function org-table-align "org-table" ())
68 (declare-function org-table-end "org-table" (&optional table-type))
69 (declare-function orgtbl-to-generic "org-table" (table params))
70 (declare-function orgtbl-to-orgtbl "org-table" (table params))
71 (declare-function org-babel-lob-get-info "ob-lob" nil)
72 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
73 (declare-function org-babel-ref-parse "ob-ref" (assignment))
74 (declare-function org-babel-ref-resolve "ob-ref" (ref))
75 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
76 (declare-function org-number-sequence "org-compat" (from &optional to inc))
77 (declare-function org-in-item-p "org-list" ())
78 (declare-function org-at-item-p "org-list" ())
79 (declare-function org-list-parse-list "org-list" (&optional delete))
80 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
81 (declare-function org-list-struct "org-list" ())
82 (declare-function org-list-prevs-alist "org-list" (struct))
83 (declare-function org-list-get-list-end "org-list" (item struct prevs))
85 (defgroup org-babel nil
86 "Code block evaluation and management in `org-mode' documents."
87 :tag "Babel"
88 :group 'org)
90 (defcustom org-confirm-babel-evaluate t
91 "Confirm before evaluation.
92 Require confirmation before interactively evaluating code
93 blocks in Org-mode buffers. The default value of this variable
94 is t, meaning confirmation is required for any code block
95 evaluation. This variable can be set to nil to inhibit any
96 future confirmation requests. This variable can also be set to a
97 function which takes two arguments the language of the code block
98 and the body of the code block. Such a function should then
99 return a non-nil value if the user should be prompted for
100 execution or nil if no prompt is required.
102 Warning: Disabling confirmation may result in accidental
103 evaluation of potentially harmful code. It may be advisable
104 remove code block execution from C-c C-c as further protection
105 against accidental code block evaluation. The
106 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
107 remove code block execution from the C-c C-c keybinding."
108 :group 'org-babel
109 :type '(choice boolean function))
110 ;; don't allow this variable to be changed through file settings
111 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
113 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
114 "Remove code block evaluation from the C-c C-c key binding."
115 :group 'org-babel
116 :type 'boolean)
118 (defvar org-babel-src-name-regexp
119 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
120 "Regular expression used to match a source name line.")
122 (defvar org-babel-multi-line-header-regexp
123 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
124 "Regular expression used to match multi-line header arguments.")
126 (defvar org-babel-src-name-w-name-regexp
127 (concat org-babel-src-name-regexp
128 "\\("
129 org-babel-multi-line-header-regexp
130 "\\)*"
131 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
132 "Regular expression matching source name lines with a name.")
134 (defvar org-babel-src-block-regexp
135 (concat
136 ;; (1) indentation (2) lang
137 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
138 ;; (3) switches
139 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
140 ;; (4) header arguments
141 "\\([^\n]*\\)\n"
142 ;; (5) body
143 "\\([^\000]*?\n*\\)[ \t]*#\\+end_src")
144 "Regexp used to identify code blocks.")
146 (defvar org-babel-inline-src-block-regexp
147 (concat
148 ;; (1) replacement target (2) lang
149 "[^-[:alnum:]]\\(src_\\([^ \f\t\n\r\v]+\\)"
150 ;; (3,4) (unused, headers)
151 "\\(\\|\\[\\(.*?\\)\\]\\)"
152 ;; (5) body
153 "{\\([^\f\n\r\v]+?\\)}\\)")
154 "Regexp used to identify inline src-blocks.")
156 (defun org-babel-get-header (params key &optional others)
157 "Select only header argument of type KEY from a list.
158 Optional argument OTHERS indicates that only the header that do
159 not match KEY should be returned."
160 (delq nil
161 (mapcar
162 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
163 params)))
165 (defun org-babel-get-src-block-info (&optional light)
166 "Get information on the current source block.
168 Optional argument LIGHT does not resolve remote variable
169 references; a process which could likely result in the execution
170 of other code blocks.
172 Returns a list
173 (language body header-arguments-alist switches name indent)."
174 (let ((case-fold-search t) head info name indent)
175 ;; full code block
176 (if (setq head (org-babel-where-is-src-block-head))
177 (save-excursion
178 (goto-char head)
179 (setq info (org-babel-parse-src-block-match))
180 (setq indent (car (last info)))
181 (setq info (butlast info))
182 (while (and (forward-line -1)
183 (looking-at org-babel-multi-line-header-regexp))
184 (setf (nth 2 info)
185 (org-babel-merge-params
186 (nth 2 info)
187 (org-babel-parse-header-arguments (match-string 1)))))
188 (when (looking-at org-babel-src-name-w-name-regexp)
189 (setq name (org-babel-clean-text-properties (match-string 4)))
190 (when (match-string 6)
191 (setf (nth 2 info) ;; merge functional-syntax vars and header-args
192 (org-babel-merge-params
193 (mapcar (lambda (ref) (cons :var ref))
194 (org-babel-ref-split-args (match-string 6)))
195 (nth 2 info))))))
196 ;; inline source block
197 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t)
198 (looking-at org-babel-inline-src-block-regexp))
199 (setq info (org-babel-parse-inline-src-block-match))))
200 ;; resolve variable references and add summary parameters
201 (when (and info (not light))
202 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
203 (when info (append info (list name indent)))))
205 (defun org-babel-confirm-evaluate (info)
206 "Confirm evaluation of the code block INFO.
207 This behavior can be suppressed by setting the value of
208 `org-confirm-babel-evaluate' to nil, in which case all future
209 interactive code block evaluations will proceed without any
210 confirmation from the user.
212 Note disabling confirmation may result in accidental evaluation
213 of potentially harmful code."
214 (let* ((eval (or (cdr (assoc :eval (nth 2 info)))
215 (when (assoc :noeval (nth 2 info)) "no")))
216 (query (cond ((equal eval "query") t)
217 ((functionp org-confirm-babel-evaluate)
218 (funcall org-confirm-babel-evaluate
219 (nth 0 info) (nth 1 info)))
220 (t org-confirm-babel-evaluate))))
221 (if (or (equal eval "never") (equal eval "no")
222 (and query
223 (not (yes-or-no-p
224 (format "Evaluate this%scode block%son your system? "
225 (if info (format " %s " (nth 0 info)) " ")
226 (if (nth 4 info)
227 (format " (%s) " (nth 4 info)) " "))))))
228 (prog1 nil (message "Evaluation %s"
229 (if (or (equal eval "never") (equal eval "no"))
230 "Disabled" "Aborted")))
231 t)))
233 ;;;###autoload
234 (defun org-babel-execute-safely-maybe ()
235 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
236 (org-babel-execute-maybe)))
238 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
240 ;;;###autoload
241 (defun org-babel-execute-maybe ()
242 (interactive)
243 (or (org-babel-execute-src-block-maybe)
244 (org-babel-lob-execute-maybe)))
246 (defun org-babel-execute-src-block-maybe ()
247 "Conditionally execute a source block.
248 Detect if this is context for a Babel src-block and if so
249 then run `org-babel-execute-src-block'."
250 (interactive)
251 (let ((info (org-babel-get-src-block-info)))
252 (if info
253 (progn (org-babel-eval-wipe-error-buffer)
254 (org-babel-execute-src-block current-prefix-arg info) t) nil)))
256 ;;;###autoload
257 (defun org-babel-expand-src-block-maybe ()
258 "Conditionally expand a source block.
259 Detect if this is context for a org-babel src-block and if so
260 then run `org-babel-expand-src-block'."
261 (interactive)
262 (let ((info (org-babel-get-src-block-info)))
263 (if info
264 (progn (org-babel-expand-src-block current-prefix-arg info) t)
265 nil)))
267 ;;;###autoload
268 (defun org-babel-load-in-session-maybe ()
269 "Conditionally load a source block in a session.
270 Detect if this is context for a org-babel src-block and if so
271 then run `org-babel-load-in-session'."
272 (interactive)
273 (let ((info (org-babel-get-src-block-info)))
274 (if info
275 (progn (org-babel-load-in-session current-prefix-arg info) t)
276 nil)))
278 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
280 ;;;###autoload
281 (defun org-babel-pop-to-session-maybe ()
282 "Conditionally pop to a session.
283 Detect if this is context for a org-babel src-block and if so
284 then run `org-babel-pop-to-session'."
285 (interactive)
286 (let ((info (org-babel-get-src-block-info)))
287 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
289 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
291 (defconst org-babel-header-arg-names
292 '(cache cmdline colnames dir exports file noweb results
293 session tangle var eval noeval comments no-expand)
294 "Common header arguments used by org-babel.
295 Note that individual languages may define their own language
296 specific header arguments as well.")
298 (defvar org-babel-default-header-args
299 '((:session . "none") (:results . "replace") (:exports . "code")
300 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
301 "Default arguments to use when evaluating a source block.")
303 (defvar org-babel-default-inline-header-args
304 '((:session . "none") (:results . "replace") (:exports . "results"))
305 "Default arguments to use when evaluating an inline source block.")
307 (defvar org-babel-current-buffer-properties nil
308 "Local cache for buffer properties.")
309 (make-variable-buffer-local 'org-babel-current-buffer-properties)
311 (defvar org-babel-result-regexp
312 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
313 "Regular expression used to match result lines.
314 If the results are associated with a hash key then the hash will
315 be saved in the second match data.")
317 (defvar org-babel-result-w-name-regexp
318 (concat org-babel-result-regexp
319 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
321 (defvar org-babel-min-lines-for-block-output 10
322 "The minimum number of lines for block output.
323 If number of lines of output is equal to or exceeds this
324 value, the output is placed in a #+begin_example...#+end_example
325 block. Otherwise the output is marked as literal by inserting
326 colons at the starts of the lines. This variable only takes
327 effect if the :results output option is in effect.")
329 (defvar org-babel-noweb-error-langs nil
330 "Languages for which Babel will raise literate programming errors.
331 List of languages for which errors should be raised when the
332 source code block satisfying a noweb reference in this language
333 can not be resolved.")
335 (defvar org-babel-hash-show 4
336 "Number of initial characters to show of a hidden results hash.")
338 (defvar org-babel-after-execute-hook nil
339 "Hook for functions to be called after `org-babel-execute-src-block'")
340 (defun org-babel-named-src-block-regexp-for-name (name)
341 "This generates a regexp used to match a src block named NAME."
342 (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
343 (substring org-babel-src-block-regexp 1)))
345 ;;; functions
346 (defvar call-process-region)
347 ;;;###autoload
349 (defun org-babel-execute-src-block (&optional arg info params)
350 "Execute the current source code block.
351 Insert the results of execution into the buffer. Source code
352 execution and the collection and formatting of results can be
353 controlled through a variety of header arguments.
355 With prefix argument ARG, force re-execution even if a an
356 existing result cached in the buffer would otherwise have been
357 returned.
359 Optionally supply a value for INFO in the form returned by
360 `org-babel-get-src-block-info'.
362 Optionally supply a value for PARAMS which will be merged with
363 the header arguments specified at the front of the source code
364 block."
365 (interactive)
366 (let ((info (or info (org-babel-get-src-block-info))))
367 (when (org-babel-confirm-evaluate info)
368 (let* ((lang (nth 0 info))
369 (params (if params
370 (org-babel-process-params
371 (org-babel-merge-params (nth 2 info) params))
372 (nth 2 info)))
373 (cache? (and (not arg) (cdr (assoc :cache params))
374 (string= "yes" (cdr (assoc :cache params)))))
375 (result-params (cdr (assoc :result-params params)))
376 (new-hash (when cache? (org-babel-sha1-hash info)))
377 (old-hash (when cache? (org-babel-result-hash info)))
378 (body (setf (nth 1 info)
379 (let ((noweb (cdr (assoc :noweb params))))
380 (if (and noweb
381 (or (string= "yes" noweb)
382 (string= "tangle" noweb)))
383 (org-babel-expand-noweb-references info)
384 (nth 1 info)))))
385 (dir (cdr (assoc :dir params)))
386 (default-directory
387 (or (and dir (file-name-as-directory dir)) default-directory))
388 (org-babel-call-process-region-original
389 (if (boundp 'org-babel-call-process-region-original)
390 org-babel-call-process-region-original
391 (symbol-function 'call-process-region)))
392 (indent (car (last info)))
393 result cmd)
394 (unwind-protect
395 (flet ((call-process-region (&rest args)
396 (apply 'org-babel-tramp-handle-call-process-region args)))
397 (flet ((lang-check (f)
398 (let ((f (intern (concat "org-babel-execute:" f))))
399 (when (fboundp f) f))))
400 (setq cmd
401 (or (lang-check lang)
402 (lang-check (symbol-name
403 (cdr (assoc lang org-src-lang-modes))))
404 (error "No org-babel-execute function for %s!" lang))))
405 (if (and (not arg) new-hash (equal new-hash old-hash))
406 (save-excursion ;; return cached result
407 (goto-char (org-babel-where-is-src-block-result nil info))
408 (end-of-line 1) (forward-char 1)
409 (setq result (org-babel-read-result))
410 (message (replace-regexp-in-string
411 "%" "%%" (format "%S" result))) result)
412 (message "executing %s code block%s..."
413 (capitalize lang)
414 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
415 (setq result
416 ((lambda (result)
417 (if (and (eq (cdr (assoc :result-type params)) 'value)
418 (or (member "vector" result-params)
419 (member "table" result-params))
420 (not (listp result)))
421 (list (list result)) result))
422 (funcall cmd body params)))
423 ;; if non-empty result and :file then write to :file
424 (when (cdr (assoc :file params))
425 (when result
426 (with-temp-file (cdr (assoc :file params))
427 (insert
428 (org-babel-format-result
429 result (cdr (assoc :sep (nth 2 info)))))))
430 (setq result (cdr (assoc :file params))))
431 (org-babel-insert-result
432 result result-params info new-hash indent lang)
433 (run-hooks 'org-babel-after-execute-hook)
434 result))
435 (setq call-process-region 'org-babel-call-process-region-original))))))
437 (defun org-babel-expand-body:generic (body params &optional var-lines)
438 "Expand BODY with PARAMS.
439 Expand a block of code with org-babel according to it's header
440 arguments. This generic implementation of body expansion is
441 called for languages which have not defined their own specific
442 org-babel-expand-body:lang function."
443 (mapconcat #'identity (append var-lines (list body)) "\n"))
445 ;;;###autoload
446 (defun org-babel-expand-src-block (&optional arg info params)
447 "Expand the current source code block.
448 Expand according to the source code block's header
449 arguments and pop open the results in a preview buffer."
450 (interactive)
451 (let* ((info (or info (org-babel-get-src-block-info)))
452 (lang (nth 0 info))
453 (params (setf (nth 2 info)
454 (sort (org-babel-merge-params (nth 2 info) params)
455 (lambda (el1 el2) (string< (symbol-name (car el1))
456 (symbol-name (car el2)))))))
457 (body (setf (nth 1 info)
458 (if (and (cdr (assoc :noweb params))
459 (string= "yes" (cdr (assoc :noweb params))))
460 (org-babel-expand-noweb-references info) (nth 1 info))))
461 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
462 (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang)))
463 (expanded
464 (if (fboundp expand-cmd) (funcall expand-cmd body params)
465 (org-babel-expand-body:generic
466 body params (and (fboundp assignments-cmd) (funcall assignments-cmd params))))))
467 (org-edit-src-code
468 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
470 ;;;###autoload
471 (defun org-babel-load-in-session (&optional arg info)
472 "Load the body of the current source-code block.
473 Evaluate the header arguments for the source block before
474 entering the session. After loading the body this pops open the
475 session."
476 (interactive)
477 (let* ((info (or info (org-babel-get-src-block-info)))
478 (lang (nth 0 info))
479 (params (nth 2 info))
480 (body (setf (nth 1 info)
481 (if (and (cdr (assoc :noweb params))
482 (string= "yes" (cdr (assoc :noweb params))))
483 (org-babel-expand-noweb-references info)
484 (nth 1 info))))
485 (session (cdr (assoc :session params)))
486 (dir (cdr (assoc :dir params)))
487 (default-directory
488 (or (and dir (file-name-as-directory dir)) default-directory))
489 (cmd (intern (concat "org-babel-load-session:" lang))))
490 (unless (fboundp cmd)
491 (error "No org-babel-load-session function for %s!" lang))
492 (pop-to-buffer (funcall cmd session body params))
493 (end-of-line 1)))
495 ;;;###autoload
496 (defun org-babel-initiate-session (&optional arg info)
497 "Initiate session for current code block.
498 If called with a prefix argument then resolve any variable
499 references in the header arguments and assign these variables in
500 the session. Copy the body of the code block to the kill ring."
501 (interactive "P")
502 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
503 (lang (nth 0 info))
504 (body (nth 1 info))
505 (params (nth 2 info))
506 (session (cdr (assoc :session params)))
507 (dir (cdr (assoc :dir params)))
508 (default-directory
509 (or (and dir (file-name-as-directory dir)) default-directory))
510 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
511 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
512 (if (and (stringp session) (string= session "none"))
513 (error "This block is not using a session!"))
514 (unless (fboundp init-cmd)
515 (error "No org-babel-initiate-session function for %s!" lang))
516 (with-temp-buffer (insert (org-babel-trim body))
517 (copy-region-as-kill (point-min) (point-max)))
518 (when arg
519 (unless (fboundp prep-cmd)
520 (error "No org-babel-prep-session function for %s!" lang))
521 (funcall prep-cmd session params))
522 (funcall init-cmd session params)))
524 ;;;###autoload
525 (defun org-babel-switch-to-session (&optional arg info)
526 "Switch to the session of the current code block.
527 Uses `org-babel-initiate-session' to start the session. If called
528 with a prefix argument then this is passed on to
529 `org-babel-initiate-session'."
530 (interactive "P")
531 (pop-to-buffer (org-babel-initiate-session arg info))
532 (end-of-line 1))
534 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
536 ;;;###autoload
537 (defun org-babel-switch-to-session-with-code (&optional arg info)
538 "Switch to code buffer and display session."
539 (interactive "P")
540 (flet ((swap-windows
542 (let ((other-window-buffer (window-buffer (next-window))))
543 (set-window-buffer (next-window) (current-buffer))
544 (set-window-buffer (selected-window) other-window-buffer))
545 (other-window 1)))
546 (let ((info (org-babel-get-src-block-info))
547 (org-src-window-setup 'reorganize-frame))
548 (save-excursion
549 (org-babel-switch-to-session arg info))
550 (org-edit-src-code))
551 (swap-windows)))
553 (defmacro org-babel-do-in-edit-buffer (&rest body)
554 "Evaluate BODY in edit buffer if there is a code block at point.
555 Return t if a code block was found at point, nil otherwise."
556 `(let ((org-src-window-setup 'switch-invisibly))
557 (when (and (org-babel-where-is-src-block-head)
558 (org-edit-src-code nil nil nil))
559 (unwind-protect (progn ,@body)
560 (if (org-bound-and-true-p org-edit-src-from-org-mode)
561 (org-edit-src-exit)))
562 t)))
564 (defun org-babel-do-key-sequence-in-edit-buffer (key)
565 "Read key sequence and execute the command in edit buffer.
566 Enter a key sequence to be executed in the language major-mode
567 edit buffer. For example, TAB will alter the contents of the
568 Org-mode code block according to the effect of TAB in the
569 language major-mode buffer. For languages that support
570 interactive sessions, this can be used to send code from the Org
571 buffer to the session for evaluation using the native major-mode
572 evaluation mechanisms."
573 (interactive "kEnter key-sequence to execute in edit buffer: ")
574 (org-babel-do-in-edit-buffer
575 (call-interactively
576 (key-binding (or key (read-key-sequence nil))))))
578 (defvar org-bracket-link-regexp)
579 ;;;###autoload
580 (defun org-babel-open-src-block-result (&optional re-run)
581 "If `point' is on a src block then open the results of the
582 source code block, otherwise return nil. With optional prefix
583 argument RE-RUN the source-code block is evaluated even if
584 results already exist."
585 (interactive "P")
586 (let ((info (org-babel-get-src-block-info)))
587 (when info
588 (save-excursion
589 ;; go to the results, if there aren't any then run the block
590 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
591 (progn (org-babel-execute-src-block)
592 (org-babel-where-is-src-block-result))))
593 (end-of-line 1)
594 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
595 ;; open the results
596 (if (looking-at org-bracket-link-regexp)
597 ;; file results
598 (org-open-at-point)
599 (let ((r (org-babel-format-result
600 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
601 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
602 (delete-region (point-min) (point-max))
603 (insert r)))
604 t))))
606 ;;;###autoload
607 (defmacro org-babel-map-src-blocks (file &rest body)
608 "Evaluate BODY forms on each source-block in FILE.
609 If FILE is nil evaluate BODY forms on source blocks in current
610 buffer. During evaluation of BODY the following local variables
611 are set relative to the currently matched code block.
613 full-block ------- string holding the entirety of the code block
614 beg-block -------- point at the beginning of the code block
615 end-block -------- point at the end of the matched code block
616 lang ------------- string holding the language of the code block
617 beg-lang --------- point at the beginning of the lang
618 end-lang --------- point at the end of the lang
619 switches --------- string holding the switches
620 beg-switches ----- point at the beginning of the switches
621 end-switches ----- point at the end of the switches
622 header-args ------ string holding the header-args
623 beg-header-args -- point at the beginning of the header-args
624 end-header-args -- point at the end of the header-args
625 body ------------- string holding the body of the code block
626 beg-body --------- point at the beginning of the body
627 end-body --------- point at the end of the body"
628 (declare (indent 1))
629 (let ((tempvar (make-symbol "file")))
630 `(let* ((,tempvar ,file)
631 (visited-p (or (null ,tempvar)
632 (get-file-buffer (expand-file-name ,tempvar))))
633 (point (point)) to-be-removed)
634 (save-window-excursion
635 (when ,tempvar (find-file ,tempvar))
636 (setq to-be-removed (current-buffer))
637 (goto-char (point-min))
638 (while (re-search-forward org-babel-src-block-regexp nil t)
639 (goto-char (match-beginning 0))
640 (let ((full-block (match-string 0))
641 (beg-block (match-beginning 0))
642 (end-block (match-end 0))
643 (lang (match-string 2))
644 (beg-lang (match-beginning 2))
645 (end-lang (match-end 2))
646 (switches (match-string 3))
647 (beg-switches (match-beginning 3))
648 (end-switches (match-end 3))
649 (header-args (match-string 4))
650 (beg-header-args (match-beginning 4))
651 (end-header-args (match-end 4))
652 (body (match-string 5))
653 (beg-body (match-beginning 5))
654 (end-body (match-end 5)))
655 ,@body
656 (goto-char end-block))))
657 (unless visited-p (kill-buffer to-be-removed))
658 (goto-char point))))
660 ;;;###autoload
661 (defmacro org-babel-map-inline-src-blocks (file &rest body)
662 "Evaluate BODY forms on each inline source-block in FILE.
663 If FILE is nil evaluate BODY forms on source blocks in current
664 buffer."
665 (declare (indent 1))
666 (let ((tempvar (make-symbol "file")))
667 `(let* ((,tempvar ,file)
668 (visited-p (or (null ,tempvar)
669 (get-file-buffer (expand-file-name ,tempvar))))
670 (point (point)) to-be-removed)
671 (save-window-excursion
672 (when ,tempvar (find-file ,tempvar))
673 (setq to-be-removed (current-buffer))
674 (goto-char (point-min))
675 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
676 (goto-char (match-beginning 1))
677 (save-match-data ,@body)
678 (goto-char (match-end 0))))
679 (unless visited-p (kill-buffer to-be-removed))
680 (goto-char point))))
682 ;;;###autoload
683 (defun org-babel-execute-buffer (&optional arg)
684 "Execute source code blocks in a buffer.
685 Call `org-babel-execute-src-block' on every source block in
686 the current buffer."
687 (interactive "P")
688 (org-babel-eval-wipe-error-buffer)
689 (org-save-outline-visibility t
690 (org-babel-map-src-blocks nil
691 (org-babel-execute-src-block arg))
692 (org-babel-map-inline-src-blocks nil
693 (org-babel-execute-src-block arg))))
695 ;;;###autoload
696 (defun org-babel-execute-subtree (&optional arg)
697 "Execute source code blocks in a subtree.
698 Call `org-babel-execute-src-block' on every source block in
699 the current subtree."
700 (interactive "P")
701 (save-restriction
702 (save-excursion
703 (org-narrow-to-subtree)
704 (org-babel-execute-buffer arg)
705 (widen))))
707 ;;;###autoload
708 (defun org-babel-sha1-hash (&optional info)
709 "Generate an sha1 hash based on the value of info."
710 (interactive)
711 (let ((print-level nil)
712 (info (or info (org-babel-get-src-block-info))))
713 (setf (nth 2 info)
714 (sort (copy-sequence (nth 2 info))
715 (lambda (a b) (string< (car a) (car b)))))
716 ((lambda (hash) (when (interactive-p) (message hash)) hash)
717 (sha1 (format "%s-%s"
718 (mapconcat
719 #'identity
720 (delq nil
721 (mapcar
722 (lambda (arg)
723 (let ((v (cdr arg)))
724 (when (and v (not (and (sequencep v)
725 (not (consp v))
726 (= (length v) 0))))
727 ((lambda (el) (format "%S" el))
728 (cond
729 ((and (listp v) ; lists are sorted
730 (member (car arg) '(:result-params)))
731 (sort v #'string<))
732 ((and (stringp v) ; strings are sorted
733 (member (car arg) '(:results :exports)))
734 (mapconcat #'identity (sort (split-string v)
735 #'string<) " "))
736 (t v)))))) ; atomic are left untouched
737 (nth 2 info))) ":")
738 (nth 1 info))))))
740 (defun org-babel-result-hash (&optional info)
741 "Return the in-buffer hash associated with INFO."
742 (org-babel-where-is-src-block-result nil info)
743 (org-babel-clean-text-properties (match-string 3)))
745 (defun org-babel-hide-hash ()
746 "Hide the hash in the current results line.
747 Only the initial `org-babel-hash-show' characters of the hash
748 will remain visible."
749 (add-to-invisibility-spec '(org-babel-hide-hash . t))
750 (save-excursion
751 (when (and (re-search-forward org-babel-result-regexp nil t)
752 (match-string 3))
753 (let* ((start (match-beginning 3))
754 (hide-start (+ org-babel-hash-show start))
755 (end (match-end 3))
756 (hash (match-string 3))
757 ov1 ov2)
758 (setq ov1 (make-overlay start hide-start))
759 (setq ov2 (make-overlay hide-start end))
760 (overlay-put ov2 'invisible 'org-babel-hide-hash)
761 (overlay-put ov1 'babel-hash hash)))))
763 (defun org-babel-hide-all-hashes ()
764 "Hide the hash in the current buffer.
765 Only the initial `org-babel-hash-show' characters of each hash
766 will remain visible. This function should be called as part of
767 the `org-mode-hook'."
768 (save-excursion
769 (while (re-search-forward org-babel-result-regexp nil t)
770 (goto-char (match-beginning 0))
771 (org-babel-hide-hash)
772 (goto-char (match-end 0)))))
773 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
775 (defun org-babel-hash-at-point (&optional point)
776 "Return the value of the hash at POINT.
777 The hash is also added as the last element of the kill ring.
778 This can be called with C-c C-c."
779 (interactive)
780 (let ((hash (car (delq nil (mapcar
781 (lambda (ol) (overlay-get ol 'babel-hash))
782 (overlays-at (or point (point))))))))
783 (when hash (kill-new hash) (message hash))))
784 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
786 (defun org-babel-result-hide-spec ()
787 "Hide portions of results lines.
788 Add `org-babel-hide-result' as an invisibility spec for hiding
789 portions of results lines."
790 (add-to-invisibility-spec '(org-babel-hide-result . t)))
791 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
793 (defvar org-babel-hide-result-overlays nil
794 "Overlays hiding results.")
796 (defun org-babel-result-hide-all ()
797 "Fold all results in the current buffer."
798 (interactive)
799 (org-babel-show-result-all)
800 (save-excursion
801 (while (re-search-forward org-babel-result-regexp nil t)
802 (save-excursion (goto-char (match-beginning 0))
803 (org-babel-hide-result-toggle-maybe)))))
805 (defun org-babel-show-result-all ()
806 "Unfold all results in the current buffer."
807 (mapc 'delete-overlay org-babel-hide-result-overlays)
808 (setq org-babel-hide-result-overlays nil))
810 ;;;###autoload
811 (defun org-babel-hide-result-toggle-maybe ()
812 "Toggle visibility of result at point."
813 (interactive)
814 (let ((case-fold-search t))
815 (if (save-excursion
816 (beginning-of-line 1)
817 (looking-at org-babel-result-regexp))
818 (progn (org-babel-hide-result-toggle)
819 t) ;; to signal that we took action
820 nil))) ;; to signal that we did not
822 (defun org-babel-hide-result-toggle (&optional force)
823 "Toggle the visibility of the current result."
824 (interactive)
825 (save-excursion
826 (beginning-of-line)
827 (if (re-search-forward org-babel-result-regexp nil t)
828 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
829 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
831 (if (memq t (mapcar (lambda (overlay)
832 (eq (overlay-get overlay 'invisible)
833 'org-babel-hide-result))
834 (overlays-at start)))
835 (if (or (not force) (eq force 'off))
836 (mapc (lambda (ov)
837 (when (member ov org-babel-hide-result-overlays)
838 (setq org-babel-hide-result-overlays
839 (delq ov org-babel-hide-result-overlays)))
840 (when (eq (overlay-get ov 'invisible)
841 'org-babel-hide-result)
842 (delete-overlay ov)))
843 (overlays-at start)))
844 (setq ov (make-overlay start end))
845 (overlay-put ov 'invisible 'org-babel-hide-result)
846 ;; make the block accessible to isearch
847 (overlay-put
848 ov 'isearch-open-invisible
849 (lambda (ov)
850 (when (member ov org-babel-hide-result-overlays)
851 (setq org-babel-hide-result-overlays
852 (delq ov org-babel-hide-result-overlays)))
853 (when (eq (overlay-get ov 'invisible)
854 'org-babel-hide-result)
855 (delete-overlay ov))))
856 (push ov org-babel-hide-result-overlays)))
857 (error "Not looking at a result line"))))
859 ;; org-tab-after-check-for-cycling-hook
860 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
861 ;; Remove overlays when changing major mode
862 (add-hook 'org-mode-hook
863 (lambda () (org-add-hook 'change-major-mode-hook
864 'org-babel-show-result-all 'append 'local)))
866 (defvar org-file-properties)
867 (defun org-babel-params-from-properties (&optional lang)
868 "Retrieve parameters specified as properties.
869 Return an association list of any source block params which
870 may be specified in the properties of the current outline entry."
871 (save-match-data
872 (let (val sym)
873 (delq nil
874 (mapcar
875 (lambda (header-arg)
876 (and (setq val
877 (or (org-entry-get (point) header-arg t)
878 (org-entry-get (point) (concat ":" header-arg) t)))
879 (cons (intern (concat ":" header-arg))
880 (org-babel-read val))))
881 (mapcar
882 'symbol-name
883 (append
884 org-babel-header-arg-names
885 (progn
886 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
887 (and (boundp sym) (eval sym))))))))))
889 (defun org-babel-params-from-buffer ()
890 "Retrieve per-buffer parameters.
891 Return an association list of any source block params which
892 may be specified in the current buffer."
893 (or org-babel-current-buffer-properties
894 (save-match-data
895 (save-excursion
896 (save-restriction
897 (widen)
898 (goto-char (point-min))
899 (while (re-search-forward
900 (org-make-options-regexp (list "BABEL")) nil t)
901 (setq org-babel-current-buffer-properties
902 (org-babel-merge-params
903 org-babel-current-buffer-properties
904 (org-babel-parse-header-arguments
905 (org-match-string-no-properties 2)))))
906 org-babel-current-buffer-properties)))))
908 (defvar org-src-preserve-indentation)
909 (defun org-babel-parse-src-block-match ()
910 "Parse the results from a match of the `org-babel-src-block-regexp'."
911 (let* ((block-indentation (length (match-string 1)))
912 (lang (org-babel-clean-text-properties (match-string 2)))
913 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
914 (switches (match-string 3))
915 (body (org-babel-clean-text-properties (match-string 5)))
916 (preserve-indentation (or org-src-preserve-indentation
917 (string-match "-i\\>" switches))))
918 (list lang
919 ;; get block body less properties, protective commas, and indentation
920 (with-temp-buffer
921 (save-match-data
922 (insert (org-babel-strip-protective-commas body))
923 (unless preserve-indentation (org-do-remove-indentation))
924 (buffer-string)))
925 (org-babel-merge-params
926 org-babel-default-header-args
927 (org-babel-params-from-buffer)
928 (org-babel-params-from-properties lang)
929 (if (boundp lang-headers) (eval lang-headers) nil)
930 (org-babel-parse-header-arguments
931 (org-babel-clean-text-properties (or (match-string 4) ""))))
932 switches
933 block-indentation)))
935 (defun org-babel-parse-inline-src-block-match ()
936 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
937 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
938 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
939 (list lang
940 (org-babel-strip-protective-commas
941 (org-babel-clean-text-properties (match-string 5)))
942 (org-babel-merge-params
943 org-babel-default-inline-header-args
944 (org-babel-params-from-buffer)
945 (org-babel-params-from-properties lang)
946 (if (boundp lang-headers) (eval lang-headers) nil)
947 (org-babel-parse-header-arguments
948 (org-babel-clean-text-properties (or (match-string 4) "")))))))
950 (defun org-babel-parse-header-arguments (arg-string)
951 "Parse a string of header arguments returning an alist."
952 (when (> (length arg-string) 0)
953 (delq nil
954 (mapcar
955 (lambda (arg)
956 (if (string-match
957 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
958 arg)
959 (cons (intern (match-string 1 arg))
960 (org-babel-read (org-babel-chomp (match-string 2 arg))))
961 (cons (intern (org-babel-chomp arg)) nil)))
962 (let ((balance 0) (partial nil) (lst nil) (last 0))
963 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
964 (setq balance (+ balance
965 (cond ((equal 91 ch) 1)
966 ((equal 93 ch) -1)
967 (t 0))))
968 (setq partial (cons ch partial))
969 (when (and (= ch 58) (= balance 0)
970 (or (= last 32) (= last 9)))
971 (setq lst (cons (apply #'string (nreverse (cddr partial)))
972 lst))
973 (setq partial (list ch)))
974 (setq last ch))
975 (string-to-list arg-string))
976 (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
978 (defun org-babel-process-params (params)
979 "Expand variables in PARAMS and add summary parameters."
980 (let* ((vars-and-names (org-babel-disassemble-tables
981 (mapcar (lambda (el)
982 (if (consp (cdr el))
983 (cdr el) (org-babel-ref-parse (cdr el))))
984 (org-babel-get-header params :var))
985 (cdr (assoc :hlines params))
986 (cdr (assoc :colnames params))
987 (cdr (assoc :rownames params))))
988 (raw-result (or (cdr (assoc :results params)) ""))
989 (result-params (append
990 (split-string (if (stringp raw-result)
991 raw-result
992 (eval raw-result)))
993 (cdr (assoc :result-params params)))))
994 (append
995 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
996 (list
997 (cons :colname-names (cadr vars-and-names))
998 (cons :rowname-names (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)
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 (:shebang ;; take the latest -- always overwrite
1749 (setq shebang (or (list (cdr pair)) shebang)))
1750 (:comments
1751 (setq comments (e-merge '(("yes" "no")) comments
1752 (split-string (or (cdr pair) "")))))
1753 (t ;; replace: this covers e.g. :session
1754 (setq params (cons pair (assq-delete-all (car pair) params))))))
1755 plist))
1756 plists))
1757 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1758 (cons (cons :comments (mapconcat 'identity comments " "))
1759 (cons (cons :shebang (mapconcat 'identity shebang " "))
1760 (cons (cons :cache (mapconcat 'identity cache " "))
1761 (cons (cons :noweb (mapconcat 'identity noweb " "))
1762 (cons (cons :tangle (mapconcat 'identity tangle " "))
1763 (cons (cons :exports
1764 (mapconcat 'identity exports " "))
1765 (cons
1766 (cons :results
1767 (mapconcat 'identity results " "))
1768 params)))))))))
1770 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1771 "Expand Noweb references in the body of the current source code block.
1773 For example the following reference would be replaced with the
1774 body of the source-code block named 'example-block'.
1776 <<example-block>>
1778 Note that any text preceding the <<foo>> construct on a line will
1779 be interposed between the lines of the replacement text. So for
1780 example if <<foo>> is placed behind a comment, then the entire
1781 replacement text will also be commented.
1783 This function must be called from inside of the buffer containing
1784 the source-code block which holds BODY.
1786 In addition the following syntax can be used to insert the
1787 results of evaluating the source-code block named 'example-block'.
1789 <<example-block()>>
1791 Any optional arguments can be passed to example-block by placing
1792 the arguments inside the parenthesis following the convention
1793 defined by `org-babel-lob'. For example
1795 <<example-block(a=9)>>
1797 would set the value of argument \"a\" equal to \"9\". Note that
1798 these arguments are not evaluated in the current source-code
1799 block but are passed literally to the \"example-block\"."
1800 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1801 (info (or info (org-babel-get-src-block-info)))
1802 (lang (nth 0 info))
1803 (body (nth 1 info))
1804 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
1805 (new-body "") index source-name evaluate prefix)
1806 (flet ((nb-add (text) (setq new-body (concat new-body text)))
1807 (c-wrap (text)
1808 (with-temp-buffer
1809 (funcall (intern (concat lang "-mode")))
1810 (comment-region (point) (progn (insert text) (point)))
1811 (org-babel-trim (buffer-string)))))
1812 (with-temp-buffer
1813 (insert body) (goto-char (point-min))
1814 (setq index (point))
1815 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1816 (save-match-data (setf source-name (match-string 1)))
1817 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1818 (save-match-data
1819 (setq prefix
1820 (buffer-substring (match-beginning 0)
1821 (save-excursion
1822 (beginning-of-line 1) (point)))))
1823 ;; add interval to new-body (removing noweb reference)
1824 (goto-char (match-beginning 0))
1825 (nb-add (buffer-substring index (point)))
1826 (goto-char (match-end 0))
1827 (setq index (point))
1828 (nb-add
1829 (with-current-buffer parent-buffer
1830 (mapconcat ;; interpose PREFIX between every line
1831 #'identity
1832 (split-string
1833 (if evaluate
1834 (let ((raw (org-babel-ref-resolve source-name)))
1835 (if (stringp raw) raw (format "%S" raw)))
1836 (or (nth 2 (assoc (intern source-name)
1837 org-babel-library-of-babel))
1838 (save-restriction
1839 (widen)
1840 (let ((point (org-babel-find-named-block
1841 source-name)))
1842 (if point
1843 (save-excursion
1844 (goto-char point)
1845 ;; possibly wrap body in comments
1846 (let* ((i (org-babel-get-src-block-info 'light))
1847 (body (org-babel-trim
1848 (org-babel-expand-noweb-references
1849 i))))
1850 (if comment
1851 ((lambda (cs) (concat (c-wrap (car cs)) "\n"
1852 body
1853 "\n" (c-wrap (cadr cs))))
1854 (org-babel-tangle-comment-links i))
1855 body)))
1856 ;; optionally raise an error if named
1857 ;; source-block doesn't exist
1858 (if (member lang org-babel-noweb-error-langs)
1859 (error "%s"
1860 (concat
1861 "<<" source-name ">> "
1862 "could not be resolved (see "
1863 "`org-babel-noweb-error-langs')"))
1864 ""))))))
1865 "[\n\r]") (concat "\n" prefix)))))
1866 (nb-add (buffer-substring index (point-max)))))
1867 new-body))
1869 (defun org-babel-clean-text-properties (text)
1870 "Strip all properties from text return."
1871 (when text
1872 (set-text-properties 0 (length text) nil text) text))
1874 (defun org-babel-strip-protective-commas (body)
1875 "Strip protective commas from bodies of source blocks."
1876 (replace-regexp-in-string "^,#" "#" body))
1878 (defun org-babel-script-escape (str)
1879 "Safely convert tables into elisp lists."
1880 (let (in-single in-double out)
1881 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
1882 (if (and (stringp str)
1883 (> (length str) 2)
1884 (string-equal "[" (substring str 0 1))
1885 (string-equal "]" (substring str -1)))
1886 (org-babel-read
1887 (concat
1889 (progn
1890 (mapc
1891 (lambda (ch)
1892 (setq
1894 (case ch
1895 (91 (if (or in-double in-single) ; [
1896 (cons 91 out)
1897 (cons 40 out)))
1898 (93 (if (or in-double in-single) ; ]
1899 (cons 93 out)
1900 (cons 41 out)))
1901 (44 (if (or in-double in-single) ; ,
1902 (cons 44 out) (cons 32 out)))
1903 (39 (if in-double ; '
1904 (cons 39 out)
1905 (setq in-single (not in-single)) (cons 34 out)))
1906 (34 (if in-single ; "
1907 (append (list 34 32) out)
1908 (setq in-double (not in-double)) (cons 34 out)))
1909 (t (cons ch out)))))
1910 (string-to-list str))
1911 (apply #'string (reverse out)))))
1912 str))))
1914 (defun org-babel-read (cell &optional inhibit-lisp-eval)
1915 "Convert the string value of CELL to a number if appropriate.
1916 Otherwise if cell looks like lisp (meaning it starts with a
1917 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
1918 return it unmodified as a string. Optional argument NO-LISP-EVAL
1919 inhibits lisp evaluation for situations in which is it not
1920 appropriate."
1921 (if (and (stringp cell) (not (equal cell "")))
1922 (or (org-babel-number-p cell)
1923 (if (and (not inhibit-lisp-eval)
1924 (member (substring cell 0 1) '("(" "'" "`" "[")))
1925 (eval (read cell))
1926 (progn (set-text-properties 0 (length cell) nil cell) cell)))
1927 cell))
1929 (defun org-babel-number-p (string)
1930 "If STRING represents a number return it's value."
1931 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1932 (= (length (substring string (match-beginning 0)
1933 (match-end 0)))
1934 (length string)))
1935 (string-to-number string)))
1937 (defun org-babel-import-elisp-from-file (file-name &optional separator)
1938 "Read the results located at FILE-NAME into an elisp table.
1939 If the table is trivial, then return it as a scalar."
1940 (let (result)
1941 (save-window-excursion
1942 (with-temp-buffer
1943 (condition-case nil
1944 (progn
1945 (org-table-import file-name separator)
1946 (delete-file file-name)
1947 (setq result (mapcar (lambda (row)
1948 (mapcar #'org-babel-string-read row))
1949 (org-table-to-lisp))))
1950 (error nil)))
1951 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
1952 (if (consp (car result))
1953 (if (null (cdr (car result)))
1954 (caar result)
1955 result)
1956 (car result))
1957 result))))
1959 (defun org-babel-string-read (cell)
1960 "Strip nested \"s from around strings."
1961 (org-babel-read (or (and (stringp cell)
1962 (string-match "\\\"\\(.+\\)\\\"" cell)
1963 (match-string 1 cell))
1964 cell)))
1966 (defun org-babel-reverse-string (string)
1967 "Return the reverse of STRING."
1968 (apply 'string (reverse (string-to-list string))))
1970 (defun org-babel-chomp (string &optional regexp)
1971 "Strip trailing spaces and carriage returns from STRING.
1972 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1973 overwritten by specifying a regexp as a second argument."
1974 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
1975 (while (and (> (length string) 0)
1976 (string-match regexp (substring string -1)))
1977 (setq string (substring string 0 -1)))
1978 string))
1980 (defun org-babel-trim (string &optional regexp)
1981 "Strip leading and trailing spaces and carriage returns from STRING.
1982 Like `org-babel-chomp' only it runs on both the front and back
1983 of the string."
1984 (org-babel-chomp (org-babel-reverse-string
1985 (org-babel-chomp (org-babel-reverse-string string) regexp))
1986 regexp))
1988 (defvar org-babel-org-babel-call-process-region-original nil)
1989 (defun org-babel-tramp-handle-call-process-region
1990 (start end program &optional delete buffer display &rest args)
1991 "Use tramp to handle call-process-region.
1992 Fixes a bug in `tramp-handle-call-process-region'."
1993 (if (and (featurep 'tramp) (file-remote-p default-directory))
1994 (let ((tmpfile (tramp-compat-make-temp-file "")))
1995 (write-region start end tmpfile)
1996 (when delete (delete-region start end))
1997 (unwind-protect
1998 ;; (apply 'call-process program tmpfile buffer display args)
1999 ;; bug in tramp
2000 (apply 'process-file program tmpfile buffer display args)
2001 (delete-file tmpfile)))
2002 ;; org-babel-call-process-region-original is the original emacs
2003 ;; definition. It is in scope from the let binding in
2004 ;; org-babel-execute-src-block
2005 (apply org-babel-call-process-region-original
2006 start end program delete buffer display args)))
2008 (defun org-babel-local-file-name (file)
2009 "Return the local name component of FILE."
2010 (if (file-remote-p file)
2011 (let (localname)
2012 (with-parsed-tramp-file-name file nil
2013 localname))
2014 file))
2016 (defun org-babel-process-file-name (name &optional no-quote-p)
2017 "Prepare NAME to be used in an external process.
2018 If NAME specifies a remote location, the remote portion of the
2019 name is removed, since in that case the process will be executing
2020 remotely. The file name is then processed by
2021 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2022 the file name is additionally processed by
2023 `shell-quote-argument'"
2024 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2025 (expand-file-name (org-babel-local-file-name name))))
2027 (defvar org-babel-temporary-directory)
2028 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2029 (defvar org-babel-temporary-directory
2030 (or (and (boundp 'org-babel-temporary-directory)
2031 (file-exists-p org-babel-temporary-directory)
2032 org-babel-temporary-directory)
2033 (make-temp-file "babel-" t))
2034 "Directory to hold temporary files created to execute code blocks.
2035 Used by `org-babel-temp-file'. This directory will be removed on
2036 Emacs shutdown."))
2038 (defun org-babel-temp-file (prefix &optional suffix)
2039 "Create a temporary file in the `org-babel-temporary-directory'.
2040 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2041 value of `temporary-file-directory' temporarily set to the value
2042 of `org-babel-temporary-directory'."
2043 (if (file-remote-p default-directory)
2044 (make-temp-file
2045 (concat (file-remote-p default-directory)
2046 (expand-file-name
2047 prefix temporary-file-directory)
2048 nil suffix))
2049 (let ((temporary-file-directory
2050 (or (and (boundp 'org-babel-temporary-directory)
2051 (file-exists-p org-babel-temporary-directory)
2052 org-babel-temporary-directory)
2053 temporary-file-directory)))
2054 (make-temp-file prefix nil suffix))))
2056 (defun org-babel-remove-temporary-directory ()
2057 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2058 (when (and (boundp 'org-babel-temporary-directory)
2059 (file-exists-p org-babel-temporary-directory))
2060 ;; taken from `delete-directory' in files.el
2061 (condition-case nil
2062 (progn
2063 (mapc (lambda (file)
2064 ;; This test is equivalent to
2065 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2066 ;; but more efficient
2067 (if (eq t (car (file-attributes file)))
2068 (delete-directory file)
2069 (delete-file file)))
2070 ;; We do not want to delete "." and "..".
2071 (directory-files org-babel-temporary-directory 'full
2072 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2073 (delete-directory org-babel-temporary-directory))
2074 (error
2075 (message "Failed to remove temporary Org-babel directory %s"
2076 (if (boundp 'org-babel-temporary-directory)
2077 org-babel-temporary-directory
2078 "[directory not defined]"))))))
2080 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2082 (provide 'ob)
2084 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
2086 ;;; ob.el ends here