1 ;;; ob-core.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 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-split-string
"org" (string &optional separators
))
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-next-block
"org" (arg &optional backward block-regexp
))
63 (declare-function org-previous-block
"org" (arg &optional block-regexp
))
64 (declare-function org-show-context
"org" (&optional key
))
65 (declare-function org-at-table-p
"org" (&optional table-type
))
66 (declare-function org-cycle
"org" (&optional arg
))
67 (declare-function org-uniquify
"org" (list))
68 (declare-function org-current-level
"org" ())
69 (declare-function org-table-import
"org-table" (file arg
))
70 (declare-function org-add-hook
"org-compat"
71 (hook function
&optional append local
))
72 (declare-function org-table-align
"org-table" ())
73 (declare-function org-table-end
"org-table" (&optional table-type
))
74 (declare-function orgtbl-to-generic
"org-table" (table params
))
75 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
76 (declare-function org-babel-tangle-comment-links
"ob-tangle" (&optional info
))
77 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
78 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
79 (declare-function org-babel-ref-parse
"ob-ref" (assignment))
80 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
81 (declare-function org-babel-ref-goto-headline-id
"ob-ref" (id))
82 (declare-function org-babel-ref-headline-body
"ob-ref" ())
83 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
84 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
85 (declare-function org-at-item-p
"org-list" ())
86 (declare-function org-list-parse-list
"org-list" (&optional delete
))
87 (declare-function org-list-to-generic
"org-list" (LIST PARAMS
))
88 (declare-function org-list-struct
"org-list" ())
89 (declare-function org-list-prevs-alist
"org-list" (struct))
90 (declare-function org-list-get-list-end
"org-list" (item struct prevs
))
91 (declare-function org-remove-if
"org" (predicate seq
))
92 (declare-function org-completing-read
"org" (&rest args
))
93 (declare-function org-escape-code-in-region
"org-src" (beg end
))
94 (declare-function org-unescape-code-in-string
"org-src" (s))
95 (declare-function org-table-to-lisp
"org-table" (&optional txt
))
96 (declare-function org-reverse-string
"org" (string))
98 (defgroup org-babel nil
99 "Code block evaluation and management in `org-mode' documents."
103 (defcustom org-confirm-babel-evaluate t
104 "Confirm before evaluation.
105 Require confirmation before interactively evaluating code
106 blocks in Org-mode buffers. The default value of this variable
107 is t, meaning confirmation is required for any code block
108 evaluation. This variable can be set to nil to inhibit any
109 future confirmation requests. This variable can also be set to a
110 function which takes two arguments the language of the code block
111 and the body of the code block. Such a function should then
112 return a non-nil value if the user should be prompted for
113 execution or nil if no prompt is required.
115 Warning: Disabling confirmation may result in accidental
116 evaluation of potentially harmful code. It may be advisable
117 remove code block execution from C-c C-c as further protection
118 against accidental code block evaluation. The
119 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
120 remove code block execution from the C-c C-c keybinding."
123 :type
'(choice boolean function
))
124 ;; don't allow this variable to be changed through file settings
125 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
127 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
128 "Remove code block evaluation from the C-c C-c key binding."
133 (defcustom org-babel-results-keyword
"RESULTS"
134 "Keyword used to name results generated by code blocks.
135 Should be either RESULTS or NAME however any capitalization may
139 :package-version
'(Org .
"8.0")
142 (defcustom org-babel-noweb-wrap-start
"<<"
143 "String used to begin a noweb reference in a code block.
144 See also `org-babel-noweb-wrap-end'."
148 (defcustom org-babel-noweb-wrap-end
">>"
149 "String used to end a noweb reference in a code block.
150 See also `org-babel-noweb-wrap-start'."
154 (defun org-babel-noweb-wrap (&optional regexp
)
155 (concat org-babel-noweb-wrap-start
156 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
157 org-babel-noweb-wrap-end
))
159 (defvar org-babel-src-name-regexp
160 "^[ \t]*#\\+name:[ \t]*"
161 "Regular expression used to match a source name line.")
163 (defvar org-babel-multi-line-header-regexp
164 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
165 "Regular expression used to match multi-line header arguments.")
167 (defvar org-babel-src-name-w-name-regexp
168 (concat org-babel-src-name-regexp
170 org-babel-multi-line-header-regexp
172 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
173 "Regular expression matching source name lines with a name.")
175 (defvar org-babel-src-block-regexp
177 ;; (1) indentation (2) lang
178 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
180 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
181 ;; (4) header arguments
184 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
185 "Regexp used to identify code blocks.")
187 (defvar org-babel-inline-src-block-regexp
189 ;; (1) replacement target (2) lang
190 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
191 ;; (3,4) (unused, headers)
192 "\\(\\|\\[\\(.*?\\)\\]\\)"
194 "{\\([^\f\n\r\v]+?\\)}\\)")
195 "Regexp used to identify inline src-blocks.")
197 (defun org-babel-get-header (params key
&optional others
)
198 "Select only header argument of type KEY from a list.
199 Optional argument OTHERS indicates that only the header that do
200 not match KEY should be returned."
203 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
206 (defun org-babel-get-inline-src-block-matches()
207 "Set match data if within body of an inline source block.
208 Returns non-nil if match-data set"
209 (let ((src-at-0-p (save-excursion
210 (beginning-of-line 1)
211 (string= "src" (thing-at-point 'word
))))
212 (first-line-p (= 1 (line-number-at-pos)))
214 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
215 (first-line-p "[[:punct:] \t]src_")
216 (t "[[:punct:] \f\t\n\r\v]src_")))
217 (lower-limit (if first-line-p
219 (- (point-at-bol) 1))))
221 (when (or (and src-at-0-p
(bobp))
222 (and (re-search-forward "}" (point-at-eol) t
)
223 (re-search-backward search-for lower-limit t
)
225 (when (looking-at org-babel-inline-src-block-regexp
)
228 (defvar org-babel-inline-lob-one-liner-regexp
)
229 (defun org-babel-get-lob-one-liner-matches()
230 "Set match data if on line of an lob one liner.
231 Returns non-nil if match-data set"
233 (unless (= (point) (point-at-bol)) ;; move before inline block
234 (re-search-backward "[ \f\t\n\r\v]" nil t
))
235 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
239 (defun org-babel-get-src-block-info (&optional light
)
240 "Get information on the current source block.
242 Optional argument LIGHT does not resolve remote variable
243 references; a process which could likely result in the execution
244 of other code blocks.
247 (language body header-arguments-alist switches name indent)."
248 (let ((case-fold-search t
) head info name indent
)
250 (if (setq head
(org-babel-where-is-src-block-head))
253 (setq info
(org-babel-parse-src-block-match))
254 (setq indent
(car (last info
)))
255 (setq info
(butlast info
))
256 (while (and (forward-line -
1)
257 (looking-at org-babel-multi-line-header-regexp
))
259 (org-babel-merge-params
261 (org-babel-parse-header-arguments (match-string 1)))))
262 (when (looking-at org-babel-src-name-w-name-regexp
)
263 (setq name
(org-no-properties (match-string 3)))
264 (when (and (match-string 5) (> (length (match-string 5)) 0))
265 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
266 (org-babel-merge-params
268 (lambda (ref) (cons :var ref
))
270 (lambda (var) ;; check that each variable is initialized
271 (if (string-match ".+=.+" var
)
274 "variable \"%s\"%s must be assigned a default value"
275 var
(if name
(format " in block \"%s\"" name
) ""))))
276 (org-babel-ref-split-args (match-string 5))))
278 ;; inline source block
279 (when (org-babel-get-inline-src-block-matches)
280 (setq info
(org-babel-parse-inline-src-block-match))))
281 ;; resolve variable references and add summary parameters
282 (when (and info
(not light
))
283 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
284 (when info
(append info
(list name indent
)))))
286 (defvar org-current-export-file
) ; dynamically bound
287 (defun org-babel-confirm-evaluate (info)
288 "Confirm evaluation of the code block INFO.
289 This behavior can be suppressed by setting the value of
290 `org-confirm-babel-evaluate' to nil, in which case all future
291 interactive code block evaluations will proceed without any
292 confirmation from the user.
294 Note disabling confirmation may result in accidental evaluation
295 of potentially harmful code."
296 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
297 (when (assoc :noeval
(nth 2 info
)) "no")))
298 (query (cond ((equal eval
"query") t
)
299 ((and (boundp 'org-current-export-file
)
300 org-current-export-file
301 (equal eval
"query-export")) t
)
302 ((functionp org-confirm-babel-evaluate
)
303 (funcall org-confirm-babel-evaluate
304 (nth 0 info
) (nth 1 info
)))
305 (t org-confirm-babel-evaluate
))))
306 (if (or (equal eval
"never") (equal eval
"no")
307 (and (boundp 'org-current-export-file
)
308 org-current-export-file
309 (or (equal eval
"no-export")
310 (equal eval
"never-export")))
313 (format "Evaluate this%scode block%son your system? "
314 (if info
(format " %s " (nth 0 info
)) " ")
316 (format " (%s) " (nth 4 info
)) " "))))))
317 (prog1 nil
(message "Evaluation %s"
318 (if (or (equal eval
"never") (equal eval
"no")
319 (equal eval
"no-export")
320 (equal eval
"never-export"))
321 "Disabled" "Aborted")))
325 (defun org-babel-execute-safely-maybe ()
326 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
327 (org-babel-execute-maybe)))
329 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
332 (defun org-babel-execute-maybe ()
334 (or (org-babel-execute-src-block-maybe)
335 (org-babel-lob-execute-maybe)))
337 (defun org-babel-execute-src-block-maybe ()
338 "Conditionally execute a source block.
339 Detect if this is context for a Babel src-block and if so
340 then run `org-babel-execute-src-block'."
342 (let ((info (org-babel-get-src-block-info)))
344 (progn (org-babel-eval-wipe-error-buffer)
345 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
348 (defun org-babel-view-src-block-info ()
349 "Display information on the current source block.
350 This includes header arguments, language and name, and is largely
351 a window into the `org-babel-get-src-block-info' function."
353 (let ((info (org-babel-get-src-block-info 'light
))
354 (full (lambda (it) (> (length it
) 0)))
355 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
357 (with-help-window (help-buffer)
358 (let ((name (nth 4 info
))
360 (switches (nth 3 info
))
361 (header-args (nth 2 info
)))
362 (when name
(funcall printf
"Name: %s\n" name
))
363 (when lang
(funcall printf
"Lang: %s\n" lang
))
364 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
365 (funcall printf
"Header Arguments:\n")
366 (dolist (pair (sort header-args
367 (lambda (a b
) (string< (symbol-name (car a
))
368 (symbol-name (car b
))))))
369 (when (funcall full
(cdr pair
))
370 (funcall printf
"\t%S%s\t%s\n"
372 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
376 (defun org-babel-expand-src-block-maybe ()
377 "Conditionally expand a source block.
378 Detect if this is context for a org-babel src-block and if so
379 then run `org-babel-expand-src-block'."
381 (let ((info (org-babel-get-src-block-info)))
383 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
387 (defun org-babel-load-in-session-maybe ()
388 "Conditionally load a source block in a session.
389 Detect if this is context for a org-babel src-block and if so
390 then run `org-babel-load-in-session'."
392 (let ((info (org-babel-get-src-block-info)))
394 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
397 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
400 (defun org-babel-pop-to-session-maybe ()
401 "Conditionally pop to a session.
402 Detect if this is context for a org-babel src-block and if so
403 then run `org-babel-pop-to-session'."
405 (let ((info (org-babel-get-src-block-info)))
406 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
408 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
410 (defconst org-babel-common-header-args-w-values
411 '((cache .
((no yes
)))
413 (colnames .
((nil no yes
)))
414 (comments .
((no link yes org both noweb
)))
416 (eval .
((never query
)))
417 (exports .
((code results both none
)))
420 (hlines .
((no yes
)))
421 (mkdirp .
((yes no
)))
424 (noweb .
((yes no tangle no-export strip-export
)))
427 (padline .
((yes no
)))
428 (results .
((file list vector table scalar verbatim
)
429 (raw html latex org code pp drawer
)
430 (replace silent none append prepend
)
432 (rownames .
((no yes
)))
436 (tangle .
((tangle yes no
:any
)))
440 (defconst org-babel-header-arg-names
441 (mapcar #'car org-babel-common-header-args-w-values
)
442 "Common header arguments used by org-babel.
443 Note that individual languages may define their own language
444 specific header arguments as well.")
446 (defvar org-babel-default-header-args
447 '((:session .
"none") (:results .
"replace") (:exports .
"code")
448 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
449 (:padnewline .
"yes"))
450 "Default arguments to use when evaluating a source block.")
452 (defvar org-babel-default-inline-header-args
453 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
454 "Default arguments to use when evaluating an inline source block.")
456 (defvar org-babel-data-names
'("tblname" "results" "name"))
458 (defvar org-babel-result-regexp
459 (concat "^[ \t]*#\\+"
460 (regexp-opt org-babel-data-names t
)
462 ;; FIXME The string below is `org-ts-regexp'
463 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
464 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
465 "Regular expression used to match result lines.
466 If the results are associated with a hash key then the hash will
467 be saved in the second match data.")
469 (defvar org-babel-result-w-name-regexp
470 (concat org-babel-result-regexp
471 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
473 (defvar org-babel-min-lines-for-block-output
10
474 "The minimum number of lines for block output.
475 If number of lines of output is equal to or exceeds this
476 value, the output is placed in a #+begin_example...#+end_example
477 block. Otherwise the output is marked as literal by inserting
478 colons at the starts of the lines. This variable only takes
479 effect if the :results output option is in effect.")
481 (defvar org-babel-noweb-error-langs nil
482 "Languages for which Babel will raise literate programming errors.
483 List of languages for which errors should be raised when the
484 source code block satisfying a noweb reference in this language
485 can not be resolved.")
487 (defvar org-babel-hash-show
4
488 "Number of initial characters to show of a hidden results hash.")
490 (defvar org-babel-hash-show-time nil
491 "When not nil show the time the code block was evaluated in the result hash.")
493 (defvar org-babel-after-execute-hook nil
494 "Hook for functions to be called after `org-babel-execute-src-block'")
496 (defun org-babel-named-src-block-regexp-for-name (name)
497 "This generates a regexp used to match a src block named NAME."
498 (concat org-babel-src-name-regexp
(regexp-quote name
)
499 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
500 (substring org-babel-src-block-regexp
1)))
502 (defun org-babel-named-data-regexp-for-name (name)
503 "This generates a regexp used to match data named NAME."
504 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
507 (defvar call-process-region
)
510 (defun org-babel-execute-src-block (&optional arg info params
)
511 "Execute the current source code block.
512 Insert the results of execution into the buffer. Source code
513 execution and the collection and formatting of results can be
514 controlled through a variety of header arguments.
516 With prefix argument ARG, force re-execution even if an existing
517 result cached in the buffer would otherwise have been returned.
519 Optionally supply a value for INFO in the form returned by
520 `org-babel-get-src-block-info'.
522 Optionally supply a value for PARAMS which will be merged with
523 the header arguments specified at the front of the source code
526 (let* ((info (or info
(org-babel-get-src-block-info)))
527 (merged-params (org-babel-merge-params (nth 2 info
) params
)))
528 (when (org-babel-confirm-evaluate
529 (let ((i info
)) (setf (nth 2 i
) merged-params
) i
))
530 (let* ((lang (nth 0 info
))
532 (org-babel-process-params merged-params
)
534 (cache-p (and (not arg
) (cdr (assoc :cache params
))
535 (string= "yes" (cdr (assoc :cache params
)))))
536 (result-params (cdr (assoc :result-params params
)))
537 (new-hash (when cache-p
(org-babel-sha1-hash info
)))
538 (old-hash (when cache-p
(org-babel-current-result-hash)))
539 (cache-current-p (and (not arg
) new-hash
(equal new-hash old-hash
)))
540 (body (setf (nth 1 info
)
541 (if (org-babel-noweb-p params
:eval
)
542 (org-babel-expand-noweb-references info
)
544 (dir (cdr (assoc :dir params
)))
546 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
548 (org-babel-call-process-region-original
549 (if (boundp 'org-babel-call-process-region-original
)
550 org-babel-call-process-region-original
551 (symbol-function 'call-process-region
)))
552 (indent (car (last info
)))
555 (let ((call-process-region
557 (apply 'org-babel-tramp-handle-call-process-region args
))))
558 (let ((lang-check (lambda (f)
559 (let ((f (intern (concat "org-babel-execute:" f
))))
560 (when (fboundp f
) f
)))))
562 (or (funcall lang-check lang
)
563 (funcall lang-check
(symbol-name
564 (cdr (assoc lang org-src-lang-modes
))))
565 (error "No org-babel-execute function for %s!" lang
))))
567 (save-excursion ;; return cached result
568 (goto-char (org-babel-where-is-src-block-result nil info
))
569 (end-of-line 1) (forward-char 1)
570 (setq result
(org-babel-read-result))
571 (message (replace-regexp-in-string
572 "%" "%%" (format "%S" result
))) result
)
573 (message "executing %s code block%s..."
575 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
576 (if (member "none" result-params
)
578 (funcall cmd body params
)
579 (message "result silenced"))
582 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
583 (or (member "vector" result-params
)
584 (member "table" result-params
))
585 (not (listp result
)))
586 (list (list result
)) result
))
587 (funcall cmd body params
)))
588 ;; if non-empty result and :file then write to :file
589 (when (cdr (assoc :file params
))
591 (with-temp-file (cdr (assoc :file params
))
593 (org-babel-format-result
594 result
(cdr (assoc :sep
(nth 2 info
)))))))
595 (setq result
(cdr (assoc :file params
))))
596 (org-babel-insert-result
597 result result-params info new-hash indent lang
)
598 (run-hooks 'org-babel-after-execute-hook
)
601 (setq call-process-region
'org-babel-call-process-region-original
))))))
603 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
604 "Expand BODY with PARAMS.
605 Expand a block of code with org-babel according to its header
606 arguments. This generic implementation of body expansion is
607 called for languages which have not defined their own specific
608 org-babel-expand-body:lang function."
609 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
612 (defun org-babel-expand-src-block (&optional arg info params
)
613 "Expand the current source code block.
614 Expand according to the source code block's header
615 arguments and pop open the results in a preview buffer."
617 (let* ((info (or info
(org-babel-get-src-block-info)))
619 (params (setf (nth 2 info
)
620 (sort (org-babel-merge-params (nth 2 info
) params
)
621 (lambda (el1 el2
) (string< (symbol-name (car el1
))
622 (symbol-name (car el2
)))))))
623 (body (setf (nth 1 info
)
624 (if (org-babel-noweb-p params
:eval
)
625 (org-babel-expand-noweb-references info
) (nth 1 info
))))
626 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
627 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
630 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
631 (org-babel-expand-body:generic
632 body params
(and (fboundp assignments-cmd
)
633 (funcall assignments-cmd params
))))))
634 (if (called-interactively-p 'any
)
637 (concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))
640 (defun org-babel-edit-distance (s1 s2
)
641 "Return the edit (levenshtein) distance between strings S1 S2."
642 (let* ((l1 (length s1
))
644 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
645 (number-sequence 1 (1+ l1
)))))
646 (in (lambda (i j
) (aref (aref dist i
) j
))))
647 (setf (aref (aref dist
0) 0) 0)
648 (dolist (j (number-sequence 1 l2
))
649 (setf (aref (aref dist
0) j
) j
))
650 (dolist (i (number-sequence 1 l1
))
651 (setf (aref (aref dist i
) 0) i
)
652 (dolist (j (number-sequence 1 l2
))
653 (setf (aref (aref dist i
) j
)
655 (1+ (funcall in
(1- i
) j
))
656 (1+ (funcall in i
(1- j
)))
657 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
658 (funcall in
(1- i
) (1- j
)))))))
661 (defun org-babel-combine-header-arg-lists (original &rest others
)
662 "Combine a number of lists of header argument names and arguments."
663 (let ((results (copy-sequence original
)))
664 (dolist (new-list others
)
665 (dolist (arg-pair new-list
)
666 (let ((header (car arg-pair
))
667 (args (cdr arg-pair
)))
669 (cons arg-pair
(org-remove-if
670 (lambda (pair) (equal header
(car pair
)))
675 (defun org-babel-check-src-block ()
676 "Check for misspelled header arguments in the current code block."
678 ;; TODO: report malformed code block
679 ;; TODO: report incompatible combinations of header arguments
680 ;; TODO: report uninitialized variables
681 (let ((too-close 2) ;; <- control closeness to report potential match
682 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
683 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
684 (and (org-babel-where-is-src-block-head)
685 (org-babel-parse-header-arguments
687 (match-string 4))))))
689 (when (and (not (string= header name
))
690 (<= (org-babel-edit-distance header name
) too-close
)
691 (not (member header names
)))
692 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
694 (message "No suspicious header arguments found.")))
697 (defun org-babel-insert-header-arg ()
698 "Insert a header argument selecting from lists of common args and values."
700 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
701 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
702 (headers (org-babel-combine-header-arg-lists
703 org-babel-common-header-args-w-values
704 (if (boundp lang-headers
) (eval lang-headers
) nil
)))
705 (arg (org-icompleting-read
708 (lambda (header-spec) (symbol-name (car header-spec
)))
711 (let ((vals (cdr (assoc (intern arg
) headers
))))
717 (read-from-minibuffer "value: "))
721 (let ((arg (org-icompleting-read
723 (cons "default" (mapcar #'symbol-name group
)))))
724 (if (and arg
(not (string= "default" arg
)))
729 ;; Add support for completing-read insertion of header arguments after ":"
730 (defun org-babel-header-arg-expand ()
731 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
732 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
733 (org-babel-enter-header-arg-w-completion (match-string 2))))
735 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
736 "Insert header argument appropriate for LANG with completion."
737 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
738 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
739 (headers-w-values (org-babel-combine-header-arg-lists
740 org-babel-common-header-args-w-values lang-headers
))
741 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
742 (header (org-completing-read "Header Arg: " headers
))
743 (args (cdr (assoc (intern header
) headers-w-values
)))
744 (arg (when (and args
(listp args
))
746 (format "%s: " header
)
747 (mapcar #'symbol-name
(apply #'append args
))))))
748 (insert (concat header
" " (or arg
"")))
751 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
754 (defun org-babel-load-in-session (&optional arg info
)
755 "Load the body of the current source-code block.
756 Evaluate the header arguments for the source block before
757 entering the session. After loading the body this pops open the
760 (let* ((info (or info
(org-babel-get-src-block-info)))
762 (params (nth 2 info
))
764 (user-error "No src code block at point")
766 (if (org-babel-noweb-p params
:eval
)
767 (org-babel-expand-noweb-references info
)
769 (session (cdr (assoc :session params
)))
770 (dir (cdr (assoc :dir params
)))
772 (or (and dir
(file-name-as-directory dir
)) default-directory
))
773 (cmd (intern (concat "org-babel-load-session:" lang
))))
774 (unless (fboundp cmd
)
775 (error "No org-babel-load-session function for %s!" lang
))
776 (pop-to-buffer (funcall cmd session body params
))
780 (defun org-babel-initiate-session (&optional arg info
)
781 "Initiate session for current code block.
782 If called with a prefix argument then resolve any variable
783 references in the header arguments and assign these variables in
784 the session. Copy the body of the code block to the kill ring."
786 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
789 (params (nth 2 info
))
790 (session (cdr (assoc :session params
)))
791 (dir (cdr (assoc :dir params
)))
793 (or (and dir
(file-name-as-directory dir
)) default-directory
))
794 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
795 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
796 (if (and (stringp session
) (string= session
"none"))
797 (error "This block is not using a session!"))
798 (unless (fboundp init-cmd
)
799 (error "No org-babel-initiate-session function for %s!" lang
))
800 (with-temp-buffer (insert (org-babel-trim body
))
801 (copy-region-as-kill (point-min) (point-max)))
803 (unless (fboundp prep-cmd
)
804 (error "No org-babel-prep-session function for %s!" lang
))
805 (funcall prep-cmd session params
))
806 (funcall init-cmd session params
)))
809 (defun org-babel-switch-to-session (&optional arg info
)
810 "Switch to the session of the current code block.
811 Uses `org-babel-initiate-session' to start the session. If called
812 with a prefix argument then this is passed on to
813 `org-babel-initiate-session'."
815 (pop-to-buffer (org-babel-initiate-session arg info
))
818 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
821 (defun org-babel-switch-to-session-with-code (&optional arg info
)
822 "Switch to code buffer and display session."
826 (let ((other-window-buffer (window-buffer (next-window))))
827 (set-window-buffer (next-window) (current-buffer))
828 (set-window-buffer (selected-window) other-window-buffer
))
830 (info (org-babel-get-src-block-info))
831 (org-src-window-setup 'reorganize-frame
))
833 (org-babel-switch-to-session arg info
))
835 (funcall swap-windows
)))
837 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
838 "Evaluate BODY in edit buffer if there is a code block at point.
839 Return t if a code block was found at point, nil otherwise."
840 `(let ((org-src-window-setup 'switch-invisibly
))
841 (when (and (org-babel-where-is-src-block-head)
842 (org-edit-src-code nil nil nil
))
843 (unwind-protect (progn ,@body
)
844 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
845 (org-edit-src-exit)))
847 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
849 (defun org-babel-do-key-sequence-in-edit-buffer (key)
850 "Read key sequence and execute the command in edit buffer.
851 Enter a key sequence to be executed in the language major-mode
852 edit buffer. For example, TAB will alter the contents of the
853 Org-mode code block according to the effect of TAB in the
854 language major-mode buffer. For languages that support
855 interactive sessions, this can be used to send code from the Org
856 buffer to the session for evaluation using the native major-mode
857 evaluation mechanisms."
858 (interactive "kEnter key-sequence to execute in edit buffer: ")
859 (org-babel-do-in-edit-buffer
861 (key-binding (or key
(read-key-sequence nil
))))))
863 (defvar org-bracket-link-regexp
)
866 (defun org-babel-open-src-block-result (&optional re-run
)
867 "If `point' is on a src block then open the results of the
868 source code block, otherwise return nil. With optional prefix
869 argument RE-RUN the source-code block is evaluated even if
870 results already exist."
872 (let ((info (org-babel-get-src-block-info)))
875 ;; go to the results, if there aren't any then run the block
876 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
877 (progn (org-babel-execute-src-block)
878 (org-babel-where-is-src-block-result))))
880 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
882 (if (looking-at org-bracket-link-regexp
)
885 (let ((r (org-babel-format-result
886 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
887 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
888 (delete-region (point-min) (point-max))
893 (defmacro org-babel-map-src-blocks
(file &rest body
)
894 "Evaluate BODY forms on each source-block in FILE.
895 If FILE is nil evaluate BODY forms on source blocks in current
896 buffer. During evaluation of BODY the following local variables
897 are set relative to the currently matched code block.
899 full-block ------- string holding the entirety of the code block
900 beg-block -------- point at the beginning of the code block
901 end-block -------- point at the end of the matched code block
902 lang ------------- string holding the language of the code block
903 beg-lang --------- point at the beginning of the lang
904 end-lang --------- point at the end of the lang
905 switches --------- string holding the switches
906 beg-switches ----- point at the beginning of the switches
907 end-switches ----- point at the end of the switches
908 header-args ------ string holding the header-args
909 beg-header-args -- point at the beginning of the header-args
910 end-header-args -- point at the end of the header-args
911 body ------------- string holding the body of the code block
912 beg-body --------- point at the beginning of the body
913 end-body --------- point at the end of the body"
915 (let ((tempvar (make-symbol "file")))
916 `(let* ((,tempvar
,file
)
917 (visited-p (or (null ,tempvar
)
918 (get-file-buffer (expand-file-name ,tempvar
))))
919 (point (point)) to-be-removed
)
920 (save-window-excursion
921 (when ,tempvar
(find-file ,tempvar
))
922 (setq to-be-removed
(current-buffer))
923 (goto-char (point-min))
924 (while (re-search-forward org-babel-src-block-regexp nil t
)
925 (goto-char (match-beginning 0))
926 (let ((full-block (match-string 0))
927 (beg-block (match-beginning 0))
928 (end-block (match-end 0))
929 (lang (match-string 2))
930 (beg-lang (match-beginning 2))
931 (end-lang (match-end 2))
932 (switches (match-string 3))
933 (beg-switches (match-beginning 3))
934 (end-switches (match-end 3))
935 (header-args (match-string 4))
936 (beg-header-args (match-beginning 4))
937 (end-header-args (match-end 4))
938 (body (match-string 5))
939 (beg-body (match-beginning 5))
940 (end-body (match-end 5)))
942 (goto-char end-block
))))
943 (unless visited-p
(kill-buffer to-be-removed
))
945 (def-edebug-spec org-babel-map-src-blocks
(form body
))
948 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
949 "Evaluate BODY forms on each inline source-block 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-inline-src-block-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-inline-src-blocks
(form body
))
970 (defvar org-babel-lob-one-liner-regexp
)
973 (defmacro org-babel-map-call-lines
(file &rest body
)
974 "Evaluate BODY forms on each call line in FILE.
975 If FILE is nil evaluate BODY forms on source blocks in current
978 (let ((tempvar (make-symbol "file")))
979 `(let* ((,tempvar
,file
)
980 (visited-p (or (null ,tempvar
)
981 (get-file-buffer (expand-file-name ,tempvar
))))
982 (point (point)) to-be-removed
)
983 (save-window-excursion
984 (when ,tempvar
(find-file ,tempvar
))
985 (setq to-be-removed
(current-buffer))
986 (goto-char (point-min))
987 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
988 (goto-char (match-beginning 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-call-lines
(form body
))
996 (defmacro org-babel-map-executables
(file &rest body
)
998 (let ((tempvar (make-symbol "file"))
999 (rx (make-symbol "rx")))
1000 `(let* ((,tempvar
,file
)
1001 (,rx
(concat "\\(" org-babel-src-block-regexp
1002 "\\|" org-babel-inline-src-block-regexp
1003 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
1004 (visited-p (or (null ,tempvar
)
1005 (get-file-buffer (expand-file-name ,tempvar
))))
1006 (point (point)) to-be-removed
)
1007 (save-window-excursion
1008 (when ,tempvar
(find-file ,tempvar
))
1009 (setq to-be-removed
(current-buffer))
1010 (goto-char (point-min))
1011 (while (re-search-forward ,rx nil t
)
1012 (goto-char (match-beginning 1))
1013 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
1014 (save-match-data ,@body
)
1015 (goto-char (match-end 0))))
1016 (unless visited-p
(kill-buffer to-be-removed
))
1017 (goto-char point
))))
1018 (def-edebug-spec org-babel-map-executables
(form body
))
1021 (defun org-babel-execute-buffer (&optional arg
)
1022 "Execute source code blocks in a buffer.
1023 Call `org-babel-execute-src-block' on every source block in
1024 the current buffer."
1026 (org-babel-eval-wipe-error-buffer)
1027 (org-save-outline-visibility t
1028 (org-babel-map-executables nil
1029 (if (looking-at org-babel-lob-one-liner-regexp
)
1030 (org-babel-lob-execute-maybe)
1031 (org-babel-execute-src-block arg
)))))
1034 (defun org-babel-execute-subtree (&optional arg
)
1035 "Execute source code blocks in a subtree.
1036 Call `org-babel-execute-src-block' on every source block in
1037 the current subtree."
1041 (org-narrow-to-subtree)
1042 (org-babel-execute-buffer arg
)
1046 (defun org-babel-sha1-hash (&optional info
)
1047 "Generate an sha1 hash based on the value of info."
1049 (let ((print-level nil
)
1050 (info (or info
(org-babel-get-src-block-info))))
1052 (sort (copy-sequence (nth 2 info
))
1053 (lambda (a b
) (string< (car a
) (car b
)))))
1054 (let* ((rm (lambda (lst)
1055 (dolist (p '("replace" "silent" "none"
1056 "append" "prepend"))
1057 (setq lst
(remove p lst
)))
1060 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1061 (copy-sequence (cdr arg
))
1063 (when (and v
(not (and (sequencep v
)
1067 ((and (listp v
) ; lists are sorted
1068 (member (car arg
) '(:result-params
)))
1069 (sort (funcall rm v
) #'string
<))
1070 ((and (stringp v
) ; strings are sorted
1071 (member (car arg
) '(:results
:exports
)))
1072 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1076 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
1077 (let ((it (format "%s-%s"
1080 (delq nil
(mapcar (lambda (arg)
1081 (let ((normalized (funcall norm arg
)))
1083 (format "%S" normalized
))))
1088 (defun org-babel-current-result-hash ()
1089 "Return the current in-buffer hash."
1090 (org-babel-where-is-src-block-result)
1091 (org-no-properties (match-string 5)))
1093 (defun org-babel-set-current-result-hash (hash)
1094 "Set the current in-buffer hash to HASH."
1095 (org-babel-where-is-src-block-result)
1096 (save-excursion (goto-char (match-beginning 3))
1097 ;; (mapc #'delete-overlay (overlays-at (point)))
1098 (replace-match hash nil nil nil
3)
1099 (org-babel-hide-hash)))
1101 (defun org-babel-hide-hash ()
1102 "Hide the hash in the current results line.
1103 Only the initial `org-babel-hash-show' characters of the hash
1104 will remain visible."
1105 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1107 (when (and (re-search-forward org-babel-result-regexp nil t
)
1109 (let* ((start (match-beginning 5))
1110 (hide-start (+ org-babel-hash-show start
))
1112 (hash (match-string 5))
1114 (setq ov1
(make-overlay start hide-start
))
1115 (setq ov2
(make-overlay hide-start end
))
1116 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1117 (overlay-put ov1
'babel-hash hash
)))))
1119 (defun org-babel-hide-all-hashes ()
1120 "Hide the hash in the current buffer.
1121 Only the initial `org-babel-hash-show' characters of each hash
1122 will remain visible. This function should be called as part of
1123 the `org-mode-hook'."
1125 (while (and (not org-babel-hash-show-time
)
1126 (re-search-forward org-babel-result-regexp nil t
))
1127 (goto-char (match-beginning 0))
1128 (org-babel-hide-hash)
1129 (goto-char (match-end 0)))))
1130 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1132 (defun org-babel-hash-at-point (&optional point
)
1133 "Return the value of the hash at POINT.
1134 The hash is also added as the last element of the kill ring.
1135 This can be called with C-c C-c."
1137 (let ((hash (car (delq nil
(mapcar
1138 (lambda (ol) (overlay-get ol
'babel-hash
))
1139 (overlays-at (or point
(point))))))))
1140 (when hash
(kill-new hash
) (message hash
))))
1141 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1143 (defun org-babel-result-hide-spec ()
1144 "Hide portions of results lines.
1145 Add `org-babel-hide-result' as an invisibility spec for hiding
1146 portions of results lines."
1147 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1148 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1150 (defvar org-babel-hide-result-overlays nil
1151 "Overlays hiding results.")
1153 (defun org-babel-result-hide-all ()
1154 "Fold all results in the current buffer."
1156 (org-babel-show-result-all)
1158 (while (re-search-forward org-babel-result-regexp nil t
)
1159 (save-excursion (goto-char (match-beginning 0))
1160 (org-babel-hide-result-toggle-maybe)))))
1162 (defun org-babel-show-result-all ()
1163 "Unfold all results in the current buffer."
1164 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1165 (setq org-babel-hide-result-overlays nil
))
1168 (defun org-babel-hide-result-toggle-maybe ()
1169 "Toggle visibility of result at point."
1171 (let ((case-fold-search t
))
1173 (beginning-of-line 1)
1174 (looking-at org-babel-result-regexp
))
1175 (progn (org-babel-hide-result-toggle)
1176 t
) ;; to signal that we took action
1177 nil
))) ;; to signal that we did not
1179 (defun org-babel-hide-result-toggle (&optional force
)
1180 "Toggle the visibility of the current result."
1184 (if (re-search-forward org-babel-result-regexp nil t
)
1185 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1187 (while (looking-at org-babel-multi-line-header-regexp
)
1189 (goto-char (- (org-babel-result-end) 1)) (point)))
1191 (if (memq t
(mapcar (lambda (overlay)
1192 (eq (overlay-get overlay
'invisible
)
1193 'org-babel-hide-result
))
1194 (overlays-at start
)))
1195 (if (or (not force
) (eq force
'off
))
1197 (when (member ov org-babel-hide-result-overlays
)
1198 (setq org-babel-hide-result-overlays
1199 (delq ov org-babel-hide-result-overlays
)))
1200 (when (eq (overlay-get ov
'invisible
)
1201 'org-babel-hide-result
)
1202 (delete-overlay ov
)))
1203 (overlays-at start
)))
1204 (setq ov
(make-overlay start end
))
1205 (overlay-put ov
'invisible
'org-babel-hide-result
)
1206 ;; make the block accessible to isearch
1208 ov
'isearch-open-invisible
1210 (when (member ov org-babel-hide-result-overlays
)
1211 (setq org-babel-hide-result-overlays
1212 (delq ov org-babel-hide-result-overlays
)))
1213 (when (eq (overlay-get ov
'invisible
)
1214 'org-babel-hide-result
)
1215 (delete-overlay ov
))))
1216 (push ov org-babel-hide-result-overlays
)))
1217 (error "Not looking at a result line"))))
1219 ;; org-tab-after-check-for-cycling-hook
1220 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1221 ;; Remove overlays when changing major mode
1222 (add-hook 'org-mode-hook
1223 (lambda () (org-add-hook 'change-major-mode-hook
1224 'org-babel-show-result-all
'append
'local
)))
1226 (defvar org-file-properties
)
1227 (defun org-babel-params-from-properties (&optional lang
)
1228 "Retrieve parameters specified as properties.
1229 Return an association list of any source block params which
1230 may be specified in the properties of the current outline entry."
1233 (org-babel-parse-multiple-vars
1236 (lambda (header-arg)
1237 (and (setq val
(org-entry-get (point) header-arg t
))
1238 (cons (intern (concat ":" header-arg
))
1239 (org-babel-read val
))))
1244 (org-babel-combine-header-arg-lists
1245 org-babel-common-header-args-w-values
1247 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1248 (and (boundp sym
) (eval sym
))))))))))))
1250 (defvar org-src-preserve-indentation
)
1251 (defun org-babel-parse-src-block-match ()
1252 "Parse the results from a match of the `org-babel-src-block-regexp'."
1253 (let* ((block-indentation (length (match-string 1)))
1254 (lang (org-no-properties (match-string 2)))
1255 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1256 (switches (match-string 3))
1257 (body (org-no-properties
1258 (let* ((body (match-string 5))
1259 (sub-length (- (length body
) 1)))
1260 (if (and (> sub-length
0)
1261 (string= "\n" (substring body sub-length
)))
1262 (substring body
0 sub-length
)
1264 (preserve-indentation (or org-src-preserve-indentation
1266 (string-match "-i\\>" switches
)))))
1268 ;; get block body less properties, protective commas, and indentation
1271 (insert (org-unescape-code-in-string body
))
1272 (unless preserve-indentation
(org-do-remove-indentation))
1274 (org-babel-merge-params
1275 org-babel-default-header-args
1276 (org-babel-params-from-properties lang
)
1277 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1278 (org-babel-parse-header-arguments
1279 (org-no-properties (or (match-string 4) ""))))
1281 block-indentation
)))
1283 (defun org-babel-parse-inline-src-block-match ()
1284 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1285 (let* ((lang (org-no-properties (match-string 2)))
1286 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1288 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1289 (org-babel-merge-params
1290 org-babel-default-inline-header-args
1291 (org-babel-params-from-properties lang
)
1292 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1293 (org-babel-parse-header-arguments
1294 (org-no-properties (or (match-string 4) "")))))))
1296 (defun org-babel-balanced-split (string alts
)
1297 "Split STRING on instances of ALTS.
1298 ALTS is a cons of two character options where each option may be
1299 either the numeric code of a single character or a list of
1300 character alternatives. For example to split on balanced
1301 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1302 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1303 (matched (lambda (ch last
)
1305 (and (funcall matches ch
(cdr alts
))
1306 (funcall matches last
(car alts
)))
1307 (funcall matches ch alts
))))
1308 (balance 0) (last 0)
1310 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1311 (setq balance
(+ balance
1312 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1313 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1315 (when (and (equal 34 ch
) (not (equal 92 last
)))
1316 (setq quote
(not quote
)))
1317 (setq partial
(cons ch partial
))
1318 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1319 (setq lst
(cons (apply #'string
(nreverse
1326 (string-to-list string
))
1327 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1329 (defun org-babel-join-splits-near-ch (ch list
)
1330 "Join splits where \"=\" is on either end of the split."
1331 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1332 (first= (lambda (str) (= ch
(aref str
0)))))
1334 (org-reduce (lambda (acc el
)
1335 (let ((head (car acc
)))
1336 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1337 (cons (concat head el
) (cdr acc
))
1339 list
:initial-value nil
))))
1341 (defun org-babel-parse-header-arguments (arg-string)
1342 "Parse a string of header arguments returning an alist."
1343 (when (> (length arg-string
) 0)
1344 (org-babel-parse-multiple-vars
1349 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1351 (cons (intern (match-string 1 arg
))
1352 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1353 (cons (intern (org-babel-chomp arg
)) nil
)))
1355 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1356 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1358 (defun org-babel-parse-multiple-vars (header-arguments)
1359 "Expand multiple variable assignments behind a single :var keyword.
1361 This allows expression of multiple variables with one :var as
1364 #+PROPERTY: var foo=1, bar=2"
1366 (mapc (lambda (pair)
1367 (if (eq (car pair
) :var
)
1368 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1369 (org-babel-join-splits-near-ch
1370 61 (org-babel-balanced-split (cdr pair
) 32)))
1371 (push pair results
)))
1373 (nreverse results
)))
1375 (defun org-babel-process-params (params)
1376 "Expand variables in PARAMS and add summary parameters."
1377 (let* ((processed-vars (mapcar (lambda (el)
1378 (if (consp (cdr el
))
1380 (org-babel-ref-parse (cdr el
))))
1381 (org-babel-get-header params
:var
)))
1382 (vars-and-names (if (and (assoc :colname-names params
)
1383 (assoc :rowname-names params
))
1384 (list processed-vars
)
1385 (org-babel-disassemble-tables
1387 (cdr (assoc :hlines params
))
1388 (cdr (assoc :colnames params
))
1389 (cdr (assoc :rownames params
)))))
1390 (raw-result (or (cdr (assoc :results params
)) ""))
1391 (result-params (append
1392 (split-string (if (stringp raw-result
)
1395 (cdr (assoc :result-params params
)))))
1397 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1399 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1400 (cadr vars-and-names
)))
1401 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1402 (caddr vars-and-names
)))
1403 (cons :result-params result-params
)
1404 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1405 ((member "value" result-params
) 'value
)
1407 (org-babel-get-header params
:var
'other
))))
1409 ;; row and column names
1410 (defun org-babel-del-hlines (table)
1411 "Remove all 'hlines from TABLE."
1412 (remove 'hline table
))
1414 (defun org-babel-get-colnames (table)
1415 "Return the column names of TABLE.
1416 Return a cons cell, the `car' of which contains the TABLE less
1417 colnames, and the `cdr' of which contains a list of the column
1419 (if (equal 'hline
(nth 1 table
))
1420 (cons (cddr table
) (car table
))
1421 (cons (cdr table
) (car table
))))
1423 (defun org-babel-get-rownames (table)
1424 "Return the row names of TABLE.
1425 Return a cons cell, the `car' of which contains the TABLE less
1426 colnames, and the `cdr' of which contains a list of the column
1427 names. Note: this function removes any hlines in TABLE."
1428 (let* ((trans (lambda (table) (apply #'mapcar
* #'list table
)))
1430 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1431 (table (funcall trans
(mapcar (lambda (row)
1432 (if (not (equal row
'hline
))
1436 (setq row
(cons 'hline row
)))
1439 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1440 (funcall trans
(cdr table
)))
1441 (remove 'hline
(car table
)))))
1443 (defun org-babel-put-colnames (table colnames
)
1444 "Add COLNAMES to TABLE if they exist."
1445 (if colnames
(apply 'list colnames
'hline table
) table
))
1447 (defun org-babel-put-rownames (table rownames
)
1448 "Add ROWNAMES to TABLE if they exist."
1450 (mapcar (lambda (row)
1452 (cons (or (pop rownames
) "") row
)
1456 (defun org-babel-pick-name (names selector
)
1457 "Select one out of an alist of row or column names.
1458 SELECTOR can be either a list of names in which case those names
1459 will be returned directly, or an index into the list NAMES in
1460 which case the indexed names will be return."
1461 (if (listp selector
)
1464 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1465 (cdr (assoc selector names
))
1466 (if (integerp selector
)
1467 (nth (- selector
1) names
)
1468 (cdr (car (last names
))))))))
1470 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1471 "Parse tables for further processing.
1472 Process the variables in VARS according to the HLINES,
1473 ROWNAMES and COLNAMES header arguments. Return a list consisting
1474 of the vars, cnames and rnames."
1475 (let (cnames rnames
)
1479 (when (listp (cdr var
))
1480 (when (and (not (equal colnames
"no"))
1481 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1482 (not (member 'hline
(cddr (cdr var
)))))))
1483 (let ((both (org-babel-get-colnames (cdr var
))))
1484 (setq cnames
(cons (cons (car var
) (cdr both
))
1486 (setq var
(cons (car var
) (car both
)))))
1487 (when (and rownames
(not (equal rownames
"no")))
1488 (let ((both (org-babel-get-rownames (cdr var
))))
1489 (setq rnames
(cons (cons (car var
) (cdr both
))
1491 (setq var
(cons (car var
) (car both
)))))
1492 (when (and hlines
(not (equal hlines
"yes")))
1493 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1496 (reverse cnames
) (reverse rnames
))))
1498 (defun org-babel-reassemble-table (table colnames rownames
)
1499 "Add column and row names to a table.
1500 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1501 to the table for reinsertion to org-mode."
1504 (if (and colnames
(listp (car table
)) (= (length (car table
))
1506 (org-babel-put-colnames table colnames
) table
))
1507 (if (and rownames
(= (length table
) (length rownames
)))
1508 (org-babel-put-rownames table rownames
) table
))
1511 (defun org-babel-where-is-src-block-head ()
1512 "Find where the current source block begins.
1513 Return the point at the beginning of the current source
1514 block. Specifically at the beginning of the #+BEGIN_SRC line.
1515 If the point is not on a source block then return nil."
1516 (let ((initial (point)) (case-fold-search t
) top bottom
)
1518 (save-excursion ;; on a source name line or a #+header line
1519 (beginning-of-line 1)
1520 (and (or (looking-at org-babel-src-name-regexp
)
1521 (looking-at org-babel-multi-line-header-regexp
))
1523 (while (and (forward-line 1)
1524 (or (looking-at org-babel-src-name-regexp
)
1525 (looking-at org-babel-multi-line-header-regexp
))))
1526 (looking-at org-babel-src-block-regexp
))
1528 (save-excursion ;; on a #+begin_src line
1529 (beginning-of-line 1)
1530 (and (looking-at org-babel-src-block-regexp
)
1532 (save-excursion ;; inside a src block
1534 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1535 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1536 (< top initial
) (< initial bottom
)
1537 (progn (goto-char top
) (beginning-of-line 1)
1538 (looking-at org-babel-src-block-regexp
))
1542 (defun org-babel-goto-src-block-head ()
1543 "Go to the beginning of the current code block."
1546 (if head
(goto-char head
) (error "Not currently in a code block")))
1547 (org-babel-where-is-src-block-head)))
1550 (defun org-babel-goto-named-src-block (name)
1551 "Go to a named source-code block."
1553 (let ((completion-ignore-case t
)
1554 (case-fold-search t
)
1555 (under-point (thing-at-point 'line
)))
1556 (list (org-icompleting-read
1557 "source-block name: " (org-babel-src-block-names) nil t
1560 ((string-match (org-babel-noweb-wrap) under-point
)
1561 (let ((block-name (match-string 1 under-point
)))
1562 (string-match "[^(]*" block-name
)
1563 (match-string 0 block-name
)))
1565 ((string-match org-babel-lob-one-liner-regexp under-point
)
1566 (let ((source-info (car (org-babel-lob-get-info))))
1567 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1568 (let ((source-name (match-string 1 source-info
)))
1571 ((string-match (concat "#\\+" org-babel-results-keyword
1572 "\\:\s+\\([^\\(]*\\)") under-point
)
1573 (match-string 1 under-point
))
1575 ((and (thing-at-point 'symbol
))
1576 (org-babel-find-named-block (thing-at-point 'symbol
))
1577 (thing-at-point 'symbol
))
1579 (let ((point (org-babel-find-named-block name
)))
1581 ;; taken from `org-open-at-point'
1582 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1583 (message "source-code block '%s' not found in this buffer" name
))))
1585 (defun org-babel-find-named-block (name)
1586 "Find a named source-code block.
1587 Return the location of the source block identified by source
1588 NAME, or nil if no such block exists. Set match data according to
1589 org-babel-named-src-block-regexp."
1591 (let ((case-fold-search t
)
1592 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1593 (goto-char (point-min))
1594 (when (or (re-search-forward regexp nil t
)
1595 (re-search-backward regexp nil t
))
1596 (match-beginning 0)))))
1598 (defun org-babel-src-block-names (&optional file
)
1599 "Returns the names of source blocks in FILE or the current buffer."
1601 (when file
(find-file file
)) (goto-char (point-min))
1602 (let ((case-fold-search t
) names
)
1603 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1604 (setq names
(cons (match-string 3) names
)))
1608 (defun org-babel-goto-named-result (name)
1609 "Go to a named result."
1611 (let ((completion-ignore-case t
))
1612 (list (org-icompleting-read "source-block name: "
1613 (org-babel-result-names) nil t
))))
1614 (let ((point (org-babel-find-named-result name
)))
1616 ;; taken from `org-open-at-point'
1617 (progn (goto-char point
) (org-show-context))
1618 (message "result '%s' not found in this buffer" name
))))
1620 (defun org-babel-find-named-result (name &optional point
)
1621 "Find a named result.
1622 Return the location of the result named NAME in the current
1623 buffer or nil if no such result exists."
1625 (let ((case-fold-search t
))
1626 (goto-char (or point
(point-min)))
1627 (catch 'is-a-code-block
1628 (when (re-search-forward
1629 (concat org-babel-result-regexp
1630 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1631 (when (and (string= "name" (downcase (match-string 1)))
1632 (or (beginning-of-line 1)
1633 (looking-at org-babel-src-block-regexp
)
1634 (looking-at org-babel-multi-line-header-regexp
)))
1635 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1636 (beginning-of-line 0) (point))))))
1638 (defun org-babel-result-names (&optional file
)
1639 "Returns the names of results in FILE or the current buffer."
1641 (when file
(find-file file
)) (goto-char (point-min))
1642 (let ((case-fold-search t
) names
)
1643 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1644 (setq names
(cons (match-string 4) names
)))
1648 (defun org-babel-next-src-block (&optional arg
)
1649 "Jump to the next source block.
1650 With optional prefix argument ARG, jump forward ARG many source blocks."
1652 (org-next-block arg nil org-babel-src-block-regexp
))
1655 (defun org-babel-previous-src-block (&optional arg
)
1656 "Jump to the previous source block.
1657 With optional prefix argument ARG, jump backward ARG many source blocks."
1659 (org-previous-block arg org-babel-src-block-regexp
))
1661 (defvar org-babel-load-languages
)
1664 (defun org-babel-mark-block ()
1665 "Mark current src block."
1671 (looking-at org-babel-src-block-regexp
))
1672 (push-mark (match-end 5) nil t
)
1673 (goto-char (match-beginning 5))))
1674 (org-babel-where-is-src-block-head)))
1676 (defun org-babel-demarcate-block (&optional arg
)
1677 "Wrap or split the code in the region or on the point.
1678 When called from inside of a code block the current block is
1679 split. When called from outside of a code block a new code block
1680 is created. In both cases if the region is demarcated and if the
1681 region is not active then the point is demarcated."
1683 (let ((info (org-babel-get-src-block-info 'light
))
1684 (headers (progn (org-babel-where-is-src-block-head)
1686 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1692 (let ((lang (nth 0 info
))
1693 (indent (make-string (nth 5 info
) ?
)))
1694 (when (string-match "^[[:space:]]*$"
1695 (buffer-substring (point-at-bol)
1697 (delete-region (point-at-bol) (point-at-eol)))
1699 (if (looking-at "^") "" "\n")
1700 indent
"#+end_src\n"
1701 (if arg stars indent
) "\n"
1702 indent
"#+begin_src " lang
1703 (if (> (length headers
) 1)
1704 (concat " " headers
) headers
)
1705 (if (looking-at "[\n\r]")
1707 (concat "\n" (make-string (current-column) ?
)))))))
1708 (move-end-of-line 2))
1709 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1710 (let ((start (point))
1711 (lang (org-icompleting-read "Lang: "
1712 (mapcar (lambda (el) (symbol-name (car el
)))
1713 org-babel-load-languages
)))
1714 (body (delete-and-extract-region
1715 (if (org-region-active-p) (mark) (point)) (point))))
1716 (insert (concat (if (looking-at "^") "" "\n")
1717 (if arg
(concat stars
"\n") "")
1718 "#+begin_src " lang
"\n"
1720 (if (or (= (length body
) 0)
1721 (string-match "[\r\n]$" body
)) "" "\n")
1723 (goto-char start
) (move-end-of-line 1)))))
1725 (defvar org-babel-lob-one-liner-regexp
)
1726 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1727 "Find where the current source block results begin.
1728 Return the point at the beginning of the result of the current
1729 source block. Specifically at the beginning of the results line.
1730 If no result exists for this block then create a results line
1731 following the source block."
1733 (let* ((case-fold-search t
)
1734 (on-lob-line (save-excursion
1735 (beginning-of-line 1)
1736 (looking-at org-babel-lob-one-liner-regexp
)))
1737 (inlinep (when (org-babel-get-inline-src-block-matches)
1739 (name (if on-lob-line
1740 (mapconcat #'identity
(butlast (org-babel-lob-get-info)) "")
1741 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1742 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1744 (when head
(goto-char head
))
1745 (org-with-wide-buffer
1747 found
;; was there a result (before we potentially insert one)
1752 ;; - return t if it is found, else return nil
1753 ;; - if it does not need to be rebuilt, then don't set end
1754 ;; - if it does need to be rebuilt then do set end
1755 name
(setq beg
(org-babel-find-named-result name
))
1757 (when (and hash
(not (string= hash
(match-string 5))))
1758 (goto-char beg
) (setq end beg
) ;; beginning of result
1760 (delete-region end
(org-babel-result-end)) nil
)))
1763 ;; - return t if it is found, else return nil
1764 ;; - if it is found, and the hash doesn't match, delete and set end
1765 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1766 (progn (end-of-line 1)
1767 (if (eobp) (insert "\n") (forward-char 1))
1770 (progn ;; unnamed results line already exists
1771 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1772 (beginning-of-line 1)
1774 (concat org-babel-result-regexp
"\n")))
1775 (let ((this-hash (match-string 5)))
1777 ;; must remove and rebuild if hash!=old-hash
1778 (if (and hash
(not (string= hash this-hash
)))
1782 end
(org-babel-result-end)))
1783 (setq end nil
)))))))))))
1784 (if (not (and insert end
)) found
1787 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1789 (when (wholenump indent
) (make-string indent ?
))
1790 "#+" org-babel-results-keyword
1792 (if org-babel-hash-show-time
1794 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1795 (concat "["hash
"]")))
1797 (when name
(concat " " name
)) "\n"))
1798 (unless beg
(insert "\n") (backward-char))
1799 (beginning-of-line 0)
1800 (if hash
(org-babel-hide-hash))
1803 (defvar org-block-regexp
)
1804 (defun org-babel-read-result ()
1805 "Read the result at `point' into emacs-lisp."
1806 (let ((case-fold-search t
) result-string
)
1808 ((org-at-table-p) (org-babel-read-table))
1809 ((org-at-item-p) (org-babel-read-list))
1810 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1811 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1812 ((looking-at "^[ \t]*: ")
1815 (mapconcat (lambda (line)
1816 (if (and (> (length line
) 1)
1817 (string-match "^[ \t]*: \\(.+\\)" line
))
1818 (match-string 1 line
)
1822 (point) (org-babel-result-end)) "[\r\n]+")
1824 (or (org-babel-number-p result-string
) result-string
))
1825 ((looking-at org-babel-result-regexp
)
1826 (save-excursion (forward-line 1) (org-babel-read-result))))))
1828 (defun org-babel-read-table ()
1829 "Read the table at `point' into emacs-lisp."
1830 (mapcar (lambda (row)
1831 (if (and (symbolp row
) (equal row
'hline
)) row
1832 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1833 (org-table-to-lisp)))
1835 (defun org-babel-read-list ()
1836 "Read the list at `point' into emacs-lisp."
1837 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1838 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1840 (defvar org-link-types-re
)
1841 (defun org-babel-read-link ()
1842 "Read the link at `point' into emacs-lisp.
1843 If the path of the link is a file path it is expanded using
1844 `expand-file-name'."
1845 (let* ((case-fold-search t
)
1846 (raw (and (looking-at org-bracket-link-regexp
)
1847 (org-no-properties (match-string 1))))
1848 (type (and (string-match org-link-types-re raw
)
1849 (match-string 1 raw
))))
1851 ((not type
) (expand-file-name raw
))
1852 ((string= type
"file")
1853 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1854 (expand-file-name (match-string 2 raw
))))
1857 (defun org-babel-format-result (result &optional sep
)
1858 "Format RESULT for writing to file."
1859 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
1863 result
(list :sep
(or sep
"\t") :fmt echo-res
))
1865 (funcall echo-res result
))))
1867 (defun org-babel-insert-result
1868 (result &optional result-params info hash indent lang
)
1869 "Insert RESULT into the current buffer.
1870 By default RESULT is inserted after the end of the
1871 current source block. With optional argument RESULT-PARAMS
1872 controls insertion of results in the org-mode file.
1873 RESULT-PARAMS can take the following values:
1875 replace - (default option) insert results after the source block
1876 replacing any previously inserted results
1878 silent -- no results are inserted into the Org-mode buffer but
1879 the results are echoed to the minibuffer and are
1880 ingested by Emacs (a potentially time consuming
1883 file ---- the results are interpreted as a file path, and are
1884 inserted into the buffer using the Org-mode file syntax
1886 list ---- the results are interpreted as an Org-mode list.
1888 raw ----- results are added directly to the Org-mode file. This
1889 is a good option if you code block will output org-mode
1892 drawer -- results are added directly to the Org-mode file as with
1893 \"raw\", but are wrapped in a RESULTS drawer, allowing
1894 them to later be replaced or removed automatically.
1896 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1897 They are not comma-escaped when inserted, but Org syntax
1898 here will be discarded when exporting the file.
1900 html ---- results are added inside of a #+BEGIN_HTML block. This
1901 is a good option if you code block will output html
1904 latex --- results are added inside of a #+BEGIN_LATEX block.
1905 This is a good option if you code block will output
1906 latex formatted text.
1908 code ---- the results are extracted in the syntax of the source
1909 code of the language being evaluated and are added
1910 inside of a #+BEGIN_SRC block with the source-code
1911 language set appropriately. Note this relies on the
1912 optional LANG argument."
1913 (if (stringp result
)
1915 (setq result
(org-no-properties result
))
1916 (when (member "file" result-params
)
1917 (setq result
(org-babel-result-to-file
1918 result
(when (assoc :file-desc
(nth 2 info
))
1919 (or (cdr (assoc :file-desc
(nth 2 info
)))
1921 (unless (listp result
) (setq result
(format "%S" result
))))
1922 (if (and result-params
(member "silent" result-params
))
1924 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1929 (when (or (org-babel-get-inline-src-block-matches)
1930 (org-babel-get-lob-one-liner-matches))
1931 (goto-char (match-end 0))
1932 (insert (if (listp result
) "\n" " "))
1934 (existing-result (unless inlinep
1935 (org-babel-where-is-src-block-result
1936 t info hash indent
)))
1938 (cdr (assoc :results_switches
(nth 2 info
))))
1939 (visible-beg (copy-marker (point-min)))
1940 (visible-end (copy-marker (point-max)))
1941 ;; When results exist outside of the current visible
1942 ;; region of the buffer, be sure to widen buffer to
1944 (outside-scope-p (and existing-result
1945 (or (> visible-beg existing-result
)
1946 (<= visible-end existing-result
))))
1948 (when (and (stringp result
) ; ensure results end in a newline
1950 (> (length result
) 0)
1951 (not (or (string-equal (substring result -
1) "\n")
1952 (string-equal (substring result -
1) "\r"))))
1953 (setq result
(concat result
"\n")))
1956 (when outside-scope-p
(widen))
1957 (if (not existing-result
)
1958 (setq beg
(or inlinep
(point)))
1959 (goto-char existing-result
)
1961 (re-search-forward "#" nil t
)
1962 (setq indent
(- (current-column) 1)))
1966 ((member "replace" result-params
)
1967 (delete-region (point) (org-babel-result-end)))
1968 ((member "append" result-params
)
1969 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1970 ((member "prepend" result-params
)))) ; already there
1971 (setq results-switches
1972 (if results-switches
(concat " " results-switches
) ""))
1973 (let ((wrap (lambda (start finish
&optional no-escape
)
1974 (goto-char end
) (insert (concat finish
"\n"))
1975 (goto-char beg
) (insert (concat start
"\n"))
1977 (org-escape-code-in-region (min (point) end
) end
))
1978 (goto-char end
) (goto-char (point-at-eol))
1979 (setq end
(point-marker))))
1980 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
1981 ;; insert results based on type
1983 ;; do nothing for an empty result
1985 ;; insert a list if preferred
1986 ((member "list" result-params
)
1989 (org-list-to-generic
1992 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1993 (if (listp result
) result
(list result
))))
1994 '(:splicep nil
:istart
"- " :iend
"\n")))
1996 ;; assume the result is a table if it's not a string
1997 ((funcall proper-list-p result
)
1999 (insert (concat (orgtbl-to-orgtbl
2000 (if (or (eq 'hline
(car result
))
2001 (and (listp (car result
))
2002 (listp (cdr (car result
)))))
2003 result
(list result
))
2004 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
2005 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
2006 ((and (listp result
) (not (funcall proper-list-p result
)))
2007 (insert (format "%s\n" result
)))
2008 ((member "file" result-params
)
2009 (when inlinep
(goto-char inlinep
))
2011 (t (goto-char beg
) (insert result
)))
2012 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2013 (setq end
(point-marker))
2014 ;; possibly wrap result
2016 ((assoc :wrap
(nth 2 info
))
2017 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2018 (funcall wrap
(concat "#+BEGIN_" name
)
2019 (concat "#+END_" (car (org-split-string name
))))))
2020 ((member "html" result-params
)
2021 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2022 ((member "latex" result-params
)
2023 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2024 ((member "org" result-params
)
2025 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2026 ((member "code" result-params
)
2027 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2029 ((member "raw" result-params
)
2030 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2031 ((or (member "drawer" result-params
)
2032 ;; Stay backward compatible with <7.9.2
2033 (member "wrap" result-params
))
2034 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2035 ((and (not (funcall proper-list-p result
))
2036 (not (member "file" result-params
)))
2037 (org-babel-examplize-region beg end results-switches
)
2038 (setq end
(point)))))
2039 ;; possibly indent the results to match the #+results line
2040 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2041 ;; in this case `table-align' does the work for us
2042 (not (and (listp result
)
2043 (member "append" result-params
))))
2044 (indent-rigidly beg end indent
))
2046 (if (member "value" result-params
)
2047 (message "Code block returned no value.")
2048 (message "Code block produced no output."))
2049 (message "Code block evaluation complete.")))
2050 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2051 (set-marker visible-beg nil
)
2052 (set-marker visible-end nil
))))))
2054 (defun org-babel-remove-result (&optional info
)
2055 "Remove the result of the current source block."
2057 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
2059 (setq start
(- location
1))
2061 (goto-char location
) (forward-line 1)
2062 (delete-region start
(org-babel-result-end))))))
2064 (defun org-babel-result-end ()
2065 "Return the point at the end of the current set of results."
2068 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2069 ((org-at-item-p) (let* ((struct (org-list-struct))
2070 (prvs (org-list-prevs-alist struct
)))
2071 (org-list-get-list-end (point-at-bol) struct prvs
)))
2072 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2073 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2074 (forward-char 1) (point)))
2076 (let ((case-fold-search t
))
2077 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2078 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2081 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2085 (defun org-babel-result-to-file (result &optional description
)
2086 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2087 If the `default-directory' is different from the containing
2088 file's directory then expand relative links."
2089 (when (stringp result
)
2090 (format "[[file:%s]%s]"
2091 (if (and default-directory
2093 (not (string= (expand-file-name default-directory
)
2095 (file-name-directory buffer-file-name
)))))
2096 (expand-file-name result default-directory
)
2098 (if description
(concat "[" description
"]") ""))))
2100 (defvar org-babel-capitalize-examplize-region-markers nil
2101 "Make true to capitalize begin/end example markers inserted by code blocks.")
2103 (defun org-babel-examplize-region (beg end
&optional results-switches
)
2104 "Comment out region using the inline '==' or ': ' org example quote."
2106 (let ((chars-between (lambda (b e
)
2107 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2108 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2109 (upcase str
) str
))))
2110 (if (or (funcall chars-between
(save-excursion (goto-char beg
) (point-at-bol)) beg
)
2111 (funcall chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2114 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
2115 (delete-region beg end
)))))
2116 (let ((size (count-lines beg end
)))
2118 (cond ((= size
0)) ; do nothing for an empty result
2119 ((< size org-babel-min-lines-for-block-output
)
2122 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2125 (insert (if results-switches
2127 (funcall maybe-cap
"#+begin_example")
2129 (funcall maybe-cap
"#+begin_example\n")))
2130 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2131 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2133 (defun org-babel-update-block-body (new-body)
2134 "Update the body of the current code block to NEW-BODY."
2135 (if (not (org-babel-where-is-src-block-head))
2136 (error "Not in a source block")
2138 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2139 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2141 (defun org-babel-merge-params (&rest plists
)
2142 "Combine all parameter association lists in PLISTS.
2143 Later elements of PLISTS override the values of previous elements.
2144 This takes into account some special considerations for certain
2145 parameters when merging lists."
2146 (let* ((results-exclusive-groups
2147 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2148 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2149 (exports-exclusive-groups
2150 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2151 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2153 (e-merge (lambda (exclusive-groups &rest result-params
)
2154 ;; maintain exclusivity of mutually exclusive parameters
2156 (mapc (lambda (new-params)
2157 (mapc (lambda (new-param)
2158 (mapc (lambda (exclusive-group)
2159 (when (member new-param exclusive-group
)
2160 (mapcar (lambda (excluded-param)
2167 (setq output
(org-uniquify
2168 (cons new-param output
))))
2172 params results exports tangle noweb cache vars shebang comments padline
)
2180 (let ((name (if (listp (cdr pair
))
2182 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2184 (intern (match-string 1 (cdr pair
)))))))
2188 (if (member name
(mapcar #'car vars
))
2192 (unless (equal (car p
) name
) p
))
2195 (list (cons name pair
))))
2196 ;; if no name is given and we already have named variables
2197 ;; then assign to named variables in order
2198 (if (and vars
(nth variable-index vars
))
2199 (prog1 (setf (cddr (nth variable-index vars
))
2200 (concat (symbol-name
2201 (car (nth variable-index vars
)))
2203 (incf variable-index
))
2204 (error "Variable \"%s\" must be assigned a default value"
2207 (setq results
(funcall e-merge results-exclusive-groups
2210 (let ((r (cdr pair
)))
2211 (if (stringp r
) r
(eval r
)))))))
2214 (setq results
(funcall e-merge results-exclusive-groups
2216 (unless (or (member "both" exports
)
2217 (member "none" exports
)
2218 (member "code" exports
))
2219 (setq exports
(funcall e-merge exports-exclusive-groups
2220 exports
'("results"))))
2221 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2223 (setq exports
(funcall e-merge exports-exclusive-groups
2224 exports
(split-string (cdr pair
)))))
2225 (:tangle
;; take the latest -- always overwrite
2226 (setq tangle
(or (list (cdr pair
)) tangle
)))
2228 (setq noweb
(funcall e-merge
2229 '(("yes" "no" "tangle" "no-export"
2230 "strip-export" "eval"))
2232 (split-string (or (cdr pair
) "")))))
2234 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2235 (split-string (or (cdr pair
) "")))))
2237 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2238 (split-string (or (cdr pair
) "")))))
2239 (:shebang
;; take the latest -- always overwrite
2240 (setq shebang
(or (list (cdr pair
)) shebang
)))
2242 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2243 (split-string (or (cdr pair
) "")))))
2244 (t ;; replace: this covers e.g. :session
2245 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2248 (setq vars
(reverse vars
))
2249 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2252 (let ((key (intern (concat ":" (symbol-name hd
))))
2254 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2255 '(results exports tangle noweb padline cache shebang comments
))
2258 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2259 "Set to true to use regular expressions to expand noweb references.
2260 This results in much faster noweb reference expansion but does
2261 not properly allow code blocks to inherit the \":noweb-ref\"
2262 header argument from buffer or subtree wide properties.")
2264 (defun org-babel-noweb-p (params context
)
2265 "Check if PARAMS require expansion in CONTEXT.
2266 CONTEXT may be one of :tangle, :export or :eval."
2268 (intersect (lambda (as bs
)
2270 (if (member (car as
) bs
)
2272 (funcall intersect
(cdr as
) bs
))))))
2273 (funcall intersect
(case context
2274 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2275 (:eval
'("yes" "no-export" "strip-export" "eval"))
2277 (split-string (or (cdr (assoc :noweb params
)) "")))))
2279 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2280 "Expand Noweb references in the body of the current source code block.
2282 For example the following reference would be replaced with the
2283 body of the source-code block named 'example-block'.
2287 Note that any text preceding the <<foo>> construct on a line will
2288 be interposed between the lines of the replacement text. So for
2289 example if <<foo>> is placed behind a comment, then the entire
2290 replacement text will also be commented.
2292 This function must be called from inside of the buffer containing
2293 the source-code block which holds BODY.
2295 In addition the following syntax can be used to insert the
2296 results of evaluating the source-code block named 'example-block'.
2300 Any optional arguments can be passed to example-block by placing
2301 the arguments inside the parenthesis following the convention
2302 defined by `org-babel-lob'. For example
2304 <<example-block(a=9)>>
2306 would set the value of argument \"a\" equal to \"9\". Note that
2307 these arguments are not evaluated in the current source-code
2308 block but are passed literally to the \"example-block\"."
2309 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2310 (info (or info
(org-babel-get-src-block-info)))
2313 (ob-nww-start org-babel-noweb-wrap-start
)
2314 (ob-nww-end org-babel-noweb-wrap-end
)
2315 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2316 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2317 ":noweb-ref[ \t]+" "\\)"))
2319 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2320 (c-wrap (lambda (text)
2322 (funcall (intern (concat lang
"-mode")))
2323 (comment-region (point) (progn (insert text
) (point)))
2324 (org-babel-trim (buffer-string)))))
2325 index source-name evaluate prefix blocks-in-buffer
)
2327 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2328 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2329 (insert body
) (goto-char (point-min))
2330 (setq index
(point))
2331 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2332 (save-match-data (setf source-name
(match-string 1)))
2333 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2336 (buffer-substring (match-beginning 0)
2338 (beginning-of-line 1) (point)))))
2339 ;; add interval to new-body (removing noweb reference)
2340 (goto-char (match-beginning 0))
2341 (funcall nb-add
(buffer-substring index
(point)))
2342 (goto-char (match-end 0))
2343 (setq index
(point))
2345 (with-current-buffer parent-buffer
2348 (mapconcat ;; interpose PREFIX between every line
2352 (let ((raw (org-babel-ref-resolve source-name
)))
2353 (if (stringp raw
) raw
(format "%S" raw
)))
2355 ;; retrieve from the library of babel
2356 (nth 2 (assoc (intern source-name
)
2357 org-babel-library-of-babel
))
2358 ;; return the contents of headlines literally
2360 (when (org-babel-ref-goto-headline-id source-name
)
2361 (org-babel-ref-headline-body)))
2362 ;; find the expansion of reference in this buffer
2363 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2366 (goto-char (point-min))
2367 (if org-babel-use-quick-and-dirty-noweb-expansion
2368 (while (re-search-forward rx nil t
)
2369 (let* ((i (org-babel-get-src-block-info 'light
))
2370 (body (org-babel-expand-noweb-references i
))
2371 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2375 (concat (funcall c-wrap
(car cs
)) "\n"
2377 (funcall c-wrap
(cadr cs
))))
2378 (org-babel-tangle-comment-links i
))
2380 (setq expansion
(cons sep
(cons full expansion
)))))
2381 (org-babel-map-src-blocks nil
2382 (let ((i (org-babel-get-src-block-info 'light
)))
2383 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2386 (let* ((body (org-babel-expand-noweb-references i
))
2387 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2391 (concat (funcall c-wrap
(car cs
)) "\n"
2393 (funcall c-wrap
(cadr cs
))))
2394 (org-babel-tangle-comment-links i
))
2397 (cons sep
(cons full expansion
)))))))))
2399 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2400 ;; possibly raise an error if named block doesn't exist
2401 (if (member lang org-babel-noweb-error-langs
)
2403 (org-babel-noweb-wrap source-name
)
2404 "could not be resolved (see "
2405 "`org-babel-noweb-error-langs')"))
2407 "[\n\r]") (concat "\n" prefix
))))))
2408 (funcall nb-add
(buffer-substring index
(point-max))))
2411 (defun org-babel-script-escape (str &optional force
)
2412 "Safely convert tables into elisp lists."
2413 (let (in-single in-double out
)
2414 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2418 (or (and (string-equal "[" (substring str
0 1))
2419 (string-equal "]" (substring str -
1)))
2420 (and (string-equal "{" (substring str
0 1))
2421 (string-equal "}" (substring str -
1)))
2422 (and (string-equal "(" (substring str
0 1))
2423 (string-equal ")" (substring str -
1))))))
2433 (91 (if (or in-double in-single
) ; [
2436 (93 (if (or in-double in-single
) ; ]
2439 (123 (if (or in-double in-single
) ; {
2442 (125 (if (or in-double in-single
) ; }
2445 (44 (if (or in-double in-single
) ; ,
2446 (cons 44 out
) (cons 32 out
)))
2447 (39 (if in-double
; '
2449 (setq in-single
(not in-single
)) (cons 34 out
)))
2450 (34 (if in-single
; "
2451 (append (list 34 32) out
)
2452 (setq in-double
(not in-double
)) (cons 34 out
)))
2453 (t (cons ch out
)))))
2454 (string-to-list str
))
2455 (apply #'string
(reverse out
)))))
2458 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2459 "Convert the string value of CELL to a number if appropriate.
2460 Otherwise if cell looks like lisp (meaning it starts with a
2461 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2462 return it unmodified as a string. Optional argument NO-LISP-EVAL
2463 inhibits lisp evaluation for situations in which is it not
2465 (if (and (stringp cell
) (not (equal cell
"")))
2466 (or (org-babel-number-p cell
)
2467 (if (and (not inhibit-lisp-eval
)
2468 (member (substring cell
0 1) '("(" "'" "`" "[")))
2470 (if (string= (substring cell
0 1) "\"")
2472 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2475 (defun org-babel-number-p (string)
2476 "If STRING represents a number return its value."
2477 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2478 (= (length (substring string
(match-beginning 0)
2481 (string-to-number string
)))
2483 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2484 "Read the results located at FILE-NAME into an elisp table.
2485 If the table is trivial, then return it as a scalar."
2487 (save-window-excursion
2491 (org-table-import file-name separator
)
2492 (delete-file file-name
)
2493 (setq result
(mapcar (lambda (row)
2494 (mapcar #'org-babel-string-read row
))
2495 (org-table-to-lisp))))
2496 (error (message "Error reading results: %s" err
) nil
)))
2497 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2498 (if (consp (car result
))
2499 (if (null (cdr (car result
)))
2505 (defun org-babel-string-read (cell)
2506 "Strip nested \"s from around strings."
2507 (org-babel-read (or (and (stringp cell
)
2508 (string-match "\\\"\\(.+\\)\\\"" cell
)
2509 (match-string 1 cell
))
2512 (defun org-babel-chomp (string &optional regexp
)
2513 "Strip trailing spaces and carriage returns from STRING.
2514 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2515 overwritten by specifying a regexp as a second argument."
2516 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2517 (while (and (> (length string
) 0)
2518 (string-match regexp
(substring string -
1)))
2519 (setq string
(substring string
0 -
1)))
2522 (defun org-babel-trim (string &optional regexp
)
2523 "Strip leading and trailing spaces and carriage returns from STRING.
2524 Like `org-babel-chomp' only it runs on both the front and back
2526 (org-babel-chomp (org-reverse-string
2527 (org-babel-chomp (org-reverse-string string
) regexp
))
2530 (defvar org-babel-org-babel-call-process-region-original nil
)
2531 (defun org-babel-tramp-handle-call-process-region
2532 (start end program
&optional delete buffer display
&rest args
)
2533 "Use Tramp to handle `call-process-region'.
2534 Fixes a bug in `tramp-handle-call-process-region'."
2535 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2536 (let ((tmpfile (tramp-compat-make-temp-file "")))
2537 (write-region start end tmpfile
)
2538 (when delete
(delete-region start end
))
2540 ;; (apply 'call-process program tmpfile buffer display args)
2542 (apply 'process-file program tmpfile buffer display args
)
2543 (delete-file tmpfile
)))
2544 ;; org-babel-call-process-region-original is the original emacs
2545 ;; definition. It is in scope from the let binding in
2546 ;; org-babel-execute-src-block
2547 (apply org-babel-call-process-region-original
2548 start end program delete buffer display args
)))
2550 (defun org-babel-local-file-name (file)
2551 "Return the local name component of FILE."
2552 (if (file-remote-p file
)
2554 (with-parsed-tramp-file-name file nil
2558 (defun org-babel-process-file-name (name &optional no-quote-p
)
2559 "Prepare NAME to be used in an external process.
2560 If NAME specifies a remote location, the remote portion of the
2561 name is removed, since in that case the process will be executing
2562 remotely. The file name is then processed by `expand-file-name'.
2563 Unless second argument NO-QUOTE-P is non-nil, the file name is
2564 additionally processed by `shell-quote-argument'"
2565 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2566 (expand-file-name (org-babel-local-file-name name
))))
2568 (defvar org-babel-temporary-directory
)
2569 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2570 (defvar org-babel-temporary-directory
2571 (or (and (boundp 'org-babel-temporary-directory
)
2572 (file-exists-p org-babel-temporary-directory
)
2573 org-babel-temporary-directory
)
2574 (make-temp-file "babel-" t
))
2575 "Directory to hold temporary files created to execute code blocks.
2576 Used by `org-babel-temp-file'. This directory will be removed on
2579 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2580 "Call the code to parse raw string results according to RESULT-PARAMS."
2582 (debug (form form
&rest form
)))
2583 `(unless (member "none" ,result-params
)
2584 (if (or (member "scalar" ,result-params
)
2585 (member "verbatim" ,result-params
)
2586 (member "html" ,result-params
)
2587 (member "code" ,result-params
)
2588 (member "pp" ,result-params
)
2589 (and (member "output" ,result-params
)
2590 (not (member "table" ,result-params
))))
2594 (defun org-babel-temp-file (prefix &optional suffix
)
2595 "Create a temporary file in the `org-babel-temporary-directory'.
2596 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2597 value of `temporary-file-directory' temporarily set to the value
2598 of `org-babel-temporary-directory'."
2599 (let ((temporary-file-directory
2600 (if (file-remote-p default-directory
)
2601 (concat (file-remote-p default-directory
) "/tmp")
2602 (or (and (boundp 'org-babel-temporary-directory
)
2603 (file-exists-p org-babel-temporary-directory
)
2604 org-babel-temporary-directory
)
2605 temporary-file-directory
))))
2606 (make-temp-file prefix nil suffix
)))
2608 (defun org-babel-remove-temporary-directory ()
2609 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2610 (when (and (boundp 'org-babel-temporary-directory
)
2611 (file-exists-p org-babel-temporary-directory
))
2612 ;; taken from `delete-directory' in files.el
2615 (mapc (lambda (file)
2616 ;; This test is equivalent to
2617 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2618 ;; but more efficient
2619 (if (eq t
(car (file-attributes file
)))
2620 (delete-directory file
)
2621 (delete-file file
)))
2622 ;; We do not want to delete "." and "..".
2623 (directory-files org-babel-temporary-directory
'full
2624 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2625 (delete-directory org-babel-temporary-directory
))
2627 (message "Failed to remove temporary Org-babel directory %s"
2628 (if (boundp 'org-babel-temporary-directory
)
2629 org-babel-temporary-directory
2630 "[directory not defined]"))))))
2632 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2637 ;; generated-autoload-file: "org-loaddefs.el"
2640 ;;; ob-core.el ends here