1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2012 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
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/>.
31 (defconst org-babel-exeext
32 (if (memq system-type
'(windows-nt cygwin
))
35 (defvar org-babel-call-process-region-original
)
36 (defvar org-src-lang-modes
)
37 (defvar org-babel-library-of-babel
)
38 (declare-function show-all
"outline" ())
39 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
40 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
41 (declare-function org-strip-protective-commas
"org" (beg end
))
42 (declare-function tramp-compat-make-temp-file
"tramp-compat"
43 (filename &optional dir-flag
))
44 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
45 (declare-function tramp-file-name-user
"tramp" (vec))
46 (declare-function tramp-file-name-host
"tramp" (vec))
47 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
48 (declare-function org-icompleting-read
"org" (&rest args
))
49 (declare-function org-edit-src-code
"org-src"
50 (&optional context code edit-buffer-name quietp
))
51 (declare-function org-edit-src-exit
"org-src" (&optional context
))
52 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
53 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
54 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
55 (declare-function org-set-outline-overlay-data
"org" (data))
56 (declare-function org-narrow-to-subtree
"org" ())
57 (declare-function org-entry-get
"org"
58 (pom property
&optional inherit literal-nil
))
59 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
60 (declare-function org-do-remove-indentation
"org" (&optional n
))
61 (declare-function org-show-context
"org" (&optional key
))
62 (declare-function org-at-table-p
"org" (&optional table-type
))
63 (declare-function org-cycle
"org" (&optional arg
))
64 (declare-function org-uniquify
"org" (list))
65 (declare-function org-current-level
"org" ())
66 (declare-function org-strip-protective-commas
"org" (beg end
))
67 (declare-function org-table-import
"org-table" (file arg
))
68 (declare-function org-add-hook
"org-compat"
69 (hook function
&optional append local
))
70 (declare-function org-table-align
"org-table" ())
71 (declare-function org-table-end
"org-table" (&optional table-type
))
72 (declare-function orgtbl-to-generic
"org-table" (table params
))
73 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
74 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
75 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
76 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
77 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
78 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
79 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
80 (declare-function org-babel-ref-headline-body
"ob-ref" ())
81 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
82 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
83 (declare-function org-at-item-p
"org-list" ())
84 (declare-function org-list-parse-list
"org-list" (&optional delete
))
85 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
86 (declare-function org-list-struct
"org-list" ())
87 (declare-function org-list-prevs-alist
"org-list" (struct))
88 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
89 (declare-function org-strip-protective-commas
"org" (beg end
))
90 (declare-function org-remove-if
"org" (predicate seq
))
91 (declare-function org-completing-read
"org" (&rest args
))
93 (defgroup org-babel nil
94 "Code block evaluation and management in `org-mode' documents."
98 (defcustom org-confirm-babel-evaluate t
99 "Confirm before evaluation.
100 Require confirmation before interactively evaluating code
101 blocks in Org-mode buffers. The default value of this variable
102 is t, meaning confirmation is required for any code block
103 evaluation. This variable can be set to nil to inhibit any
104 future confirmation requests. This variable can also be set to a
105 function which takes two arguments the language of the code block
106 and the body of the code block. Such a function should then
107 return a non-nil value if the user should be prompted for
108 execution or nil if no prompt is required.
110 Warning: Disabling confirmation may result in accidental
111 evaluation of potentially harmful code. It may be advisable
112 remove code block execution from C-c C-c as further protection
113 against accidental code block evaluation. The
114 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
115 remove code block execution from the C-c C-c keybinding."
118 :type
'(choice boolean function
))
119 ;; don't allow this variable to be changed through file settings
120 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
122 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
123 "Remove code block evaluation from the C-c C-c key binding."
128 (defcustom org-babel-results-keyword
"RESULTS"
129 "Keyword used to name results generated by code blocks.
130 Should be either RESULTS or NAME however any capitalization may
135 (defcustom org-babel-noweb-wrap-start
"<<"
136 "String used to begin a noweb reference in a code block.
137 See also `org-babel-noweb-wrap-end'."
141 (defcustom org-babel-noweb-wrap-end
">>"
142 "String used to end a noweb reference in a code block.
143 See also `org-babel-noweb-wrap-start'."
147 (defun org-babel-noweb-wrap (&optional regexp
)
148 (concat org-babel-noweb-wrap-start
149 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
150 org-babel-noweb-wrap-end
))
152 (defvar org-babel-src-name-regexp
153 "^[ \t]*#\\+name:[ \t]*"
154 "Regular expression used to match a source name line.")
156 (defvar org-babel-multi-line-header-regexp
157 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
158 "Regular expression used to match multi-line header arguments.")
160 (defvar org-babel-src-name-w-name-regexp
161 (concat org-babel-src-name-regexp
163 org-babel-multi-line-header-regexp
165 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
166 "Regular expression matching source name lines with a name.")
168 (defvar org-babel-src-block-regexp
170 ;; (1) indentation (2) lang
171 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
173 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
174 ;; (4) header arguments
177 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
178 "Regexp used to identify code blocks.")
180 (defvar org-babel-inline-src-block-regexp
182 ;; (1) replacement target (2) lang
183 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
184 ;; (3,4) (unused, headers)
185 "\\(\\|\\[\\(.*?\\)\\]\\)"
187 "{\\([^\f\n\r\v]+?\\)}\\)")
188 "Regexp used to identify inline src-blocks.")
190 (defun org-babel-get-header (params key
&optional others
)
191 "Select only header argument of type KEY from a list.
192 Optional argument OTHERS indicates that only the header that do
193 not match KEY should be returned."
196 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
199 (defun org-babel-get-inline-src-block-matches()
200 "Set match data if within body of an inline source block.
201 Returns non-nil if match-data set"
202 (let ((src-at-0-p (save-excursion
203 (beginning-of-line 1)
204 (string= "src" (thing-at-point 'word
))))
205 (first-line-p (= 1 (line-number-at-pos)))
207 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
208 (first-line-p "[[:punct:] \t]src_")
209 (t "[[:punct:] \f\t\n\r\v]src_")))
210 (lower-limit (if first-line-p
212 (- (point-at-bol) 1))))
214 (when (or (and src-at-0-p
(bobp))
215 (and (re-search-forward "}" (point-at-eol) t
)
216 (re-search-backward search-for lower-limit t
)
218 (when (looking-at org-babel-inline-src-block-regexp
)
221 (defvar org-babel-inline-lob-one-liner-regexp
)
222 (defun org-babel-get-lob-one-liner-matches()
223 "Set match data if on line of an lob one liner.
224 Returns non-nil if match-data set"
226 (unless (= (point) (point-at-bol)) ;; move before inline block
227 (re-search-backward "[ \f\t\n\r\v]" nil t
))
228 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
232 (defun org-babel-get-src-block-info (&optional light
)
233 "Get information on the current source block.
235 Optional argument LIGHT does not resolve remote variable
236 references; a process which could likely result in the execution
237 of other code blocks.
240 (language body header-arguments-alist switches name indent)."
241 (let ((case-fold-search t
) head info name indent
)
243 (if (setq head
(org-babel-where-is-src-block-head))
246 (setq info
(org-babel-parse-src-block-match))
247 (setq indent
(car (last info
)))
248 (setq info
(butlast info
))
249 (while (and (forward-line -
1)
250 (looking-at org-babel-multi-line-header-regexp
))
252 (org-babel-merge-params
254 (org-babel-parse-header-arguments (match-string 1)))))
255 (when (looking-at org-babel-src-name-w-name-regexp
)
256 (setq name
(org-babel-clean-text-properties (match-string 3)))
257 (when (and (match-string 5) (> (length (match-string 5)) 0))
258 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
259 (org-babel-merge-params
261 (lambda (ref) (cons :var ref
))
263 (lambda (var) ;; check that each variable is initialized
264 (if (string-match ".+=.+" var
)
267 "variable \"%s\"%s must be assigned a default value"
268 var
(if name
(format " in block \"%s\"" name
) ""))))
269 (org-babel-ref-split-args (match-string 5))))
271 ;; inline source block
272 (when (org-babel-get-inline-src-block-matches)
273 (setq info
(org-babel-parse-inline-src-block-match))))
274 ;; resolve variable references and add summary parameters
275 (when (and info
(not light
))
276 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
277 (when info
(append info
(list name indent
)))))
279 (defvar org-current-export-file
) ; dynamically bound
280 (defun org-babel-confirm-evaluate (info)
281 "Confirm evaluation of the code block INFO.
282 This behavior can be suppressed by setting the value of
283 `org-confirm-babel-evaluate' to nil, in which case all future
284 interactive code block evaluations will proceed without any
285 confirmation from the user.
287 Note disabling confirmation may result in accidental evaluation
288 of potentially harmful code."
289 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
290 (when (assoc :noeval
(nth 2 info
)) "no")))
291 (query (cond ((equal eval
"query") t
)
292 ((and (boundp 'org-current-export-file
)
293 org-current-export-file
294 (equal eval
"query-export")) t
)
295 ((functionp org-confirm-babel-evaluate
)
296 (funcall org-confirm-babel-evaluate
297 (nth 0 info
) (nth 1 info
)))
298 (t org-confirm-babel-evaluate
))))
299 (if (or (equal eval
"never") (equal eval
"no")
300 (and (boundp 'org-current-export-file
)
301 org-current-export-file
302 (or (equal eval
"no-export")
303 (equal eval
"never-export")))
306 (format "Evaluate this%scode block%son your system? "
307 (if info
(format " %s " (nth 0 info
)) " ")
309 (format " (%s) " (nth 4 info
)) " "))))))
310 (prog1 nil
(message "Evaluation %s"
311 (if (or (equal eval
"never") (equal eval
"no")
312 (equal eval
"no-export")
313 (equal eval
"never-export"))
314 "Disabled" "Aborted")))
318 (defun org-babel-execute-safely-maybe ()
319 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
320 (org-babel-execute-maybe)))
322 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
325 (defun org-babel-execute-maybe ()
327 (or (org-babel-execute-src-block-maybe)
328 (org-babel-lob-execute-maybe)))
330 (defun org-babel-execute-src-block-maybe ()
331 "Conditionally execute a source block.
332 Detect if this is context for a Babel src-block and if so
333 then run `org-babel-execute-src-block'."
335 (let ((info (org-babel-get-src-block-info)))
337 (progn (org-babel-eval-wipe-error-buffer)
338 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
341 (defun org-babel-view-src-block-info ()
342 "Display information on the current source block.
343 This includes header arguments, language and name, and is largely
344 a window into the `org-babel-get-src-block-info' function."
346 (let ((info (org-babel-get-src-block-info 'light
))
347 (full (lambda (it) (> (length it
) 0)))
348 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
350 (with-help-window (help-buffer)
351 (let ((name (nth 4 info
))
353 (switches (nth 3 info
))
354 (header-args (nth 2 info
)))
355 (when name
(funcall printf
"Name: %s\n" name
))
356 (when lang
(funcall printf
"Lang: %s\n" lang
))
357 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
358 (funcall printf
"Header Arguments:\n")
359 (dolist (pair (sort header-args
360 (lambda (a b
) (string< (symbol-name (car a
))
361 (symbol-name (car b
))))))
362 (when (funcall full
(cdr pair
))
363 (funcall printf
"\t%S%s\t%s\n"
365 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
369 (defun org-babel-expand-src-block-maybe ()
370 "Conditionally expand a source block.
371 Detect if this is context for a org-babel src-block and if so
372 then run `org-babel-expand-src-block'."
374 (let ((info (org-babel-get-src-block-info)))
376 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
380 (defun org-babel-load-in-session-maybe ()
381 "Conditionally load a source block in a session.
382 Detect if this is context for a org-babel src-block and if so
383 then run `org-babel-load-in-session'."
385 (let ((info (org-babel-get-src-block-info)))
387 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
390 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
393 (defun org-babel-pop-to-session-maybe ()
394 "Conditionally pop to a session.
395 Detect if this is context for a org-babel src-block and if so
396 then run `org-babel-pop-to-session'."
398 (let ((info (org-babel-get-src-block-info)))
399 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
401 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
403 (defconst org-babel-common-header-args-w-values
404 '((cache .
((no yes
)))
406 (colnames .
((nil no yes
)))
407 (comments .
((no link yes org both noweb
)))
409 (eval .
((never query
)))
410 (exports .
((code results both none
)))
413 (hlines .
((no yes
)))
414 (mkdirp .
((yes no
)))
417 (noweb .
((yes no tangle no-export strip-export
)))
420 (padline .
((yes no
)))
421 (results .
((file list vector table scalar verbatim
)
422 (raw org html latex code pp wrap
)
423 (replace silent append prepend
)
425 (rownames .
((no yes
)))
429 (tangle .
((tangle yes no
:any
)))
433 (defconst org-babel-header-arg-names
434 (mapcar #'car org-babel-common-header-args-w-values
)
435 "Common header arguments used by org-babel.
436 Note that individual languages may define their own language
437 specific header arguments as well.")
439 (defvar org-babel-default-header-args
440 '((:session .
"none") (:results .
"replace") (:exports .
"code")
441 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
442 (:padnewline .
"yes"))
443 "Default arguments to use when evaluating a source block.")
445 (defvar org-babel-default-inline-header-args
446 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
447 "Default arguments to use when evaluating an inline source block.")
449 (defvar org-babel-data-names
'("tblname" "results" "name"))
451 (defvar org-babel-result-regexp
452 (concat "^[ \t]*#\\+"
453 (regexp-opt org-babel-data-names t
)
454 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
455 "Regular expression used to match result lines.
456 If the results are associated with a hash key then the hash will
457 be saved in the second match data.")
459 (defvar org-babel-result-w-name-regexp
460 (concat org-babel-result-regexp
461 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
463 (defvar org-babel-min-lines-for-block-output
10
464 "The minimum number of lines for block output.
465 If number of lines of output is equal to or exceeds this
466 value, the output is placed in a #+begin_example...#+end_example
467 block. Otherwise the output is marked as literal by inserting
468 colons at the starts of the lines. This variable only takes
469 effect if the :results output option is in effect.")
471 (defvar org-babel-noweb-error-langs nil
472 "Languages for which Babel will raise literate programming errors.
473 List of languages for which errors should be raised when the
474 source code block satisfying a noweb reference in this language
475 can not be resolved.")
477 (defvar org-babel-hash-show
4
478 "Number of initial characters to show of a hidden results hash.")
480 (defvar org-babel-after-execute-hook nil
481 "Hook for functions to be called after `org-babel-execute-src-block'")
483 (defun org-babel-named-src-block-regexp-for-name (name)
484 "This generates a regexp used to match a src block named NAME."
485 (concat org-babel-src-name-regexp
(regexp-quote name
)
486 "\\([ \t]\\|$\\|(\\)" ".*[\r\n]"
487 (substring org-babel-src-block-regexp
1)))
489 (defun org-babel-named-data-regexp-for-name (name)
490 "This generates a regexp used to match data named NAME."
491 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
494 (defvar call-process-region
)
497 (defun org-babel-execute-src-block (&optional arg info params
)
498 "Execute the current source code block.
499 Insert the results of execution into the buffer. Source code
500 execution and the collection and formatting of results can be
501 controlled through a variety of header arguments.
503 With prefix argument ARG, force re-execution even if an existing
504 result cached in the buffer would otherwise have been returned.
506 Optionally supply a value for INFO in the form returned by
507 `org-babel-get-src-block-info'.
509 Optionally supply a value for PARAMS which will be merged with
510 the header arguments specified at the front of the source code
513 (let ((info (or info
(org-babel-get-src-block-info))))
514 (when (org-babel-confirm-evaluate
516 (setf (nth 2 i
) (org-babel-merge-params (nth 2 info
) params
))
518 (let* ((lang (nth 0 info
))
520 (org-babel-process-params
521 (org-babel-merge-params (nth 2 info
) params
))
523 (cache?
(and (not arg
) (cdr (assoc :cache params
))
524 (string= "yes" (cdr (assoc :cache params
)))))
525 (result-params (cdr (assoc :result-params params
)))
526 (new-hash (when cache?
(org-babel-sha1-hash info
)))
527 (old-hash (when cache?
(org-babel-current-result-hash)))
528 (body (setf (nth 1 info
)
529 (if (org-babel-noweb-p params
:eval
)
530 (org-babel-expand-noweb-references info
)
532 (dir (cdr (assoc :dir params
)))
534 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
536 (org-babel-call-process-region-original
537 (if (boundp 'org-babel-call-process-region-original
)
538 org-babel-call-process-region-original
539 (symbol-function 'call-process-region
)))
540 (indent (car (last info
)))
543 (let ((call-process-region
545 (apply 'org-babel-tramp-handle-call-process-region args
))))
546 (let ((lang-check (lambda (f)
547 (let ((f (intern (concat "org-babel-execute:" f
))))
548 (when (fboundp f
) f
)))))
550 (or (funcall lang-check lang
)
551 (funcall lang-check
(symbol-name
552 (cdr (assoc lang org-src-lang-modes
))))
553 (error "No org-babel-execute function for %s!" lang
))))
554 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
555 (save-excursion ;; return cached result
556 (goto-char (org-babel-where-is-src-block-result nil info
))
557 (end-of-line 1) (forward-char 1)
558 (setq result
(org-babel-read-result))
559 (message (replace-regexp-in-string
560 "%" "%%" (format "%S" result
))) result
)
561 (message "executing %s code block%s..."
563 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
566 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
567 (or (member "vector" result-params
)
568 (member "table" result-params
))
569 (not (listp result
)))
570 (list (list result
)) result
))
571 (funcall cmd body params
)))
572 ;; if non-empty result and :file then write to :file
573 (when (cdr (assoc :file params
))
575 (with-temp-file (cdr (assoc :file params
))
577 (org-babel-format-result
578 result
(cdr (assoc :sep
(nth 2 info
)))))))
579 (setq result
(cdr (assoc :file params
))))
580 (org-babel-insert-result
581 result result-params info new-hash indent lang
)
582 (run-hooks 'org-babel-after-execute-hook
)
584 (setq call-process-region
'org-babel-call-process-region-original
))))))
586 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
587 "Expand BODY with PARAMS.
588 Expand a block of code with org-babel according to its header
589 arguments. This generic implementation of body expansion is
590 called for languages which have not defined their own specific
591 org-babel-expand-body:lang function."
592 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
595 (defun org-babel-expand-src-block (&optional arg info params
)
596 "Expand the current source code block.
597 Expand according to the source code block's header
598 arguments and pop open the results in a preview buffer."
600 (let* ((info (or info
(org-babel-get-src-block-info)))
602 (params (setf (nth 2 info
)
603 (sort (org-babel-merge-params (nth 2 info
) params
)
604 (lambda (el1 el2
) (string< (symbol-name (car el1
))
605 (symbol-name (car el2
)))))))
606 (body (setf (nth 1 info
)
607 (if (org-babel-noweb-p params
:eval
)
608 (org-babel-expand-noweb-references info
) (nth 1 info
))))
609 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
610 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
613 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
614 (org-babel-expand-body:generic
615 body params
(and (fboundp assignments-cmd
)
616 (funcall assignments-cmd params
))))))
618 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
620 (defun org-babel-edit-distance (s1 s2
)
621 "Return the edit (levenshtein) distance between strings S1 S2."
622 (let* ((l1 (length s1
))
624 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
625 (number-sequence 1 (1+ l1
)))))
626 (in (lambda (i j
) (aref (aref dist i
) j
)))
627 (mmin (lambda (&rest lst
) (apply #'min
(remove nil lst
)))))
628 (setf (aref (aref dist
0) 0) 0)
629 (dolist (i (number-sequence 1 l1
))
630 (dolist (j (number-sequence 1 l2
))
631 (setf (aref (aref dist i
) j
)
632 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
633 (funcall mmin
(funcall in
(1- i
) j
)
634 (funcall in i
(1- j
))
635 (funcall in
(1- i
) (1- j
)))))))
638 (defun org-babel-combine-header-arg-lists (original &rest others
)
639 "Combine a number of lists of header argument names and arguments."
640 (let ((results (copy-sequence original
)))
641 (dolist (new-list others
)
642 (dolist (arg-pair new-list
)
643 (let ((header (car arg-pair
))
644 (args (cdr arg-pair
)))
646 (cons arg-pair
(org-remove-if
647 (lambda (pair) (equal header
(car pair
)))
652 (defun org-babel-check-src-block ()
653 "Check for misspelled header arguments in the current code block."
655 ;; TODO: report malformed code block
656 ;; TODO: report incompatible combinations of header arguments
657 ;; TODO: report uninitialized variables
658 (let ((too-close 2) ;; <- control closeness to report potential match
659 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
660 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
661 (and (org-babel-where-is-src-block-head)
662 (org-babel-parse-header-arguments
663 (org-babel-clean-text-properties
664 (match-string 4))))))
666 (when (and (not (string= header name
))
667 (<= (org-babel-edit-distance header name
) too-close
)
668 (not (member header names
)))
669 (error "supplied header \"%S\" is suspiciously close to \"%S\""
671 (message "No suspicious header arguments found.")))
674 (defun org-babel-insert-header-arg ()
675 "Insert a header argument selecting from lists of common args and values."
677 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
678 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
679 (headers (org-babel-combine-header-arg-lists
680 org-babel-common-header-args-w-values
681 (if (boundp lang-headers
) (eval lang-headers
) nil
)))
682 (arg (org-icompleting-read
685 (lambda (header-spec) (symbol-name (car header-spec
)))
688 (let ((vals (cdr (assoc (intern arg
) headers
))))
694 (read-from-minibuffer "value: "))
698 (let ((arg (org-icompleting-read
700 (cons "default" (mapcar #'symbol-name group
)))))
701 (if (and arg
(not (string= "default" arg
)))
706 ;; Add support for completing-read insertion of header arguments after ":"
707 (defun org-babel-header-arg-expand ()
708 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
709 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
710 (org-babel-enter-header-arg-w-completion (match-string 2))))
712 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
713 "Insert header argument appropriate for LANG with completion."
714 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
715 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
716 (headers-w-values (org-babel-combine-header-arg-lists
717 org-babel-common-header-args-w-values lang-headers
))
718 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
719 (header (org-completing-read "Header Arg: " headers
))
720 (args (cdr (assoc (intern header
) headers-w-values
)))
721 (arg (when (and args
(listp args
))
723 (format "%s: " header
)
724 (mapcar #'symbol-name
(apply #'append args
))))))
725 (insert (concat header
" " (or arg
"")))
728 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
731 (defun org-babel-load-in-session (&optional arg info
)
732 "Load the body of the current source-code block.
733 Evaluate the header arguments for the source block before
734 entering the session. After loading the body this pops open the
737 (let* ((info (or info
(org-babel-get-src-block-info)))
739 (params (nth 2 info
))
740 (body (setf (nth 1 info
)
741 (if (org-babel-noweb-p params
:eval
)
742 (org-babel-expand-noweb-references info
)
744 (session (cdr (assoc :session params
)))
745 (dir (cdr (assoc :dir params
)))
747 (or (and dir
(file-name-as-directory dir
)) default-directory
))
748 (cmd (intern (concat "org-babel-load-session:" lang
))))
749 (unless (fboundp cmd
)
750 (error "No org-babel-load-session function for %s!" lang
))
751 (pop-to-buffer (funcall cmd session body params
))
755 (defun org-babel-initiate-session (&optional arg info
)
756 "Initiate session for current code block.
757 If called with a prefix argument then resolve any variable
758 references in the header arguments and assign these variables in
759 the session. Copy the body of the code block to the kill ring."
761 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
764 (params (nth 2 info
))
765 (session (cdr (assoc :session params
)))
766 (dir (cdr (assoc :dir params
)))
768 (or (and dir
(file-name-as-directory dir
)) default-directory
))
769 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
770 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
771 (if (and (stringp session
) (string= session
"none"))
772 (error "This block is not using a session!"))
773 (unless (fboundp init-cmd
)
774 (error "No org-babel-initiate-session function for %s!" lang
))
775 (with-temp-buffer (insert (org-babel-trim body
))
776 (copy-region-as-kill (point-min) (point-max)))
778 (unless (fboundp prep-cmd
)
779 (error "No org-babel-prep-session function for %s!" lang
))
780 (funcall prep-cmd session params
))
781 (funcall init-cmd session params
)))
784 (defun org-babel-switch-to-session (&optional arg info
)
785 "Switch to the session of the current code block.
786 Uses `org-babel-initiate-session' to start the session. If called
787 with a prefix argument then this is passed on to
788 `org-babel-initiate-session'."
790 (pop-to-buffer (org-babel-initiate-session arg info
))
793 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
796 (defun org-babel-switch-to-session-with-code (&optional arg info
)
797 "Switch to code buffer and display session."
801 (let ((other-window-buffer (window-buffer (next-window))))
802 (set-window-buffer (next-window) (current-buffer))
803 (set-window-buffer (selected-window) other-window-buffer
))
805 (info (org-babel-get-src-block-info))
806 (org-src-window-setup 'reorganize-frame
))
808 (org-babel-switch-to-session arg info
))
810 (funcall swap-windows
)))
812 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
813 "Evaluate BODY in edit buffer if there is a code block at point.
814 Return t if a code block was found at point, nil otherwise."
815 `(let ((org-src-window-setup 'switch-invisibly
))
816 (when (and (org-babel-where-is-src-block-head)
817 (org-edit-src-code nil nil nil
))
818 (unwind-protect (progn ,@body
)
819 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
820 (org-edit-src-exit)))
822 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
824 (defun org-babel-do-key-sequence-in-edit-buffer (key)
825 "Read key sequence and execute the command in edit buffer.
826 Enter a key sequence to be executed in the language major-mode
827 edit buffer. For example, TAB will alter the contents of the
828 Org-mode code block according to the effect of TAB in the
829 language major-mode buffer. For languages that support
830 interactive sessions, this can be used to send code from the Org
831 buffer to the session for evaluation using the native major-mode
832 evaluation mechanisms."
833 (interactive "kEnter key-sequence to execute in edit buffer: ")
834 (org-babel-do-in-edit-buffer
836 (key-binding (or key
(read-key-sequence nil
))))))
838 (defvar org-bracket-link-regexp
)
840 (defun org-babel-open-src-block-result (&optional re-run
)
841 "If `point' is on a src block then open the results of the
842 source code block, otherwise return nil. With optional prefix
843 argument RE-RUN the source-code block is evaluated even if
844 results already exist."
846 (let ((info (org-babel-get-src-block-info)))
849 ;; go to the results, if there aren't any then run the block
850 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
851 (progn (org-babel-execute-src-block)
852 (org-babel-where-is-src-block-result))))
854 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
856 (if (looking-at org-bracket-link-regexp
)
859 (let ((r (org-babel-format-result
860 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
861 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
862 (delete-region (point-min) (point-max))
867 (defmacro org-babel-map-src-blocks
(file &rest body
)
868 "Evaluate BODY forms on each source-block in FILE.
869 If FILE is nil evaluate BODY forms on source blocks in current
870 buffer. During evaluation of BODY the following local variables
871 are set relative to the currently matched code block.
873 full-block ------- string holding the entirety of the code block
874 beg-block -------- point at the beginning of the code block
875 end-block -------- point at the end of the matched code block
876 lang ------------- string holding the language of the code block
877 beg-lang --------- point at the beginning of the lang
878 end-lang --------- point at the end of the lang
879 switches --------- string holding the switches
880 beg-switches ----- point at the beginning of the switches
881 end-switches ----- point at the end of the switches
882 header-args ------ string holding the header-args
883 beg-header-args -- point at the beginning of the header-args
884 end-header-args -- point at the end of the header-args
885 body ------------- string holding the body of the code block
886 beg-body --------- point at the beginning of the body
887 end-body --------- point at the end of the body"
889 (let ((tempvar (make-symbol "file")))
890 `(let* ((,tempvar
,file
)
891 (visited-p (or (null ,tempvar
)
892 (get-file-buffer (expand-file-name ,tempvar
))))
893 (point (point)) to-be-removed
)
894 (save-window-excursion
895 (when ,tempvar
(find-file ,tempvar
))
896 (setq to-be-removed
(current-buffer))
897 (goto-char (point-min))
898 (while (re-search-forward org-babel-src-block-regexp nil t
)
899 (goto-char (match-beginning 0))
900 (let ((full-block (match-string 0))
901 (beg-block (match-beginning 0))
902 (end-block (match-end 0))
903 (lang (match-string 2))
904 (beg-lang (match-beginning 2))
905 (end-lang (match-end 2))
906 (switches (match-string 3))
907 (beg-switches (match-beginning 3))
908 (end-switches (match-end 3))
909 (header-args (match-string 4))
910 (beg-header-args (match-beginning 4))
911 (end-header-args (match-end 4))
912 (body (match-string 5))
913 (beg-body (match-beginning 5))
914 (end-body (match-end 5)))
916 (goto-char end-block
))))
917 (unless visited-p
(kill-buffer to-be-removed
))
919 (def-edebug-spec org-babel-map-src-blocks
(form body
))
922 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
923 "Evaluate BODY forms on each inline source-block in FILE.
924 If FILE is nil evaluate BODY forms on source blocks in current
927 (let ((tempvar (make-symbol "file")))
928 `(let* ((,tempvar
,file
)
929 (visited-p (or (null ,tempvar
)
930 (get-file-buffer (expand-file-name ,tempvar
))))
931 (point (point)) to-be-removed
)
932 (save-window-excursion
933 (when ,tempvar
(find-file ,tempvar
))
934 (setq to-be-removed
(current-buffer))
935 (goto-char (point-min))
936 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
937 (goto-char (match-beginning 1))
938 (save-match-data ,@body
)
939 (goto-char (match-end 0))))
940 (unless visited-p
(kill-buffer to-be-removed
))
942 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
944 (defvar org-babel-lob-one-liner-regexp
)
946 (defmacro org-babel-map-call-lines
(file &rest body
)
947 "Evaluate BODY forms on each call line in FILE.
948 If FILE is nil evaluate BODY forms on source blocks in current
951 (let ((tempvar (make-symbol "file")))
952 `(let* ((,tempvar
,file
)
953 (visited-p (or (null ,tempvar
)
954 (get-file-buffer (expand-file-name ,tempvar
))))
955 (point (point)) to-be-removed
)
956 (save-window-excursion
957 (when ,tempvar
(find-file ,tempvar
))
958 (setq to-be-removed
(current-buffer))
959 (goto-char (point-min))
960 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
961 (goto-char (match-beginning 1))
962 (save-match-data ,@body
)
963 (goto-char (match-end 0))))
964 (unless visited-p
(kill-buffer to-be-removed
))
966 (def-edebug-spec org-babel-map-call-lines
(form body
))
969 (defmacro org-babel-map-executables
(file &rest body
)
971 (let ((tempvar (make-symbol "file"))
972 (rx (make-symbol "rx")))
973 `(let* ((,tempvar
,file
)
974 (,rx
(concat "\\(" org-babel-src-block-regexp
975 "\\|" org-babel-inline-src-block-regexp
976 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
977 (visited-p (or (null ,tempvar
)
978 (get-file-buffer (expand-file-name ,tempvar
))))
979 (point (point)) to-be-removed
)
980 (save-window-excursion
981 (when ,tempvar
(find-file ,tempvar
))
982 (setq to-be-removed
(current-buffer))
983 (goto-char (point-min))
984 (while (re-search-forward ,rx nil t
)
985 (goto-char (match-beginning 1))
986 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
987 (save-match-data ,@body
)
988 (goto-char (match-end 0))))
989 (unless visited-p
(kill-buffer to-be-removed
))
991 (def-edebug-spec org-babel-map-executables
(form body
))
994 (defun org-babel-execute-buffer (&optional arg
)
995 "Execute source code blocks in a buffer.
996 Call `org-babel-execute-src-block' on every source block in
999 (org-babel-eval-wipe-error-buffer)
1000 (org-save-outline-visibility t
1001 (org-babel-map-executables nil
1002 (if (looking-at org-babel-lob-one-liner-regexp
)
1003 (org-babel-lob-execute-maybe)
1004 (org-babel-execute-src-block arg
)))))
1007 (defun org-babel-execute-subtree (&optional arg
)
1008 "Execute source code blocks in a subtree.
1009 Call `org-babel-execute-src-block' on every source block in
1010 the current subtree."
1014 (org-narrow-to-subtree)
1015 (org-babel-execute-buffer arg
)
1019 (defun org-babel-sha1-hash (&optional info
)
1020 "Generate an sha1 hash based on the value of info."
1022 (let ((print-level nil
)
1023 (info (or info
(org-babel-get-src-block-info))))
1025 (sort (copy-sequence (nth 2 info
))
1026 (lambda (a b
) (string< (car a
) (car b
)))))
1027 (let* ((rm (lambda (lst)
1028 (dolist (p '("replace" "silent" "append" "prepend"))
1029 (setq lst
(remove p lst
)))
1032 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1033 (copy-sequence (cdr arg
))
1035 (when (and v
(not (and (sequencep v
)
1039 ((and (listp v
) ; lists are sorted
1040 (member (car arg
) '(:result-params
)))
1041 (sort (funcall rm v
) #'string
<))
1042 ((and (stringp v
) ; strings are sorted
1043 (member (car arg
) '(:results
:exports
)))
1044 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1048 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
1049 (let ((it (format "%s-%s"
1052 (delq nil
(mapcar (lambda (arg)
1053 (let ((normalized (funcall norm arg
)))
1055 (format "%S" normalized
))))
1060 (defun org-babel-current-result-hash ()
1061 "Return the current in-buffer hash."
1062 (org-babel-where-is-src-block-result)
1063 (org-babel-clean-text-properties (match-string 3)))
1065 (defun org-babel-set-current-result-hash (hash)
1066 "Set the current in-buffer hash to HASH."
1067 (org-babel-where-is-src-block-result)
1068 (save-excursion (goto-char (match-beginning 3))
1069 ;; (mapc #'delete-overlay (overlays-at (point)))
1070 (replace-match hash nil nil nil
3)
1071 (org-babel-hide-hash)))
1073 (defun org-babel-hide-hash ()
1074 "Hide the hash in the current results line.
1075 Only the initial `org-babel-hash-show' characters of the hash
1076 will remain visible."
1077 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1079 (when (and (re-search-forward org-babel-result-regexp nil t
)
1081 (let* ((start (match-beginning 3))
1082 (hide-start (+ org-babel-hash-show start
))
1084 (hash (match-string 3))
1086 (setq ov1
(make-overlay start hide-start
))
1087 (setq ov2
(make-overlay hide-start end
))
1088 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1089 (overlay-put ov1
'babel-hash hash
)))))
1091 (defun org-babel-hide-all-hashes ()
1092 "Hide the hash in the current buffer.
1093 Only the initial `org-babel-hash-show' characters of each hash
1094 will remain visible. This function should be called as part of
1095 the `org-mode-hook'."
1097 (while (re-search-forward org-babel-result-regexp nil t
)
1098 (goto-char (match-beginning 0))
1099 (org-babel-hide-hash)
1100 (goto-char (match-end 0)))))
1101 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1103 (defun org-babel-hash-at-point (&optional point
)
1104 "Return the value of the hash at POINT.
1105 The hash is also added as the last element of the kill ring.
1106 This can be called with C-c C-c."
1108 (let ((hash (car (delq nil
(mapcar
1109 (lambda (ol) (overlay-get ol
'babel-hash
))
1110 (overlays-at (or point
(point))))))))
1111 (when hash
(kill-new hash
) (message hash
))))
1112 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1114 (defun org-babel-result-hide-spec ()
1115 "Hide portions of results lines.
1116 Add `org-babel-hide-result' as an invisibility spec for hiding
1117 portions of results lines."
1118 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1119 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1121 (defvar org-babel-hide-result-overlays nil
1122 "Overlays hiding results.")
1124 (defun org-babel-result-hide-all ()
1125 "Fold all results in the current buffer."
1127 (org-babel-show-result-all)
1129 (while (re-search-forward org-babel-result-regexp nil t
)
1130 (save-excursion (goto-char (match-beginning 0))
1131 (org-babel-hide-result-toggle-maybe)))))
1133 (defun org-babel-show-result-all ()
1134 "Unfold all results in the current buffer."
1135 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1136 (setq org-babel-hide-result-overlays nil
))
1139 (defun org-babel-hide-result-toggle-maybe ()
1140 "Toggle visibility of result at point."
1142 (let ((case-fold-search t
))
1144 (beginning-of-line 1)
1145 (looking-at org-babel-result-regexp
))
1146 (progn (org-babel-hide-result-toggle)
1147 t
) ;; to signal that we took action
1148 nil
))) ;; to signal that we did not
1150 (defun org-babel-hide-result-toggle (&optional force
)
1151 "Toggle the visibility of the current result."
1155 (if (re-search-forward org-babel-result-regexp nil t
)
1156 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1158 (while (looking-at org-babel-multi-line-header-regexp
)
1160 (goto-char (- (org-babel-result-end) 1)) (point)))
1162 (if (memq t
(mapcar (lambda (overlay)
1163 (eq (overlay-get overlay
'invisible
)
1164 'org-babel-hide-result
))
1165 (overlays-at start
)))
1166 (if (or (not force
) (eq force
'off
))
1168 (when (member ov org-babel-hide-result-overlays
)
1169 (setq org-babel-hide-result-overlays
1170 (delq ov org-babel-hide-result-overlays
)))
1171 (when (eq (overlay-get ov
'invisible
)
1172 'org-babel-hide-result
)
1173 (delete-overlay ov
)))
1174 (overlays-at start
)))
1175 (setq ov
(make-overlay start end
))
1176 (overlay-put ov
'invisible
'org-babel-hide-result
)
1177 ;; make the block accessible to isearch
1179 ov
'isearch-open-invisible
1181 (when (member ov org-babel-hide-result-overlays
)
1182 (setq org-babel-hide-result-overlays
1183 (delq ov org-babel-hide-result-overlays
)))
1184 (when (eq (overlay-get ov
'invisible
)
1185 'org-babel-hide-result
)
1186 (delete-overlay ov
))))
1187 (push ov org-babel-hide-result-overlays
)))
1188 (error "Not looking at a result line"))))
1190 ;; org-tab-after-check-for-cycling-hook
1191 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1192 ;; Remove overlays when changing major mode
1193 (add-hook 'org-mode-hook
1194 (lambda () (org-add-hook 'change-major-mode-hook
1195 'org-babel-show-result-all
'append
'local
)))
1197 (defvar org-file-properties
)
1198 (defun org-babel-params-from-properties (&optional lang
)
1199 "Retrieve parameters specified as properties.
1200 Return an association list of any source block params which
1201 may be specified in the properties of the current outline entry."
1204 (org-babel-parse-multiple-vars
1207 (lambda (header-arg)
1208 (and (setq val
(org-entry-get (point) header-arg t
))
1209 (cons (intern (concat ":" header-arg
))
1210 (org-babel-read val
))))
1215 (org-babel-combine-header-arg-lists
1216 org-babel-common-header-args-w-values
1218 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1219 (and (boundp sym
) (eval sym
))))))))))))
1221 (defvar org-src-preserve-indentation
)
1222 (defun org-babel-parse-src-block-match ()
1223 "Parse the results from a match of the `org-babel-src-block-regexp'."
1224 (let* ((block-indentation (length (match-string 1)))
1225 (lang (org-babel-clean-text-properties (match-string 2)))
1226 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1227 (switches (match-string 3))
1228 (body (org-babel-clean-text-properties
1229 (let* ((body (match-string 5))
1230 (sub-length (- (length body
) 1)))
1231 (if (and (> sub-length
0)
1232 (string= "\n" (substring body sub-length
)))
1233 (substring body
0 sub-length
)
1235 (preserve-indentation (or org-src-preserve-indentation
1237 (string-match "-i\\>" switches
)))))
1239 ;; get block body less properties, protective commas, and indentation
1242 (insert (org-babel-strip-protective-commas body lang
))
1243 (unless preserve-indentation
(org-do-remove-indentation))
1245 (org-babel-merge-params
1246 org-babel-default-header-args
1247 (org-babel-params-from-properties lang
)
1248 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1249 (org-babel-parse-header-arguments
1250 (org-babel-clean-text-properties (or (match-string 4) ""))))
1252 block-indentation
)))
1254 (defun org-babel-parse-inline-src-block-match ()
1255 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1256 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
1257 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1259 (org-babel-strip-protective-commas
1260 (org-babel-clean-text-properties (match-string 5)) lang
)
1261 (org-babel-merge-params
1262 org-babel-default-inline-header-args
1263 (org-babel-params-from-properties lang
)
1264 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1265 (org-babel-parse-header-arguments
1266 (org-babel-clean-text-properties (or (match-string 4) "")))))))
1268 (defun org-babel-balanced-split (string alts
)
1269 "Split STRING on instances of ALTS.
1270 ALTS is a cons of two character options where each option may be
1271 either the numeric code of a single character or a list of
1272 character alternatives. For example to split on balanced
1273 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1274 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1275 (matched (lambda (ch last
)
1277 (and (funcall matches ch
(cdr alts
))
1278 (funcall matches last
(car alts
)))
1279 (funcall matches ch alts
))))
1280 (balance 0) (last 0)
1282 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1283 (setq balance
(+ balance
1284 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1285 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1287 (when (and (equal 34 ch
) (not (equal 92 last
)))
1288 (setq quote
(not quote
)))
1289 (setq partial
(cons ch partial
))
1290 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1291 (setq lst
(cons (apply #'string
(nreverse
1298 (string-to-list string
))
1299 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1301 (defun org-babel-join-splits-near-ch (ch list
)
1302 "Join splits where \"=\" is on either end of the split."
1303 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1304 (first= (lambda (str) (= ch
(aref str
0)))))
1306 (org-reduce (lambda (acc el
)
1307 (let ((head (car acc
)))
1308 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1309 (cons (concat head el
) (cdr acc
))
1311 list
:initial-value nil
))))
1313 (defun org-babel-parse-header-arguments (arg-string)
1314 "Parse a string of header arguments returning an alist."
1315 (when (> (length arg-string
) 0)
1316 (org-babel-parse-multiple-vars
1321 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1323 (cons (intern (match-string 1 arg
))
1324 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1325 (cons (intern (org-babel-chomp arg
)) nil
)))
1327 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1328 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1330 (defun org-babel-parse-multiple-vars (header-arguments)
1331 "Expand multiple variable assignments behind a single :var keyword.
1333 This allows expression of multiple variables with one :var as
1336 #+PROPERTY: var foo=1, bar=2"
1338 (mapc (lambda (pair)
1339 (if (eq (car pair
) :var
)
1340 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1341 (org-babel-join-splits-near-ch
1342 61 (org-babel-balanced-split (cdr pair
) 32)))
1343 (push pair results
)))
1345 (nreverse results
)))
1347 (defun org-babel-process-params (params)
1348 "Expand variables in PARAMS and add summary parameters."
1349 (let* ((processed-vars (mapcar (lambda (el)
1350 (if (consp (cdr el
))
1352 (org-babel-ref-parse (cdr el
))))
1353 (org-babel-get-header params
:var
)))
1354 (vars-and-names (if (and (assoc :colname-names params
)
1355 (assoc :rowname-names params
))
1356 (list processed-vars
)
1357 (org-babel-disassemble-tables
1359 (cdr (assoc :hlines params
))
1360 (cdr (assoc :colnames params
))
1361 (cdr (assoc :rownames params
)))))
1362 (raw-result (or (cdr (assoc :results params
)) ""))
1363 (result-params (append
1364 (split-string (if (stringp raw-result
)
1367 (cdr (assoc :result-params params
)))))
1369 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1371 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1372 (cadr vars-and-names
)))
1373 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1374 (caddr vars-and-names
)))
1375 (cons :result-params result-params
)
1376 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1377 ((member "value" result-params
) 'value
)
1379 (org-babel-get-header params
:var
'other
))))
1381 ;; row and column names
1382 (defun org-babel-del-hlines (table)
1383 "Remove all 'hlines from TABLE."
1384 (remove 'hline table
))
1386 (defun org-babel-get-colnames (table)
1387 "Return the column names of TABLE.
1388 Return a cons cell, the `car' of which contains the TABLE less
1389 colnames, and the `cdr' of which contains a list of the column
1391 (if (equal 'hline
(nth 1 table
))
1392 (cons (cddr table
) (car table
))
1393 (cons (cdr table
) (car table
))))
1395 (defun org-babel-get-rownames (table)
1396 "Return the row names of TABLE.
1397 Return a cons cell, the `car' of which contains the TABLE less
1398 colnames, and the `cdr' of which contains a list of the column
1399 names. Note: this function removes any hlines in TABLE."
1400 (let* ((trans (lambda (table) (apply #'mapcar
* #'list table
)))
1402 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1403 (table (funcall trans
(mapcar (lambda (row)
1404 (if (not (equal row
'hline
))
1408 (setq row
(cons 'hline row
)))
1411 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1412 (funcall trans
(cdr table
)))
1413 (remove 'hline
(car table
)))))
1415 (defun org-babel-put-colnames (table colnames
)
1416 "Add COLNAMES to TABLE if they exist."
1417 (if colnames
(apply 'list colnames
'hline table
) table
))
1419 (defun org-babel-put-rownames (table rownames
)
1420 "Add ROWNAMES to TABLE if they exist."
1422 (mapcar (lambda (row)
1424 (cons (or (pop rownames
) "") row
)
1428 (defun org-babel-pick-name (names selector
)
1429 "Select one out of an alist of row or column names.
1430 SELECTOR can be either a list of names in which case those names
1431 will be returned directly, or an index into the list NAMES in
1432 which case the indexed names will be return."
1433 (if (listp selector
)
1436 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1437 (cdr (assoc selector names
))
1438 (if (integerp selector
)
1439 (nth (- selector
1) names
)
1440 (cdr (car (last names
))))))))
1442 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1443 "Parse tables for further processing.
1444 Process the variables in VARS according to the HLINES,
1445 ROWNAMES and COLNAMES header arguments. Return a list consisting
1446 of the vars, cnames and rnames."
1447 (let (cnames rnames
)
1451 (when (listp (cdr var
))
1452 (when (and (not (equal colnames
"no"))
1453 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1454 (not (member 'hline
(cddr (cdr var
)))))))
1455 (let ((both (org-babel-get-colnames (cdr var
))))
1456 (setq cnames
(cons (cons (car var
) (cdr both
))
1458 (setq var
(cons (car var
) (car both
)))))
1459 (when (and rownames
(not (equal rownames
"no")))
1460 (let ((both (org-babel-get-rownames (cdr var
))))
1461 (setq rnames
(cons (cons (car var
) (cdr both
))
1463 (setq var
(cons (car var
) (car both
)))))
1464 (when (and hlines
(not (equal hlines
"yes")))
1465 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1468 (reverse cnames
) (reverse rnames
))))
1470 (defun org-babel-reassemble-table (table colnames rownames
)
1471 "Add column and row names to a table.
1472 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1473 to the table for reinsertion to org-mode."
1476 (if (and colnames
(listp (car table
)) (= (length (car table
))
1478 (org-babel-put-colnames table colnames
) table
))
1479 (if (and rownames
(= (length table
) (length rownames
)))
1480 (org-babel-put-rownames table rownames
) table
))
1483 (defun org-babel-where-is-src-block-head ()
1484 "Find where the current source block begins.
1485 Return the point at the beginning of the current source
1486 block. Specifically at the beginning of the #+BEGIN_SRC line.
1487 If the point is not on a source block then return nil."
1488 (let ((initial (point)) (case-fold-search t
) top bottom
)
1490 (save-excursion ;; on a source name line or a #+header line
1491 (beginning-of-line 1)
1492 (and (or (looking-at org-babel-src-name-regexp
)
1493 (looking-at org-babel-multi-line-header-regexp
))
1495 (while (and (forward-line 1)
1496 (looking-at org-babel-multi-line-header-regexp
)))
1497 (looking-at org-babel-src-block-regexp
))
1499 (save-excursion ;; on a #+begin_src line
1500 (beginning-of-line 1)
1501 (and (looking-at org-babel-src-block-regexp
)
1503 (save-excursion ;; inside a src block
1505 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1506 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1507 (< top initial
) (< initial bottom
)
1508 (progn (goto-char top
) (beginning-of-line 1)
1509 (looking-at org-babel-src-block-regexp
))
1513 (defun org-babel-goto-src-block-head ()
1514 "Go to the beginning of the current code block."
1517 (if head
(goto-char head
) (error "not currently in a code block")))
1518 (org-babel-where-is-src-block-head)))
1521 (defun org-babel-goto-named-src-block (name)
1522 "Go to a named source-code block."
1524 (let ((completion-ignore-case t
)
1525 (case-fold-search t
)
1526 (under-point (thing-at-point 'line
)))
1527 (list (org-icompleting-read
1528 "source-block name: " (org-babel-src-block-names) nil t
1531 ((string-match (org-babel-noweb-wrap) under-point
)
1532 (let ((block-name (match-string 1 under-point
)))
1533 (string-match "[^(]*" block-name
)
1534 (match-string 0 block-name
)))
1536 ((string-match org-babel-lob-one-liner-regexp under-point
)
1537 (let ((source-info (car (org-babel-lob-get-info))))
1538 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1539 (let ((source-name (match-string 1 source-info
)))
1542 ((string-match (concat "#\\+" org-babel-results-keyword
1543 "\\:\s+\\([^\\(]*\\)") under-point
)
1544 (match-string 1 under-point
))
1546 ((and (thing-at-point 'symbol
))
1547 (org-babel-find-named-block (thing-at-point 'symbol
))
1548 (thing-at-point 'symbol
))
1550 (let ((point (org-babel-find-named-block name
)))
1552 ;; taken from `org-open-at-point'
1553 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1554 (message "source-code block '%s' not found in this buffer" name
))))
1556 (defun org-babel-find-named-block (name)
1557 "Find a named source-code block.
1558 Return the location of the source block identified by source
1559 NAME, or nil if no such block exists. Set match data according to
1560 org-babel-named-src-block-regexp."
1562 (let ((case-fold-search t
)
1563 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1564 (goto-char (point-min))
1565 (when (or (re-search-forward regexp nil t
)
1566 (re-search-backward regexp nil t
))
1567 (match-beginning 0)))))
1569 (defun org-babel-src-block-names (&optional file
)
1570 "Returns the names of source blocks in FILE or the current buffer."
1572 (when file
(find-file file
)) (goto-char (point-min))
1573 (let ((case-fold-search t
) names
)
1574 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1575 (setq names
(cons (match-string 3) names
)))
1579 (defun org-babel-goto-named-result (name)
1580 "Go to a named result."
1582 (let ((completion-ignore-case t
))
1583 (list (org-icompleting-read "source-block name: "
1584 (org-babel-result-names) nil t
))))
1585 (let ((point (org-babel-find-named-result name
)))
1587 ;; taken from `org-open-at-point'
1588 (progn (goto-char point
) (org-show-context))
1589 (message "result '%s' not found in this buffer" name
))))
1591 (defun org-babel-find-named-result (name &optional point
)
1592 "Find a named result.
1593 Return the location of the result named NAME in the current
1594 buffer or nil if no such result exists."
1596 (let ((case-fold-search t
))
1597 (goto-char (or point
(point-min)))
1598 (catch 'is-a-code-block
1599 (when (re-search-forward
1600 (concat org-babel-result-regexp
1601 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1602 (when (and (string= "name" (downcase (match-string 1)))
1603 (or (beginning-of-line 1)
1604 (looking-at org-babel-src-block-regexp
)
1605 (looking-at org-babel-multi-line-header-regexp
)))
1606 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1607 (beginning-of-line 0) (point))))))
1609 (defun org-babel-result-names (&optional file
)
1610 "Returns the names of results in FILE or the current buffer."
1612 (when file
(find-file file
)) (goto-char (point-min))
1613 (let ((case-fold-search t
) names
)
1614 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1615 (setq names
(cons (match-string 4) names
)))
1619 (defun org-babel-next-src-block (&optional arg
)
1620 "Jump to the next source block.
1621 With optional prefix argument ARG, jump forward ARG many source blocks."
1623 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1625 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1626 (error (error "No further code blocks")))
1627 (goto-char (match-beginning 0)) (org-show-context))
1630 (defun org-babel-previous-src-block (&optional arg
)
1631 "Jump to the previous source block.
1632 With optional prefix argument ARG, jump backward ARG many source blocks."
1635 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1636 (error (error "No previous code blocks")))
1637 (goto-char (match-beginning 0)) (org-show-context))
1639 (defvar org-babel-load-languages
)
1642 (defun org-babel-mark-block ()
1643 "Mark current src block."
1649 (looking-at org-babel-src-block-regexp
))
1650 (push-mark (match-end 5) nil t
)
1651 (goto-char (match-beginning 5))))
1652 (org-babel-where-is-src-block-head)))
1654 (defun org-babel-demarcate-block (&optional arg
)
1655 "Wrap or split the code in the region or on the point.
1656 When called from inside of a code block the current block is
1657 split. When called from outside of a code block a new code block
1658 is created. In both cases if the region is demarcated and if the
1659 region is not active then the point is demarcated."
1661 (let ((info (org-babel-get-src-block-info 'light
))
1662 (headers (progn (org-babel-where-is-src-block-head)
1664 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1670 (let ((lang (nth 0 info
))
1671 (indent (make-string (nth 5 info
) ?
)))
1672 (when (string-match "^[[:space:]]*$"
1673 (buffer-substring (point-at-bol)
1675 (delete-region (point-at-bol) (point-at-eol)))
1677 (if (looking-at "^") "" "\n")
1678 indent
"#+end_src\n"
1679 (if arg stars indent
) "\n"
1680 indent
"#+begin_src " lang
1681 (if (> (length headers
) 1)
1682 (concat " " headers
) headers
)
1683 (if (looking-at "[\n\r]")
1685 (concat "\n" (make-string (current-column) ?
)))))))
1686 (move-end-of-line 2))
1687 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1688 (let ((start (point))
1689 (lang (org-icompleting-read "Lang: "
1690 (mapcar (lambda (el) (symbol-name (car el
)))
1691 org-babel-load-languages
)))
1692 (body (delete-and-extract-region
1693 (if (region-active-p) (mark) (point)) (point))))
1694 (insert (concat (if (looking-at "^") "" "\n")
1695 (if arg
(concat stars
"\n") "")
1696 "#+begin_src " lang
"\n"
1698 (if (or (= (length body
) 0)
1699 (string-match "[\r\n]$" body
)) "" "\n")
1701 (goto-char start
) (move-end-of-line 1)))))
1703 (defvar org-babel-lob-one-liner-regexp
)
1704 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1705 "Find where the current source block results begin.
1706 Return the point at the beginning of the result of the current
1707 source block. Specifically at the beginning of the results line.
1708 If no result exists for this block then create a results line
1709 following the source block."
1711 (let* ((case-fold-search t
)
1712 (on-lob-line (save-excursion
1713 (beginning-of-line 1)
1714 (looking-at org-babel-lob-one-liner-regexp
)))
1715 (inlinep (when (org-babel-get-inline-src-block-matches)
1717 (name (if on-lob-line
1718 (mapconcat #'identity
(butlast (org-babel-lob-get-info)) "")
1719 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1720 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1722 (when head
(goto-char head
))
1724 found
;; was there a result (before we potentially insert one)
1729 ;; - return t if it is found, else return nil
1730 ;; - if it does not need to be rebuilt, then don't set end
1731 ;; - if it does need to be rebuilt then do set end
1732 name
(setq beg
(org-babel-find-named-result name
))
1734 (when (and hash
(not (string= hash
(match-string 3))))
1735 (goto-char beg
) (setq end beg
) ;; beginning of result
1737 (delete-region end
(org-babel-result-end)) nil
)))
1740 ;; - return t if it is found, else return nil
1741 ;; - if it is found, and the hash doesn't match, delete and set end
1742 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1743 (progn (end-of-line 1)
1744 (if (eobp) (insert "\n") (forward-char 1))
1747 (progn ;; unnamed results line already exists
1748 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1749 (beginning-of-line 1)
1751 (concat org-babel-result-regexp
"\n")))
1753 ;; must remove and rebuild if hash!=old-hash
1754 (if (and hash
(not (string= hash
(match-string 3))))
1758 end
(org-babel-result-end)))
1759 (setq end nil
)))))))))
1760 (if (and insert end
)
1764 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1769 (org-number-sequence 1 indent
) "")
1771 "#+" org-babel-results-keyword
1772 (when hash
(concat "["hash
"]"))
1774 (when name
(concat " " name
)) "\n"))
1775 (unless beg
(insert "\n") (backward-char))
1776 (beginning-of-line 0)
1777 (if hash
(org-babel-hide-hash))
1781 (defvar org-block-regexp
)
1782 (defun org-babel-read-result ()
1783 "Read the result at `point' into emacs-lisp."
1784 (let ((case-fold-search t
) result-string
)
1786 ((org-at-table-p) (org-babel-read-table))
1787 ((org-at-item-p) (org-babel-read-list))
1788 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1789 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1790 ((looking-at "^[ \t]*: ")
1793 (mapconcat (lambda (line)
1794 (if (and (> (length line
) 1)
1795 (string-match "^[ \t]*: \\(.+\\)" line
))
1796 (match-string 1 line
)
1800 (point) (org-babel-result-end)) "[\r\n]+")
1802 (or (org-babel-number-p result-string
) result-string
))
1803 ((looking-at org-babel-result-regexp
)
1804 (save-excursion (forward-line 1) (org-babel-read-result))))))
1806 (defun org-babel-read-table ()
1807 "Read the table at `point' into emacs-lisp."
1808 (mapcar (lambda (row)
1809 (if (and (symbolp row
) (equal row
'hline
)) row
1810 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1811 (org-table-to-lisp)))
1813 (defun org-babel-read-list ()
1814 "Read the list at `point' into emacs-lisp."
1815 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1816 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1818 (defvar org-link-types-re
)
1819 (defun org-babel-read-link ()
1820 "Read the link at `point' into emacs-lisp.
1821 If the path of the link is a file path it is expanded using
1822 `expand-file-name'."
1823 (let* ((case-fold-search t
)
1824 (raw (and (looking-at org-bracket-link-regexp
)
1825 (org-babel-clean-text-properties (match-string 1))))
1826 (type (and (string-match org-link-types-re raw
)
1827 (match-string 1 raw
))))
1829 ((not type
) (expand-file-name raw
))
1830 ((string= type
"file")
1831 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1832 (expand-file-name (match-string 2 raw
))))
1835 (defun org-babel-format-result (result &optional sep
)
1836 "Format RESULT for writing to file."
1837 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
1841 result
(list :sep
(or sep
"\t") :fmt echo-res
))
1843 (funcall echo-res result
))))
1845 (defun org-babel-insert-result
1846 (result &optional result-params info hash indent lang
)
1847 "Insert RESULT into the current buffer.
1848 By default RESULT is inserted after the end of the
1849 current source block. With optional argument RESULT-PARAMS
1850 controls insertion of results in the org-mode file.
1851 RESULT-PARAMS can take the following values...
1853 replace - (default option) insert results after the source block
1854 replacing any previously inserted results
1856 silent -- no results are inserted
1858 file ---- the results are interpreted as a file path, and are
1859 inserted into the buffer using the Org-mode file syntax
1861 list ---- the results are interpreted as an Org-mode list.
1863 raw ----- results are added directly to the Org-mode file. This
1864 is a good option if you code block will output org-mode
1867 wrap ---- results are added directly to the Org-mode file as with
1868 \"raw\", but are wrapped in a RESULTS drawer, allowing
1869 them to later be replaced or removed automatically.
1871 org ----- similar in effect to raw, only the results are wrapped
1872 in an org code block. Similar to the raw option, on
1873 export the results will be interpreted as org-formatted
1874 text, however by wrapping the results in an org code
1875 block they can be replaced upon re-execution of the
1878 html ---- results are added inside of a #+BEGIN_HTML block. This
1879 is a good option if you code block will output html
1882 latex --- results are added inside of a #+BEGIN_LATEX block.
1883 This is a good option if you code block will output
1884 latex formatted text.
1886 code ---- the results are extracted in the syntax of the source
1887 code of the language being evaluated and are added
1888 inside of a #+BEGIN_SRC block with the source-code
1889 language set appropriately. Note this relies on the
1890 optional LANG argument."
1891 (if (stringp result
)
1893 (setq result
(org-babel-clean-text-properties result
))
1894 (when (member "file" result-params
)
1895 (setq result
(org-babel-result-to-file
1896 result
(when (assoc :file-desc
(nth 2 info
))
1897 (or (cdr (assoc :file-desc
(nth 2 info
)))
1899 (unless (listp result
) (setq result
(format "%S" result
))))
1900 (if (and result-params
(member "silent" result-params
))
1902 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1907 (when (or (org-babel-get-inline-src-block-matches)
1908 (org-babel-get-lob-one-liner-matches))
1909 (goto-char (match-end 0))
1910 (insert (if (listp result
) "\n" " "))
1912 (existing-result (unless inlinep
1913 (org-babel-where-is-src-block-result
1914 t info hash indent
)))
1916 (cdr (assoc :results_switches
(nth 2 info
))))
1918 (when (and (stringp result
) ; ensure results end in a newline
1920 (> (length result
) 0)
1921 (not (or (string-equal (substring result -
1) "\n")
1922 (string-equal (substring result -
1) "\r"))))
1923 (setq result
(concat result
"\n")))
1924 (if (not existing-result
)
1925 (setq beg
(or inlinep
(point)))
1926 (goto-char existing-result
)
1928 (re-search-forward "#" nil t
)
1929 (setq indent
(- (current-column) 1)))
1933 ((member "replace" result-params
)
1934 (delete-region (point) (org-babel-result-end)))
1935 ((member "append" result-params
)
1936 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1937 ((member "prepend" result-params
)))) ; already there
1938 (setq results-switches
1939 (if results-switches
(concat " " results-switches
) ""))
1940 (let ((wrap (lambda (start finish
)
1941 (goto-char end
) (insert (concat finish
"\n"))
1942 (goto-char beg
) (insert (concat start
"\n"))
1943 (goto-char end
) (goto-char (point-at-eol))
1944 (setq end
(point-marker))))
1945 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
1946 ;; insert results based on type
1948 ;; do nothing for an empty result
1950 ;; insert a list if preferred
1951 ((member "list" result-params
)
1954 (org-list-to-generic
1957 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1958 (if (listp result
) result
(list result
))))
1959 '(:splicep nil
:istart
"- " :iend
"\n")))
1961 ;; assume the result is a table if it's not a string
1962 ((funcall proper-list-p result
)
1964 (insert (concat (orgtbl-to-orgtbl
1965 (if (or (eq 'hline
(car result
))
1966 (and (listp (car result
))
1967 (listp (cdr (car result
)))))
1968 result
(list result
))
1969 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1970 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1971 ((and (listp result
) (not (funcall proper-list-p result
)))
1972 (insert (format "%s\n" result
)))
1973 ((member "file" result-params
)
1974 (when inlinep
(goto-char inlinep
))
1976 (t (goto-char beg
) (insert result
)))
1977 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
1978 (setq end
(point-marker))
1979 ;; possibly wrap result
1981 ((assoc :wrap
(nth 2 info
))
1982 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
1983 (funcall wrap
(concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1984 ((member "html" result-params
)
1985 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
1986 ((member "latex" result-params
)
1987 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
1988 ((member "code" result-params
)
1989 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1991 ((member "org" result-params
)
1992 (funcall wrap
"#+BEGIN_ORG" "#+END_ORG"))
1993 ((member "raw" result-params
)
1994 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1995 ((member "wrap" result-params
)
1996 (funcall wrap
":RESULTS:" ":END:"))
1997 ((and (not (funcall proper-list-p result
))
1998 (not (member "file" result-params
)))
1999 (org-babel-examplize-region beg end results-switches
)
2000 (setq end
(point)))))
2001 ;; possibly indent the results to match the #+results line
2002 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2003 ;; in this case `table-align' does the work for us
2004 (not (and (listp result
)
2005 (member "append" result-params
))))
2006 (indent-rigidly beg end indent
))))
2008 (if (member "value" result-params
)
2009 (message "Code block returned no value.")
2010 (message "Code block produced no output."))
2011 (message "Code block evaluation complete."))))
2013 (defun org-babel-remove-result (&optional info
)
2014 "Remove the result of the current source block."
2016 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
2018 (setq start
(- location
1))
2020 (goto-char location
) (forward-line 1)
2021 (delete-region start
(org-babel-result-end))))))
2023 (defun org-babel-result-end ()
2024 "Return the point at the end of the current set of results."
2027 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2028 ((org-at-item-p) (let* ((struct (org-list-struct))
2029 (prvs (org-list-prevs-alist struct
)))
2030 (org-list-get-list-end (point-at-bol) struct prvs
)))
2031 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2032 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2033 (forward-char 1) (point)))
2035 (let ((case-fold-search t
))
2036 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2037 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2040 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2044 (defun org-babel-result-to-file (result &optional description
)
2045 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2046 If the `default-directory' is different from the containing
2047 file's directory then expand relative links."
2048 (when (stringp result
)
2049 (format "[[file:%s]%s]"
2050 (if (and default-directory
2052 (not (string= (expand-file-name default-directory
)
2054 (file-name-directory buffer-file-name
)))))
2055 (expand-file-name result default-directory
)
2057 (if description
(concat "[" description
"]") ""))))
2059 (defvar org-babel-capitalize-examplize-region-markers nil
2060 "Make true to capitalize begin/end example markers inserted by code blocks.")
2062 (defun org-babel-examplize-region (beg end
&optional results-switches
)
2063 "Comment out region using the inline '==' or ': ' org example quote."
2065 (let ((chars-between (lambda (b e
)
2066 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2067 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2068 (upcase str
) str
))))
2069 (if (or (funcall chars-between
(save-excursion (goto-char beg
) (point-at-bol)) beg
)
2070 (funcall chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2073 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
2074 (delete-region beg end
)))))
2075 (let ((size (count-lines beg end
)))
2077 (cond ((= size
0)) ; do nothing for an empty result
2078 ((< size org-babel-min-lines-for-block-output
)
2081 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2084 (insert (if results-switches
2086 (funcall maybe-cap
"#+begin_example")
2088 (funcall maybe-cap
"#+begin_example\n")))
2089 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2090 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2092 (defun org-babel-update-block-body (new-body)
2093 "Update the body of the current code block to NEW-BODY."
2094 (if (not (org-babel-where-is-src-block-head))
2095 (error "not in source block")
2097 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2098 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2100 (defun org-babel-merge-params (&rest plists
)
2101 "Combine all parameter association lists in PLISTS.
2102 Later elements of PLISTS override the values of previous elements.
2103 This takes into account some special considerations for certain
2104 parameters when merging lists."
2105 (let* ((results-exclusive-groups
2106 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2107 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2108 (exports-exclusive-groups
2109 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2110 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2112 (e-merge (lambda (exclusive-groups &rest result-params
)
2113 ;; maintain exclusivity of mutually exclusive parameters
2115 (mapc (lambda (new-params)
2116 (mapc (lambda (new-param)
2117 (mapc (lambda (exclusive-group)
2118 (when (member new-param exclusive-group
)
2119 (mapcar (lambda (excluded-param)
2126 (setq output
(org-uniquify
2127 (cons new-param output
))))
2131 params results exports tangle noweb cache vars shebang comments padline
)
2139 (let ((name (if (listp (cdr pair
))
2141 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2143 (intern (match-string 1 (cdr pair
)))))))
2147 (if (member name
(mapcar #'car vars
))
2151 (unless (equal (car p
) name
) p
))
2154 (list (cons name pair
))))
2155 ;; if no name is given and we already have named variables
2156 ;; then assign to named variables in order
2157 (if (and vars
(nth variable-index vars
))
2158 (prog1 (setf (cddr (nth variable-index vars
))
2159 (concat (symbol-name
2160 (car (nth variable-index vars
)))
2162 (incf variable-index
))
2163 (error "variable \"%s\" must be assigned a default value"
2166 (setq results
(funcall e-merge results-exclusive-groups
2169 (let ((r (cdr pair
)))
2170 (if (stringp r
) r
(eval r
)))))))
2173 (setq results
(funcall e-merge results-exclusive-groups
2175 (unless (or (member "both" exports
)
2176 (member "none" exports
)
2177 (member "code" exports
))
2178 (setq exports
(funcall e-merge exports-exclusive-groups
2179 exports
'("results"))))
2180 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2182 (setq exports
(funcall e-merge exports-exclusive-groups
2183 exports
(split-string (cdr pair
)))))
2184 (:tangle
;; take the latest -- always overwrite
2185 (setq tangle
(or (list (cdr pair
)) tangle
)))
2187 (setq noweb
(funcall e-merge
2188 '(("yes" "no" "tangle" "no-export"
2189 "strip-export" "eval"))
2191 (split-string (or (cdr pair
) "")))))
2193 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2194 (split-string (or (cdr pair
) "")))))
2196 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2197 (split-string (or (cdr pair
) "")))))
2198 (:shebang
;; take the latest -- always overwrite
2199 (setq shebang
(or (list (cdr pair
)) shebang
)))
2201 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2202 (split-string (or (cdr pair
) "")))))
2203 (t ;; replace: this covers e.g. :session
2204 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2207 (setq vars
(reverse vars
))
2208 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2211 (let ((key (intern (concat ":" (symbol-name hd
))))
2213 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2214 '(results exports tangle noweb padline cache shebang comments
))
2217 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2218 "Set to true to use regular expressions to expand noweb references.
2219 This results in much faster noweb reference expansion but does
2220 not properly allow code blocks to inherit the \":noweb-ref\"
2221 header argument from buffer or subtree wide properties.")
2223 (defun org-babel-noweb-p (params context
)
2224 "Check if PARAMS require expansion in CONTEXT.
2225 CONTEXT may be one of :tangle, :export or :eval."
2226 (letrec ((intersect (lambda (as bs
)
2228 (if (member (car as
) bs
)
2230 (funcall intersect
(cdr as
) bs
))))))
2231 (funcall intersect
(case context
2232 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2233 (:eval
'("yes" "no-export" "strip-export" "eval"))
2235 (split-string (or (cdr (assoc :noweb params
)) "")))))
2237 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2238 "Expand Noweb references in the body of the current source code block.
2240 For example the following reference would be replaced with the
2241 body of the source-code block named 'example-block'.
2245 Note that any text preceding the <<foo>> construct on a line will
2246 be interposed between the lines of the replacement text. So for
2247 example if <<foo>> is placed behind a comment, then the entire
2248 replacement text will also be commented.
2250 This function must be called from inside of the buffer containing
2251 the source-code block which holds BODY.
2253 In addition the following syntax can be used to insert the
2254 results of evaluating the source-code block named 'example-block'.
2258 Any optional arguments can be passed to example-block by placing
2259 the arguments inside the parenthesis following the convention
2260 defined by `org-babel-lob'. For example
2262 <<example-block(a=9)>>
2264 would set the value of argument \"a\" equal to \"9\". Note that
2265 these arguments are not evaluated in the current source-code
2266 block but are passed literally to the \"example-block\"."
2267 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2268 (info (or info
(org-babel-get-src-block-info)))
2271 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2272 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2273 ":noweb-ref[ \t]+" "\\)"))
2275 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2276 (c-wrap (lambda (text)
2278 (funcall (intern (concat lang
"-mode")))
2279 (comment-region (point) (progn (insert text
) (point)))
2280 (org-babel-trim (buffer-string)))))
2281 index source-name evaluate prefix blocks-in-buffer
)
2283 (insert body
) (goto-char (point-min))
2284 (setq index
(point))
2285 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2286 (save-match-data (setf source-name
(match-string 1)))
2287 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2290 (buffer-substring (match-beginning 0)
2292 (beginning-of-line 1) (point)))))
2293 ;; add interval to new-body (removing noweb reference)
2294 (goto-char (match-beginning 0))
2295 (funcall nb-add
(buffer-substring index
(point)))
2296 (goto-char (match-end 0))
2297 (setq index
(point))
2299 (with-current-buffer parent-buffer
2302 (mapconcat ;; interpose PREFIX between every line
2306 (let ((raw (org-babel-ref-resolve source-name
)))
2307 (if (stringp raw
) raw
(format "%S" raw
)))
2309 ;; retrieve from the library of babel
2310 (nth 2 (assoc (intern source-name
)
2311 org-babel-library-of-babel
))
2312 ;; return the contents of headlines literally
2314 (when (org-babel-ref-goto-headline-id source-name
)
2315 (org-babel-ref-headline-body)))
2316 ;; find the expansion of reference in this buffer
2317 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2320 (goto-char (point-min))
2321 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2322 (while (re-search-forward rx nil t
)
2323 (let* ((i (org-babel-get-src-block-info 'light
))
2324 (body (org-babel-expand-noweb-references i
))
2325 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2329 (concat (funcall c-wrap
(car cs
)) "\n"
2331 (funcall c-wrap
(cadr cs
))))
2332 (org-babel-tangle-comment-links i
))
2334 (setq expansion
(cons sep
(cons full expansion
)))))
2335 (org-babel-map-src-blocks nil
2336 (let ((i (org-babel-get-src-block-info 'light
)))
2337 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2340 (let* ((body (org-babel-expand-noweb-references i
))
2341 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2345 (concat (funcall c-wrap
(car cs
)) "\n"
2347 (funcall c-wrap
(cadr cs
))))
2348 (org-babel-tangle-comment-links i
))
2351 (cons sep
(cons full expansion
)))))))))
2353 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2354 ;; possibly raise an error if named block doesn't exist
2355 (if (member lang org-babel-noweb-error-langs
)
2357 (org-babel-noweb-wrap source-name
)
2358 "could not be resolved (see "
2359 "`org-babel-noweb-error-langs')"))
2361 "[\n\r]") (concat "\n" prefix
))))))
2362 (funcall nb-add
(buffer-substring index
(point-max))))
2365 (defun org-babel-clean-text-properties (text)
2366 "Strip all properties from text return."
2368 (set-text-properties 0 (length text
) nil text
) text
))
2370 (defun org-babel-strip-protective-commas (body &optional lang
)
2371 "Strip protective commas from bodies of source blocks."
2374 (if (and lang
(string= lang
"org"))
2375 (progn (goto-char (point-min))
2376 (while (re-search-forward "^[ \t]*\\(,\\)" nil t
)
2377 (replace-match "" nil nil nil
1)))
2378 (org-strip-protective-commas (point-min) (point-max)))
2381 (defun org-babel-script-escape (str &optional force
)
2382 "Safely convert tables into elisp lists."
2383 (let (in-single in-double out
)
2384 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2388 (or (and (string-equal "[" (substring str
0 1))
2389 (string-equal "]" (substring str -
1)))
2390 (and (string-equal "{" (substring str
0 1))
2391 (string-equal "}" (substring str -
1)))
2392 (and (string-equal "(" (substring str
0 1))
2393 (string-equal ")" (substring str -
1))))))
2403 (91 (if (or in-double in-single
) ; [
2406 (93 (if (or in-double in-single
) ; ]
2409 (123 (if (or in-double in-single
) ; {
2412 (125 (if (or in-double in-single
) ; }
2415 (44 (if (or in-double in-single
) ; ,
2416 (cons 44 out
) (cons 32 out
)))
2417 (39 (if in-double
; '
2419 (setq in-single
(not in-single
)) (cons 34 out
)))
2420 (34 (if in-single
; "
2421 (append (list 34 32) out
)
2422 (setq in-double
(not in-double
)) (cons 34 out
)))
2423 (t (cons ch out
)))))
2424 (string-to-list str
))
2425 (apply #'string
(reverse out
)))))
2428 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2429 "Convert the string value of CELL to a number if appropriate.
2430 Otherwise if cell looks like lisp (meaning it starts with a
2431 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2432 return it unmodified as a string. Optional argument NO-LISP-EVAL
2433 inhibits lisp evaluation for situations in which is it not
2435 (if (and (stringp cell
) (not (equal cell
"")))
2436 (or (org-babel-number-p cell
)
2437 (if (and (not inhibit-lisp-eval
)
2438 (member (substring cell
0 1) '("(" "'" "`" "[")))
2440 (if (string= (substring cell
0 1) "\"")
2442 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2445 (defun org-babel-number-p (string)
2446 "If STRING represents a number return its value."
2447 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2448 (= (length (substring string
(match-beginning 0)
2451 (string-to-number string
)))
2453 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2454 "Read the results located at FILE-NAME into an elisp table.
2455 If the table is trivial, then return it as a scalar."
2457 (save-window-excursion
2461 (org-table-import file-name separator
)
2462 (delete-file file-name
)
2463 (setq result
(mapcar (lambda (row)
2464 (mapcar #'org-babel-string-read row
))
2465 (org-table-to-lisp))))
2466 (error (message "error reading results: %s" err
) nil
)))
2467 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2468 (if (consp (car result
))
2469 (if (null (cdr (car result
)))
2475 (defun org-babel-string-read (cell)
2476 "Strip nested \"s from around strings."
2477 (org-babel-read (or (and (stringp cell
)
2478 (string-match "\\\"\\(.+\\)\\\"" cell
)
2479 (match-string 1 cell
))
2482 (defun org-babel-reverse-string (string)
2483 "Return the reverse of STRING."
2484 (apply 'string
(reverse (string-to-list string
))))
2486 (defun org-babel-chomp (string &optional regexp
)
2487 "Strip trailing spaces and carriage returns from STRING.
2488 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2489 overwritten by specifying a regexp as a second argument."
2490 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2491 (while (and (> (length string
) 0)
2492 (string-match regexp
(substring string -
1)))
2493 (setq string
(substring string
0 -
1)))
2496 (defun org-babel-trim (string &optional regexp
)
2497 "Strip leading and trailing spaces and carriage returns from STRING.
2498 Like `org-babel-chomp' only it runs on both the front and back
2500 (org-babel-chomp (org-babel-reverse-string
2501 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2504 (defvar org-babel-org-babel-call-process-region-original nil
)
2505 (defun org-babel-tramp-handle-call-process-region
2506 (start end program
&optional delete buffer display
&rest args
)
2507 "Use Tramp to handle `call-process-region'.
2508 Fixes a bug in `tramp-handle-call-process-region'."
2509 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2510 (let ((tmpfile (tramp-compat-make-temp-file "")))
2511 (write-region start end tmpfile
)
2512 (when delete
(delete-region start end
))
2514 ;; (apply 'call-process program tmpfile buffer display args)
2516 (apply 'process-file program tmpfile buffer display args
)
2517 (delete-file tmpfile
)))
2518 ;; org-babel-call-process-region-original is the original emacs
2519 ;; definition. It is in scope from the let binding in
2520 ;; org-babel-execute-src-block
2521 (apply org-babel-call-process-region-original
2522 start end program delete buffer display args
)))
2524 (defun org-babel-local-file-name (file)
2525 "Return the local name component of FILE."
2526 (if (file-remote-p file
)
2528 (with-parsed-tramp-file-name file nil
2532 (defun org-babel-process-file-name (name &optional no-quote-p
)
2533 "Prepare NAME to be used in an external process.
2534 If NAME specifies a remote location, the remote portion of the
2535 name is removed, since in that case the process will be executing
2536 remotely. The file name is then processed by `expand-file-name'.
2537 Unless second argument NO-QUOTE-P is non-nil, the file name is
2538 additionally processed by `shell-quote-argument'"
2539 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2540 (expand-file-name (org-babel-local-file-name name
))))
2542 (defvar org-babel-temporary-directory
)
2543 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2544 (defvar org-babel-temporary-directory
2545 (or (and (boundp 'org-babel-temporary-directory
)
2546 (file-exists-p org-babel-temporary-directory
)
2547 org-babel-temporary-directory
)
2548 (make-temp-file "babel-" t
))
2549 "Directory to hold temporary files created to execute code blocks.
2550 Used by `org-babel-temp-file'. This directory will be removed on
2553 (defun org-babel-temp-file (prefix &optional suffix
)
2554 "Create a temporary file in the `org-babel-temporary-directory'.
2555 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2556 value of `temporary-file-directory' temporarily set to the value
2557 of `org-babel-temporary-directory'."
2558 (if (file-remote-p default-directory
)
2560 (concat (file-remote-p default-directory
)
2562 prefix temporary-file-directory
)
2564 (let ((temporary-file-directory
2565 (or (and (boundp 'org-babel-temporary-directory
)
2566 (file-exists-p org-babel-temporary-directory
)
2567 org-babel-temporary-directory
)
2568 temporary-file-directory
)))
2569 (make-temp-file prefix nil suffix
))))
2571 (defun org-babel-remove-temporary-directory ()
2572 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2573 (when (and (boundp 'org-babel-temporary-directory
)
2574 (file-exists-p org-babel-temporary-directory
))
2575 ;; taken from `delete-directory' in files.el
2578 (mapc (lambda (file)
2579 ;; This test is equivalent to
2580 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2581 ;; but more efficient
2582 (if (eq t
(car (file-attributes file
)))
2583 (delete-directory file
)
2584 (delete-file file
)))
2585 ;; We do not want to delete "." and "..".
2586 (directory-files org-babel-temporary-directory
'full
2587 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2588 (delete-directory org-babel-temporary-directory
))
2590 (message "Failed to remove temporary Org-babel directory %s"
2591 (if (boundp 'org-babel-temporary-directory
)
2592 org-babel-temporary-directory
2593 "[directory not defined]"))))))
2595 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)