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