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