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