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