ob: replace call to called-interactively-p with backwards-compatible interactive-p
[org-mode/org-jambu.git] / lisp / ob.el
blob6616f2e79ae9d59417991fc3a56f838d998f53a4
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]*?\\)[ \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
295 padline noweb-ref)
296 "Common header arguments used by org-babel.
297 Note that individual languages may define their own language
298 specific header arguments as well.")
300 (defvar org-babel-default-header-args
301 '((:session . "none") (:results . "replace") (:exports . "code")
302 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no")
303 (:padnewline . "yes"))
304 "Default arguments to use when evaluating a source block.")
306 (defvar org-babel-default-inline-header-args
307 '((:session . "none") (:results . "replace") (:exports . "results"))
308 "Default arguments to use when evaluating an inline source block.")
310 (defvar org-babel-data-names '("TBLNAME" "RESNAME" "RESULTS" "DATA"))
312 (defvar org-babel-result-regexp
313 (concat "^[ \t]*#\\+"
314 (regexp-opt org-babel-data-names t)
315 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
316 "Regular expression used to match result lines.
317 If the results are associated with a hash key then the hash will
318 be saved in the second match data.")
320 (defvar org-babel-result-w-name-regexp
321 (concat org-babel-result-regexp
322 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
324 (defvar org-babel-min-lines-for-block-output 10
325 "The minimum number of lines for block output.
326 If number of lines of output is equal to or exceeds this
327 value, the output is placed in a #+begin_example...#+end_example
328 block. Otherwise the output is marked as literal by inserting
329 colons at the starts of the lines. This variable only takes
330 effect if the :results output option is in effect.")
332 (defvar org-babel-noweb-error-langs nil
333 "Languages for which Babel will raise literate programming errors.
334 List of languages for which errors should be raised when the
335 source code block satisfying a noweb reference in this language
336 can not be resolved.")
338 (defvar org-babel-hash-show 4
339 "Number of initial characters to show of a hidden results hash.")
341 (defvar org-babel-after-execute-hook nil
342 "Hook for functions to be called after `org-babel-execute-src-block'")
343 (defun org-babel-named-src-block-regexp-for-name (name)
344 "This generates a regexp used to match a src block named NAME."
345 (concat org-babel-src-name-regexp (regexp-quote name) "[ \t\n]*"
346 (substring org-babel-src-block-regexp 1)))
348 ;;; functions
349 (defvar call-process-region)
350 ;;;###autoload
352 (defun org-babel-execute-src-block (&optional arg info params)
353 "Execute the current source code block.
354 Insert the results of execution into the buffer. Source code
355 execution and the collection and formatting of results can be
356 controlled through a variety of header arguments.
358 With prefix argument ARG, force re-execution even if a an
359 existing result cached in the buffer would otherwise have been
360 returned.
362 Optionally supply a value for INFO in the form returned by
363 `org-babel-get-src-block-info'.
365 Optionally supply a value for PARAMS which will be merged with
366 the header arguments specified at the front of the source code
367 block."
368 (interactive)
369 (let ((info (or info (org-babel-get-src-block-info))))
370 (when (org-babel-confirm-evaluate info)
371 (let* ((lang (nth 0 info))
372 (params (if params
373 (org-babel-process-params
374 (org-babel-merge-params (nth 2 info) params))
375 (nth 2 info)))
376 (cache? (and (not arg) (cdr (assoc :cache params))
377 (string= "yes" (cdr (assoc :cache params)))))
378 (result-params (cdr (assoc :result-params params)))
379 (new-hash (when cache? (org-babel-sha1-hash info)))
380 (old-hash (when cache? (org-babel-result-hash info)))
381 (body (setf (nth 1 info)
382 (let ((noweb (cdr (assoc :noweb params))))
383 (if (and noweb
384 (or (string= "yes" noweb)
385 (string= "tangle" noweb)))
386 (org-babel-expand-noweb-references info)
387 (nth 1 info)))))
388 (dir (cdr (assoc :dir params)))
389 (default-directory
390 (or (and dir (file-name-as-directory dir)) default-directory))
391 (org-babel-call-process-region-original
392 (if (boundp 'org-babel-call-process-region-original)
393 org-babel-call-process-region-original
394 (symbol-function 'call-process-region)))
395 (indent (car (last info)))
396 result cmd)
397 (unwind-protect
398 (flet ((call-process-region (&rest args)
399 (apply 'org-babel-tramp-handle-call-process-region args)))
400 (flet ((lang-check (f)
401 (let ((f (intern (concat "org-babel-execute:" f))))
402 (when (fboundp f) f))))
403 (setq cmd
404 (or (lang-check lang)
405 (lang-check (symbol-name
406 (cdr (assoc lang org-src-lang-modes))))
407 (error "No org-babel-execute function for %s!" lang))))
408 (if (and (not arg) new-hash (equal new-hash old-hash))
409 (save-excursion ;; return cached result
410 (goto-char (org-babel-where-is-src-block-result nil info))
411 (end-of-line 1) (forward-char 1)
412 (setq result (org-babel-read-result))
413 (message (replace-regexp-in-string
414 "%" "%%" (format "%S" result))) result)
415 (message "executing %s code block%s..."
416 (capitalize lang)
417 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
418 (setq result
419 ((lambda (result)
420 (if (and (eq (cdr (assoc :result-type params)) 'value)
421 (or (member "vector" result-params)
422 (member "table" result-params))
423 (not (listp result)))
424 (list (list result)) result))
425 (funcall cmd body params)))
426 ;; if non-empty result and :file then write to :file
427 (when (cdr (assoc :file params))
428 (when result
429 (with-temp-file (cdr (assoc :file params))
430 (insert
431 (org-babel-format-result
432 result (cdr (assoc :sep (nth 2 info)))))))
433 (setq result (cdr (assoc :file params))))
434 (org-babel-insert-result
435 result result-params info new-hash indent lang)
436 (run-hooks 'org-babel-after-execute-hook)
437 result))
438 (setq call-process-region 'org-babel-call-process-region-original))))))
440 (defun org-babel-expand-body:generic (body params &optional var-lines)
441 "Expand BODY with PARAMS.
442 Expand a block of code with org-babel according to it's header
443 arguments. This generic implementation of body expansion is
444 called for languages which have not defined their own specific
445 org-babel-expand-body:lang function."
446 (mapconcat #'identity (append var-lines (list body)) "\n"))
448 ;;;###autoload
449 (defun org-babel-expand-src-block (&optional arg info params)
450 "Expand the current source code block.
451 Expand according to the source code block's header
452 arguments and pop open the results in a preview buffer."
453 (interactive)
454 (let* ((info (or info (org-babel-get-src-block-info)))
455 (lang (nth 0 info))
456 (params (setf (nth 2 info)
457 (sort (org-babel-merge-params (nth 2 info) params)
458 (lambda (el1 el2) (string< (symbol-name (car el1))
459 (symbol-name (car el2)))))))
460 (body (setf (nth 1 info)
461 (if (and (cdr (assoc :noweb params))
462 (string= "yes" (cdr (assoc :noweb params))))
463 (org-babel-expand-noweb-references info) (nth 1 info))))
464 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
465 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
466 lang)))
467 (expanded
468 (if (fboundp expand-cmd) (funcall expand-cmd body params)
469 (org-babel-expand-body:generic
470 body params (and (fboundp assignments-cmd)
471 (funcall assignments-cmd params))))))
472 (org-edit-src-code
473 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
475 (defun org-babel-edit-distance (s1 s2)
476 "Return the edit (levenshtein) distance between strings S1 S2."
477 (let* ((l1 (length s1))
478 (l2 (length s2))
479 (dist (map 'vector (lambda (_) (make-vector (1+ l2) nil))
480 (number-sequence 1 (1+ l1)))))
481 (flet ((in (i j) (aref (aref dist i) j))
482 (mmin (&rest lst) (apply #'min (remove nil lst))))
483 (setf (aref (aref dist 0) 0) 0)
484 (dolist (i (number-sequence 1 l1))
485 (dolist (j (number-sequence 1 l2))
486 (setf (aref (aref dist i) j)
487 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
488 (mmin (in (1- i) j) (in i (1- j)) (in (1- i) (1- j)))))))
489 (in l1 l2))))
491 ;;;###autoload
492 (defun org-babel-check-src-block ()
493 "Check for misspelled header arguments in the current code block."
494 (interactive)
495 ;; TODO: report malformed code block
496 ;; TODO: report incompatible combinations of header arguments
497 (let ((too-close 2)) ;; <- control closeness to report potential match
498 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
499 (and (org-babel-where-is-src-block-head)
500 (org-babel-parse-header-arguments
501 (org-babel-clean-text-properties
502 (match-string 4))))))
503 (dolist (name (mapcar #'symbol-name org-babel-header-arg-names))
504 (when (and (not (string= header name))
505 (<= (org-babel-edit-distance header name) too-close))
506 (error "supplied header \"%S\" is suspiciously close to \"%S\""
507 header name))))
508 (message "No suspicious header arguments found.")))
510 ;;;###autoload
511 (defun org-babel-load-in-session (&optional arg info)
512 "Load the body of the current source-code block.
513 Evaluate the header arguments for the source block before
514 entering the session. After loading the body this pops open the
515 session."
516 (interactive)
517 (let* ((info (or info (org-babel-get-src-block-info)))
518 (lang (nth 0 info))
519 (params (nth 2 info))
520 (body (setf (nth 1 info)
521 (if (and (cdr (assoc :noweb params))
522 (string= "yes" (cdr (assoc :noweb params))))
523 (org-babel-expand-noweb-references info)
524 (nth 1 info))))
525 (session (cdr (assoc :session params)))
526 (dir (cdr (assoc :dir params)))
527 (default-directory
528 (or (and dir (file-name-as-directory dir)) default-directory))
529 (cmd (intern (concat "org-babel-load-session:" lang))))
530 (unless (fboundp cmd)
531 (error "No org-babel-load-session function for %s!" lang))
532 (pop-to-buffer (funcall cmd session body params))
533 (end-of-line 1)))
535 ;;;###autoload
536 (defun org-babel-initiate-session (&optional arg info)
537 "Initiate session for current code block.
538 If called with a prefix argument then resolve any variable
539 references in the header arguments and assign these variables in
540 the session. Copy the body of the code block to the kill ring."
541 (interactive "P")
542 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
543 (lang (nth 0 info))
544 (body (nth 1 info))
545 (params (nth 2 info))
546 (session (cdr (assoc :session params)))
547 (dir (cdr (assoc :dir params)))
548 (default-directory
549 (or (and dir (file-name-as-directory dir)) default-directory))
550 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
551 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
552 (if (and (stringp session) (string= session "none"))
553 (error "This block is not using a session!"))
554 (unless (fboundp init-cmd)
555 (error "No org-babel-initiate-session function for %s!" lang))
556 (with-temp-buffer (insert (org-babel-trim body))
557 (copy-region-as-kill (point-min) (point-max)))
558 (when arg
559 (unless (fboundp prep-cmd)
560 (error "No org-babel-prep-session function for %s!" lang))
561 (funcall prep-cmd session params))
562 (funcall init-cmd session params)))
564 ;;;###autoload
565 (defun org-babel-switch-to-session (&optional arg info)
566 "Switch to the session of the current code block.
567 Uses `org-babel-initiate-session' to start the session. If called
568 with a prefix argument then this is passed on to
569 `org-babel-initiate-session'."
570 (interactive "P")
571 (pop-to-buffer (org-babel-initiate-session arg info))
572 (end-of-line 1))
574 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
576 ;;;###autoload
577 (defun org-babel-switch-to-session-with-code (&optional arg info)
578 "Switch to code buffer and display session."
579 (interactive "P")
580 (flet ((swap-windows
582 (let ((other-window-buffer (window-buffer (next-window))))
583 (set-window-buffer (next-window) (current-buffer))
584 (set-window-buffer (selected-window) other-window-buffer))
585 (other-window 1)))
586 (let ((info (org-babel-get-src-block-info))
587 (org-src-window-setup 'reorganize-frame))
588 (save-excursion
589 (org-babel-switch-to-session arg info))
590 (org-edit-src-code))
591 (swap-windows)))
593 (defmacro org-babel-do-in-edit-buffer (&rest body)
594 "Evaluate BODY in edit buffer if there is a code block at point.
595 Return t if a code block was found at point, nil otherwise."
596 `(let ((org-src-window-setup 'switch-invisibly))
597 (when (and (org-babel-where-is-src-block-head)
598 (org-edit-src-code nil nil nil))
599 (unwind-protect (progn ,@body)
600 (if (org-bound-and-true-p org-edit-src-from-org-mode)
601 (org-edit-src-exit)))
602 t)))
604 (defun org-babel-do-key-sequence-in-edit-buffer (key)
605 "Read key sequence and execute the command in edit buffer.
606 Enter a key sequence to be executed in the language major-mode
607 edit buffer. For example, TAB will alter the contents of the
608 Org-mode code block according to the effect of TAB in the
609 language major-mode buffer. For languages that support
610 interactive sessions, this can be used to send code from the Org
611 buffer to the session for evaluation using the native major-mode
612 evaluation mechanisms."
613 (interactive "kEnter key-sequence to execute in edit buffer: ")
614 (org-babel-do-in-edit-buffer
615 (call-interactively
616 (key-binding (or key (read-key-sequence nil))))))
618 (defvar org-bracket-link-regexp)
619 ;;;###autoload
620 (defun org-babel-open-src-block-result (&optional re-run)
621 "If `point' is on a src block then open the results of the
622 source code block, otherwise return nil. With optional prefix
623 argument RE-RUN the source-code block is evaluated even if
624 results already exist."
625 (interactive "P")
626 (let ((info (org-babel-get-src-block-info)))
627 (when info
628 (save-excursion
629 ;; go to the results, if there aren't any then run the block
630 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
631 (progn (org-babel-execute-src-block)
632 (org-babel-where-is-src-block-result))))
633 (end-of-line 1)
634 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
635 ;; open the results
636 (if (looking-at org-bracket-link-regexp)
637 ;; file results
638 (org-open-at-point)
639 (let ((r (org-babel-format-result
640 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
641 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
642 (delete-region (point-min) (point-max))
643 (insert r)))
644 t))))
646 ;;;###autoload
647 (defmacro org-babel-map-src-blocks (file &rest body)
648 "Evaluate BODY forms on each source-block in FILE.
649 If FILE is nil evaluate BODY forms on source blocks in current
650 buffer. During evaluation of BODY the following local variables
651 are set relative to the currently matched code block.
653 full-block ------- string holding the entirety of the code block
654 beg-block -------- point at the beginning of the code block
655 end-block -------- point at the end of the matched code block
656 lang ------------- string holding the language of the code block
657 beg-lang --------- point at the beginning of the lang
658 end-lang --------- point at the end of the lang
659 switches --------- string holding the switches
660 beg-switches ----- point at the beginning of the switches
661 end-switches ----- point at the end of the switches
662 header-args ------ string holding the header-args
663 beg-header-args -- point at the beginning of the header-args
664 end-header-args -- point at the end of the header-args
665 body ------------- string holding the body of the code block
666 beg-body --------- point at the beginning of the body
667 end-body --------- point at the end of the body"
668 (declare (indent 1))
669 (let ((tempvar (make-symbol "file")))
670 `(let* ((,tempvar ,file)
671 (visited-p (or (null ,tempvar)
672 (get-file-buffer (expand-file-name ,tempvar))))
673 (point (point)) to-be-removed)
674 (save-window-excursion
675 (when ,tempvar (find-file ,tempvar))
676 (setq to-be-removed (current-buffer))
677 (goto-char (point-min))
678 (while (re-search-forward org-babel-src-block-regexp nil t)
679 (goto-char (match-beginning 0))
680 (let ((full-block (match-string 0))
681 (beg-block (match-beginning 0))
682 (end-block (match-end 0))
683 (lang (match-string 2))
684 (beg-lang (match-beginning 2))
685 (end-lang (match-end 2))
686 (switches (match-string 3))
687 (beg-switches (match-beginning 3))
688 (end-switches (match-end 3))
689 (header-args (match-string 4))
690 (beg-header-args (match-beginning 4))
691 (end-header-args (match-end 4))
692 (body (match-string 5))
693 (beg-body (match-beginning 5))
694 (end-body (match-end 5)))
695 ,@body
696 (goto-char end-block))))
697 (unless visited-p (kill-buffer to-be-removed))
698 (goto-char point))))
700 ;;;###autoload
701 (defmacro org-babel-map-inline-src-blocks (file &rest body)
702 "Evaluate BODY forms on each inline source-block in FILE.
703 If FILE is nil evaluate BODY forms on source blocks in current
704 buffer."
705 (declare (indent 1))
706 (let ((tempvar (make-symbol "file")))
707 `(let* ((,tempvar ,file)
708 (visited-p (or (null ,tempvar)
709 (get-file-buffer (expand-file-name ,tempvar))))
710 (point (point)) to-be-removed)
711 (save-window-excursion
712 (when ,tempvar (find-file ,tempvar))
713 (setq to-be-removed (current-buffer))
714 (goto-char (point-min))
715 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
716 (goto-char (match-beginning 1))
717 (save-match-data ,@body)
718 (goto-char (match-end 0))))
719 (unless visited-p (kill-buffer to-be-removed))
720 (goto-char point))))
722 ;;;###autoload
723 (defun org-babel-execute-buffer (&optional arg)
724 "Execute source code blocks in a buffer.
725 Call `org-babel-execute-src-block' on every source block in
726 the current buffer."
727 (interactive "P")
728 (org-babel-eval-wipe-error-buffer)
729 (org-save-outline-visibility t
730 (org-babel-map-src-blocks nil
731 (org-babel-execute-src-block arg))
732 (org-babel-map-inline-src-blocks nil
733 (org-babel-execute-src-block arg))))
735 ;;;###autoload
736 (defun org-babel-execute-subtree (&optional arg)
737 "Execute source code blocks in a subtree.
738 Call `org-babel-execute-src-block' on every source block in
739 the current subtree."
740 (interactive "P")
741 (save-restriction
742 (save-excursion
743 (org-narrow-to-subtree)
744 (org-babel-execute-buffer arg)
745 (widen))))
747 ;;;###autoload
748 (defun org-babel-sha1-hash (&optional info)
749 "Generate an sha1 hash based on the value of info."
750 (interactive)
751 (let ((print-level nil)
752 (info (or info (org-babel-get-src-block-info))))
753 (setf (nth 2 info)
754 (sort (copy-sequence (nth 2 info))
755 (lambda (a b) (string< (car a) (car b)))))
756 ((lambda (hash) (when (interactive-p) (message hash)) hash)
757 (sha1 (format "%s-%s"
758 (mapconcat
759 #'identity
760 (delq nil
761 (mapcar
762 (lambda (arg)
763 (let ((v (cdr arg)))
764 (when (and v (not (and (sequencep v)
765 (not (consp v))
766 (= (length v) 0))))
767 ((lambda (el) (format "%S" el))
768 (cond
769 ((and (listp v) ; lists are sorted
770 (member (car arg) '(:result-params)))
771 (sort (copy-sequence v) #'string<))
772 ((and (stringp v) ; strings are sorted
773 (member (car arg) '(:results :exports)))
774 (mapconcat #'identity (sort (split-string v)
775 #'string<) " "))
776 (t v)))))) ; atomic are left untouched
777 (nth 2 info))) ":")
778 (nth 1 info))))))
780 (defun org-babel-result-hash (&optional info)
781 "Return the in-buffer hash associated with INFO."
782 (org-babel-where-is-src-block-result nil info)
783 (org-babel-clean-text-properties (match-string 3)))
785 (defun org-babel-hide-hash ()
786 "Hide the hash in the current results line.
787 Only the initial `org-babel-hash-show' characters of the hash
788 will remain visible."
789 (add-to-invisibility-spec '(org-babel-hide-hash . t))
790 (save-excursion
791 (when (and (re-search-forward org-babel-result-regexp nil t)
792 (match-string 3))
793 (let* ((start (match-beginning 3))
794 (hide-start (+ org-babel-hash-show start))
795 (end (match-end 3))
796 (hash (match-string 3))
797 ov1 ov2)
798 (setq ov1 (make-overlay start hide-start))
799 (setq ov2 (make-overlay hide-start end))
800 (overlay-put ov2 'invisible 'org-babel-hide-hash)
801 (overlay-put ov1 'babel-hash hash)))))
803 (defun org-babel-hide-all-hashes ()
804 "Hide the hash in the current buffer.
805 Only the initial `org-babel-hash-show' characters of each hash
806 will remain visible. This function should be called as part of
807 the `org-mode-hook'."
808 (save-excursion
809 (while (re-search-forward org-babel-result-regexp nil t)
810 (goto-char (match-beginning 0))
811 (org-babel-hide-hash)
812 (goto-char (match-end 0)))))
813 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
815 (defun org-babel-hash-at-point (&optional point)
816 "Return the value of the hash at POINT.
817 The hash is also added as the last element of the kill ring.
818 This can be called with C-c C-c."
819 (interactive)
820 (let ((hash (car (delq nil (mapcar
821 (lambda (ol) (overlay-get ol 'babel-hash))
822 (overlays-at (or point (point))))))))
823 (when hash (kill-new hash) (message hash))))
824 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
826 (defun org-babel-result-hide-spec ()
827 "Hide portions of results lines.
828 Add `org-babel-hide-result' as an invisibility spec for hiding
829 portions of results lines."
830 (add-to-invisibility-spec '(org-babel-hide-result . t)))
831 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
833 (defvar org-babel-hide-result-overlays nil
834 "Overlays hiding results.")
836 (defun org-babel-result-hide-all ()
837 "Fold all results in the current buffer."
838 (interactive)
839 (org-babel-show-result-all)
840 (save-excursion
841 (while (re-search-forward org-babel-result-regexp nil t)
842 (save-excursion (goto-char (match-beginning 0))
843 (org-babel-hide-result-toggle-maybe)))))
845 (defun org-babel-show-result-all ()
846 "Unfold all results in the current buffer."
847 (mapc 'delete-overlay org-babel-hide-result-overlays)
848 (setq org-babel-hide-result-overlays nil))
850 ;;;###autoload
851 (defun org-babel-hide-result-toggle-maybe ()
852 "Toggle visibility of result at point."
853 (interactive)
854 (let ((case-fold-search t))
855 (if (save-excursion
856 (beginning-of-line 1)
857 (looking-at org-babel-result-regexp))
858 (progn (org-babel-hide-result-toggle)
859 t) ;; to signal that we took action
860 nil))) ;; to signal that we did not
862 (defun org-babel-hide-result-toggle (&optional force)
863 "Toggle the visibility of the current result."
864 (interactive)
865 (save-excursion
866 (beginning-of-line)
867 (if (re-search-forward org-babel-result-regexp nil t)
868 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
869 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
871 (if (memq t (mapcar (lambda (overlay)
872 (eq (overlay-get overlay 'invisible)
873 'org-babel-hide-result))
874 (overlays-at start)))
875 (if (or (not force) (eq force 'off))
876 (mapc (lambda (ov)
877 (when (member ov org-babel-hide-result-overlays)
878 (setq org-babel-hide-result-overlays
879 (delq ov org-babel-hide-result-overlays)))
880 (when (eq (overlay-get ov 'invisible)
881 'org-babel-hide-result)
882 (delete-overlay ov)))
883 (overlays-at start)))
884 (setq ov (make-overlay start end))
885 (overlay-put ov 'invisible 'org-babel-hide-result)
886 ;; make the block accessible to isearch
887 (overlay-put
888 ov 'isearch-open-invisible
889 (lambda (ov)
890 (when (member ov org-babel-hide-result-overlays)
891 (setq org-babel-hide-result-overlays
892 (delq ov org-babel-hide-result-overlays)))
893 (when (eq (overlay-get ov 'invisible)
894 'org-babel-hide-result)
895 (delete-overlay ov))))
896 (push ov org-babel-hide-result-overlays)))
897 (error "Not looking at a result line"))))
899 ;; org-tab-after-check-for-cycling-hook
900 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
901 ;; Remove overlays when changing major mode
902 (add-hook 'org-mode-hook
903 (lambda () (org-add-hook 'change-major-mode-hook
904 'org-babel-show-result-all 'append 'local)))
906 (defvar org-file-properties)
907 (defun org-babel-params-from-properties (&optional lang)
908 "Retrieve parameters specified as properties.
909 Return an association list of any source block params which
910 may be specified in the properties of the current outline entry."
911 (save-match-data
912 (let (val sym)
913 (delq nil
914 (mapcar
915 (lambda (header-arg)
916 (and (setq val
917 (or (org-entry-get (point) header-arg t)
918 (org-entry-get (point) (concat ":" header-arg) t)))
919 (cons (intern (concat ":" header-arg))
920 (org-babel-read val))))
921 (mapcar
922 'symbol-name
923 (append
924 org-babel-header-arg-names
925 (progn
926 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
927 (and (boundp sym) (eval sym))))))))))
929 (defun org-babel-params-from-buffer ()
930 "Retrieve per-buffer parameters.
931 Return an association list of any source block params which
932 may be specified in the current buffer."
933 (let (local-properties)
934 (save-match-data
935 (save-excursion
936 (save-restriction
937 (widen)
938 (goto-char (point-min))
939 (while (re-search-forward
940 (org-make-options-regexp (list "BABEL" "PROPERTIES")) nil t)
941 (setq local-properties
942 (org-babel-merge-params
943 local-properties
944 (org-babel-parse-header-arguments
945 (org-match-string-no-properties 2)))))
946 local-properties)))))
948 (defvar org-src-preserve-indentation)
949 (defun org-babel-parse-src-block-match ()
950 "Parse the results from a match of the `org-babel-src-block-regexp'."
951 (let* ((block-indentation (length (match-string 1)))
952 (lang (org-babel-clean-text-properties (match-string 2)))
953 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
954 (switches (match-string 3))
955 (body (org-babel-clean-text-properties (match-string 5)))
956 (preserve-indentation (or org-src-preserve-indentation
957 (string-match "-i\\>" switches))))
958 (list lang
959 ;; get block body less properties, protective commas, and indentation
960 (with-temp-buffer
961 (save-match-data
962 (insert (org-babel-strip-protective-commas body))
963 (unless preserve-indentation (org-do-remove-indentation))
964 (buffer-string)))
965 (org-babel-merge-params
966 org-babel-default-header-args
967 (org-babel-params-from-buffer)
968 (org-babel-params-from-properties lang)
969 (if (boundp lang-headers) (eval lang-headers) nil)
970 (org-babel-parse-header-arguments
971 (org-babel-clean-text-properties (or (match-string 4) ""))))
972 switches
973 block-indentation)))
975 (defun org-babel-parse-inline-src-block-match ()
976 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
977 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
978 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
979 (list lang
980 (org-babel-strip-protective-commas
981 (org-babel-clean-text-properties (match-string 5)))
982 (org-babel-merge-params
983 org-babel-default-inline-header-args
984 (org-babel-params-from-buffer)
985 (org-babel-params-from-properties lang)
986 (if (boundp lang-headers) (eval lang-headers) nil)
987 (org-babel-parse-header-arguments
988 (org-babel-clean-text-properties (or (match-string 4) "")))))))
990 (defun org-babel-parse-header-arguments (arg-string)
991 "Parse a string of header arguments returning an alist."
992 (when (> (length arg-string) 0)
993 (delq nil
994 (mapcar
995 (lambda (arg)
996 (if (string-match
997 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
998 arg)
999 (cons (intern (match-string 1 arg))
1000 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1001 (cons (intern (org-babel-chomp arg)) nil)))
1002 (let ((balance 0) (partial nil) (lst nil) (last 0))
1003 (mapc (lambda (ch) ; split on [] balanced instances of [ \t]:
1004 (setq balance (+ balance
1005 (cond ((equal 91 ch) 1)
1006 ((equal 93 ch) -1)
1007 (t 0))))
1008 (setq partial (cons ch partial))
1009 (when (and (= ch 58) (= balance 0)
1010 (or (= last 32) (= last 9)))
1011 (setq lst (cons (apply #'string (nreverse (cddr partial)))
1012 lst))
1013 (setq partial (list ch)))
1014 (setq last ch))
1015 (string-to-list arg-string))
1016 (nreverse (cons (apply #'string (nreverse partial)) lst)))))))
1018 (defun org-babel-process-params (params)
1019 "Expand variables in PARAMS and add summary parameters."
1020 (let* ((vars-and-names (org-babel-disassemble-tables
1021 (mapcar (lambda (el)
1022 (if (consp (cdr el))
1023 (cdr el) (org-babel-ref-parse (cdr el))))
1024 (org-babel-get-header params :var))
1025 (cdr (assoc :hlines params))
1026 (cdr (assoc :colnames params))
1027 (cdr (assoc :rownames params))))
1028 (raw-result (or (cdr (assoc :results params)) ""))
1029 (result-params (append
1030 (split-string (if (stringp raw-result)
1031 raw-result
1032 (eval raw-result)))
1033 (cdr (assoc :result-params params)))))
1034 (append
1035 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1036 (list
1037 (cons :colname-names (or (cdr (assoc :colname-names params))
1038 (cadr vars-and-names)))
1039 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1040 (caddr vars-and-names)))
1041 (cons :result-params result-params)
1042 (cons :result-type (cond ((member "output" result-params) 'output)
1043 ((member "value" result-params) 'value)
1044 (t 'value))))
1045 (org-babel-get-header params :var 'other))))
1047 ;; row and column names
1048 (defun org-babel-del-hlines (table)
1049 "Remove all 'hlines from TABLE."
1050 (remove 'hline table))
1052 (defun org-babel-get-colnames (table)
1053 "Return the column names of TABLE.
1054 Return a cons cell, the `car' of which contains the TABLE less
1055 colnames, and the `cdr' of which contains a list of the column
1056 names."
1057 (if (equal 'hline (nth 1 table))
1058 (cons (cddr table) (car table))
1059 (cons (cdr table) (car table))))
1061 (defun org-babel-get-rownames (table)
1062 "Return the row names of TABLE.
1063 Return a cons cell, the `car' of which contains the TABLE less
1064 colnames, and the `cdr' of which contains a list of the column
1065 names. Note: this function removes any hlines in TABLE."
1066 (flet ((trans (table) (apply #'mapcar* #'list table)))
1067 (let* ((width (apply 'max
1068 (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
1069 (table (trans (mapcar (lambda (row)
1070 (if (not (equal row 'hline))
1072 (setq row '())
1073 (dotimes (n width)
1074 (setq row (cons 'hline row)))
1075 row))
1076 table))))
1077 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
1078 (trans (cdr table)))
1079 (remove 'hline (car table))))))
1081 (defun org-babel-put-colnames (table colnames)
1082 "Add COLNAMES to TABLE if they exist."
1083 (if colnames (apply 'list colnames 'hline table) table))
1085 (defun org-babel-put-rownames (table rownames)
1086 "Add ROWNAMES to TABLE if they exist."
1087 (if rownames
1088 (mapcar (lambda (row)
1089 (if (listp row)
1090 (cons (or (pop rownames) "") row)
1091 row)) table)
1092 table))
1094 (defun org-babel-pick-name (names selector)
1095 "Select one out of an alist of row or column names.
1096 SELECTOR can be either a list of names in which case those names
1097 will be returned directly, or an index into the list NAMES in
1098 which case the indexed names will be return."
1099 (if (listp selector)
1100 selector
1101 (when names
1102 (if (and selector (symbolp selector) (not (equal t selector)))
1103 (cdr (assoc selector names))
1104 (if (integerp selector)
1105 (nth (- selector 1) names)
1106 (cdr (car (last names))))))))
1108 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1109 "Parse tables for further processing.
1110 Process the variables in VARS according to the HLINES,
1111 ROWNAMES and COLNAMES header arguments. Return a list consisting
1112 of the vars, cnames and rnames."
1113 (let (cnames rnames)
1114 (list
1115 (mapcar
1116 (lambda (var)
1117 (when (listp (cdr var))
1118 (when (and (not (equal colnames "no"))
1119 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1120 (not (member 'hline (cddr (cdr var)))))))
1121 (let ((both (org-babel-get-colnames (cdr var))))
1122 (setq cnames (cons (cons (car var) (cdr both))
1123 cnames))
1124 (setq var (cons (car var) (car both)))))
1125 (when (and rownames (not (equal rownames "no")))
1126 (let ((both (org-babel-get-rownames (cdr var))))
1127 (setq rnames (cons (cons (car var) (cdr both))
1128 rnames))
1129 (setq var (cons (car var) (car both)))))
1130 (when (and hlines (not (equal hlines "yes")))
1131 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1132 var)
1133 vars)
1134 cnames rnames)))
1136 (defun org-babel-reassemble-table (table colnames rownames)
1137 "Add column and row names to a table.
1138 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1139 to the table for reinsertion to org-mode."
1140 (if (listp table)
1141 ((lambda (table)
1142 (if (and colnames (listp (car table)) (= (length (car table))
1143 (length colnames)))
1144 (org-babel-put-colnames table colnames) table))
1145 (if (and rownames (= (length table) (length rownames)))
1146 (org-babel-put-rownames table rownames) table))
1147 table))
1149 (defun org-babel-where-is-src-block-head ()
1150 "Find where the current source block begins.
1151 Return the point at the beginning of the current source
1152 block. Specifically at the beginning of the #+BEGIN_SRC line.
1153 If the point is not on a source block then return nil."
1154 (let ((initial (point)) top bottom)
1156 (save-excursion ;; on a source name line or a #+header line
1157 (beginning-of-line 1)
1158 (and (or (looking-at org-babel-src-name-regexp)
1159 (looking-at org-babel-multi-line-header-regexp))
1160 (progn
1161 (while (and (forward-line 1)
1162 (looking-at org-babel-multi-line-header-regexp)))
1163 (looking-at org-babel-src-block-regexp))
1164 (point)))
1165 (save-excursion ;; on a #+begin_src line
1166 (beginning-of-line 1)
1167 (and (looking-at org-babel-src-block-regexp)
1168 (point)))
1169 (save-excursion ;; inside a src block
1170 (and
1171 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1172 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1173 (< top initial) (< initial bottom)
1174 (progn (goto-char top) (beginning-of-line 1)
1175 (looking-at org-babel-src-block-regexp))
1176 (point))))))
1178 ;;;###autoload
1179 (defun org-babel-goto-src-block-head ()
1180 "Go to the beginning of the current code block."
1181 (interactive)
1182 ((lambda (head)
1183 (if head (goto-char head) (error "not currently in a code block")))
1184 (org-babel-where-is-src-block-head)))
1186 ;;;###autoload
1187 (defun org-babel-goto-named-src-block (name)
1188 "Go to a named source-code block."
1189 (interactive
1190 (let ((completion-ignore-case t))
1191 (list (org-icompleting-read "source-block name: "
1192 (org-babel-src-block-names) nil t))))
1193 (let ((point (org-babel-find-named-block name)))
1194 (if point
1195 ;; taken from `org-open-at-point'
1196 (progn (goto-char point) (org-show-context))
1197 (message "source-code block '%s' not found in this buffer" name))))
1199 (defun org-babel-find-named-block (name)
1200 "Find a named source-code block.
1201 Return the location of the source block identified by source
1202 NAME, or nil if no such block exists. Set match data according to
1203 org-babel-named-src-block-regexp."
1204 (save-excursion
1205 (let ((case-fold-search t)
1206 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
1207 (goto-char (point-min))
1208 (when (or (re-search-forward regexp nil t)
1209 (re-search-backward regexp nil t))
1210 (match-beginning 0)))))
1212 (defun org-babel-src-block-names (&optional file)
1213 "Returns the names of source blocks in FILE or the current buffer."
1214 (save-excursion
1215 (when file (find-file file)) (goto-char (point-min))
1216 (let (names)
1217 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1218 (setq names (cons (match-string 4) names)))
1219 names)))
1221 ;;;###autoload
1222 (defun org-babel-goto-named-result (name)
1223 "Go to a named result."
1224 (interactive
1225 (let ((completion-ignore-case t))
1226 (list (org-icompleting-read "source-block name: "
1227 (org-babel-result-names) nil t))))
1228 (let ((point (org-babel-find-named-result name)))
1229 (if point
1230 ;; taken from `org-open-at-point'
1231 (progn (goto-char point) (org-show-context))
1232 (message "result '%s' not found in this buffer" name))))
1234 (defun org-babel-find-named-result (name)
1235 "Find a named result.
1236 Return the location of the result named NAME in the current
1237 buffer or nil if no such result exists."
1238 (save-excursion
1239 (goto-char (point-min))
1240 (when (re-search-forward
1241 (concat org-babel-result-regexp
1242 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
1243 (beginning-of-line 0) (point))))
1245 (defun org-babel-result-names (&optional file)
1246 "Returns the names of results in FILE or the current buffer."
1247 (save-excursion
1248 (when file (find-file file)) (goto-char (point-min))
1249 (let (names)
1250 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1251 (setq names (cons (match-string 4) names)))
1252 names)))
1254 ;;;###autoload
1255 (defun org-babel-next-src-block (&optional arg)
1256 "Jump to the next source block.
1257 With optional prefix argument ARG, jump forward ARG many source blocks."
1258 (interactive "P")
1259 (when (looking-at org-babel-src-block-regexp) (forward-char 1))
1260 (condition-case nil
1261 (re-search-forward org-babel-src-block-regexp nil nil (or arg 1))
1262 (error (error "No further code blocks")))
1263 (goto-char (match-beginning 0)) (org-show-context))
1265 ;;;###autoload
1266 (defun org-babel-previous-src-block (&optional arg)
1267 "Jump to the previous source block.
1268 With optional prefix argument ARG, jump backward ARG many source blocks."
1269 (interactive "P")
1270 (condition-case nil
1271 (re-search-backward org-babel-src-block-regexp nil nil (or arg 1))
1272 (error (error "No previous code blocks")))
1273 (goto-char (match-beginning 0)) (org-show-context))
1275 (defvar org-babel-load-languages)
1277 ;;;###autoload
1278 (defun org-babel-mark-block ()
1279 "Mark current src block"
1280 (interactive)
1281 ((lambda (head)
1282 (when head
1283 (save-excursion
1284 (goto-char head)
1285 (looking-at org-babel-src-block-regexp))
1286 (push-mark (match-end 5) nil t)
1287 (goto-char (match-beginning 5))))
1288 (org-babel-where-is-src-block-head)))
1290 (defun org-babel-demarcate-block (&optional arg)
1291 "Wrap or split the code in the region or on the point.
1292 When called from inside of a code block the current block is
1293 split. When called from outside of a code block a new code block
1294 is created. In both cases if the region is demarcated and if the
1295 region is not active then the point is demarcated."
1296 (interactive "P")
1297 (let ((info (org-babel-get-src-block-info 'light))
1298 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1299 (if info
1300 (mapc
1301 (lambda (place)
1302 (save-excursion
1303 (goto-char place)
1304 (let ((lang (nth 0 info))
1305 (indent (make-string (nth 5 info) ? )))
1306 (when (string-match "^[[:space:]]*$"
1307 (buffer-substring (point-at-bol)
1308 (point-at-eol)))
1309 (delete-region (point-at-bol) (point-at-eol)))
1310 (insert (concat (if (looking-at "^") "" "\n")
1311 indent "#+end_src\n"
1312 (if arg stars indent) "\n"
1313 indent "#+begin_src " lang
1314 (if (looking-at "[\n\r]") "" "\n")))))
1315 (move-end-of-line 2))
1316 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1317 (let ((start (point))
1318 (lang (org-icompleting-read "Lang: "
1319 (mapcar (lambda (el) (symbol-name (car el)))
1320 org-babel-load-languages)))
1321 (body (delete-and-extract-region
1322 (if (region-active-p) (mark) (point)) (point))))
1323 (insert (concat (if (looking-at "^") "" "\n")
1324 (if arg (concat stars "\n") "")
1325 "#+begin_src " lang "\n"
1326 body
1327 (if (or (= (length body) 0)
1328 (string-match "[\r\n]$" body)) "" "\n")
1329 "#+end_src\n"))
1330 (goto-char start) (move-end-of-line 1)))))
1332 (defvar org-babel-lob-one-liner-regexp)
1333 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1334 "Find where the current source block results begin.
1335 Return the point at the beginning of the result of the current
1336 source block. Specifically at the beginning of the results line.
1337 If no result exists for this block then create a results line
1338 following the source block."
1339 (save-excursion
1340 (let* ((on-lob-line (save-excursion
1341 (beginning-of-line 1)
1342 (looking-at org-babel-lob-one-liner-regexp)))
1343 (inlinep (save-excursion
1344 (re-search-backward "[ \f\t\n\r\v]" nil t)
1345 (when (looking-at org-babel-inline-src-block-regexp)
1346 (match-end 0))))
1347 (name (if on-lob-line
1348 (nth 0 (org-babel-lob-get-info))
1349 (nth 4 (or info (org-babel-get-src-block-info)))))
1350 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1351 found beg end)
1352 (when head (goto-char head))
1353 (setq
1354 found ;; was there a result (before we potentially insert one)
1356 inlinep
1357 (and
1358 ;; named results:
1359 ;; - return t if it is found, else return nil
1360 ;; - if it does not need to be rebuilt, then don't set end
1361 ;; - if it does need to be rebuilt then do set end
1362 name (setq beg (org-babel-find-named-result name))
1363 (prog1 beg
1364 (when (and hash (not (string= hash (match-string 3))))
1365 (goto-char beg) (setq end beg) ;; beginning of result
1366 (forward-line 1)
1367 (delete-region end (org-babel-result-end)) nil)))
1368 (and
1369 ;; unnamed results:
1370 ;; - return t if it is found, else return nil
1371 ;; - if it is found, and the hash doesn't match, delete and set end
1372 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1373 (progn (end-of-line 1)
1374 (if (eobp) (insert "\n") (forward-char 1))
1375 (setq end (point))
1376 (or (and (not name)
1377 (progn ;; unnamed results line already exists
1378 (re-search-forward "[^ \f\t\n\r\v]" nil t)
1379 (beginning-of-line 1)
1380 (looking-at
1381 (concat org-babel-result-regexp "\n")))
1382 (prog1 (point)
1383 ;; must remove and rebuild if hash!=old-hash
1384 (if (and hash (not (string= hash (match-string 3))))
1385 (prog1 nil
1386 (forward-line 1)
1387 (delete-region
1388 end (org-babel-result-end)))
1389 (setq end nil)))))))))
1390 (if (and insert end)
1391 (progn
1392 (goto-char end)
1393 (unless beg
1394 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1395 (insert (concat
1396 (if indent
1397 (mapconcat
1398 (lambda (el) " ")
1399 (org-number-sequence 1 indent) "")
1401 "#+results"
1402 (when hash (concat "["hash"]"))
1404 (when name (concat " " name)) "\n"))
1405 (unless beg (insert "\n") (backward-char))
1406 (beginning-of-line 0)
1407 (if hash (org-babel-hide-hash))
1408 (point))
1409 found))))
1411 (defvar org-block-regexp)
1412 (defun org-babel-read-result ()
1413 "Read the result at `point' into emacs-lisp."
1414 (let ((case-fold-search t) result-string)
1415 (cond
1416 ((org-at-table-p) (org-babel-read-table))
1417 ((org-at-item-p) (org-babel-read-list))
1418 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1419 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1420 ((looking-at "^[ \t]*: ")
1421 (setq result-string
1422 (org-babel-trim
1423 (mapconcat (lambda (line)
1424 (if (and (> (length line) 1)
1425 (string-match "^[ \t]*: \\(.+\\)" line))
1426 (match-string 1 line)
1427 line))
1428 (split-string
1429 (buffer-substring
1430 (point) (org-babel-result-end)) "[\r\n]+")
1431 "\n")))
1432 (or (org-babel-number-p result-string) result-string))
1433 ((looking-at org-babel-result-regexp)
1434 (save-excursion (forward-line 1) (org-babel-read-result))))))
1436 (defun org-babel-read-table ()
1437 "Read the table at `point' into emacs-lisp."
1438 (mapcar (lambda (row)
1439 (if (and (symbolp row) (equal row 'hline)) row
1440 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1441 (org-table-to-lisp)))
1443 (defun org-babel-read-list ()
1444 "Read the list at `point' into emacs-lisp."
1445 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1446 (mapcar #'cadr (cdr (org-list-parse-list)))))
1448 (defvar org-link-types-re)
1449 (defun org-babel-read-link ()
1450 "Read the link at `point' into emacs-lisp.
1451 If the path of the link is a file path it is expanded using
1452 `expand-file-name'."
1453 (let* ((case-fold-search t)
1454 (raw (and (looking-at org-bracket-link-regexp)
1455 (org-babel-clean-text-properties (match-string 1))))
1456 (type (and (string-match org-link-types-re raw)
1457 (match-string 1 raw))))
1458 (cond
1459 ((not type) (expand-file-name raw))
1460 ((string= type "file")
1461 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1462 (expand-file-name (match-string 2 raw))))
1463 (t raw))))
1465 (defun org-babel-format-result (result &optional sep)
1466 "Format RESULT for writing to file."
1467 (flet ((echo-res (result)
1468 (if (stringp result) result (format "%S" result))))
1469 (if (listp result)
1470 ;; table result
1471 (orgtbl-to-generic
1472 result
1473 (list
1474 :sep (or sep "\t")
1475 :fmt 'echo-res))
1476 ;; scalar result
1477 (echo-res result))))
1479 (defun org-babel-insert-result
1480 (result &optional result-params info hash indent lang)
1481 "Insert RESULT into the current buffer.
1482 By default RESULT is inserted after the end of the
1483 current source block. With optional argument RESULT-PARAMS
1484 controls insertion of results in the org-mode file.
1485 RESULT-PARAMS can take the following values...
1487 replace - (default option) insert results after the source block
1488 replacing any previously inserted results
1490 silent -- no results are inserted
1492 file ---- the results are interpreted as a file path, and are
1493 inserted into the buffer using the Org-mode file syntax
1495 list ---- the results are interpreted as an Org-mode list.
1497 raw ----- results are added directly to the Org-mode file. This
1498 is a good option if you code block will output org-mode
1499 formatted text.
1501 org ----- similar in effect to raw, only the results are wrapped
1502 in an org code block. Similar to the raw option, on
1503 export the results will be interpreted as org-formatted
1504 text, however by wrapping the results in an org code
1505 block they can be replaced upon re-execution of the
1506 code block.
1508 html ---- results are added inside of a #+BEGIN_HTML block. This
1509 is a good option if you code block will output html
1510 formatted text.
1512 latex --- results are added inside of a #+BEGIN_LATEX block.
1513 This is a good option if you code block will output
1514 latex formatted text.
1516 code ---- the results are extracted in the syntax of the source
1517 code of the language being evaluated and are added
1518 inside of a #+BEGIN_SRC block with the source-code
1519 language set appropriately. Note this relies on the
1520 optional LANG argument."
1521 (if (stringp result)
1522 (progn
1523 (setq result (org-babel-clean-text-properties result))
1524 (when (member "file" result-params)
1525 (setq result (org-babel-result-to-file result))))
1526 (unless (listp result) (setq result (format "%S" result))))
1527 (if (and result-params (member "silent" result-params))
1528 (progn
1529 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1530 result)
1531 (save-excursion
1532 (let* ((inlinep
1533 (save-excursion
1534 (re-search-backward "[ \f\t\n\r\v]" nil t)
1535 (when (or (looking-at org-babel-inline-src-block-regexp)
1536 (looking-at org-babel-inline-lob-one-liner-regexp))
1537 (goto-char (match-end 0))
1538 (insert (if (listp result) "\n" " "))
1539 (point))))
1540 (existing-result (unless inlinep
1541 (org-babel-where-is-src-block-result
1542 t info hash indent)))
1543 (results-switches
1544 (cdr (assoc :results_switches (nth 2 info))))
1545 beg end)
1546 (when (and (stringp result) ; ensure results end in a newline
1547 (not inlinep)
1548 (> (length result) 0)
1549 (not (or (string-equal (substring result -1) "\n")
1550 (string-equal (substring result -1) "\r"))))
1551 (setq result (concat result "\n")))
1552 (if (not existing-result)
1553 (setq beg (or inlinep (point)))
1554 (goto-char existing-result)
1555 (save-excursion
1556 (re-search-forward "#" nil t)
1557 (setq indent (- (current-column) 1)))
1558 (forward-line 1)
1559 (setq beg (point))
1560 (cond
1561 ((member "replace" result-params)
1562 (delete-region (point) (org-babel-result-end)))
1563 ((member "append" result-params)
1564 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
1565 ((member "prepend" result-params)))) ; already there
1566 (setq results-switches
1567 (if results-switches (concat " " results-switches) ""))
1568 ;; insert results based on type
1569 (cond
1570 ;; do nothing for an empty result
1571 ((= (length result) 0))
1572 ;; insert a list if preferred
1573 ((member "list" result-params)
1574 (insert
1575 (org-babel-trim
1576 (org-list-to-generic
1577 (cons 'unordered
1578 (mapcar
1579 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
1580 (if (listp result) result (list result))))
1581 '(:splicep nil :istart "- " :iend "\n")))
1582 "\n"))
1583 ;; assume the result is a table if it's not a string
1584 ((not (stringp result))
1585 (goto-char beg)
1586 (insert (concat (orgtbl-to-orgtbl
1587 (if (or (eq 'hline (car result))
1588 (and (listp (car result))
1589 (listp (cdr (car result)))))
1590 result (list result))
1591 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1592 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1593 ((member "file" result-params)
1594 (insert result))
1595 (t (goto-char beg) (insert result)))
1596 (when (listp result) (goto-char (org-table-end)))
1597 (setq end (point-marker))
1598 ;; possibly wrap result
1599 (flet ((wrap (start finish)
1600 (goto-char beg) (insert (concat start "\n"))
1601 (goto-char end) (insert (concat finish "\n"))
1602 (setq end (point-marker))))
1603 (cond
1604 ((member "html" result-params)
1605 (wrap "#+BEGIN_HTML" "#+END_HTML"))
1606 ((member "latex" result-params)
1607 (wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
1608 ((member "code" result-params)
1609 (wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
1610 "#+END_SRC"))
1611 ((member "org" result-params)
1612 (wrap "#+BEGIN_ORG" "#+END_ORG"))
1613 ((member "raw" result-params)
1614 (goto-char beg) (if (org-at-table-p) (org-cycle)))
1615 ((member "wrap" result-params)
1616 (when (and (stringp result) (not (member "file" result-params)))
1617 (org-babel-examplize-region beg end results-switches))
1618 (wrap "#+BEGIN_RESULT" "#+END_RESULT"))
1619 ((and (stringp result) (not (member "file" result-params)))
1620 (org-babel-examplize-region beg end results-switches)
1621 (setq end (point)))))
1622 ;; possibly indent the results to match the #+results line
1623 (when (and (not inlinep) (numberp indent) indent (> indent 0)
1624 ;; in this case `table-align' does the work for us
1625 (not (and (listp result)
1626 (member "append" result-params))))
1627 (indent-rigidly beg end indent))))
1628 (if (= (length result) 0)
1629 (if (member "value" result-params)
1630 (message "Code block returned no value.")
1631 (message "Code block produced no output."))
1632 (message "Code block evaluation complete."))))
1634 (defun org-babel-remove-result (&optional info)
1635 "Remove the result of the current source block."
1636 (interactive)
1637 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1638 (when location
1639 (save-excursion
1640 (goto-char location) (setq start (point)) (forward-line 1)
1641 (delete-region start (org-babel-result-end))))))
1643 (defun org-babel-result-end ()
1644 "Return the point at the end of the current set of results"
1645 (save-excursion
1646 (cond
1647 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
1648 ((org-at-item-p) (let* ((struct (org-list-struct))
1649 (prvs (org-list-prevs-alist struct)))
1650 (org-list-get-list-end (point-at-bol) struct prvs)))
1652 (let ((case-fold-search t)
1653 (blocks-re (regexp-opt
1654 (list "latex" "html" "example" "src" "result" "org"))))
1655 (if (looking-at (concat "[ \t]*#\\+begin_" blocks-re))
1656 (progn (re-search-forward (concat "[ \t]*#\\+end_" blocks-re) nil t)
1657 (forward-char 1))
1658 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1659 (forward-line 1))))
1660 (point)))))
1662 (defun org-babel-result-to-file (result)
1663 "Convert RESULT into an `org-mode' link.
1664 If the `default-directory' is different from the containing
1665 file's directory then expand relative links."
1666 (flet ((cond-exp (file)
1667 (if (and default-directory
1668 buffer-file-name
1669 (not (string= (expand-file-name default-directory)
1670 (expand-file-name
1671 (file-name-directory buffer-file-name)))))
1672 (expand-file-name file default-directory)
1673 file)))
1674 (if (stringp result)
1675 (format "[[file:%s]]" (cond-exp result))
1676 (when (and (listp result) (= 2 (length result))
1677 (stringp (car result)) (stringp (cadr result)))
1678 (format "[[file:%s][%s]]" (car result) (cadr result))))))
1680 (defun org-babel-examplize-region (beg end &optional results-switches)
1681 "Comment out region using the inline '==' or ': ' org example quote."
1682 (interactive "*r")
1683 (flet ((chars-between (b e) (string-match "[\\S]" (buffer-substring b e))))
1684 (if (or (chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
1685 (chars-between end (save-excursion (goto-char end) (point-at-eol))))
1686 (save-excursion
1687 (goto-char beg)
1688 (insert (format "=%s=" (prog1 (buffer-substring beg end)
1689 (delete-region beg end)))))
1690 (let ((size (count-lines beg end)))
1691 (save-excursion
1692 (cond ((= size 0)) ; do nothing for an empty result
1693 ((< size org-babel-min-lines-for-block-output)
1694 (goto-char beg)
1695 (dotimes (n size)
1696 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1698 (goto-char beg)
1699 (insert (if results-switches
1700 (format "#+begin_example%s\n" results-switches)
1701 "#+begin_example\n"))
1702 (if (markerp end) (goto-char end) (forward-char (- end beg)))
1703 (insert "#+end_example\n"))))))))
1705 (defun org-babel-update-block-body (new-body)
1706 "Update the body of the current code block to NEW-BODY."
1707 (if (not (org-babel-where-is-src-block-head))
1708 (error "not in source block")
1709 (save-match-data
1710 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
1711 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
1713 (defun org-babel-merge-params (&rest plists)
1714 "Combine all parameter association lists in PLISTS.
1715 Later elements of PLISTS override the values of previous elements.
1716 This takes into account some special considerations for certain
1717 parameters when merging lists."
1718 (let ((results-exclusive-groups
1719 '(("file" "list" "vector" "table" "scalar" "raw" "org"
1720 "html" "latex" "code" "pp" "wrap")
1721 ("replace" "silent" "append" "prepend")
1722 ("output" "value")))
1723 (exports-exclusive-groups
1724 '(("code" "results" "both" "none")))
1725 params results exports tangle noweb cache vars shebang comments padline)
1726 (flet ((e-merge (exclusive-groups &rest result-params)
1727 ;; maintain exclusivity of mutually exclusive parameters
1728 (let (output)
1729 (mapc (lambda (new-params)
1730 (mapc (lambda (new-param)
1731 (mapc (lambda (exclusive-group)
1732 (when (member new-param exclusive-group)
1733 (mapcar (lambda (excluded-param)
1734 (setq output
1735 (delete
1736 excluded-param
1737 output)))
1738 exclusive-group)))
1739 exclusive-groups)
1740 (setq output (org-uniquify
1741 (cons new-param output))))
1742 new-params))
1743 result-params)
1744 output)))
1745 (mapc
1746 (lambda (plist)
1747 (mapc
1748 (lambda (pair)
1749 (case (car pair)
1750 (:var
1751 (let ((name (if (listp (cdr pair))
1752 (cadr pair)
1753 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1754 (cdr pair))
1755 (intern (match-string 1 (cdr pair)))))))
1756 (when name
1757 (setq vars
1758 (cons (cons name pair)
1759 (if (member name (mapcar #'car vars))
1760 (delq nil
1761 (mapcar
1762 (lambda (p) (unless (equal (car p) name) p))
1763 vars))
1764 vars))))))
1765 (:results
1766 (setq results (e-merge results-exclusive-groups
1767 results
1768 (split-string
1769 (let ((r (cdr pair)))
1770 (if (stringp r) r (eval r)))))))
1771 (:file
1772 (when (cdr pair)
1773 (setq results (e-merge results-exclusive-groups
1774 results '("file")))
1775 (unless (or (member "both" exports)
1776 (member "none" exports)
1777 (member "code" exports))
1778 (setq exports (e-merge exports-exclusive-groups
1779 exports '("results"))))
1780 (setq params (cons pair (assq-delete-all (car pair) params)))))
1781 (:exports
1782 (setq exports (e-merge exports-exclusive-groups
1783 exports (split-string (cdr pair)))))
1784 (:tangle ;; take the latest -- always overwrite
1785 (setq tangle (or (list (cdr pair)) tangle)))
1786 (:noweb
1787 (setq noweb (e-merge '(("yes" "no" "tangle")) noweb
1788 (split-string (or (cdr pair) "")))))
1789 (:cache
1790 (setq cache (e-merge '(("yes" "no")) cache
1791 (split-string (or (cdr pair) "")))))
1792 (:padline
1793 (setq padline (e-merge '(("yes" "no")) padline
1794 (split-string (or (cdr pair) "")))))
1795 (:shebang ;; take the latest -- always overwrite
1796 (setq shebang (or (list (cdr pair)) shebang)))
1797 (:comments
1798 (setq comments (e-merge '(("yes" "no")) comments
1799 (split-string (or (cdr pair) "")))))
1800 (t ;; replace: this covers e.g. :session
1801 (setq params (cons pair (assq-delete-all (car pair) params))))))
1802 plist))
1803 plists))
1804 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
1805 (mapc
1806 (lambda (hd)
1807 (let ((key (intern (concat ":" (symbol-name hd))))
1808 (val (eval hd)))
1809 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
1810 '(results exports tangle noweb padline cache shebang comments))
1811 params))
1813 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1814 "Expand Noweb references in the body of the current source code block.
1816 For example the following reference would be replaced with the
1817 body of the source-code block named 'example-block'.
1819 <<example-block>>
1821 Note that any text preceding the <<foo>> construct on a line will
1822 be interposed between the lines of the replacement text. So for
1823 example if <<foo>> is placed behind a comment, then the entire
1824 replacement text will also be commented.
1826 This function must be called from inside of the buffer containing
1827 the source-code block which holds BODY.
1829 In addition the following syntax can be used to insert the
1830 results of evaluating the source-code block named 'example-block'.
1832 <<example-block()>>
1834 Any optional arguments can be passed to example-block by placing
1835 the arguments inside the parenthesis following the convention
1836 defined by `org-babel-lob'. For example
1838 <<example-block(a=9)>>
1840 would set the value of argument \"a\" equal to \"9\". Note that
1841 these arguments are not evaluated in the current source-code
1842 block but are passed literally to the \"example-block\"."
1843 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1844 (info (or info (org-babel-get-src-block-info)))
1845 (lang (nth 0 info))
1846 (body (nth 1 info))
1847 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
1848 (new-body "") index source-name evaluate prefix blocks-in-buffer)
1849 (flet ((nb-add (text) (setq new-body (concat new-body text)))
1850 (c-wrap (text)
1851 (with-temp-buffer
1852 (funcall (intern (concat lang "-mode")))
1853 (comment-region (point) (progn (insert text) (point)))
1854 (org-babel-trim (buffer-string))))
1855 (blocks () ;; return the info lists of all blocks in this buffer
1856 (let (infos)
1857 (save-restriction
1858 (widen)
1859 (org-babel-map-src-blocks nil
1860 (setq infos (cons (org-babel-get-src-block-info 'light)
1861 infos))))
1862 (reverse infos))))
1863 (with-temp-buffer
1864 (insert body) (goto-char (point-min))
1865 (setq index (point))
1866 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1867 (save-match-data (setf source-name (match-string 1)))
1868 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1869 (save-match-data
1870 (setq prefix
1871 (buffer-substring (match-beginning 0)
1872 (save-excursion
1873 (beginning-of-line 1) (point)))))
1874 ;; add interval to new-body (removing noweb reference)
1875 (goto-char (match-beginning 0))
1876 (nb-add (buffer-substring index (point)))
1877 (goto-char (match-end 0))
1878 (setq index (point))
1879 (nb-add
1880 (with-current-buffer parent-buffer
1881 (mapconcat ;; interpose PREFIX between every line
1882 #'identity
1883 (split-string
1884 (if evaluate
1885 (let ((raw (org-babel-ref-resolve source-name)))
1886 (if (stringp raw) raw (format "%S" raw)))
1888 ;; retrieve from the library of babel
1889 (nth 2 (assoc (intern source-name)
1890 org-babel-library-of-babel))
1891 ;; find the expansion of reference in this buffer
1892 (or (mapconcat
1893 (lambda (i)
1894 (when (string= source-name
1895 (or (cdr (assoc :noweb-ref (nth 2 i)))
1896 (nth 4 i)))
1897 (let ((body (org-babel-expand-noweb-references i)))
1898 (if comment
1899 ((lambda (cs) (concat (c-wrap (car cs)) "\n"
1900 body "\n" (c-wrap (cadr cs))))
1901 (org-babel-tangle-comment-links i))
1902 body))))
1903 (or blocks-in-buffer
1904 (setq blocks-in-buffer (blocks)))
1906 ;; possibly raise an error if named block doesn't exist
1907 (if (member lang org-babel-noweb-error-langs)
1908 (error "%s" (concat
1909 "<<" source-name ">> "
1910 "could not be resolved (see "
1911 "`org-babel-noweb-error-langs')"))
1912 ""))))
1913 "[\n\r]") (concat "\n" prefix)))))
1914 (nb-add (buffer-substring index (point-max)))))
1915 new-body))
1917 (defun org-babel-clean-text-properties (text)
1918 "Strip all properties from text return."
1919 (when text
1920 (set-text-properties 0 (length text) nil text) text))
1922 (defun org-babel-strip-protective-commas (body)
1923 "Strip protective commas from bodies of source blocks."
1924 (replace-regexp-in-string "^,#" "#" body))
1926 (defun org-babel-script-escape (str)
1927 "Safely convert tables into elisp lists."
1928 (let (in-single in-double out)
1929 ((lambda (escaped) (condition-case nil (org-babel-read escaped) (error escaped)))
1930 (if (and (stringp str)
1931 (> (length str) 2)
1932 (string-equal "[" (substring str 0 1))
1933 (string-equal "]" (substring str -1)))
1934 (org-babel-read
1935 (concat
1937 (progn
1938 (mapc
1939 (lambda (ch)
1940 (setq
1942 (case ch
1943 (91 (if (or in-double in-single) ; [
1944 (cons 91 out)
1945 (cons 40 out)))
1946 (93 (if (or in-double in-single) ; ]
1947 (cons 93 out)
1948 (cons 41 out)))
1949 (44 (if (or in-double in-single) ; ,
1950 (cons 44 out) (cons 32 out)))
1951 (39 (if in-double ; '
1952 (cons 39 out)
1953 (setq in-single (not in-single)) (cons 34 out)))
1954 (34 (if in-single ; "
1955 (append (list 34 32) out)
1956 (setq in-double (not in-double)) (cons 34 out)))
1957 (t (cons ch out)))))
1958 (string-to-list str))
1959 (apply #'string (reverse out)))))
1960 str))))
1962 (defun org-babel-read (cell &optional inhibit-lisp-eval)
1963 "Convert the string value of CELL to a number if appropriate.
1964 Otherwise if cell looks like lisp (meaning it starts with a
1965 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
1966 return it unmodified as a string. Optional argument NO-LISP-EVAL
1967 inhibits lisp evaluation for situations in which is it not
1968 appropriate."
1969 (if (and (stringp cell) (not (equal cell "")))
1970 (or (org-babel-number-p cell)
1971 (if (and (not inhibit-lisp-eval)
1972 (member (substring cell 0 1) '("(" "'" "`" "[")))
1973 (eval (read cell))
1974 (if (string= (substring cell 0 1) "\"")
1975 (read cell)
1976 (progn (set-text-properties 0 (length cell) nil cell) cell))))
1977 cell))
1979 (defun org-babel-number-p (string)
1980 "If STRING represents a number return it's value."
1981 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1982 (= (length (substring string (match-beginning 0)
1983 (match-end 0)))
1984 (length string)))
1985 (string-to-number string)))
1987 (defun org-babel-import-elisp-from-file (file-name &optional separator)
1988 "Read the results located at FILE-NAME into an elisp table.
1989 If the table is trivial, then return it as a scalar."
1990 (let (result)
1991 (save-window-excursion
1992 (with-temp-buffer
1993 (condition-case nil
1994 (progn
1995 (org-table-import file-name separator)
1996 (delete-file file-name)
1997 (setq result (mapcar (lambda (row)
1998 (mapcar #'org-babel-string-read row))
1999 (org-table-to-lisp))))
2000 (error nil)))
2001 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2002 (if (consp (car result))
2003 (if (null (cdr (car result)))
2004 (caar result)
2005 result)
2006 (car result))
2007 result))))
2009 (defun org-babel-string-read (cell)
2010 "Strip nested \"s from around strings."
2011 (org-babel-read (or (and (stringp cell)
2012 (string-match "\\\"\\(.+\\)\\\"" cell)
2013 (match-string 1 cell))
2014 cell)))
2016 (defun org-babel-reverse-string (string)
2017 "Return the reverse of STRING."
2018 (apply 'string (reverse (string-to-list string))))
2020 (defun org-babel-chomp (string &optional regexp)
2021 "Strip trailing spaces and carriage returns from STRING.
2022 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2023 overwritten by specifying a regexp as a second argument."
2024 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2025 (while (and (> (length string) 0)
2026 (string-match regexp (substring string -1)))
2027 (setq string (substring string 0 -1)))
2028 string))
2030 (defun org-babel-trim (string &optional regexp)
2031 "Strip leading and trailing spaces and carriage returns from STRING.
2032 Like `org-babel-chomp' only it runs on both the front and back
2033 of the string."
2034 (org-babel-chomp (org-babel-reverse-string
2035 (org-babel-chomp (org-babel-reverse-string string) regexp))
2036 regexp))
2038 (defvar org-babel-org-babel-call-process-region-original nil)
2039 (defun org-babel-tramp-handle-call-process-region
2040 (start end program &optional delete buffer display &rest args)
2041 "Use tramp to handle call-process-region.
2042 Fixes a bug in `tramp-handle-call-process-region'."
2043 (if (and (featurep 'tramp) (file-remote-p default-directory))
2044 (let ((tmpfile (tramp-compat-make-temp-file "")))
2045 (write-region start end tmpfile)
2046 (when delete (delete-region start end))
2047 (unwind-protect
2048 ;; (apply 'call-process program tmpfile buffer display args)
2049 ;; bug in tramp
2050 (apply 'process-file program tmpfile buffer display args)
2051 (delete-file tmpfile)))
2052 ;; org-babel-call-process-region-original is the original emacs
2053 ;; definition. It is in scope from the let binding in
2054 ;; org-babel-execute-src-block
2055 (apply org-babel-call-process-region-original
2056 start end program delete buffer display args)))
2058 (defun org-babel-local-file-name (file)
2059 "Return the local name component of FILE."
2060 (if (file-remote-p file)
2061 (let (localname)
2062 (with-parsed-tramp-file-name file nil
2063 localname))
2064 file))
2066 (defun org-babel-process-file-name (name &optional no-quote-p)
2067 "Prepare NAME to be used in an external process.
2068 If NAME specifies a remote location, the remote portion of the
2069 name is removed, since in that case the process will be executing
2070 remotely. The file name is then processed by
2071 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
2072 the file name is additionally processed by
2073 `shell-quote-argument'"
2074 ((lambda (f) (if no-quote-p f (shell-quote-argument f)))
2075 (expand-file-name (org-babel-local-file-name name))))
2077 (defvar org-babel-temporary-directory)
2078 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2079 (defvar org-babel-temporary-directory
2080 (or (and (boundp 'org-babel-temporary-directory)
2081 (file-exists-p org-babel-temporary-directory)
2082 org-babel-temporary-directory)
2083 (make-temp-file "babel-" t))
2084 "Directory to hold temporary files created to execute code blocks.
2085 Used by `org-babel-temp-file'. This directory will be removed on
2086 Emacs shutdown."))
2088 (defun org-babel-temp-file (prefix &optional suffix)
2089 "Create a temporary file in the `org-babel-temporary-directory'.
2090 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2091 value of `temporary-file-directory' temporarily set to the value
2092 of `org-babel-temporary-directory'."
2093 (if (file-remote-p default-directory)
2094 (make-temp-file
2095 (concat (file-remote-p default-directory)
2096 (expand-file-name
2097 prefix temporary-file-directory)
2098 nil suffix))
2099 (let ((temporary-file-directory
2100 (or (and (boundp 'org-babel-temporary-directory)
2101 (file-exists-p org-babel-temporary-directory)
2102 org-babel-temporary-directory)
2103 temporary-file-directory)))
2104 (make-temp-file prefix nil suffix))))
2106 (defun org-babel-remove-temporary-directory ()
2107 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2108 (when (and (boundp 'org-babel-temporary-directory)
2109 (file-exists-p org-babel-temporary-directory))
2110 ;; taken from `delete-directory' in files.el
2111 (condition-case nil
2112 (progn
2113 (mapc (lambda (file)
2114 ;; This test is equivalent to
2115 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2116 ;; but more efficient
2117 (if (eq t (car (file-attributes file)))
2118 (delete-directory file)
2119 (delete-file file)))
2120 ;; We do not want to delete "." and "..".
2121 (directory-files org-babel-temporary-directory 'full
2122 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2123 (delete-directory org-babel-temporary-directory))
2124 (error
2125 (message "Failed to remove temporary Org-babel directory %s"
2126 (if (boundp 'org-babel-temporary-directory)
2127 org-babel-temporary-directory
2128 "[directory not defined]"))))))
2130 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2132 (provide 'ob)
2134 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
2136 ;;; ob.el ends here