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/>.
32 (defconst org-babel-exeext
33 (if (memq system-type
'(windows-nt cygwin
))
36 (defvar org-babel-call-process-region-original
)
37 (defvar org-src-lang-modes
)
38 (defvar org-babel-library-of-babel
)
39 (declare-function show-all
"outline" ())
40 (declare-function org-reduce
"org" (CL-FUNC CL-SEQ
&rest CL-KEYS
))
41 (declare-function org-mark-ring-push
"org" (&optional pos buffer
))
42 (declare-function org-strip-protective-commas
"org" (beg end
))
43 (declare-function tramp-compat-make-temp-file
"tramp-compat"
44 (filename &optional dir-flag
))
45 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
46 (declare-function tramp-file-name-user
"tramp" (vec))
47 (declare-function tramp-file-name-host
"tramp" (vec))
48 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
49 (declare-function org-icompleting-read
"org" (&rest args
))
50 (declare-function org-edit-src-code
"org-src"
51 (&optional context code edit-buffer-name quietp
))
52 (declare-function org-edit-src-exit
"org-src" (&optional context
))
53 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
54 (declare-function org-save-outline-visibility
"org-macs" (use-markers &rest body
))
55 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
56 (declare-function org-set-outline-overlay-data
"org" (data))
57 (declare-function org-narrow-to-subtree
"org" ())
58 (declare-function org-entry-get
"org"
59 (pom property
&optional inherit literal-nil
))
60 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
61 (declare-function org-do-remove-indentation
"org" (&optional n
))
62 (declare-function org-show-context
"org" (&optional key
))
63 (declare-function org-at-table-p
"org" (&optional table-type
))
64 (declare-function org-cycle
"org" (&optional arg
))
65 (declare-function org-uniquify
"org" (list))
66 (declare-function org-current-level
"org" ())
67 (declare-function org-strip-protective-commas
"org" (beg end
))
68 (declare-function org-table-import
"org-table" (file arg
))
69 (declare-function org-add-hook
"org-compat"
70 (hook function
&optional append local
))
71 (declare-function org-table-align
"org-table" ())
72 (declare-function org-table-end
"org-table" (&optional table-type
))
73 (declare-function orgtbl-to-generic
"org-table" (table params
))
74 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
75 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
76 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
77 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
78 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
79 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
80 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
81 (declare-function org-babel-ref-headline-body
"ob-ref" ())
82 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
83 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
84 (declare-function org-at-item-p
"org-list" ())
85 (declare-function org-list-parse-list
"org-list" (&optional delete
))
86 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
87 (declare-function org-list-struct
"org-list" ())
88 (declare-function org-list-prevs-alist
"org-list" (struct))
89 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
90 (declare-function org-strip-protective-commas
"org" (beg end
))
91 (declare-function org-remove-if
"org" (predicate seq
))
92 (declare-function org-completing-read
"org" (&rest args
))
93 (declare-function org-add-protective-commas
"org-src" (beg end
))
95 (defgroup org-babel nil
96 "Code block evaluation and management in `org-mode' documents."
100 (defcustom org-confirm-babel-evaluate t
101 "Confirm before evaluation.
102 Require confirmation before interactively evaluating code
103 blocks in Org-mode buffers. The default value of this variable
104 is t, meaning confirmation is required for any code block
105 evaluation. This variable can be set to nil to inhibit any
106 future confirmation requests. This variable can also be set to a
107 function which takes two arguments the language of the code block
108 and the body of the code block. Such a function should then
109 return a non-nil value if the user should be prompted for
110 execution or nil if no prompt is required.
112 Warning: Disabling confirmation may result in accidental
113 evaluation of potentially harmful code. It may be advisable
114 remove code block execution from C-c C-c as further protection
115 against accidental code block evaluation. The
116 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
117 remove code block execution from the C-c C-c keybinding."
120 :type
'(choice boolean function
))
121 ;; don't allow this variable to be changed through file settings
122 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
124 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
125 "Remove code block evaluation from the C-c C-c key binding."
130 (defcustom org-babel-results-keyword
"RESULTS"
131 "Keyword used to name results generated by code blocks.
132 Should be either RESULTS or NAME however any capitalization may
137 (defcustom org-babel-noweb-wrap-start
"<<"
138 "String used to begin a noweb reference in a code block.
139 See also `org-babel-noweb-wrap-end'."
143 (defcustom org-babel-noweb-wrap-end
">>"
144 "String used to end a noweb reference in a code block.
145 See also `org-babel-noweb-wrap-start'."
149 (defun org-babel-noweb-wrap (&optional regexp
)
150 (concat org-babel-noweb-wrap-start
151 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
152 org-babel-noweb-wrap-end
))
154 (defvar org-babel-src-name-regexp
155 "^[ \t]*#\\+name:[ \t]*"
156 "Regular expression used to match a source name line.")
158 (defvar org-babel-multi-line-header-regexp
159 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
160 "Regular expression used to match multi-line header arguments.")
162 (defvar org-babel-src-name-w-name-regexp
163 (concat org-babel-src-name-regexp
165 org-babel-multi-line-header-regexp
167 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
168 "Regular expression matching source name lines with a name.")
170 (defvar org-babel-src-block-regexp
172 ;; (1) indentation (2) lang
173 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
175 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
176 ;; (4) header arguments
179 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
180 "Regexp used to identify code blocks.")
182 (defvar org-babel-inline-src-block-regexp
184 ;; (1) replacement target (2) lang
185 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
186 ;; (3,4) (unused, headers)
187 "\\(\\|\\[\\(.*?\\)\\]\\)"
189 "{\\([^\f\n\r\v]+?\\)}\\)")
190 "Regexp used to identify inline src-blocks.")
192 (defun org-babel-get-header (params key
&optional others
)
193 "Select only header argument of type KEY from a list.
194 Optional argument OTHERS indicates that only the header that do
195 not match KEY should be returned."
198 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
201 (defun org-babel-get-inline-src-block-matches()
202 "Set match data if within body of an inline source block.
203 Returns non-nil if match-data set"
204 (let ((src-at-0-p (save-excursion
205 (beginning-of-line 1)
206 (string= "src" (thing-at-point 'word
))))
207 (first-line-p (= 1 (line-number-at-pos)))
209 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
210 (first-line-p "[[:punct:] \t]src_")
211 (t "[[:punct:] \f\t\n\r\v]src_")))
212 (lower-limit (if first-line-p
214 (- (point-at-bol) 1))))
216 (when (or (and src-at-0-p
(bobp))
217 (and (re-search-forward "}" (point-at-eol) t
)
218 (re-search-backward search-for lower-limit t
)
220 (when (looking-at org-babel-inline-src-block-regexp
)
223 (defvar org-babel-inline-lob-one-liner-regexp
)
224 (defun org-babel-get-lob-one-liner-matches()
225 "Set match data if on line of an lob one liner.
226 Returns non-nil if match-data set"
228 (unless (= (point) (point-at-bol)) ;; move before inline block
229 (re-search-backward "[ \f\t\n\r\v]" nil t
))
230 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
234 (defun org-babel-get-src-block-info (&optional light
)
235 "Get information on the current source block.
237 Optional argument LIGHT does not resolve remote variable
238 references; a process which could likely result in the execution
239 of other code blocks.
242 (language body header-arguments-alist switches name indent)."
243 (let ((case-fold-search t
) head info name indent
)
245 (if (setq head
(org-babel-where-is-src-block-head))
248 (setq info
(org-babel-parse-src-block-match))
249 (setq indent
(car (last info
)))
250 (setq info
(butlast info
))
251 (while (and (forward-line -
1)
252 (looking-at org-babel-multi-line-header-regexp
))
254 (org-babel-merge-params
256 (org-babel-parse-header-arguments (match-string 1)))))
257 (when (looking-at org-babel-src-name-w-name-regexp
)
258 (setq name
(org-no-properties (match-string 3)))
259 (when (and (match-string 5) (> (length (match-string 5)) 0))
260 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
261 (org-babel-merge-params
263 (lambda (ref) (cons :var ref
))
265 (lambda (var) ;; check that each variable is initialized
266 (if (string-match ".+=.+" var
)
269 "variable \"%s\"%s must be assigned a default value"
270 var
(if name
(format " in block \"%s\"" name
) ""))))
271 (org-babel-ref-split-args (match-string 5))))
273 ;; inline source block
274 (when (org-babel-get-inline-src-block-matches)
275 (setq info
(org-babel-parse-inline-src-block-match))))
276 ;; resolve variable references and add summary parameters
277 (when (and info
(not light
))
278 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
279 (when info
(append info
(list name indent
)))))
281 (defvar org-current-export-file
) ; dynamically bound
282 (defun org-babel-confirm-evaluate (info)
283 "Confirm evaluation of the code block INFO.
284 This behavior can be suppressed by setting the value of
285 `org-confirm-babel-evaluate' to nil, in which case all future
286 interactive code block evaluations will proceed without any
287 confirmation from the user.
289 Note disabling confirmation may result in accidental evaluation
290 of potentially harmful code."
291 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
292 (when (assoc :noeval
(nth 2 info
)) "no")))
293 (query (cond ((equal eval
"query") t
)
294 ((and (boundp 'org-current-export-file
)
295 org-current-export-file
296 (equal eval
"query-export")) t
)
297 ((functionp org-confirm-babel-evaluate
)
298 (funcall org-confirm-babel-evaluate
299 (nth 0 info
) (nth 1 info
)))
300 (t org-confirm-babel-evaluate
))))
301 (if (or (equal eval
"never") (equal eval
"no")
302 (and (boundp 'org-current-export-file
)
303 org-current-export-file
304 (or (equal eval
"no-export")
305 (equal eval
"never-export")))
308 (format "Evaluate this%scode block%son your system? "
309 (if info
(format " %s " (nth 0 info
)) " ")
311 (format " (%s) " (nth 4 info
)) " "))))))
312 (prog1 nil
(message "Evaluation %s"
313 (if (or (equal eval
"never") (equal eval
"no")
314 (equal eval
"no-export")
315 (equal eval
"never-export"))
316 "Disabled" "Aborted")))
320 (defun org-babel-execute-safely-maybe ()
321 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
322 (org-babel-execute-maybe)))
324 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
327 (defun org-babel-execute-maybe ()
329 (or (org-babel-execute-src-block-maybe)
330 (org-babel-lob-execute-maybe)))
332 (defun org-babel-execute-src-block-maybe ()
333 "Conditionally execute a source block.
334 Detect if this is context for a Babel src-block and if so
335 then run `org-babel-execute-src-block'."
337 (let ((info (org-babel-get-src-block-info)))
339 (progn (org-babel-eval-wipe-error-buffer)
340 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
343 (defun org-babel-view-src-block-info ()
344 "Display information on the current source block.
345 This includes header arguments, language and name, and is largely
346 a window into the `org-babel-get-src-block-info' function."
348 (let ((info (org-babel-get-src-block-info 'light
))
349 (full (lambda (it) (> (length it
) 0)))
350 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
352 (with-help-window (help-buffer)
353 (let ((name (nth 4 info
))
355 (switches (nth 3 info
))
356 (header-args (nth 2 info
)))
357 (when name
(funcall printf
"Name: %s\n" name
))
358 (when lang
(funcall printf
"Lang: %s\n" lang
))
359 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
360 (funcall printf
"Header Arguments:\n")
361 (dolist (pair (sort header-args
362 (lambda (a b
) (string< (symbol-name (car a
))
363 (symbol-name (car b
))))))
364 (when (funcall full
(cdr pair
))
365 (funcall printf
"\t%S%s\t%s\n"
367 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
371 (defun org-babel-expand-src-block-maybe ()
372 "Conditionally expand a source block.
373 Detect if this is context for a org-babel src-block and if so
374 then run `org-babel-expand-src-block'."
376 (let ((info (org-babel-get-src-block-info)))
378 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
382 (defun org-babel-load-in-session-maybe ()
383 "Conditionally load a source block in a session.
384 Detect if this is context for a org-babel src-block and if so
385 then run `org-babel-load-in-session'."
387 (let ((info (org-babel-get-src-block-info)))
389 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
392 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
395 (defun org-babel-pop-to-session-maybe ()
396 "Conditionally pop to a session.
397 Detect if this is context for a org-babel src-block and if so
398 then run `org-babel-pop-to-session'."
400 (let ((info (org-babel-get-src-block-info)))
401 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
403 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
405 (defconst org-babel-common-header-args-w-values
406 '((cache .
((no yes
)))
408 (colnames .
((nil no yes
)))
409 (comments .
((no link yes org both noweb
)))
411 (eval .
((never query
)))
412 (exports .
((code results both none
)))
415 (hlines .
((no yes
)))
416 (mkdirp .
((yes no
)))
419 (noweb .
((yes no tangle no-export strip-export
)))
422 (padline .
((yes no
)))
423 (results .
((file list vector table scalar verbatim
)
424 (raw html latex org code pp drawer
)
425 (replace silent append prepend
)
427 (rownames .
((no yes
)))
431 (tangle .
((tangle yes no
:any
)))
435 (defconst org-babel-header-arg-names
436 (mapcar #'car org-babel-common-header-args-w-values
)
437 "Common header arguments used by org-babel.
438 Note that individual languages may define their own language
439 specific header arguments as well.")
441 (defvar org-babel-default-header-args
442 '((:session .
"none") (:results .
"replace") (:exports .
"code")
443 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
444 (:padnewline .
"yes"))
445 "Default arguments to use when evaluating a source block.")
447 (defvar org-babel-default-inline-header-args
448 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
449 "Default arguments to use when evaluating an inline source block.")
451 (defvar org-babel-data-names
'("tblname" "results" "name"))
453 (defvar org-babel-result-regexp
454 (concat "^[ \t]*#\\+"
455 (regexp-opt org-babel-data-names t
)
456 "\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
457 "Regular expression used to match result lines.
458 If the results are associated with a hash key then the hash will
459 be saved in the second match data.")
461 (defvar org-babel-result-w-name-regexp
462 (concat org-babel-result-regexp
463 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
465 (defvar org-babel-min-lines-for-block-output
10
466 "The minimum number of lines for block output.
467 If number of lines of output is equal to or exceeds this
468 value, the output is placed in a #+begin_example...#+end_example
469 block. Otherwise the output is marked as literal by inserting
470 colons at the starts of the lines. This variable only takes
471 effect if the :results output option is in effect.")
473 (defvar org-babel-noweb-error-langs nil
474 "Languages for which Babel will raise literate programming errors.
475 List of languages for which errors should be raised when the
476 source code block satisfying a noweb reference in this language
477 can not be resolved.")
479 (defvar org-babel-hash-show
4
480 "Number of initial characters to show of a hidden results hash.")
482 (defvar org-babel-after-execute-hook nil
483 "Hook for functions to be called after `org-babel-execute-src-block'")
485 (defun org-babel-named-src-block-regexp-for-name (name)
486 "This generates a regexp used to match a src block named NAME."
487 (concat org-babel-src-name-regexp
(regexp-quote name
)
488 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
489 (substring org-babel-src-block-regexp
1)))
491 (defun org-babel-named-data-regexp-for-name (name)
492 "This generates a regexp used to match data named NAME."
493 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
496 (defvar call-process-region
)
499 (defun org-babel-execute-src-block (&optional arg info params
)
500 "Execute the current source code block.
501 Insert the results of execution into the buffer. Source code
502 execution and the collection and formatting of results can be
503 controlled through a variety of header arguments.
505 With prefix argument ARG, force re-execution even if an existing
506 result cached in the buffer would otherwise have been returned.
508 Optionally supply a value for INFO in the form returned by
509 `org-babel-get-src-block-info'.
511 Optionally supply a value for PARAMS which will be merged with
512 the header arguments specified at the front of the source code
515 (let ((info (or info
(org-babel-get-src-block-info))))
516 (when (org-babel-confirm-evaluate
518 (setf (nth 2 i
) (org-babel-merge-params (nth 2 info
) params
))
520 (let* ((lang (nth 0 info
))
522 (org-babel-process-params
523 (org-babel-merge-params (nth 2 info
) params
))
525 (cache?
(and (not arg
) (cdr (assoc :cache params
))
526 (string= "yes" (cdr (assoc :cache params
)))))
527 (result-params (cdr (assoc :result-params params
)))
528 (new-hash (when cache?
(org-babel-sha1-hash info
)))
529 (old-hash (when cache?
(org-babel-current-result-hash)))
530 (body (setf (nth 1 info
)
531 (if (org-babel-noweb-p params
:eval
)
532 (org-babel-expand-noweb-references info
)
534 (dir (cdr (assoc :dir params
)))
536 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
538 (org-babel-call-process-region-original
539 (if (boundp 'org-babel-call-process-region-original
)
540 org-babel-call-process-region-original
541 (symbol-function 'call-process-region
)))
542 (indent (car (last info
)))
545 (let ((call-process-region
547 (apply 'org-babel-tramp-handle-call-process-region args
))))
548 (let ((lang-check (lambda (f)
549 (let ((f (intern (concat "org-babel-execute:" f
))))
550 (when (fboundp f
) f
)))))
552 (or (funcall lang-check lang
)
553 (funcall lang-check
(symbol-name
554 (cdr (assoc lang org-src-lang-modes
))))
555 (error "No org-babel-execute function for %s!" lang
))))
556 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
557 (save-excursion ;; return cached result
558 (goto-char (org-babel-where-is-src-block-result nil info
))
559 (end-of-line 1) (forward-char 1)
560 (setq result
(org-babel-read-result))
561 (message (replace-regexp-in-string
562 "%" "%%" (format "%S" result
))) result
)
563 (message "executing %s code block%s..."
565 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
568 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
569 (or (member "vector" result-params
)
570 (member "table" result-params
))
571 (not (listp result
)))
572 (list (list result
)) result
))
573 (funcall cmd body params
)))
574 ;; if non-empty result and :file then write to :file
575 (when (cdr (assoc :file params
))
577 (with-temp-file (cdr (assoc :file params
))
579 (org-babel-format-result
580 result
(cdr (assoc :sep
(nth 2 info
)))))))
581 (setq result
(cdr (assoc :file params
))))
582 (org-babel-insert-result
583 result result-params info new-hash indent lang
)
584 (run-hooks 'org-babel-after-execute-hook
)
586 (setq call-process-region
'org-babel-call-process-region-original
))))))
588 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
589 "Expand BODY with PARAMS.
590 Expand a block of code with org-babel according to its header
591 arguments. This generic implementation of body expansion is
592 called for languages which have not defined their own specific
593 org-babel-expand-body:lang function."
594 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
597 (defun org-babel-expand-src-block (&optional arg info params
)
598 "Expand the current source code block.
599 Expand according to the source code block's header
600 arguments and pop open the results in a preview buffer."
602 (let* ((info (or info
(org-babel-get-src-block-info)))
604 (params (setf (nth 2 info
)
605 (sort (org-babel-merge-params (nth 2 info
) params
)
606 (lambda (el1 el2
) (string< (symbol-name (car el1
))
607 (symbol-name (car el2
)))))))
608 (body (setf (nth 1 info
)
609 (if (org-babel-noweb-p params
:eval
)
610 (org-babel-expand-noweb-references info
) (nth 1 info
))))
611 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
612 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
615 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
616 (org-babel-expand-body:generic
617 body params
(and (fboundp assignments-cmd
)
618 (funcall assignments-cmd params
))))))
620 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
622 (defun org-babel-edit-distance (s1 s2
)
623 "Return the edit (levenshtein) distance between strings S1 S2."
624 (let* ((l1 (length s1
))
626 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
627 (number-sequence 1 (1+ l1
)))))
628 (in (lambda (i j
) (aref (aref dist i
) j
)))
629 (mmin (lambda (&rest lst
) (apply #'min
(remove nil lst
)))))
630 (setf (aref (aref dist
0) 0) 0)
631 (dolist (i (number-sequence 1 l1
))
632 (dolist (j (number-sequence 1 l2
))
633 (setf (aref (aref dist i
) j
)
634 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
635 (funcall mmin
(funcall in
(1- i
) j
)
636 (funcall in i
(1- j
))
637 (funcall in
(1- i
) (1- j
)))))))
640 (defun org-babel-combine-header-arg-lists (original &rest others
)
641 "Combine a number of lists of header argument names and arguments."
642 (let ((results (copy-sequence original
)))
643 (dolist (new-list others
)
644 (dolist (arg-pair new-list
)
645 (let ((header (car arg-pair
))
646 (args (cdr arg-pair
)))
648 (cons arg-pair
(org-remove-if
649 (lambda (pair) (equal header
(car pair
)))
654 (defun org-babel-check-src-block ()
655 "Check for misspelled header arguments in the current code block."
657 ;; TODO: report malformed code block
658 ;; TODO: report incompatible combinations of header arguments
659 ;; TODO: report uninitialized variables
660 (let ((too-close 2) ;; <- control closeness to report potential match
661 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
662 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
663 (and (org-babel-where-is-src-block-head)
664 (org-babel-parse-header-arguments
666 (match-string 4))))))
668 (when (and (not (string= header name
))
669 (<= (org-babel-edit-distance header name
) too-close
)
670 (not (member header names
)))
671 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
673 (message "No suspicious header arguments found.")))
676 (defun org-babel-insert-header-arg ()
677 "Insert a header argument selecting from lists of common args and values."
679 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
680 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
681 (headers (org-babel-combine-header-arg-lists
682 org-babel-common-header-args-w-values
683 (if (boundp lang-headers
) (eval lang-headers
) nil
)))
684 (arg (org-icompleting-read
687 (lambda (header-spec) (symbol-name (car header-spec
)))
690 (let ((vals (cdr (assoc (intern arg
) headers
))))
696 (read-from-minibuffer "value: "))
700 (let ((arg (org-icompleting-read
702 (cons "default" (mapcar #'symbol-name group
)))))
703 (if (and arg
(not (string= "default" arg
)))
708 ;; Add support for completing-read insertion of header arguments after ":"
709 (defun org-babel-header-arg-expand ()
710 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
711 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
712 (org-babel-enter-header-arg-w-completion (match-string 2))))
714 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
715 "Insert header argument appropriate for LANG with completion."
716 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
717 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
718 (headers-w-values (org-babel-combine-header-arg-lists
719 org-babel-common-header-args-w-values lang-headers
))
720 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
721 (header (org-completing-read "Header Arg: " headers
))
722 (args (cdr (assoc (intern header
) headers-w-values
)))
723 (arg (when (and args
(listp args
))
725 (format "%s: " header
)
726 (mapcar #'symbol-name
(apply #'append args
))))))
727 (insert (concat header
" " (or arg
"")))
730 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
733 (defun org-babel-load-in-session (&optional arg info
)
734 "Load the body of the current source-code block.
735 Evaluate the header arguments for the source block before
736 entering the session. After loading the body this pops open the
739 (let* ((info (or info
(org-babel-get-src-block-info)))
741 (params (nth 2 info
))
742 (body (setf (nth 1 info
)
743 (if (org-babel-noweb-p params
:eval
)
744 (org-babel-expand-noweb-references info
)
746 (session (cdr (assoc :session params
)))
747 (dir (cdr (assoc :dir params
)))
749 (or (and dir
(file-name-as-directory dir
)) default-directory
))
750 (cmd (intern (concat "org-babel-load-session:" lang
))))
751 (unless (fboundp cmd
)
752 (error "No org-babel-load-session function for %s!" lang
))
753 (pop-to-buffer (funcall cmd session body params
))
757 (defun org-babel-initiate-session (&optional arg info
)
758 "Initiate session for current code block.
759 If called with a prefix argument then resolve any variable
760 references in the header arguments and assign these variables in
761 the session. Copy the body of the code block to the kill ring."
763 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
766 (params (nth 2 info
))
767 (session (cdr (assoc :session params
)))
768 (dir (cdr (assoc :dir params
)))
770 (or (and dir
(file-name-as-directory dir
)) default-directory
))
771 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
772 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
773 (if (and (stringp session
) (string= session
"none"))
774 (error "This block is not using a session!"))
775 (unless (fboundp init-cmd
)
776 (error "No org-babel-initiate-session function for %s!" lang
))
777 (with-temp-buffer (insert (org-babel-trim body
))
778 (copy-region-as-kill (point-min) (point-max)))
780 (unless (fboundp prep-cmd
)
781 (error "No org-babel-prep-session function for %s!" lang
))
782 (funcall prep-cmd session params
))
783 (funcall init-cmd session params
)))
786 (defun org-babel-switch-to-session (&optional arg info
)
787 "Switch to the session of the current code block.
788 Uses `org-babel-initiate-session' to start the session. If called
789 with a prefix argument then this is passed on to
790 `org-babel-initiate-session'."
792 (pop-to-buffer (org-babel-initiate-session arg info
))
795 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
798 (defun org-babel-switch-to-session-with-code (&optional arg info
)
799 "Switch to code buffer and display session."
803 (let ((other-window-buffer (window-buffer (next-window))))
804 (set-window-buffer (next-window) (current-buffer))
805 (set-window-buffer (selected-window) other-window-buffer
))
807 (info (org-babel-get-src-block-info))
808 (org-src-window-setup 'reorganize-frame
))
810 (org-babel-switch-to-session arg info
))
812 (funcall swap-windows
)))
814 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
815 "Evaluate BODY in edit buffer if there is a code block at point.
816 Return t if a code block was found at point, nil otherwise."
817 `(let ((org-src-window-setup 'switch-invisibly
))
818 (when (and (org-babel-where-is-src-block-head)
819 (org-edit-src-code nil nil nil
))
820 (unwind-protect (progn ,@body
)
821 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
822 (org-edit-src-exit)))
824 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
826 (defun org-babel-do-key-sequence-in-edit-buffer (key)
827 "Read key sequence and execute the command in edit buffer.
828 Enter a key sequence to be executed in the language major-mode
829 edit buffer. For example, TAB will alter the contents of the
830 Org-mode code block according to the effect of TAB in the
831 language major-mode buffer. For languages that support
832 interactive sessions, this can be used to send code from the Org
833 buffer to the session for evaluation using the native major-mode
834 evaluation mechanisms."
835 (interactive "kEnter key-sequence to execute in edit buffer: ")
836 (org-babel-do-in-edit-buffer
838 (key-binding (or key
(read-key-sequence nil
))))))
840 (defvar org-bracket-link-regexp
)
842 (defun org-babel-open-src-block-result (&optional re-run
)
843 "If `point' is on a src block then open the results of the
844 source code block, otherwise return nil. With optional prefix
845 argument RE-RUN the source-code block is evaluated even if
846 results already exist."
848 (let ((info (org-babel-get-src-block-info)))
851 ;; go to the results, if there aren't any then run the block
852 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
853 (progn (org-babel-execute-src-block)
854 (org-babel-where-is-src-block-result))))
856 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
858 (if (looking-at org-bracket-link-regexp
)
861 (let ((r (org-babel-format-result
862 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
863 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
864 (delete-region (point-min) (point-max))
869 (defmacro org-babel-map-src-blocks
(file &rest body
)
870 "Evaluate BODY forms on each source-block in FILE.
871 If FILE is nil evaluate BODY forms on source blocks in current
872 buffer. During evaluation of BODY the following local variables
873 are set relative to the currently matched code block.
875 full-block ------- string holding the entirety of the code block
876 beg-block -------- point at the beginning of the code block
877 end-block -------- point at the end of the matched code block
878 lang ------------- string holding the language of the code block
879 beg-lang --------- point at the beginning of the lang
880 end-lang --------- point at the end of the lang
881 switches --------- string holding the switches
882 beg-switches ----- point at the beginning of the switches
883 end-switches ----- point at the end of the switches
884 header-args ------ string holding the header-args
885 beg-header-args -- point at the beginning of the header-args
886 end-header-args -- point at the end of the header-args
887 body ------------- string holding the body of the code block
888 beg-body --------- point at the beginning of the body
889 end-body --------- point at the end of the body"
891 (let ((tempvar (make-symbol "file")))
892 `(let* ((,tempvar
,file
)
893 (visited-p (or (null ,tempvar
)
894 (get-file-buffer (expand-file-name ,tempvar
))))
895 (point (point)) to-be-removed
)
896 (save-window-excursion
897 (when ,tempvar
(find-file ,tempvar
))
898 (setq to-be-removed
(current-buffer))
899 (goto-char (point-min))
900 (while (re-search-forward org-babel-src-block-regexp nil t
)
901 (goto-char (match-beginning 0))
902 (let ((full-block (match-string 0))
903 (beg-block (match-beginning 0))
904 (end-block (match-end 0))
905 (lang (match-string 2))
906 (beg-lang (match-beginning 2))
907 (end-lang (match-end 2))
908 (switches (match-string 3))
909 (beg-switches (match-beginning 3))
910 (end-switches (match-end 3))
911 (header-args (match-string 4))
912 (beg-header-args (match-beginning 4))
913 (end-header-args (match-end 4))
914 (body (match-string 5))
915 (beg-body (match-beginning 5))
916 (end-body (match-end 5)))
918 (goto-char end-block
))))
919 (unless visited-p
(kill-buffer to-be-removed
))
921 (def-edebug-spec org-babel-map-src-blocks
(form body
))
924 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
925 "Evaluate BODY forms on each inline source-block in FILE.
926 If FILE is nil evaluate BODY forms on source blocks in current
929 (let ((tempvar (make-symbol "file")))
930 `(let* ((,tempvar
,file
)
931 (visited-p (or (null ,tempvar
)
932 (get-file-buffer (expand-file-name ,tempvar
))))
933 (point (point)) to-be-removed
)
934 (save-window-excursion
935 (when ,tempvar
(find-file ,tempvar
))
936 (setq to-be-removed
(current-buffer))
937 (goto-char (point-min))
938 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
939 (goto-char (match-beginning 1))
940 (save-match-data ,@body
)
941 (goto-char (match-end 0))))
942 (unless visited-p
(kill-buffer to-be-removed
))
944 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
946 (defvar org-babel-lob-one-liner-regexp
)
948 (defmacro org-babel-map-call-lines
(file &rest body
)
949 "Evaluate BODY forms on each call line in FILE.
950 If FILE is nil evaluate BODY forms on source blocks in current
953 (let ((tempvar (make-symbol "file")))
954 `(let* ((,tempvar
,file
)
955 (visited-p (or (null ,tempvar
)
956 (get-file-buffer (expand-file-name ,tempvar
))))
957 (point (point)) to-be-removed
)
958 (save-window-excursion
959 (when ,tempvar
(find-file ,tempvar
))
960 (setq to-be-removed
(current-buffer))
961 (goto-char (point-min))
962 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
963 (goto-char (match-beginning 1))
964 (save-match-data ,@body
)
965 (goto-char (match-end 0))))
966 (unless visited-p
(kill-buffer to-be-removed
))
968 (def-edebug-spec org-babel-map-call-lines
(form body
))
971 (defmacro org-babel-map-executables
(file &rest body
)
973 (let ((tempvar (make-symbol "file"))
974 (rx (make-symbol "rx")))
975 `(let* ((,tempvar
,file
)
976 (,rx
(concat "\\(" org-babel-src-block-regexp
977 "\\|" org-babel-inline-src-block-regexp
978 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
979 (visited-p (or (null ,tempvar
)
980 (get-file-buffer (expand-file-name ,tempvar
))))
981 (point (point)) to-be-removed
)
982 (save-window-excursion
983 (when ,tempvar
(find-file ,tempvar
))
984 (setq to-be-removed
(current-buffer))
985 (goto-char (point-min))
986 (while (re-search-forward ,rx nil t
)
987 (goto-char (match-beginning 1))
988 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
989 (save-match-data ,@body
)
990 (goto-char (match-end 0))))
991 (unless visited-p
(kill-buffer to-be-removed
))
993 (def-edebug-spec org-babel-map-executables
(form body
))
996 (defun org-babel-execute-buffer (&optional arg
)
997 "Execute source code blocks in a buffer.
998 Call `org-babel-execute-src-block' on every source block in
1001 (org-babel-eval-wipe-error-buffer)
1002 (org-save-outline-visibility t
1003 (org-babel-map-executables nil
1004 (if (looking-at org-babel-lob-one-liner-regexp
)
1005 (org-babel-lob-execute-maybe)
1006 (org-babel-execute-src-block arg
)))))
1009 (defun org-babel-execute-subtree (&optional arg
)
1010 "Execute source code blocks in a subtree.
1011 Call `org-babel-execute-src-block' on every source block in
1012 the current subtree."
1016 (org-narrow-to-subtree)
1017 (org-babel-execute-buffer arg
)
1021 (defun org-babel-sha1-hash (&optional info
)
1022 "Generate an sha1 hash based on the value of info."
1024 (let ((print-level nil
)
1025 (info (or info
(org-babel-get-src-block-info))))
1027 (sort (copy-sequence (nth 2 info
))
1028 (lambda (a b
) (string< (car a
) (car b
)))))
1029 (let* ((rm (lambda (lst)
1030 (dolist (p '("replace" "silent" "append" "prepend"))
1031 (setq lst
(remove p lst
)))
1034 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1035 (copy-sequence (cdr arg
))
1037 (when (and v
(not (and (sequencep v
)
1041 ((and (listp v
) ; lists are sorted
1042 (member (car arg
) '(:result-params
)))
1043 (sort (funcall rm v
) #'string
<))
1044 ((and (stringp v
) ; strings are sorted
1045 (member (car arg
) '(:results
:exports
)))
1046 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1050 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
1051 (let ((it (format "%s-%s"
1054 (delq nil
(mapcar (lambda (arg)
1055 (let ((normalized (funcall norm arg
)))
1057 (format "%S" normalized
))))
1062 (defun org-babel-current-result-hash ()
1063 "Return the current in-buffer hash."
1064 (org-babel-where-is-src-block-result)
1065 (org-no-properties (match-string 3)))
1067 (defun org-babel-set-current-result-hash (hash)
1068 "Set the current in-buffer hash to HASH."
1069 (org-babel-where-is-src-block-result)
1070 (save-excursion (goto-char (match-beginning 3))
1071 ;; (mapc #'delete-overlay (overlays-at (point)))
1072 (replace-match hash nil nil nil
3)
1073 (org-babel-hide-hash)))
1075 (defun org-babel-hide-hash ()
1076 "Hide the hash in the current results line.
1077 Only the initial `org-babel-hash-show' characters of the hash
1078 will remain visible."
1079 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1081 (when (and (re-search-forward org-babel-result-regexp nil t
)
1083 (let* ((start (match-beginning 3))
1084 (hide-start (+ org-babel-hash-show start
))
1086 (hash (match-string 3))
1088 (setq ov1
(make-overlay start hide-start
))
1089 (setq ov2
(make-overlay hide-start end
))
1090 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1091 (overlay-put ov1
'babel-hash hash
)))))
1093 (defun org-babel-hide-all-hashes ()
1094 "Hide the hash in the current buffer.
1095 Only the initial `org-babel-hash-show' characters of each hash
1096 will remain visible. This function should be called as part of
1097 the `org-mode-hook'."
1099 (while (re-search-forward org-babel-result-regexp nil t
)
1100 (goto-char (match-beginning 0))
1101 (org-babel-hide-hash)
1102 (goto-char (match-end 0)))))
1103 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1105 (defun org-babel-hash-at-point (&optional point
)
1106 "Return the value of the hash at POINT.
1107 The hash is also added as the last element of the kill ring.
1108 This can be called with C-c C-c."
1110 (let ((hash (car (delq nil
(mapcar
1111 (lambda (ol) (overlay-get ol
'babel-hash
))
1112 (overlays-at (or point
(point))))))))
1113 (when hash
(kill-new hash
) (message hash
))))
1114 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1116 (defun org-babel-result-hide-spec ()
1117 "Hide portions of results lines.
1118 Add `org-babel-hide-result' as an invisibility spec for hiding
1119 portions of results lines."
1120 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1121 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1123 (defvar org-babel-hide-result-overlays nil
1124 "Overlays hiding results.")
1126 (defun org-babel-result-hide-all ()
1127 "Fold all results in the current buffer."
1129 (org-babel-show-result-all)
1131 (while (re-search-forward org-babel-result-regexp nil t
)
1132 (save-excursion (goto-char (match-beginning 0))
1133 (org-babel-hide-result-toggle-maybe)))))
1135 (defun org-babel-show-result-all ()
1136 "Unfold all results in the current buffer."
1137 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1138 (setq org-babel-hide-result-overlays nil
))
1141 (defun org-babel-hide-result-toggle-maybe ()
1142 "Toggle visibility of result at point."
1144 (let ((case-fold-search t
))
1146 (beginning-of-line 1)
1147 (looking-at org-babel-result-regexp
))
1148 (progn (org-babel-hide-result-toggle)
1149 t
) ;; to signal that we took action
1150 nil
))) ;; to signal that we did not
1152 (defun org-babel-hide-result-toggle (&optional force
)
1153 "Toggle the visibility of the current result."
1157 (if (re-search-forward org-babel-result-regexp nil t
)
1158 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1160 (while (looking-at org-babel-multi-line-header-regexp
)
1162 (goto-char (- (org-babel-result-end) 1)) (point)))
1164 (if (memq t
(mapcar (lambda (overlay)
1165 (eq (overlay-get overlay
'invisible
)
1166 'org-babel-hide-result
))
1167 (overlays-at start
)))
1168 (if (or (not force
) (eq force
'off
))
1170 (when (member ov org-babel-hide-result-overlays
)
1171 (setq org-babel-hide-result-overlays
1172 (delq ov org-babel-hide-result-overlays
)))
1173 (when (eq (overlay-get ov
'invisible
)
1174 'org-babel-hide-result
)
1175 (delete-overlay ov
)))
1176 (overlays-at start
)))
1177 (setq ov
(make-overlay start end
))
1178 (overlay-put ov
'invisible
'org-babel-hide-result
)
1179 ;; make the block accessible to isearch
1181 ov
'isearch-open-invisible
1183 (when (member ov org-babel-hide-result-overlays
)
1184 (setq org-babel-hide-result-overlays
1185 (delq ov org-babel-hide-result-overlays
)))
1186 (when (eq (overlay-get ov
'invisible
)
1187 'org-babel-hide-result
)
1188 (delete-overlay ov
))))
1189 (push ov org-babel-hide-result-overlays
)))
1190 (error "Not looking at a result line"))))
1192 ;; org-tab-after-check-for-cycling-hook
1193 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1194 ;; Remove overlays when changing major mode
1195 (add-hook 'org-mode-hook
1196 (lambda () (org-add-hook 'change-major-mode-hook
1197 'org-babel-show-result-all
'append
'local
)))
1199 (defvar org-file-properties
)
1200 (defun org-babel-params-from-properties (&optional lang
)
1201 "Retrieve parameters specified as properties.
1202 Return an association list of any source block params which
1203 may be specified in the properties of the current outline entry."
1206 (org-babel-parse-multiple-vars
1209 (lambda (header-arg)
1210 (and (setq val
(org-entry-get (point) header-arg t
))
1211 (cons (intern (concat ":" header-arg
))
1212 (org-babel-read val
))))
1217 (org-babel-combine-header-arg-lists
1218 org-babel-common-header-args-w-values
1220 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1221 (and (boundp sym
) (eval sym
))))))))))))
1223 (defvar org-src-preserve-indentation
)
1224 (defun org-babel-parse-src-block-match ()
1225 "Parse the results from a match of the `org-babel-src-block-regexp'."
1226 (let* ((block-indentation (length (match-string 1)))
1227 (lang (org-no-properties (match-string 2)))
1228 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1229 (switches (match-string 3))
1230 (body (org-no-properties
1231 (let* ((body (match-string 5))
1232 (sub-length (- (length body
) 1)))
1233 (if (and (> sub-length
0)
1234 (string= "\n" (substring body sub-length
)))
1235 (substring body
0 sub-length
)
1237 (preserve-indentation (or org-src-preserve-indentation
1239 (string-match "-i\\>" switches
)))))
1241 ;; get block body less properties, protective commas, and indentation
1244 (insert (org-babel-strip-protective-commas body lang
))
1245 (unless preserve-indentation
(org-do-remove-indentation))
1247 (org-babel-merge-params
1248 org-babel-default-header-args
1249 (org-babel-params-from-properties lang
)
1250 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1251 (org-babel-parse-header-arguments
1252 (org-no-properties (or (match-string 4) ""))))
1254 block-indentation
)))
1256 (defun org-babel-parse-inline-src-block-match ()
1257 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1258 (let* ((lang (org-no-properties (match-string 2)))
1259 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1261 (org-babel-strip-protective-commas
1262 (org-no-properties (match-string 5)) lang
)
1263 (org-babel-merge-params
1264 org-babel-default-inline-header-args
1265 (org-babel-params-from-properties lang
)
1266 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1267 (org-babel-parse-header-arguments
1268 (org-no-properties (or (match-string 4) "")))))))
1270 (defun org-babel-balanced-split (string alts
)
1271 "Split STRING on instances of ALTS.
1272 ALTS is a cons of two character options where each option may be
1273 either the numeric code of a single character or a list of
1274 character alternatives. For example to split on balanced
1275 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1276 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1277 (matched (lambda (ch last
)
1279 (and (funcall matches ch
(cdr alts
))
1280 (funcall matches last
(car alts
)))
1281 (funcall matches ch alts
))))
1282 (balance 0) (last 0)
1284 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1285 (setq balance
(+ balance
1286 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1287 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1289 (when (and (equal 34 ch
) (not (equal 92 last
)))
1290 (setq quote
(not quote
)))
1291 (setq partial
(cons ch partial
))
1292 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1293 (setq lst
(cons (apply #'string
(nreverse
1300 (string-to-list string
))
1301 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1303 (defun org-babel-join-splits-near-ch (ch list
)
1304 "Join splits where \"=\" is on either end of the split."
1305 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1306 (first= (lambda (str) (= ch
(aref str
0)))))
1308 (org-reduce (lambda (acc el
)
1309 (let ((head (car acc
)))
1310 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1311 (cons (concat head el
) (cdr acc
))
1313 list
:initial-value nil
))))
1315 (defun org-babel-parse-header-arguments (arg-string)
1316 "Parse a string of header arguments returning an alist."
1317 (when (> (length arg-string
) 0)
1318 (org-babel-parse-multiple-vars
1323 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1325 (cons (intern (match-string 1 arg
))
1326 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1327 (cons (intern (org-babel-chomp arg
)) nil
)))
1329 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1330 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1332 (defun org-babel-parse-multiple-vars (header-arguments)
1333 "Expand multiple variable assignments behind a single :var keyword.
1335 This allows expression of multiple variables with one :var as
1338 #+PROPERTY: var foo=1, bar=2"
1340 (mapc (lambda (pair)
1341 (if (eq (car pair
) :var
)
1342 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1343 (org-babel-join-splits-near-ch
1344 61 (org-babel-balanced-split (cdr pair
) 32)))
1345 (push pair results
)))
1347 (nreverse results
)))
1349 (defun org-babel-process-params (params)
1350 "Expand variables in PARAMS and add summary parameters."
1351 (let* ((processed-vars (mapcar (lambda (el)
1352 (if (consp (cdr el
))
1354 (org-babel-ref-parse (cdr el
))))
1355 (org-babel-get-header params
:var
)))
1356 (vars-and-names (if (and (assoc :colname-names params
)
1357 (assoc :rowname-names params
))
1358 (list processed-vars
)
1359 (org-babel-disassemble-tables
1361 (cdr (assoc :hlines params
))
1362 (cdr (assoc :colnames params
))
1363 (cdr (assoc :rownames params
)))))
1364 (raw-result (or (cdr (assoc :results params
)) ""))
1365 (result-params (append
1366 (split-string (if (stringp raw-result
)
1369 (cdr (assoc :result-params params
)))))
1371 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1373 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1374 (cadr vars-and-names
)))
1375 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1376 (caddr vars-and-names
)))
1377 (cons :result-params result-params
)
1378 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1379 ((member "value" result-params
) 'value
)
1381 (org-babel-get-header params
:var
'other
))))
1383 ;; row and column names
1384 (defun org-babel-del-hlines (table)
1385 "Remove all 'hlines from TABLE."
1386 (remove 'hline table
))
1388 (defun org-babel-get-colnames (table)
1389 "Return the column names of TABLE.
1390 Return a cons cell, the `car' of which contains the TABLE less
1391 colnames, and the `cdr' of which contains a list of the column
1393 (if (equal 'hline
(nth 1 table
))
1394 (cons (cddr table
) (car table
))
1395 (cons (cdr table
) (car table
))))
1397 (defun org-babel-get-rownames (table)
1398 "Return the row names of TABLE.
1399 Return a cons cell, the `car' of which contains the TABLE less
1400 colnames, and the `cdr' of which contains a list of the column
1401 names. Note: this function removes any hlines in TABLE."
1402 (let* ((trans (lambda (table) (apply #'mapcar
* #'list table
)))
1404 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1405 (table (funcall trans
(mapcar (lambda (row)
1406 (if (not (equal row
'hline
))
1410 (setq row
(cons 'hline row
)))
1413 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1414 (funcall trans
(cdr table
)))
1415 (remove 'hline
(car table
)))))
1417 (defun org-babel-put-colnames (table colnames
)
1418 "Add COLNAMES to TABLE if they exist."
1419 (if colnames
(apply 'list colnames
'hline table
) table
))
1421 (defun org-babel-put-rownames (table rownames
)
1422 "Add ROWNAMES to TABLE if they exist."
1424 (mapcar (lambda (row)
1426 (cons (or (pop rownames
) "") row
)
1430 (defun org-babel-pick-name (names selector
)
1431 "Select one out of an alist of row or column names.
1432 SELECTOR can be either a list of names in which case those names
1433 will be returned directly, or an index into the list NAMES in
1434 which case the indexed names will be return."
1435 (if (listp selector
)
1438 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1439 (cdr (assoc selector names
))
1440 (if (integerp selector
)
1441 (nth (- selector
1) names
)
1442 (cdr (car (last names
))))))))
1444 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1445 "Parse tables for further processing.
1446 Process the variables in VARS according to the HLINES,
1447 ROWNAMES and COLNAMES header arguments. Return a list consisting
1448 of the vars, cnames and rnames."
1449 (let (cnames rnames
)
1453 (when (listp (cdr var
))
1454 (when (and (not (equal colnames
"no"))
1455 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1456 (not (member 'hline
(cddr (cdr var
)))))))
1457 (let ((both (org-babel-get-colnames (cdr var
))))
1458 (setq cnames
(cons (cons (car var
) (cdr both
))
1460 (setq var
(cons (car var
) (car both
)))))
1461 (when (and rownames
(not (equal rownames
"no")))
1462 (let ((both (org-babel-get-rownames (cdr var
))))
1463 (setq rnames
(cons (cons (car var
) (cdr both
))
1465 (setq var
(cons (car var
) (car both
)))))
1466 (when (and hlines
(not (equal hlines
"yes")))
1467 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1470 (reverse cnames
) (reverse rnames
))))
1472 (defun org-babel-reassemble-table (table colnames rownames
)
1473 "Add column and row names to a table.
1474 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1475 to the table for reinsertion to org-mode."
1478 (if (and colnames
(listp (car table
)) (= (length (car table
))
1480 (org-babel-put-colnames table colnames
) table
))
1481 (if (and rownames
(= (length table
) (length rownames
)))
1482 (org-babel-put-rownames table rownames
) table
))
1485 (defun org-babel-where-is-src-block-head ()
1486 "Find where the current source block begins.
1487 Return the point at the beginning of the current source
1488 block. Specifically at the beginning of the #+BEGIN_SRC line.
1489 If the point is not on a source block then return nil."
1490 (let ((initial (point)) (case-fold-search t
) top bottom
)
1492 (save-excursion ;; on a source name line or a #+header line
1493 (beginning-of-line 1)
1494 (and (or (looking-at org-babel-src-name-regexp
)
1495 (looking-at org-babel-multi-line-header-regexp
))
1497 (while (and (forward-line 1)
1498 (or (looking-at org-babel-src-name-regexp
)
1499 (looking-at org-babel-multi-line-header-regexp
))))
1500 (looking-at org-babel-src-block-regexp
))
1502 (save-excursion ;; on a #+begin_src line
1503 (beginning-of-line 1)
1504 (and (looking-at org-babel-src-block-regexp
)
1506 (save-excursion ;; inside a src block
1508 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1509 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1510 (< top initial
) (< initial bottom
)
1511 (progn (goto-char top
) (beginning-of-line 1)
1512 (looking-at org-babel-src-block-regexp
))
1516 (defun org-babel-goto-src-block-head ()
1517 "Go to the beginning of the current code block."
1520 (if head
(goto-char head
) (error "Not currently in a code block")))
1521 (org-babel-where-is-src-block-head)))
1524 (defun org-babel-goto-named-src-block (name)
1525 "Go to a named source-code block."
1527 (let ((completion-ignore-case t
)
1528 (case-fold-search t
)
1529 (under-point (thing-at-point 'line
)))
1530 (list (org-icompleting-read
1531 "source-block name: " (org-babel-src-block-names) nil t
1534 ((string-match (org-babel-noweb-wrap) under-point
)
1535 (let ((block-name (match-string 1 under-point
)))
1536 (string-match "[^(]*" block-name
)
1537 (match-string 0 block-name
)))
1539 ((string-match org-babel-lob-one-liner-regexp under-point
)
1540 (let ((source-info (car (org-babel-lob-get-info))))
1541 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1542 (let ((source-name (match-string 1 source-info
)))
1545 ((string-match (concat "#\\+" org-babel-results-keyword
1546 "\\:\s+\\([^\\(]*\\)") under-point
)
1547 (match-string 1 under-point
))
1549 ((and (thing-at-point 'symbol
))
1550 (org-babel-find-named-block (thing-at-point 'symbol
))
1551 (thing-at-point 'symbol
))
1553 (let ((point (org-babel-find-named-block name
)))
1555 ;; taken from `org-open-at-point'
1556 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1557 (message "source-code block '%s' not found in this buffer" name
))))
1559 (defun org-babel-find-named-block (name)
1560 "Find a named source-code block.
1561 Return the location of the source block identified by source
1562 NAME, or nil if no such block exists. Set match data according to
1563 org-babel-named-src-block-regexp."
1565 (let ((case-fold-search t
)
1566 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1567 (goto-char (point-min))
1568 (when (or (re-search-forward regexp nil t
)
1569 (re-search-backward regexp nil t
))
1570 (match-beginning 0)))))
1572 (defun org-babel-src-block-names (&optional file
)
1573 "Returns the names of source blocks in FILE or the current buffer."
1575 (when file
(find-file file
)) (goto-char (point-min))
1576 (let ((case-fold-search t
) names
)
1577 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1578 (setq names
(cons (match-string 3) names
)))
1582 (defun org-babel-goto-named-result (name)
1583 "Go to a named result."
1585 (let ((completion-ignore-case t
))
1586 (list (org-icompleting-read "source-block name: "
1587 (org-babel-result-names) nil t
))))
1588 (let ((point (org-babel-find-named-result name
)))
1590 ;; taken from `org-open-at-point'
1591 (progn (goto-char point
) (org-show-context))
1592 (message "result '%s' not found in this buffer" name
))))
1594 (defun org-babel-find-named-result (name &optional point
)
1595 "Find a named result.
1596 Return the location of the result named NAME in the current
1597 buffer or nil if no such result exists."
1599 (let ((case-fold-search t
))
1600 (goto-char (or point
(point-min)))
1601 (catch 'is-a-code-block
1602 (when (re-search-forward
1603 (concat org-babel-result-regexp
1604 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1605 (when (and (string= "name" (downcase (match-string 1)))
1606 (or (beginning-of-line 1)
1607 (looking-at org-babel-src-block-regexp
)
1608 (looking-at org-babel-multi-line-header-regexp
)))
1609 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1610 (beginning-of-line 0) (point))))))
1612 (defun org-babel-result-names (&optional file
)
1613 "Returns the names of results in FILE or the current buffer."
1615 (when file
(find-file file
)) (goto-char (point-min))
1616 (let ((case-fold-search t
) names
)
1617 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1618 (setq names
(cons (match-string 4) names
)))
1622 (defun org-babel-next-src-block (&optional arg
)
1623 "Jump to the next source block.
1624 With optional prefix argument ARG, jump forward ARG many source blocks."
1626 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1628 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1629 (error (error "No further code blocks")))
1630 (goto-char (match-beginning 0)) (org-show-context))
1633 (defun org-babel-previous-src-block (&optional arg
)
1634 "Jump to the previous source block.
1635 With optional prefix argument ARG, jump backward ARG many source blocks."
1638 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1639 (error (error "No previous code blocks")))
1640 (goto-char (match-beginning 0)) (org-show-context))
1642 (defvar org-babel-load-languages
)
1645 (defun org-babel-mark-block ()
1646 "Mark current src block."
1652 (looking-at org-babel-src-block-regexp
))
1653 (push-mark (match-end 5) nil t
)
1654 (goto-char (match-beginning 5))))
1655 (org-babel-where-is-src-block-head)))
1657 (defun org-babel-demarcate-block (&optional arg
)
1658 "Wrap or split the code in the region or on the point.
1659 When called from inside of a code block the current block is
1660 split. When called from outside of a code block a new code block
1661 is created. In both cases if the region is demarcated and if the
1662 region is not active then the point is demarcated."
1664 (let ((info (org-babel-get-src-block-info 'light
))
1665 (headers (progn (org-babel-where-is-src-block-head)
1667 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1673 (let ((lang (nth 0 info
))
1674 (indent (make-string (nth 5 info
) ?
)))
1675 (when (string-match "^[[:space:]]*$"
1676 (buffer-substring (point-at-bol)
1678 (delete-region (point-at-bol) (point-at-eol)))
1680 (if (looking-at "^") "" "\n")
1681 indent
"#+end_src\n"
1682 (if arg stars indent
) "\n"
1683 indent
"#+begin_src " lang
1684 (if (> (length headers
) 1)
1685 (concat " " headers
) headers
)
1686 (if (looking-at "[\n\r]")
1688 (concat "\n" (make-string (current-column) ?
)))))))
1689 (move-end-of-line 2))
1690 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1691 (let ((start (point))
1692 (lang (org-icompleting-read "Lang: "
1693 (mapcar (lambda (el) (symbol-name (car el
)))
1694 org-babel-load-languages
)))
1695 (body (delete-and-extract-region
1696 (if (org-region-active-p) (mark) (point)) (point))))
1697 (insert (concat (if (looking-at "^") "" "\n")
1698 (if arg
(concat stars
"\n") "")
1699 "#+begin_src " lang
"\n"
1701 (if (or (= (length body
) 0)
1702 (string-match "[\r\n]$" body
)) "" "\n")
1704 (goto-char start
) (move-end-of-line 1)))))
1706 (defvar org-babel-lob-one-liner-regexp
)
1707 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1708 "Find where the current source block results begin.
1709 Return the point at the beginning of the result of the current
1710 source block. Specifically at the beginning of the results line.
1711 If no result exists for this block then create a results line
1712 following the source block."
1714 (let* ((case-fold-search t
)
1715 (on-lob-line (save-excursion
1716 (beginning-of-line 1)
1717 (looking-at org-babel-lob-one-liner-regexp
)))
1718 (inlinep (when (org-babel-get-inline-src-block-matches)
1720 (name (if on-lob-line
1721 (mapconcat #'identity
(butlast (org-babel-lob-get-info)) "")
1722 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1723 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1725 (when head
(goto-char head
))
1727 found
;; was there a result (before we potentially insert one)
1732 ;; - return t if it is found, else return nil
1733 ;; - if it does not need to be rebuilt, then don't set end
1734 ;; - if it does need to be rebuilt then do set end
1735 name
(setq beg
(org-babel-find-named-result name
))
1737 (when (and hash
(not (string= hash
(match-string 3))))
1738 (goto-char beg
) (setq end beg
) ;; beginning of result
1740 (delete-region end
(org-babel-result-end)) nil
)))
1743 ;; - return t if it is found, else return nil
1744 ;; - if it is found, and the hash doesn't match, delete and set end
1745 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1746 (progn (end-of-line 1)
1747 (if (eobp) (insert "\n") (forward-char 1))
1750 (progn ;; unnamed results line already exists
1751 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1752 (beginning-of-line 1)
1754 (concat org-babel-result-regexp
"\n")))
1756 ;; must remove and rebuild if hash!=old-hash
1757 (if (and hash
(not (string= hash
(match-string 3))))
1761 end
(org-babel-result-end)))
1762 (setq end nil
)))))))))
1763 (if (and insert end
)
1767 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1772 (org-number-sequence 1 indent
) "")
1774 "#+" org-babel-results-keyword
1775 (when hash
(concat "["hash
"]"))
1777 (when name
(concat " " name
)) "\n"))
1778 (unless beg
(insert "\n") (backward-char))
1779 (beginning-of-line 0)
1780 (if hash
(org-babel-hide-hash))
1784 (defvar org-block-regexp
)
1785 (defun org-babel-read-result ()
1786 "Read the result at `point' into emacs-lisp."
1787 (let ((case-fold-search t
) result-string
)
1789 ((org-at-table-p) (org-babel-read-table))
1790 ((org-at-item-p) (org-babel-read-list))
1791 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1792 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1793 ((looking-at "^[ \t]*: ")
1796 (mapconcat (lambda (line)
1797 (if (and (> (length line
) 1)
1798 (string-match "^[ \t]*: \\(.+\\)" line
))
1799 (match-string 1 line
)
1803 (point) (org-babel-result-end)) "[\r\n]+")
1805 (or (org-babel-number-p result-string
) result-string
))
1806 ((looking-at org-babel-result-regexp
)
1807 (save-excursion (forward-line 1) (org-babel-read-result))))))
1809 (defun org-babel-read-table ()
1810 "Read the table at `point' into emacs-lisp."
1811 (mapcar (lambda (row)
1812 (if (and (symbolp row
) (equal row
'hline
)) row
1813 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1814 (org-table-to-lisp)))
1816 (defun org-babel-read-list ()
1817 "Read the list at `point' into emacs-lisp."
1818 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1819 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1821 (defvar org-link-types-re
)
1822 (defun org-babel-read-link ()
1823 "Read the link at `point' into emacs-lisp.
1824 If the path of the link is a file path it is expanded using
1825 `expand-file-name'."
1826 (let* ((case-fold-search t
)
1827 (raw (and (looking-at org-bracket-link-regexp
)
1828 (org-no-properties (match-string 1))))
1829 (type (and (string-match org-link-types-re raw
)
1830 (match-string 1 raw
))))
1832 ((not type
) (expand-file-name raw
))
1833 ((string= type
"file")
1834 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1835 (expand-file-name (match-string 2 raw
))))
1838 (defun org-babel-format-result (result &optional sep
)
1839 "Format RESULT for writing to file."
1840 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
1844 result
(list :sep
(or sep
"\t") :fmt echo-res
))
1846 (funcall echo-res result
))))
1848 (defun org-babel-insert-result
1849 (result &optional result-params info hash indent lang
)
1850 "Insert RESULT into the current buffer.
1851 By default RESULT is inserted after the end of the
1852 current source block. With optional argument RESULT-PARAMS
1853 controls insertion of results in the org-mode file.
1854 RESULT-PARAMS can take the following values:
1856 replace - (default option) insert results after the source block
1857 replacing any previously inserted results
1859 silent -- no results are inserted
1861 file ---- the results are interpreted as a file path, and are
1862 inserted into the buffer using the Org-mode file syntax
1864 list ---- the results are interpreted as an Org-mode list.
1866 raw ----- results are added directly to the Org-mode file. This
1867 is a good option if you code block will output org-mode
1870 drawer -- results are added directly to the Org-mode file as with
1871 \"raw\", but are wrapped in a RESULTS drawer, allowing
1872 them to later be replaced or removed automatically.
1874 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1875 They are not comma-escaped when inserted, but Org syntax
1876 here will be discarded when exporting the file.
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-no-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
&optional escape
)
1941 (goto-char end
) (insert (concat finish
"\n"))
1942 (goto-char beg
) (insert (concat start
"\n"))
1943 (if escape
(org-add-protective-commas (point) end
))
1944 (goto-char end
) (goto-char (point-at-eol))
1945 (setq end
(point-marker))))
1946 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
1947 ;; insert results based on type
1949 ;; do nothing for an empty result
1951 ;; insert a list if preferred
1952 ((member "list" result-params
)
1955 (org-list-to-generic
1958 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1959 (if (listp result
) result
(list result
))))
1960 '(:splicep nil
:istart
"- " :iend
"\n")))
1962 ;; assume the result is a table if it's not a string
1963 ((funcall proper-list-p result
)
1965 (insert (concat (orgtbl-to-orgtbl
1966 (if (or (eq 'hline
(car result
))
1967 (and (listp (car result
))
1968 (listp (cdr (car result
)))))
1969 result
(list result
))
1970 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1971 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1972 ((and (listp result
) (not (funcall proper-list-p result
)))
1973 (insert (format "%s\n" result
)))
1974 ((member "file" result-params
)
1975 (when inlinep
(goto-char inlinep
))
1977 (t (goto-char beg
) (insert result
)))
1978 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
1979 (setq end
(point-marker))
1980 ;; possibly wrap result
1982 ((assoc :wrap
(nth 2 info
))
1983 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
1984 (funcall wrap
(concat "#+BEGIN_" name
) (concat "#+END_" name
))))
1985 ((member "html" result-params
)
1986 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
1987 ((member "latex" result-params
)
1988 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
1989 ((member "org" result-params
)
1990 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC" 'escape
))
1991 ((member "code" result-params
)
1992 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
1994 ((member "raw" result-params
)
1995 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
1996 ((or (member "drawer" result-params
)
1997 ;; Stay backward compatible with <7.9.2
1998 (member "wrap" result-params
))
1999 (funcall wrap
":RESULTS:" ":END:"))
2000 ((and (not (funcall proper-list-p result
))
2001 (not (member "file" result-params
)))
2002 (org-babel-examplize-region beg end results-switches
)
2003 (setq end
(point)))))
2004 ;; possibly indent the results to match the #+results line
2005 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2006 ;; in this case `table-align' does the work for us
2007 (not (and (listp result
)
2008 (member "append" result-params
))))
2009 (indent-rigidly beg end indent
))))
2011 (if (member "value" result-params
)
2012 (message "Code block returned no value.")
2013 (message "Code block produced no output."))
2014 (message "Code block evaluation complete."))))
2016 (defun org-babel-remove-result (&optional info
)
2017 "Remove the result of the current source block."
2019 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
2021 (setq start
(- location
1))
2023 (goto-char location
) (forward-line 1)
2024 (delete-region start
(org-babel-result-end))))))
2026 (defun org-babel-result-end ()
2027 "Return the point at the end of the current set of results."
2030 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2031 ((org-at-item-p) (let* ((struct (org-list-struct))
2032 (prvs (org-list-prevs-alist struct
)))
2033 (org-list-get-list-end (point-at-bol) struct prvs
)))
2034 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2035 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2036 (forward-char 1) (point)))
2038 (let ((case-fold-search t
))
2039 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2040 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2043 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2047 (defun org-babel-result-to-file (result &optional description
)
2048 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2049 If the `default-directory' is different from the containing
2050 file's directory then expand relative links."
2051 (when (stringp result
)
2052 (format "[[file:%s]%s]"
2053 (if (and default-directory
2055 (not (string= (expand-file-name default-directory
)
2057 (file-name-directory buffer-file-name
)))))
2058 (expand-file-name result default-directory
)
2060 (if description
(concat "[" description
"]") ""))))
2062 (defvar org-babel-capitalize-examplize-region-markers nil
2063 "Make true to capitalize begin/end example markers inserted by code blocks.")
2065 (defun org-babel-examplize-region (beg end
&optional results-switches
)
2066 "Comment out region using the inline '==' or ': ' org example quote."
2068 (let ((chars-between (lambda (b e
)
2069 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2070 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2071 (upcase str
) str
))))
2072 (if (or (funcall chars-between
(save-excursion (goto-char beg
) (point-at-bol)) beg
)
2073 (funcall chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2076 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
2077 (delete-region beg end
)))))
2078 (let ((size (count-lines beg end
)))
2080 (cond ((= size
0)) ; do nothing for an empty result
2081 ((< size org-babel-min-lines-for-block-output
)
2084 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2087 (insert (if results-switches
2089 (funcall maybe-cap
"#+begin_example")
2091 (funcall maybe-cap
"#+begin_example\n")))
2092 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2093 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2095 (defun org-babel-update-block-body (new-body)
2096 "Update the body of the current code block to NEW-BODY."
2097 (if (not (org-babel-where-is-src-block-head))
2098 (error "Not in a source block")
2100 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2101 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2103 (defun org-babel-merge-params (&rest plists
)
2104 "Combine all parameter association lists in PLISTS.
2105 Later elements of PLISTS override the values of previous elements.
2106 This takes into account some special considerations for certain
2107 parameters when merging lists."
2108 (let* ((results-exclusive-groups
2109 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2110 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2111 (exports-exclusive-groups
2112 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2113 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2115 (e-merge (lambda (exclusive-groups &rest result-params
)
2116 ;; maintain exclusivity of mutually exclusive parameters
2118 (mapc (lambda (new-params)
2119 (mapc (lambda (new-param)
2120 (mapc (lambda (exclusive-group)
2121 (when (member new-param exclusive-group
)
2122 (mapcar (lambda (excluded-param)
2129 (setq output
(org-uniquify
2130 (cons new-param output
))))
2134 params results exports tangle noweb cache vars shebang comments padline
)
2142 (let ((name (if (listp (cdr pair
))
2144 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2146 (intern (match-string 1 (cdr pair
)))))))
2150 (if (member name
(mapcar #'car vars
))
2154 (unless (equal (car p
) name
) p
))
2157 (list (cons name pair
))))
2158 ;; if no name is given and we already have named variables
2159 ;; then assign to named variables in order
2160 (if (and vars
(nth variable-index vars
))
2161 (prog1 (setf (cddr (nth variable-index vars
))
2162 (concat (symbol-name
2163 (car (nth variable-index vars
)))
2165 (incf variable-index
))
2166 (error "Variable \"%s\" must be assigned a default value"
2169 (setq results
(funcall e-merge results-exclusive-groups
2172 (let ((r (cdr pair
)))
2173 (if (stringp r
) r
(eval r
)))))))
2176 (setq results
(funcall e-merge results-exclusive-groups
2178 (unless (or (member "both" exports
)
2179 (member "none" exports
)
2180 (member "code" exports
))
2181 (setq exports
(funcall e-merge exports-exclusive-groups
2182 exports
'("results"))))
2183 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2185 (setq exports
(funcall e-merge exports-exclusive-groups
2186 exports
(split-string (cdr pair
)))))
2187 (:tangle
;; take the latest -- always overwrite
2188 (setq tangle
(or (list (cdr pair
)) tangle
)))
2190 (setq noweb
(funcall e-merge
2191 '(("yes" "no" "tangle" "no-export"
2192 "strip-export" "eval"))
2194 (split-string (or (cdr pair
) "")))))
2196 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2197 (split-string (or (cdr pair
) "")))))
2199 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2200 (split-string (or (cdr pair
) "")))))
2201 (:shebang
;; take the latest -- always overwrite
2202 (setq shebang
(or (list (cdr pair
)) shebang
)))
2204 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2205 (split-string (or (cdr pair
) "")))))
2206 (t ;; replace: this covers e.g. :session
2207 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2210 (setq vars
(reverse vars
))
2211 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2214 (let ((key (intern (concat ":" (symbol-name hd
))))
2216 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2217 '(results exports tangle noweb padline cache shebang comments
))
2220 (defvar *org-babel-use-quick-and-dirty-noweb-expansion
* nil
2221 "Set to true to use regular expressions to expand noweb references.
2222 This results in much faster noweb reference expansion but does
2223 not properly allow code blocks to inherit the \":noweb-ref\"
2224 header argument from buffer or subtree wide properties.")
2226 (defun org-babel-noweb-p (params context
)
2227 "Check if PARAMS require expansion in CONTEXT.
2228 CONTEXT may be one of :tangle, :export or :eval."
2230 (intersect (lambda (as bs
)
2232 (if (member (car as
) bs
)
2234 (funcall intersect
(cdr as
) bs
))))))
2235 (funcall intersect
(case context
2236 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2237 (:eval
'("yes" "no-export" "strip-export" "eval"))
2239 (split-string (or (cdr (assoc :noweb params
)) "")))))
2241 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2242 "Expand Noweb references in the body of the current source code block.
2244 For example the following reference would be replaced with the
2245 body of the source-code block named 'example-block'.
2249 Note that any text preceding the <<foo>> construct on a line will
2250 be interposed between the lines of the replacement text. So for
2251 example if <<foo>> is placed behind a comment, then the entire
2252 replacement text will also be commented.
2254 This function must be called from inside of the buffer containing
2255 the source-code block which holds BODY.
2257 In addition the following syntax can be used to insert the
2258 results of evaluating the source-code block named 'example-block'.
2262 Any optional arguments can be passed to example-block by placing
2263 the arguments inside the parenthesis following the convention
2264 defined by `org-babel-lob'. For example
2266 <<example-block(a=9)>>
2268 would set the value of argument \"a\" equal to \"9\". Note that
2269 these arguments are not evaluated in the current source-code
2270 block but are passed literally to the \"example-block\"."
2271 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2272 (info (or info
(org-babel-get-src-block-info)))
2275 (ob-nww-start org-babel-noweb-wrap-start
)
2276 (ob-nww-end org-babel-noweb-wrap-end
)
2277 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2278 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2279 ":noweb-ref[ \t]+" "\\)"))
2281 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2282 (c-wrap (lambda (text)
2284 (funcall (intern (concat lang
"-mode")))
2285 (comment-region (point) (progn (insert text
) (point)))
2286 (org-babel-trim (buffer-string)))))
2287 index source-name evaluate prefix blocks-in-buffer
)
2289 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2290 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2291 (insert body
) (goto-char (point-min))
2292 (setq index
(point))
2293 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2294 (save-match-data (setf source-name
(match-string 1)))
2295 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2298 (buffer-substring (match-beginning 0)
2300 (beginning-of-line 1) (point)))))
2301 ;; add interval to new-body (removing noweb reference)
2302 (goto-char (match-beginning 0))
2303 (funcall nb-add
(buffer-substring index
(point)))
2304 (goto-char (match-end 0))
2305 (setq index
(point))
2307 (with-current-buffer parent-buffer
2310 (mapconcat ;; interpose PREFIX between every line
2314 (let ((raw (org-babel-ref-resolve source-name
)))
2315 (if (stringp raw
) raw
(format "%S" raw
)))
2317 ;; retrieve from the library of babel
2318 (nth 2 (assoc (intern source-name
)
2319 org-babel-library-of-babel
))
2320 ;; return the contents of headlines literally
2322 (when (org-babel-ref-goto-headline-id source-name
)
2323 (org-babel-ref-headline-body)))
2324 ;; find the expansion of reference in this buffer
2325 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2328 (goto-char (point-min))
2329 (if *org-babel-use-quick-and-dirty-noweb-expansion
*
2330 (while (re-search-forward rx nil t
)
2331 (let* ((i (org-babel-get-src-block-info 'light
))
2332 (body (org-babel-expand-noweb-references i
))
2333 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2337 (concat (funcall c-wrap
(car cs
)) "\n"
2339 (funcall c-wrap
(cadr cs
))))
2340 (org-babel-tangle-comment-links i
))
2342 (setq expansion
(cons sep
(cons full expansion
)))))
2343 (org-babel-map-src-blocks nil
2344 (let ((i (org-babel-get-src-block-info 'light
)))
2345 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2348 (let* ((body (org-babel-expand-noweb-references i
))
2349 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2353 (concat (funcall c-wrap
(car cs
)) "\n"
2355 (funcall c-wrap
(cadr cs
))))
2356 (org-babel-tangle-comment-links i
))
2359 (cons sep
(cons full expansion
)))))))))
2361 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2362 ;; possibly raise an error if named block doesn't exist
2363 (if (member lang org-babel-noweb-error-langs
)
2365 (org-babel-noweb-wrap source-name
)
2366 "could not be resolved (see "
2367 "`org-babel-noweb-error-langs')"))
2369 "[\n\r]") (concat "\n" prefix
))))))
2370 (funcall nb-add
(buffer-substring index
(point-max))))
2373 (defun org-babel-strip-protective-commas (body &optional lang
)
2374 "Strip protective commas from bodies of source blocks."
2377 (if (and lang
(string= lang
"org"))
2378 (progn (goto-char (point-min))
2379 (while (re-search-forward "^[ \t]*\\(,\\)" nil t
)
2380 (replace-match "" nil nil nil
1)))
2381 (org-strip-protective-commas (point-min) (point-max)))
2384 (defun org-babel-script-escape (str &optional force
)
2385 "Safely convert tables into elisp lists."
2386 (let (in-single in-double out
)
2387 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2391 (or (and (string-equal "[" (substring str
0 1))
2392 (string-equal "]" (substring str -
1)))
2393 (and (string-equal "{" (substring str
0 1))
2394 (string-equal "}" (substring str -
1)))
2395 (and (string-equal "(" (substring str
0 1))
2396 (string-equal ")" (substring str -
1))))))
2406 (91 (if (or in-double in-single
) ; [
2409 (93 (if (or in-double in-single
) ; ]
2412 (123 (if (or in-double in-single
) ; {
2415 (125 (if (or in-double in-single
) ; }
2418 (44 (if (or in-double in-single
) ; ,
2419 (cons 44 out
) (cons 32 out
)))
2420 (39 (if in-double
; '
2422 (setq in-single
(not in-single
)) (cons 34 out
)))
2423 (34 (if in-single
; "
2424 (append (list 34 32) out
)
2425 (setq in-double
(not in-double
)) (cons 34 out
)))
2426 (t (cons ch out
)))))
2427 (string-to-list str
))
2428 (apply #'string
(reverse out
)))))
2431 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2432 "Convert the string value of CELL to a number if appropriate.
2433 Otherwise if cell looks like lisp (meaning it starts with a
2434 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2435 return it unmodified as a string. Optional argument NO-LISP-EVAL
2436 inhibits lisp evaluation for situations in which is it not
2438 (if (and (stringp cell
) (not (equal cell
"")))
2439 (or (org-babel-number-p cell
)
2440 (if (and (not inhibit-lisp-eval
)
2441 (member (substring cell
0 1) '("(" "'" "`" "[")))
2443 (if (string= (substring cell
0 1) "\"")
2445 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2448 (defun org-babel-number-p (string)
2449 "If STRING represents a number return its value."
2450 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2451 (= (length (substring string
(match-beginning 0)
2454 (string-to-number string
)))
2456 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2457 "Read the results located at FILE-NAME into an elisp table.
2458 If the table is trivial, then return it as a scalar."
2460 (save-window-excursion
2464 (org-table-import file-name separator
)
2465 (delete-file file-name
)
2466 (setq result
(mapcar (lambda (row)
2467 (mapcar #'org-babel-string-read row
))
2468 (org-table-to-lisp))))
2469 (error (message "Error reading results: %s" err
) nil
)))
2470 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2471 (if (consp (car result
))
2472 (if (null (cdr (car result
)))
2478 (defun org-babel-string-read (cell)
2479 "Strip nested \"s from around strings."
2480 (org-babel-read (or (and (stringp cell
)
2481 (string-match "\\\"\\(.+\\)\\\"" cell
)
2482 (match-string 1 cell
))
2485 (defun org-babel-reverse-string (string)
2486 "Return the reverse of STRING."
2487 (apply 'string
(reverse (string-to-list string
))))
2489 (defun org-babel-chomp (string &optional regexp
)
2490 "Strip trailing spaces and carriage returns from STRING.
2491 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2492 overwritten by specifying a regexp as a second argument."
2493 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2494 (while (and (> (length string
) 0)
2495 (string-match regexp
(substring string -
1)))
2496 (setq string
(substring string
0 -
1)))
2499 (defun org-babel-trim (string &optional regexp
)
2500 "Strip leading and trailing spaces and carriage returns from STRING.
2501 Like `org-babel-chomp' only it runs on both the front and back
2503 (org-babel-chomp (org-babel-reverse-string
2504 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2507 (defvar org-babel-org-babel-call-process-region-original nil
)
2508 (defun org-babel-tramp-handle-call-process-region
2509 (start end program
&optional delete buffer display
&rest args
)
2510 "Use Tramp to handle `call-process-region'.
2511 Fixes a bug in `tramp-handle-call-process-region'."
2512 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2513 (let ((tmpfile (tramp-compat-make-temp-file "")))
2514 (write-region start end tmpfile
)
2515 (when delete
(delete-region start end
))
2517 ;; (apply 'call-process program tmpfile buffer display args)
2519 (apply 'process-file program tmpfile buffer display args
)
2520 (delete-file tmpfile
)))
2521 ;; org-babel-call-process-region-original is the original emacs
2522 ;; definition. It is in scope from the let binding in
2523 ;; org-babel-execute-src-block
2524 (apply org-babel-call-process-region-original
2525 start end program delete buffer display args
)))
2527 (defun org-babel-local-file-name (file)
2528 "Return the local name component of FILE."
2529 (if (file-remote-p file
)
2531 (with-parsed-tramp-file-name file nil
2535 (defun org-babel-process-file-name (name &optional no-quote-p
)
2536 "Prepare NAME to be used in an external process.
2537 If NAME specifies a remote location, the remote portion of the
2538 name is removed, since in that case the process will be executing
2539 remotely. The file name is then processed by `expand-file-name'.
2540 Unless second argument NO-QUOTE-P is non-nil, the file name is
2541 additionally processed by `shell-quote-argument'"
2542 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2543 (expand-file-name (org-babel-local-file-name name
))))
2545 (defvar org-babel-temporary-directory
)
2546 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2547 (defvar org-babel-temporary-directory
2548 (or (and (boundp 'org-babel-temporary-directory
)
2549 (file-exists-p org-babel-temporary-directory
)
2550 org-babel-temporary-directory
)
2551 (make-temp-file "babel-" t
))
2552 "Directory to hold temporary files created to execute code blocks.
2553 Used by `org-babel-temp-file'. This directory will be removed on
2556 (defun org-babel-temp-file (prefix &optional suffix
)
2557 "Create a temporary file in the `org-babel-temporary-directory'.
2558 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2559 value of `temporary-file-directory' temporarily set to the value
2560 of `org-babel-temporary-directory'."
2561 (if (file-remote-p default-directory
)
2563 (concat (file-remote-p default-directory
)
2565 prefix temporary-file-directory
)
2567 (let ((temporary-file-directory
2568 (or (and (boundp 'org-babel-temporary-directory
)
2569 (file-exists-p org-babel-temporary-directory
)
2570 org-babel-temporary-directory
)
2571 temporary-file-directory
)))
2572 (make-temp-file prefix nil suffix
))))
2574 (defun org-babel-remove-temporary-directory ()
2575 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2576 (when (and (boundp 'org-babel-temporary-directory
)
2577 (file-exists-p org-babel-temporary-directory
))
2578 ;; taken from `delete-directory' in files.el
2581 (mapc (lambda (file)
2582 ;; This test is equivalent to
2583 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2584 ;; but more efficient
2585 (if (eq t
(car (file-attributes file
)))
2586 (delete-directory file
)
2587 (delete-file file
)))
2588 ;; We do not want to delete "." and "..".
2589 (directory-files org-babel-temporary-directory
'full
2590 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2591 (delete-directory org-babel-temporary-directory
))
2593 (message "Failed to remove temporary Org-babel directory %s"
2594 (if (boundp 'org-babel-temporary-directory
)
2595 org-babel-temporary-directory
2596 "[directory not defined]"))))))
2598 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)