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
))
97 (defgroup org-babel nil
98 "Code block evaluation and management in `org-mode' documents."
102 (defcustom org-confirm-babel-evaluate t
103 "Confirm before evaluation.
104 Require confirmation before interactively evaluating code
105 blocks in Org-mode buffers. The default value of this variable
106 is t, meaning confirmation is required for any code block
107 evaluation. This variable can be set to nil to inhibit any
108 future confirmation requests. This variable can also be set to a
109 function which takes two arguments the language of the code block
110 and the body of the code block. Such a function should then
111 return a non-nil value if the user should be prompted for
112 execution or nil if no prompt is required.
114 Warning: Disabling confirmation may result in accidental
115 evaluation of potentially harmful code. It may be advisable
116 remove code block execution from C-c C-c as further protection
117 against accidental code block evaluation. The
118 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
119 remove code block execution from the C-c C-c keybinding."
122 :type
'(choice boolean function
))
123 ;; don't allow this variable to be changed through file settings
124 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
126 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
127 "Remove code block evaluation from the C-c C-c key binding."
132 (defcustom org-babel-results-keyword
"RESULTS"
133 "Keyword used to name results generated by code blocks.
134 Should be either RESULTS or NAME however any capitalization may
139 (defcustom org-babel-noweb-wrap-start
"<<"
140 "String used to begin a noweb reference in a code block.
141 See also `org-babel-noweb-wrap-end'."
145 (defcustom org-babel-noweb-wrap-end
">>"
146 "String used to end a noweb reference in a code block.
147 See also `org-babel-noweb-wrap-start'."
151 (defun org-babel-noweb-wrap (&optional regexp
)
152 (concat org-babel-noweb-wrap-start
153 (or regexp
"\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
154 org-babel-noweb-wrap-end
))
156 (defvar org-babel-src-name-regexp
157 "^[ \t]*#\\+name:[ \t]*"
158 "Regular expression used to match a source name line.")
160 (defvar org-babel-multi-line-header-regexp
161 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
162 "Regular expression used to match multi-line header arguments.")
164 (defvar org-babel-src-name-w-name-regexp
165 (concat org-babel-src-name-regexp
167 org-babel-multi-line-header-regexp
169 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
170 "Regular expression matching source name lines with a name.")
172 (defvar org-babel-src-block-regexp
174 ;; (1) indentation (2) lang
175 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
177 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
178 ;; (4) header arguments
181 "\\([^\000]*?\n\\)?[ \t]*#\\+end_src")
182 "Regexp used to identify code blocks.")
184 (defvar org-babel-inline-src-block-regexp
186 ;; (1) replacement target (2) lang
187 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
188 ;; (3,4) (unused, headers)
189 "\\(\\|\\[\\(.*?\\)\\]\\)"
191 "{\\([^\f\n\r\v]+?\\)}\\)")
192 "Regexp used to identify inline src-blocks.")
194 (defun org-babel-get-header (params key
&optional others
)
195 "Select only header argument of type KEY from a list.
196 Optional argument OTHERS indicates that only the header that do
197 not match KEY should be returned."
200 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
203 (defun org-babel-get-inline-src-block-matches()
204 "Set match data if within body of an inline source block.
205 Returns non-nil if match-data set"
206 (let ((src-at-0-p (save-excursion
207 (beginning-of-line 1)
208 (string= "src" (thing-at-point 'word
))))
209 (first-line-p (= 1 (line-number-at-pos)))
211 (let ((search-for (cond ((and src-at-0-p first-line-p
"src_"))
212 (first-line-p "[[:punct:] \t]src_")
213 (t "[[:punct:] \f\t\n\r\v]src_")))
214 (lower-limit (if first-line-p
216 (- (point-at-bol) 1))))
218 (when (or (and src-at-0-p
(bobp))
219 (and (re-search-forward "}" (point-at-eol) t
)
220 (re-search-backward search-for lower-limit t
)
222 (when (looking-at org-babel-inline-src-block-regexp
)
225 (defvar org-babel-inline-lob-one-liner-regexp
)
226 (defun org-babel-get-lob-one-liner-matches()
227 "Set match data if on line of an lob one liner.
228 Returns non-nil if match-data set"
230 (unless (= (point) (point-at-bol)) ;; move before inline block
231 (re-search-backward "[ \f\t\n\r\v]" nil t
))
232 (if (looking-at org-babel-inline-lob-one-liner-regexp
)
236 (defun org-babel-get-src-block-info (&optional light
)
237 "Get information on the current source block.
239 Optional argument LIGHT does not resolve remote variable
240 references; a process which could likely result in the execution
241 of other code blocks.
244 (language body header-arguments-alist switches name indent)."
245 (let ((case-fold-search t
) head info name indent
)
247 (if (setq head
(org-babel-where-is-src-block-head))
250 (setq info
(org-babel-parse-src-block-match))
251 (setq indent
(car (last info
)))
252 (setq info
(butlast info
))
253 (while (and (forward-line -
1)
254 (looking-at org-babel-multi-line-header-regexp
))
256 (org-babel-merge-params
258 (org-babel-parse-header-arguments (match-string 1)))))
259 (when (looking-at org-babel-src-name-w-name-regexp
)
260 (setq name
(org-no-properties (match-string 3)))
261 (when (and (match-string 5) (> (length (match-string 5)) 0))
262 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
263 (org-babel-merge-params
265 (lambda (ref) (cons :var ref
))
267 (lambda (var) ;; check that each variable is initialized
268 (if (string-match ".+=.+" var
)
271 "variable \"%s\"%s must be assigned a default value"
272 var
(if name
(format " in block \"%s\"" name
) ""))))
273 (org-babel-ref-split-args (match-string 5))))
275 ;; inline source block
276 (when (org-babel-get-inline-src-block-matches)
277 (setq info
(org-babel-parse-inline-src-block-match))))
278 ;; resolve variable references and add summary parameters
279 (when (and info
(not light
))
280 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
281 (when info
(append info
(list name indent
)))))
283 (defvar org-current-export-file
) ; dynamically bound
284 (defun org-babel-confirm-evaluate (info)
285 "Confirm evaluation of the code block INFO.
286 This behavior can be suppressed by setting the value of
287 `org-confirm-babel-evaluate' to nil, in which case all future
288 interactive code block evaluations will proceed without any
289 confirmation from the user.
291 Note disabling confirmation may result in accidental evaluation
292 of potentially harmful code."
293 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
294 (when (assoc :noeval
(nth 2 info
)) "no")))
295 (query (cond ((equal eval
"query") t
)
296 ((and (boundp 'org-current-export-file
)
297 org-current-export-file
298 (equal eval
"query-export")) t
)
299 ((functionp org-confirm-babel-evaluate
)
300 (funcall org-confirm-babel-evaluate
301 (nth 0 info
) (nth 1 info
)))
302 (t org-confirm-babel-evaluate
))))
303 (if (or (equal eval
"never") (equal eval
"no")
304 (and (boundp 'org-current-export-file
)
305 org-current-export-file
306 (or (equal eval
"no-export")
307 (equal eval
"never-export")))
310 (format "Evaluate this%scode block%son your system? "
311 (if info
(format " %s " (nth 0 info
)) " ")
313 (format " (%s) " (nth 4 info
)) " "))))))
314 (prog1 nil
(message "Evaluation %s"
315 (if (or (equal eval
"never") (equal eval
"no")
316 (equal eval
"no-export")
317 (equal eval
"never-export"))
318 "Disabled" "Aborted")))
322 (defun org-babel-execute-safely-maybe ()
323 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
324 (org-babel-execute-maybe)))
326 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
329 (defun org-babel-execute-maybe ()
331 (or (org-babel-execute-src-block-maybe)
332 (org-babel-lob-execute-maybe)))
334 (defun org-babel-execute-src-block-maybe ()
335 "Conditionally execute a source block.
336 Detect if this is context for a Babel src-block and if so
337 then run `org-babel-execute-src-block'."
339 (let ((info (org-babel-get-src-block-info)))
341 (progn (org-babel-eval-wipe-error-buffer)
342 (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
345 (defun org-babel-view-src-block-info ()
346 "Display information on the current source block.
347 This includes header arguments, language and name, and is largely
348 a window into the `org-babel-get-src-block-info' function."
350 (let ((info (org-babel-get-src-block-info 'light
))
351 (full (lambda (it) (> (length it
) 0)))
352 (printf (lambda (fmt &rest args
) (princ (apply #'format fmt args
)))))
354 (with-help-window (help-buffer)
355 (let ((name (nth 4 info
))
357 (switches (nth 3 info
))
358 (header-args (nth 2 info
)))
359 (when name
(funcall printf
"Name: %s\n" name
))
360 (when lang
(funcall printf
"Lang: %s\n" lang
))
361 (when (funcall full switches
) (funcall printf
"Switches: %s\n" switches
))
362 (funcall printf
"Header Arguments:\n")
363 (dolist (pair (sort header-args
364 (lambda (a b
) (string< (symbol-name (car a
))
365 (symbol-name (car b
))))))
366 (when (funcall full
(cdr pair
))
367 (funcall printf
"\t%S%s\t%s\n"
369 (if (> (length (format "%S" (car pair
))) 7) "" "\t")
373 (defun org-babel-expand-src-block-maybe ()
374 "Conditionally expand a source block.
375 Detect if this is context for a org-babel src-block and if so
376 then run `org-babel-expand-src-block'."
378 (let ((info (org-babel-get-src-block-info)))
380 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
384 (defun org-babel-load-in-session-maybe ()
385 "Conditionally load a source block in a session.
386 Detect if this is context for a org-babel src-block and if so
387 then run `org-babel-load-in-session'."
389 (let ((info (org-babel-get-src-block-info)))
391 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
394 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
397 (defun org-babel-pop-to-session-maybe ()
398 "Conditionally pop to a session.
399 Detect if this is context for a org-babel src-block and if so
400 then run `org-babel-pop-to-session'."
402 (let ((info (org-babel-get-src-block-info)))
403 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
405 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
407 (defconst org-babel-common-header-args-w-values
408 '((cache .
((no yes
)))
410 (colnames .
((nil no yes
)))
411 (comments .
((no link yes org both noweb
)))
413 (eval .
((never query
)))
414 (exports .
((code results both none
)))
417 (hlines .
((no yes
)))
418 (mkdirp .
((yes no
)))
421 (noweb .
((yes no tangle no-export strip-export
)))
424 (padline .
((yes no
)))
425 (results .
((file list vector table scalar verbatim
)
426 (raw html latex org code pp drawer
)
427 (replace silent none append prepend
)
429 (rownames .
((no yes
)))
433 (tangle .
((tangle yes no
:any
)))
437 (defconst org-babel-header-arg-names
438 (mapcar #'car org-babel-common-header-args-w-values
)
439 "Common header arguments used by org-babel.
440 Note that individual languages may define their own language
441 specific header arguments as well.")
443 (defvar org-babel-default-header-args
444 '((:session .
"none") (:results .
"replace") (:exports .
"code")
445 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no")
446 (:padnewline .
"yes"))
447 "Default arguments to use when evaluating a source block.")
449 (defvar org-babel-default-inline-header-args
450 '((:session .
"none") (:results .
"replace") (:exports .
"results"))
451 "Default arguments to use when evaluating an inline source block.")
453 (defvar org-babel-data-names
'("tblname" "results" "name"))
455 (defvar org-babel-result-regexp
456 (concat "^[ \t]*#\\+"
457 (regexp-opt org-babel-data-names t
)
459 ;; FIXME The string below is `org-ts-regexp'
460 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
461 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
462 "Regular expression used to match result lines.
463 If the results are associated with a hash key then the hash will
464 be saved in the second match data.")
466 (defvar org-babel-result-w-name-regexp
467 (concat org-babel-result-regexp
468 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
470 (defvar org-babel-min-lines-for-block-output
10
471 "The minimum number of lines for block output.
472 If number of lines of output is equal to or exceeds this
473 value, the output is placed in a #+begin_example...#+end_example
474 block. Otherwise the output is marked as literal by inserting
475 colons at the starts of the lines. This variable only takes
476 effect if the :results output option is in effect.")
478 (defvar org-babel-noweb-error-langs nil
479 "Languages for which Babel will raise literate programming errors.
480 List of languages for which errors should be raised when the
481 source code block satisfying a noweb reference in this language
482 can not be resolved.")
484 (defvar org-babel-hash-show
4
485 "Number of initial characters to show of a hidden results hash.")
487 (defvar org-babel-hash-show-time nil
488 "When not nil show the time the code block was evaluated in the result hash.")
490 (defvar org-babel-after-execute-hook nil
491 "Hook for functions to be called after `org-babel-execute-src-block'")
493 (defun org-babel-named-src-block-regexp-for-name (name)
494 "This generates a regexp used to match a src block named NAME."
495 (concat org-babel-src-name-regexp
(regexp-quote name
)
496 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
497 (substring org-babel-src-block-regexp
1)))
499 (defun org-babel-named-data-regexp-for-name (name)
500 "This generates a regexp used to match data named NAME."
501 (concat org-babel-result-regexp
(regexp-quote name
) "\\([ \t]\\|$\\)"))
504 (defvar call-process-region
)
507 (defun org-babel-execute-src-block (&optional arg info params
)
508 "Execute the current source code block.
509 Insert the results of execution into the buffer. Source code
510 execution and the collection and formatting of results can be
511 controlled through a variety of header arguments.
513 With prefix argument ARG, force re-execution even if an existing
514 result cached in the buffer would otherwise have been returned.
516 Optionally supply a value for INFO in the form returned by
517 `org-babel-get-src-block-info'.
519 Optionally supply a value for PARAMS which will be merged with
520 the header arguments specified at the front of the source code
523 (let ((info (or info
(org-babel-get-src-block-info))))
524 (when (org-babel-confirm-evaluate
526 (setf (nth 2 i
) (org-babel-merge-params (nth 2 info
) params
))
528 (let* ((lang (nth 0 info
))
530 (org-babel-process-params
531 (org-babel-merge-params (nth 2 info
) params
))
533 (cache?
(and (not arg
) (cdr (assoc :cache params
))
534 (string= "yes" (cdr (assoc :cache params
)))))
535 (result-params (cdr (assoc :result-params params
)))
536 (new-hash (when cache?
(org-babel-sha1-hash info
)))
537 (old-hash (when cache?
(org-babel-current-result-hash)))
538 (body (setf (nth 1 info
)
539 (if (org-babel-noweb-p params
:eval
)
540 (org-babel-expand-noweb-references info
)
542 (dir (cdr (assoc :dir params
)))
544 (or (and dir
(file-name-as-directory (expand-file-name dir
)))
546 (org-babel-call-process-region-original
547 (if (boundp 'org-babel-call-process-region-original
)
548 org-babel-call-process-region-original
549 (symbol-function 'call-process-region
)))
550 (indent (car (last info
)))
553 (let ((call-process-region
555 (apply 'org-babel-tramp-handle-call-process-region args
))))
556 (let ((lang-check (lambda (f)
557 (let ((f (intern (concat "org-babel-execute:" f
))))
558 (when (fboundp f
) f
)))))
560 (or (funcall lang-check lang
)
561 (funcall lang-check
(symbol-name
562 (cdr (assoc lang org-src-lang-modes
))))
563 (error "No org-babel-execute function for %s!" lang
))))
564 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
565 (save-excursion ;; return cached result
566 (goto-char (org-babel-where-is-src-block-result nil info
))
567 (end-of-line 1) (forward-char 1)
568 (setq result
(org-babel-read-result))
569 (message (replace-regexp-in-string
570 "%" "%%" (format "%S" result
))) result
)
571 (message "executing %s code block%s..."
573 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
574 (if (member "none" result-params
)
576 (funcall cmd body params
)
577 (message "result silenced"))
580 (if (and (eq (cdr (assoc :result-type params
)) 'value
)
581 (or (member "vector" result-params
)
582 (member "table" result-params
))
583 (not (listp result
)))
584 (list (list result
)) result
))
585 (funcall cmd body params
)))
586 ;; if non-empty result and :file then write to :file
587 (when (cdr (assoc :file params
))
589 (with-temp-file (cdr (assoc :file params
))
591 (org-babel-format-result
592 result
(cdr (assoc :sep
(nth 2 info
)))))))
593 (setq result
(cdr (assoc :file params
))))
594 (org-babel-insert-result
595 result result-params info new-hash indent lang
)
596 (run-hooks 'org-babel-after-execute-hook
)
599 (setq call-process-region
'org-babel-call-process-region-original
))))))
601 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
602 "Expand BODY with PARAMS.
603 Expand a block of code with org-babel according to its header
604 arguments. This generic implementation of body expansion is
605 called for languages which have not defined their own specific
606 org-babel-expand-body:lang function."
607 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
610 (defun org-babel-expand-src-block (&optional arg info params
)
611 "Expand the current source code block.
612 Expand according to the source code block's header
613 arguments and pop open the results in a preview buffer."
615 (let* ((info (or info
(org-babel-get-src-block-info)))
617 (params (setf (nth 2 info
)
618 (sort (org-babel-merge-params (nth 2 info
) params
)
619 (lambda (el1 el2
) (string< (symbol-name (car el1
))
620 (symbol-name (car el2
)))))))
621 (body (setf (nth 1 info
)
622 (if (org-babel-noweb-p params
:eval
)
623 (org-babel-expand-noweb-references info
) (nth 1 info
))))
624 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
625 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
628 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
629 (org-babel-expand-body:generic
630 body params
(and (fboundp assignments-cmd
)
631 (funcall assignments-cmd params
))))))
633 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
635 (defun org-babel-edit-distance (s1 s2
)
636 "Return the edit (levenshtein) distance between strings S1 S2."
637 (let* ((l1 (length s1
))
639 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2
) nil
))
640 (number-sequence 1 (1+ l1
)))))
641 (in (lambda (i j
) (aref (aref dist i
) j
))))
642 (setf (aref (aref dist
0) 0) 0)
643 (dolist (j (number-sequence 1 l2
))
644 (setf (aref (aref dist
0) j
) j
))
645 (dolist (i (number-sequence 1 l1
))
646 (setf (aref (aref dist i
) 0) i
)
647 (dolist (j (number-sequence 1 l2
))
648 (setf (aref (aref dist i
) j
)
650 (1+ (funcall in
(1- i
) j
))
651 (1+ (funcall in i
(1- j
)))
652 (+ (if (equal (aref s1
(1- i
)) (aref s2
(1- j
))) 0 1)
653 (funcall in
(1- i
) (1- j
)))))))
656 (defun org-babel-combine-header-arg-lists (original &rest others
)
657 "Combine a number of lists of header argument names and arguments."
658 (let ((results (copy-sequence original
)))
659 (dolist (new-list others
)
660 (dolist (arg-pair new-list
)
661 (let ((header (car arg-pair
))
662 (args (cdr arg-pair
)))
664 (cons arg-pair
(org-remove-if
665 (lambda (pair) (equal header
(car pair
)))
670 (defun org-babel-check-src-block ()
671 "Check for misspelled header arguments in the current code block."
673 ;; TODO: report malformed code block
674 ;; TODO: report incompatible combinations of header arguments
675 ;; TODO: report uninitialized variables
676 (let ((too-close 2) ;; <- control closeness to report potential match
677 (names (mapcar #'symbol-name org-babel-header-arg-names
)))
678 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg
)) 1))
679 (and (org-babel-where-is-src-block-head)
680 (org-babel-parse-header-arguments
682 (match-string 4))))))
684 (when (and (not (string= header name
))
685 (<= (org-babel-edit-distance header name
) too-close
)
686 (not (member header names
)))
687 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
689 (message "No suspicious header arguments found.")))
692 (defun org-babel-insert-header-arg ()
693 "Insert a header argument selecting from lists of common args and values."
695 (let* ((lang (car (org-babel-get-src-block-info 'light
)))
696 (lang-headers (intern (concat "org-babel-header-args:" lang
)))
697 (headers (org-babel-combine-header-arg-lists
698 org-babel-common-header-args-w-values
699 (if (boundp lang-headers
) (eval lang-headers
) nil
)))
700 (arg (org-icompleting-read
703 (lambda (header-spec) (symbol-name (car header-spec
)))
706 (let ((vals (cdr (assoc (intern arg
) headers
))))
712 (read-from-minibuffer "value: "))
716 (let ((arg (org-icompleting-read
718 (cons "default" (mapcar #'symbol-name group
)))))
719 (if (and arg
(not (string= "default" arg
)))
724 ;; Add support for completing-read insertion of header arguments after ":"
725 (defun org-babel-header-arg-expand ()
726 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
727 (when (and (equal (char-before) ?\
:) (org-babel-where-is-src-block-head))
728 (org-babel-enter-header-arg-w-completion (match-string 2))))
730 (defun org-babel-enter-header-arg-w-completion (&optional lang
)
731 "Insert header argument appropriate for LANG with completion."
732 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang
)))
733 (lang-headers (when (boundp lang-headers-var
) (eval lang-headers-var
)))
734 (headers-w-values (org-babel-combine-header-arg-lists
735 org-babel-common-header-args-w-values lang-headers
))
736 (headers (mapcar #'symbol-name
(mapcar #'car headers-w-values
)))
737 (header (org-completing-read "Header Arg: " headers
))
738 (args (cdr (assoc (intern header
) headers-w-values
)))
739 (arg (when (and args
(listp args
))
741 (format "%s: " header
)
742 (mapcar #'symbol-name
(apply #'append args
))))))
743 (insert (concat header
" " (or arg
"")))
746 (add-hook 'org-tab-first-hook
'org-babel-header-arg-expand
)
749 (defun org-babel-load-in-session (&optional arg info
)
750 "Load the body of the current source-code block.
751 Evaluate the header arguments for the source block before
752 entering the session. After loading the body this pops open the
755 (let* ((info (or info
(org-babel-get-src-block-info)))
757 (params (nth 2 info
))
758 (body (setf (nth 1 info
)
759 (if (org-babel-noweb-p params
:eval
)
760 (org-babel-expand-noweb-references info
)
762 (session (cdr (assoc :session params
)))
763 (dir (cdr (assoc :dir params
)))
765 (or (and dir
(file-name-as-directory dir
)) default-directory
))
766 (cmd (intern (concat "org-babel-load-session:" lang
))))
767 (unless (fboundp cmd
)
768 (error "No org-babel-load-session function for %s!" lang
))
769 (pop-to-buffer (funcall cmd session body params
))
773 (defun org-babel-initiate-session (&optional arg info
)
774 "Initiate session for current code block.
775 If called with a prefix argument then resolve any variable
776 references in the header arguments and assign these variables in
777 the session. Copy the body of the code block to the kill ring."
779 (let* ((info (or info
(org-babel-get-src-block-info (not arg
))))
782 (params (nth 2 info
))
783 (session (cdr (assoc :session params
)))
784 (dir (cdr (assoc :dir params
)))
786 (or (and dir
(file-name-as-directory dir
)) default-directory
))
787 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
788 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
789 (if (and (stringp session
) (string= session
"none"))
790 (error "This block is not using a session!"))
791 (unless (fboundp init-cmd
)
792 (error "No org-babel-initiate-session function for %s!" lang
))
793 (with-temp-buffer (insert (org-babel-trim body
))
794 (copy-region-as-kill (point-min) (point-max)))
796 (unless (fboundp prep-cmd
)
797 (error "No org-babel-prep-session function for %s!" lang
))
798 (funcall prep-cmd session params
))
799 (funcall init-cmd session params
)))
802 (defun org-babel-switch-to-session (&optional arg info
)
803 "Switch to the session of the current code block.
804 Uses `org-babel-initiate-session' to start the session. If called
805 with a prefix argument then this is passed on to
806 `org-babel-initiate-session'."
808 (pop-to-buffer (org-babel-initiate-session arg info
))
811 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
814 (defun org-babel-switch-to-session-with-code (&optional arg info
)
815 "Switch to code buffer and display session."
819 (let ((other-window-buffer (window-buffer (next-window))))
820 (set-window-buffer (next-window) (current-buffer))
821 (set-window-buffer (selected-window) other-window-buffer
))
823 (info (org-babel-get-src-block-info))
824 (org-src-window-setup 'reorganize-frame
))
826 (org-babel-switch-to-session arg info
))
828 (funcall swap-windows
)))
830 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
831 "Evaluate BODY in edit buffer if there is a code block at point.
832 Return t if a code block was found at point, nil otherwise."
833 `(let ((org-src-window-setup 'switch-invisibly
))
834 (when (and (org-babel-where-is-src-block-head)
835 (org-edit-src-code nil nil nil
))
836 (unwind-protect (progn ,@body
)
837 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
838 (org-edit-src-exit)))
840 (def-edebug-spec org-babel-do-in-edit-buffer
(body))
842 (defun org-babel-do-key-sequence-in-edit-buffer (key)
843 "Read key sequence and execute the command in edit buffer.
844 Enter a key sequence to be executed in the language major-mode
845 edit buffer. For example, TAB will alter the contents of the
846 Org-mode code block according to the effect of TAB in the
847 language major-mode buffer. For languages that support
848 interactive sessions, this can be used to send code from the Org
849 buffer to the session for evaluation using the native major-mode
850 evaluation mechanisms."
851 (interactive "kEnter key-sequence to execute in edit buffer: ")
852 (org-babel-do-in-edit-buffer
854 (key-binding (or key
(read-key-sequence nil
))))))
856 (defvar org-bracket-link-regexp
)
859 (defun org-babel-open-src-block-result (&optional re-run
)
860 "If `point' is on a src block then open the results of the
861 source code block, otherwise return nil. With optional prefix
862 argument RE-RUN the source-code block is evaluated even if
863 results already exist."
865 (let ((info (org-babel-get-src-block-info)))
868 ;; go to the results, if there aren't any then run the block
869 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
870 (progn (org-babel-execute-src-block)
871 (org-babel-where-is-src-block-result))))
873 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
875 (if (looking-at org-bracket-link-regexp
)
878 (let ((r (org-babel-format-result
879 (org-babel-read-result) (cdr (assoc :sep
(nth 2 info
))))))
880 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
881 (delete-region (point-min) (point-max))
886 (defmacro org-babel-map-src-blocks
(file &rest body
)
887 "Evaluate BODY forms on each source-block in FILE.
888 If FILE is nil evaluate BODY forms on source blocks in current
889 buffer. During evaluation of BODY the following local variables
890 are set relative to the currently matched code block.
892 full-block ------- string holding the entirety of the code block
893 beg-block -------- point at the beginning of the code block
894 end-block -------- point at the end of the matched code block
895 lang ------------- string holding the language of the code block
896 beg-lang --------- point at the beginning of the lang
897 end-lang --------- point at the end of the lang
898 switches --------- string holding the switches
899 beg-switches ----- point at the beginning of the switches
900 end-switches ----- point at the end of the switches
901 header-args ------ string holding the header-args
902 beg-header-args -- point at the beginning of the header-args
903 end-header-args -- point at the end of the header-args
904 body ------------- string holding the body of the code block
905 beg-body --------- point at the beginning of the body
906 end-body --------- point at the end of the body"
908 (let ((tempvar (make-symbol "file")))
909 `(let* ((,tempvar
,file
)
910 (visited-p (or (null ,tempvar
)
911 (get-file-buffer (expand-file-name ,tempvar
))))
912 (point (point)) to-be-removed
)
913 (save-window-excursion
914 (when ,tempvar
(find-file ,tempvar
))
915 (setq to-be-removed
(current-buffer))
916 (goto-char (point-min))
917 (while (re-search-forward org-babel-src-block-regexp nil t
)
918 (goto-char (match-beginning 0))
919 (let ((full-block (match-string 0))
920 (beg-block (match-beginning 0))
921 (end-block (match-end 0))
922 (lang (match-string 2))
923 (beg-lang (match-beginning 2))
924 (end-lang (match-end 2))
925 (switches (match-string 3))
926 (beg-switches (match-beginning 3))
927 (end-switches (match-end 3))
928 (header-args (match-string 4))
929 (beg-header-args (match-beginning 4))
930 (end-header-args (match-end 4))
931 (body (match-string 5))
932 (beg-body (match-beginning 5))
933 (end-body (match-end 5)))
935 (goto-char end-block
))))
936 (unless visited-p
(kill-buffer to-be-removed
))
938 (def-edebug-spec org-babel-map-src-blocks
(form body
))
941 (defmacro org-babel-map-inline-src-blocks
(file &rest body
)
942 "Evaluate BODY forms on each inline source-block in FILE.
943 If FILE is nil evaluate BODY forms on source blocks in current
946 (let ((tempvar (make-symbol "file")))
947 `(let* ((,tempvar
,file
)
948 (visited-p (or (null ,tempvar
)
949 (get-file-buffer (expand-file-name ,tempvar
))))
950 (point (point)) to-be-removed
)
951 (save-window-excursion
952 (when ,tempvar
(find-file ,tempvar
))
953 (setq to-be-removed
(current-buffer))
954 (goto-char (point-min))
955 (while (re-search-forward org-babel-inline-src-block-regexp nil t
)
956 (goto-char (match-beginning 1))
957 (save-match-data ,@body
)
958 (goto-char (match-end 0))))
959 (unless visited-p
(kill-buffer to-be-removed
))
961 (def-edebug-spec org-babel-map-inline-src-blocks
(form body
))
963 (defvar org-babel-lob-one-liner-regexp
)
966 (defmacro org-babel-map-call-lines
(file &rest body
)
967 "Evaluate BODY forms on each call line in FILE.
968 If FILE is nil evaluate BODY forms on source blocks in current
971 (let ((tempvar (make-symbol "file")))
972 `(let* ((,tempvar
,file
)
973 (visited-p (or (null ,tempvar
)
974 (get-file-buffer (expand-file-name ,tempvar
))))
975 (point (point)) to-be-removed
)
976 (save-window-excursion
977 (when ,tempvar
(find-file ,tempvar
))
978 (setq to-be-removed
(current-buffer))
979 (goto-char (point-min))
980 (while (re-search-forward org-babel-lob-one-liner-regexp nil t
)
981 (goto-char (match-beginning 1))
982 (save-match-data ,@body
)
983 (goto-char (match-end 0))))
984 (unless visited-p
(kill-buffer to-be-removed
))
986 (def-edebug-spec org-babel-map-call-lines
(form body
))
989 (defmacro org-babel-map-executables
(file &rest body
)
991 (let ((tempvar (make-symbol "file"))
992 (rx (make-symbol "rx")))
993 `(let* ((,tempvar
,file
)
994 (,rx
(concat "\\(" org-babel-src-block-regexp
995 "\\|" org-babel-inline-src-block-regexp
996 "\\|" org-babel-lob-one-liner-regexp
"\\)"))
997 (visited-p (or (null ,tempvar
)
998 (get-file-buffer (expand-file-name ,tempvar
))))
999 (point (point)) to-be-removed
)
1000 (save-window-excursion
1001 (when ,tempvar
(find-file ,tempvar
))
1002 (setq to-be-removed
(current-buffer))
1003 (goto-char (point-min))
1004 (while (re-search-forward ,rx nil t
)
1005 (goto-char (match-beginning 1))
1006 (when (looking-at org-babel-inline-src-block-regexp
)(forward-char 1))
1007 (save-match-data ,@body
)
1008 (goto-char (match-end 0))))
1009 (unless visited-p
(kill-buffer to-be-removed
))
1010 (goto-char point
))))
1011 (def-edebug-spec org-babel-map-executables
(form body
))
1014 (defun org-babel-execute-buffer (&optional arg
)
1015 "Execute source code blocks in a buffer.
1016 Call `org-babel-execute-src-block' on every source block in
1017 the current buffer."
1019 (org-babel-eval-wipe-error-buffer)
1020 (org-save-outline-visibility t
1021 (org-babel-map-executables nil
1022 (if (looking-at org-babel-lob-one-liner-regexp
)
1023 (org-babel-lob-execute-maybe)
1024 (org-babel-execute-src-block arg
)))))
1027 (defun org-babel-execute-subtree (&optional arg
)
1028 "Execute source code blocks in a subtree.
1029 Call `org-babel-execute-src-block' on every source block in
1030 the current subtree."
1034 (org-narrow-to-subtree)
1035 (org-babel-execute-buffer arg
)
1039 (defun org-babel-sha1-hash (&optional info
)
1040 "Generate an sha1 hash based on the value of info."
1042 (let ((print-level nil
)
1043 (info (or info
(org-babel-get-src-block-info))))
1045 (sort (copy-sequence (nth 2 info
))
1046 (lambda (a b
) (string< (car a
) (car b
)))))
1047 (let* ((rm (lambda (lst)
1048 (dolist (p '("replace" "silent" "none"
1049 "append" "prepend"))
1050 (setq lst
(remove p lst
)))
1053 (let ((v (if (and (listp (cdr arg
)) (null (cddr arg
)))
1054 (copy-sequence (cdr arg
))
1056 (when (and v
(not (and (sequencep v
)
1060 ((and (listp v
) ; lists are sorted
1061 (member (car arg
) '(:result-params
)))
1062 (sort (funcall rm v
) #'string
<))
1063 ((and (stringp v
) ; strings are sorted
1064 (member (car arg
) '(:results
:exports
)))
1065 (mapconcat #'identity
(sort (funcall rm
(split-string v
))
1069 (when (org-called-interactively-p 'interactive
) (message hash
)) hash
)
1070 (let ((it (format "%s-%s"
1073 (delq nil
(mapcar (lambda (arg)
1074 (let ((normalized (funcall norm arg
)))
1076 (format "%S" normalized
))))
1081 (defun org-babel-current-result-hash ()
1082 "Return the current in-buffer hash."
1083 (org-babel-where-is-src-block-result)
1084 (org-no-properties (match-string 5)))
1086 (defun org-babel-set-current-result-hash (hash)
1087 "Set the current in-buffer hash to HASH."
1088 (org-babel-where-is-src-block-result)
1089 (save-excursion (goto-char (match-beginning 3))
1090 ;; (mapc #'delete-overlay (overlays-at (point)))
1091 (replace-match hash nil nil nil
3)
1092 (org-babel-hide-hash)))
1094 (defun org-babel-hide-hash ()
1095 "Hide the hash in the current results line.
1096 Only the initial `org-babel-hash-show' characters of the hash
1097 will remain visible."
1098 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
1100 (when (and (re-search-forward org-babel-result-regexp nil t
)
1102 (let* ((start (match-beginning 5))
1103 (hide-start (+ org-babel-hash-show start
))
1105 (hash (match-string 5))
1107 (setq ov1
(make-overlay start hide-start
))
1108 (setq ov2
(make-overlay hide-start end
))
1109 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
1110 (overlay-put ov1
'babel-hash hash
)))))
1112 (defun org-babel-hide-all-hashes ()
1113 "Hide the hash in the current buffer.
1114 Only the initial `org-babel-hash-show' characters of each hash
1115 will remain visible. This function should be called as part of
1116 the `org-mode-hook'."
1118 (while (and (not org-babel-hash-show-time
)
1119 (re-search-forward org-babel-result-regexp nil t
))
1120 (goto-char (match-beginning 0))
1121 (org-babel-hide-hash)
1122 (goto-char (match-end 0)))))
1123 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
1125 (defun org-babel-hash-at-point (&optional point
)
1126 "Return the value of the hash at POINT.
1127 The hash is also added as the last element of the kill ring.
1128 This can be called with C-c C-c."
1130 (let ((hash (car (delq nil
(mapcar
1131 (lambda (ol) (overlay-get ol
'babel-hash
))
1132 (overlays-at (or point
(point))))))))
1133 (when hash
(kill-new hash
) (message hash
))))
1134 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
1136 (defun org-babel-result-hide-spec ()
1137 "Hide portions of results lines.
1138 Add `org-babel-hide-result' as an invisibility spec for hiding
1139 portions of results lines."
1140 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
1141 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
1143 (defvar org-babel-hide-result-overlays nil
1144 "Overlays hiding results.")
1146 (defun org-babel-result-hide-all ()
1147 "Fold all results in the current buffer."
1149 (org-babel-show-result-all)
1151 (while (re-search-forward org-babel-result-regexp nil t
)
1152 (save-excursion (goto-char (match-beginning 0))
1153 (org-babel-hide-result-toggle-maybe)))))
1155 (defun org-babel-show-result-all ()
1156 "Unfold all results in the current buffer."
1157 (mapc 'delete-overlay org-babel-hide-result-overlays
)
1158 (setq org-babel-hide-result-overlays nil
))
1161 (defun org-babel-hide-result-toggle-maybe ()
1162 "Toggle visibility of result at point."
1164 (let ((case-fold-search t
))
1166 (beginning-of-line 1)
1167 (looking-at org-babel-result-regexp
))
1168 (progn (org-babel-hide-result-toggle)
1169 t
) ;; to signal that we took action
1170 nil
))) ;; to signal that we did not
1172 (defun org-babel-hide-result-toggle (&optional force
)
1173 "Toggle the visibility of the current result."
1177 (if (re-search-forward org-babel-result-regexp nil t
)
1178 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1180 (while (looking-at org-babel-multi-line-header-regexp
)
1182 (goto-char (- (org-babel-result-end) 1)) (point)))
1184 (if (memq t
(mapcar (lambda (overlay)
1185 (eq (overlay-get overlay
'invisible
)
1186 'org-babel-hide-result
))
1187 (overlays-at start
)))
1188 (if (or (not force
) (eq force
'off
))
1190 (when (member ov org-babel-hide-result-overlays
)
1191 (setq org-babel-hide-result-overlays
1192 (delq ov org-babel-hide-result-overlays
)))
1193 (when (eq (overlay-get ov
'invisible
)
1194 'org-babel-hide-result
)
1195 (delete-overlay ov
)))
1196 (overlays-at start
)))
1197 (setq ov
(make-overlay start end
))
1198 (overlay-put ov
'invisible
'org-babel-hide-result
)
1199 ;; make the block accessible to isearch
1201 ov
'isearch-open-invisible
1203 (when (member ov org-babel-hide-result-overlays
)
1204 (setq org-babel-hide-result-overlays
1205 (delq ov org-babel-hide-result-overlays
)))
1206 (when (eq (overlay-get ov
'invisible
)
1207 'org-babel-hide-result
)
1208 (delete-overlay ov
))))
1209 (push ov org-babel-hide-result-overlays
)))
1210 (error "Not looking at a result line"))))
1212 ;; org-tab-after-check-for-cycling-hook
1213 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
1214 ;; Remove overlays when changing major mode
1215 (add-hook 'org-mode-hook
1216 (lambda () (org-add-hook 'change-major-mode-hook
1217 'org-babel-show-result-all
'append
'local
)))
1219 (defvar org-file-properties
)
1220 (defun org-babel-params-from-properties (&optional lang
)
1221 "Retrieve parameters specified as properties.
1222 Return an association list of any source block params which
1223 may be specified in the properties of the current outline entry."
1226 (org-babel-parse-multiple-vars
1229 (lambda (header-arg)
1230 (and (setq val
(org-entry-get (point) header-arg t
))
1231 (cons (intern (concat ":" header-arg
))
1232 (org-babel-read val
))))
1237 (org-babel-combine-header-arg-lists
1238 org-babel-common-header-args-w-values
1240 (setq sym
(intern (concat "org-babel-header-args:" lang
)))
1241 (and (boundp sym
) (eval sym
))))))))))))
1243 (defvar org-src-preserve-indentation
)
1244 (defun org-babel-parse-src-block-match ()
1245 "Parse the results from a match of the `org-babel-src-block-regexp'."
1246 (let* ((block-indentation (length (match-string 1)))
1247 (lang (org-no-properties (match-string 2)))
1248 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
1249 (switches (match-string 3))
1250 (body (org-no-properties
1251 (let* ((body (match-string 5))
1252 (sub-length (- (length body
) 1)))
1253 (if (and (> sub-length
0)
1254 (string= "\n" (substring body sub-length
)))
1255 (substring body
0 sub-length
)
1257 (preserve-indentation (or org-src-preserve-indentation
1259 (string-match "-i\\>" switches
)))))
1261 ;; get block body less properties, protective commas, and indentation
1264 (insert (org-unescape-code-in-string body
))
1265 (unless preserve-indentation
(org-do-remove-indentation))
1267 (org-babel-merge-params
1268 org-babel-default-header-args
1269 (org-babel-params-from-properties lang
)
1270 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1271 (org-babel-parse-header-arguments
1272 (org-no-properties (or (match-string 4) ""))))
1274 block-indentation
)))
1276 (defun org-babel-parse-inline-src-block-match ()
1277 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1278 (let* ((lang (org-no-properties (match-string 2)))
1279 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
1281 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1282 (org-babel-merge-params
1283 org-babel-default-inline-header-args
1284 (org-babel-params-from-properties lang
)
1285 (if (boundp lang-headers
) (eval lang-headers
) nil
)
1286 (org-babel-parse-header-arguments
1287 (org-no-properties (or (match-string 4) "")))))))
1289 (defun org-babel-balanced-split (string alts
)
1290 "Split STRING on instances of ALTS.
1291 ALTS is a cons of two character options where each option may be
1292 either the numeric code of a single character or a list of
1293 character alternatives. For example to split on balanced
1294 instances of \"[ \t]:\" set ALTS to '((32 9) . 58)."
1295 (let* ((matches (lambda (ch spec
) (if (listp spec
) (member ch spec
) (equal spec ch
))))
1296 (matched (lambda (ch last
)
1298 (and (funcall matches ch
(cdr alts
))
1299 (funcall matches last
(car alts
)))
1300 (funcall matches ch alts
))))
1301 (balance 0) (last 0)
1303 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1304 (setq balance
(+ balance
1305 (cond ((or (equal 91 ch
) (equal 40 ch
)) 1)
1306 ((or (equal 93 ch
) (equal 41 ch
)) -
1)
1308 (when (and (equal 34 ch
) (not (equal 92 last
)))
1309 (setq quote
(not quote
)))
1310 (setq partial
(cons ch partial
))
1311 (when (and (= balance
0) (not quote
) (funcall matched ch last
))
1312 (setq lst
(cons (apply #'string
(nreverse
1319 (string-to-list string
))
1320 (nreverse (cons (apply #'string
(nreverse partial
)) lst
))))
1322 (defun org-babel-join-splits-near-ch (ch list
)
1323 "Join splits where \"=\" is on either end of the split."
1324 (let ((last= (lambda (str) (= ch
(aref str
(1- (length str
))))))
1325 (first= (lambda (str) (= ch
(aref str
0)))))
1327 (org-reduce (lambda (acc el
)
1328 (let ((head (car acc
)))
1329 (if (and head
(or (funcall last
= head
) (funcall first
= el
)))
1330 (cons (concat head el
) (cdr acc
))
1332 list
:initial-value nil
))))
1334 (defun org-babel-parse-header-arguments (arg-string)
1335 "Parse a string of header arguments returning an alist."
1336 (when (> (length arg-string
) 0)
1337 (org-babel-parse-multiple-vars
1342 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1344 (cons (intern (match-string 1 arg
))
1345 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
1346 (cons (intern (org-babel-chomp arg
)) nil
)))
1348 (cons (car raw
) (mapcar (lambda (r) (concat ":" r
)) (cdr raw
))))
1349 (org-babel-balanced-split arg-string
'((32 9) .
58))))))))
1351 (defun org-babel-parse-multiple-vars (header-arguments)
1352 "Expand multiple variable assignments behind a single :var keyword.
1354 This allows expression of multiple variables with one :var as
1357 #+PROPERTY: var foo=1, bar=2"
1359 (mapc (lambda (pair)
1360 (if (eq (car pair
) :var
)
1361 (mapcar (lambda (v) (push (cons :var
(org-babel-trim v
)) results
))
1362 (org-babel-join-splits-near-ch
1363 61 (org-babel-balanced-split (cdr pair
) 32)))
1364 (push pair results
)))
1366 (nreverse results
)))
1368 (defun org-babel-process-params (params)
1369 "Expand variables in PARAMS and add summary parameters."
1370 (let* ((processed-vars (mapcar (lambda (el)
1371 (if (consp (cdr el
))
1373 (org-babel-ref-parse (cdr el
))))
1374 (org-babel-get-header params
:var
)))
1375 (vars-and-names (if (and (assoc :colname-names params
)
1376 (assoc :rowname-names params
))
1377 (list processed-vars
)
1378 (org-babel-disassemble-tables
1380 (cdr (assoc :hlines params
))
1381 (cdr (assoc :colnames params
))
1382 (cdr (assoc :rownames params
)))))
1383 (raw-result (or (cdr (assoc :results params
)) ""))
1384 (result-params (append
1385 (split-string (if (stringp raw-result
)
1388 (cdr (assoc :result-params params
)))))
1390 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
1392 (cons :colname-names
(or (cdr (assoc :colname-names params
))
1393 (cadr vars-and-names
)))
1394 (cons :rowname-names
(or (cdr (assoc :rowname-names params
))
1395 (caddr vars-and-names
)))
1396 (cons :result-params result-params
)
1397 (cons :result-type
(cond ((member "output" result-params
) 'output
)
1398 ((member "value" result-params
) 'value
)
1400 (org-babel-get-header params
:var
'other
))))
1402 ;; row and column names
1403 (defun org-babel-del-hlines (table)
1404 "Remove all 'hlines from TABLE."
1405 (remove 'hline table
))
1407 (defun org-babel-get-colnames (table)
1408 "Return the column names of TABLE.
1409 Return a cons cell, the `car' of which contains the TABLE less
1410 colnames, and the `cdr' of which contains a list of the column
1412 (if (equal 'hline
(nth 1 table
))
1413 (cons (cddr table
) (car table
))
1414 (cons (cdr table
) (car table
))))
1416 (defun org-babel-get-rownames (table)
1417 "Return the row names of TABLE.
1418 Return a cons cell, the `car' of which contains the TABLE less
1419 colnames, and the `cdr' of which contains a list of the column
1420 names. Note: this function removes any hlines in TABLE."
1421 (let* ((trans (lambda (table) (apply #'mapcar
* #'list table
)))
1423 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
1424 (table (funcall trans
(mapcar (lambda (row)
1425 (if (not (equal row
'hline
))
1429 (setq row
(cons 'hline row
)))
1432 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
1433 (funcall trans
(cdr table
)))
1434 (remove 'hline
(car table
)))))
1436 (defun org-babel-put-colnames (table colnames
)
1437 "Add COLNAMES to TABLE if they exist."
1438 (if colnames
(apply 'list colnames
'hline table
) table
))
1440 (defun org-babel-put-rownames (table rownames
)
1441 "Add ROWNAMES to TABLE if they exist."
1443 (mapcar (lambda (row)
1445 (cons (or (pop rownames
) "") row
)
1449 (defun org-babel-pick-name (names selector
)
1450 "Select one out of an alist of row or column names.
1451 SELECTOR can be either a list of names in which case those names
1452 will be returned directly, or an index into the list NAMES in
1453 which case the indexed names will be return."
1454 (if (listp selector
)
1457 (if (and selector
(symbolp selector
) (not (equal t selector
)))
1458 (cdr (assoc selector names
))
1459 (if (integerp selector
)
1460 (nth (- selector
1) names
)
1461 (cdr (car (last names
))))))))
1463 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
1464 "Parse tables for further processing.
1465 Process the variables in VARS according to the HLINES,
1466 ROWNAMES and COLNAMES header arguments. Return a list consisting
1467 of the vars, cnames and rnames."
1468 (let (cnames rnames
)
1472 (when (listp (cdr var
))
1473 (when (and (not (equal colnames
"no"))
1474 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
1475 (not (member 'hline
(cddr (cdr var
)))))))
1476 (let ((both (org-babel-get-colnames (cdr var
))))
1477 (setq cnames
(cons (cons (car var
) (cdr both
))
1479 (setq var
(cons (car var
) (car both
)))))
1480 (when (and rownames
(not (equal rownames
"no")))
1481 (let ((both (org-babel-get-rownames (cdr var
))))
1482 (setq rnames
(cons (cons (car var
) (cdr both
))
1484 (setq var
(cons (car var
) (car both
)))))
1485 (when (and hlines
(not (equal hlines
"yes")))
1486 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1489 (reverse cnames
) (reverse rnames
))))
1491 (defun org-babel-reassemble-table (table colnames rownames
)
1492 "Add column and row names to a table.
1493 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1494 to the table for reinsertion to org-mode."
1497 (if (and colnames
(listp (car table
)) (= (length (car table
))
1499 (org-babel-put-colnames table colnames
) table
))
1500 (if (and rownames
(= (length table
) (length rownames
)))
1501 (org-babel-put-rownames table rownames
) table
))
1504 (defun org-babel-where-is-src-block-head ()
1505 "Find where the current source block begins.
1506 Return the point at the beginning of the current source
1507 block. Specifically at the beginning of the #+BEGIN_SRC line.
1508 If the point is not on a source block then return nil."
1509 (let ((initial (point)) (case-fold-search t
) top bottom
)
1511 (save-excursion ;; on a source name line or a #+header line
1512 (beginning-of-line 1)
1513 (and (or (looking-at org-babel-src-name-regexp
)
1514 (looking-at org-babel-multi-line-header-regexp
))
1516 (while (and (forward-line 1)
1517 (or (looking-at org-babel-src-name-regexp
)
1518 (looking-at org-babel-multi-line-header-regexp
))))
1519 (looking-at org-babel-src-block-regexp
))
1521 (save-excursion ;; on a #+begin_src line
1522 (beginning-of-line 1)
1523 (and (looking-at org-babel-src-block-regexp
)
1525 (save-excursion ;; inside a src block
1527 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1528 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1529 (< top initial
) (< initial bottom
)
1530 (progn (goto-char top
) (beginning-of-line 1)
1531 (looking-at org-babel-src-block-regexp
))
1535 (defun org-babel-goto-src-block-head ()
1536 "Go to the beginning of the current code block."
1539 (if head
(goto-char head
) (error "Not currently in a code block")))
1540 (org-babel-where-is-src-block-head)))
1543 (defun org-babel-goto-named-src-block (name)
1544 "Go to a named source-code block."
1546 (let ((completion-ignore-case t
)
1547 (case-fold-search t
)
1548 (under-point (thing-at-point 'line
)))
1549 (list (org-icompleting-read
1550 "source-block name: " (org-babel-src-block-names) nil t
1553 ((string-match (org-babel-noweb-wrap) under-point
)
1554 (let ((block-name (match-string 1 under-point
)))
1555 (string-match "[^(]*" block-name
)
1556 (match-string 0 block-name
)))
1558 ((string-match org-babel-lob-one-liner-regexp under-point
)
1559 (let ((source-info (car (org-babel-lob-get-info))))
1560 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info
)
1561 (let ((source-name (match-string 1 source-info
)))
1564 ((string-match (concat "#\\+" org-babel-results-keyword
1565 "\\:\s+\\([^\\(]*\\)") under-point
)
1566 (match-string 1 under-point
))
1568 ((and (thing-at-point 'symbol
))
1569 (org-babel-find-named-block (thing-at-point 'symbol
))
1570 (thing-at-point 'symbol
))
1572 (let ((point (org-babel-find-named-block name
)))
1574 ;; taken from `org-open-at-point'
1575 (progn (org-mark-ring-push) (goto-char point
) (org-show-context))
1576 (message "source-code block '%s' not found in this buffer" name
))))
1578 (defun org-babel-find-named-block (name)
1579 "Find a named source-code block.
1580 Return the location of the source block identified by source
1581 NAME, or nil if no such block exists. Set match data according to
1582 org-babel-named-src-block-regexp."
1584 (let ((case-fold-search t
)
1585 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1586 (goto-char (point-min))
1587 (when (or (re-search-forward regexp nil t
)
1588 (re-search-backward regexp nil t
))
1589 (match-beginning 0)))))
1591 (defun org-babel-src-block-names (&optional file
)
1592 "Returns the names of source blocks in FILE or the current buffer."
1594 (when file
(find-file file
)) (goto-char (point-min))
1595 (let ((case-fold-search t
) names
)
1596 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1597 (setq names
(cons (match-string 3) names
)))
1601 (defun org-babel-goto-named-result (name)
1602 "Go to a named result."
1604 (let ((completion-ignore-case t
))
1605 (list (org-icompleting-read "source-block name: "
1606 (org-babel-result-names) nil t
))))
1607 (let ((point (org-babel-find-named-result name
)))
1609 ;; taken from `org-open-at-point'
1610 (progn (goto-char point
) (org-show-context))
1611 (message "result '%s' not found in this buffer" name
))))
1613 (defun org-babel-find-named-result (name &optional point
)
1614 "Find a named result.
1615 Return the location of the result named NAME in the current
1616 buffer or nil if no such result exists."
1618 (let ((case-fold-search t
))
1619 (goto-char (or point
(point-min)))
1620 (catch 'is-a-code-block
1621 (when (re-search-forward
1622 (concat org-babel-result-regexp
1623 "[ \t]" (regexp-quote name
) "[ \t]*[\n\f\v\r]") nil t
)
1624 (when (and (string= "name" (downcase (match-string 1)))
1625 (or (beginning-of-line 1)
1626 (looking-at org-babel-src-block-regexp
)
1627 (looking-at org-babel-multi-line-header-regexp
)))
1628 (throw 'is-a-code-block
(org-babel-find-named-result name
(point))))
1629 (beginning-of-line 0) (point))))))
1631 (defun org-babel-result-names (&optional file
)
1632 "Returns the names of results in FILE or the current buffer."
1634 (when file
(find-file file
)) (goto-char (point-min))
1635 (let ((case-fold-search t
) names
)
1636 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1637 (setq names
(cons (match-string 4) names
)))
1641 (defun org-babel-next-src-block (&optional arg
)
1642 "Jump to the next source block.
1643 With optional prefix argument ARG, jump forward ARG many source blocks."
1645 (org-next-block arg nil org-babel-src-block-regexp
))
1648 (defun org-babel-previous-src-block (&optional arg
)
1649 "Jump to the previous source block.
1650 With optional prefix argument ARG, jump backward ARG many source blocks."
1652 (org-previous-block arg org-babel-src-block-regexp
))
1654 (defvar org-babel-load-languages
)
1657 (defun org-babel-mark-block ()
1658 "Mark current src block."
1664 (looking-at org-babel-src-block-regexp
))
1665 (push-mark (match-end 5) nil t
)
1666 (goto-char (match-beginning 5))))
1667 (org-babel-where-is-src-block-head)))
1669 (defun org-babel-demarcate-block (&optional arg
)
1670 "Wrap or split the code in the region or on the point.
1671 When called from inside of a code block the current block is
1672 split. When called from outside of a code block a new code block
1673 is created. In both cases if the region is demarcated and if the
1674 region is not active then the point is demarcated."
1676 (let ((info (org-babel-get-src-block-info 'light
))
1677 (headers (progn (org-babel-where-is-src-block-head)
1679 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1685 (let ((lang (nth 0 info
))
1686 (indent (make-string (nth 5 info
) ?
)))
1687 (when (string-match "^[[:space:]]*$"
1688 (buffer-substring (point-at-bol)
1690 (delete-region (point-at-bol) (point-at-eol)))
1692 (if (looking-at "^") "" "\n")
1693 indent
"#+end_src\n"
1694 (if arg stars indent
) "\n"
1695 indent
"#+begin_src " lang
1696 (if (> (length headers
) 1)
1697 (concat " " headers
) headers
)
1698 (if (looking-at "[\n\r]")
1700 (concat "\n" (make-string (current-column) ?
)))))))
1701 (move-end-of-line 2))
1702 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1703 (let ((start (point))
1704 (lang (org-icompleting-read "Lang: "
1705 (mapcar (lambda (el) (symbol-name (car el
)))
1706 org-babel-load-languages
)))
1707 (body (delete-and-extract-region
1708 (if (org-region-active-p) (mark) (point)) (point))))
1709 (insert (concat (if (looking-at "^") "" "\n")
1710 (if arg
(concat stars
"\n") "")
1711 "#+begin_src " lang
"\n"
1713 (if (or (= (length body
) 0)
1714 (string-match "[\r\n]$" body
)) "" "\n")
1716 (goto-char start
) (move-end-of-line 1)))))
1718 (defvar org-babel-lob-one-liner-regexp
)
1719 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1720 "Find where the current source block results begin.
1721 Return the point at the beginning of the result of the current
1722 source block. Specifically at the beginning of the results line.
1723 If no result exists for this block then create a results line
1724 following the source block."
1726 (let* ((case-fold-search t
)
1727 (on-lob-line (save-excursion
1728 (beginning-of-line 1)
1729 (looking-at org-babel-lob-one-liner-regexp
)))
1730 (inlinep (when (org-babel-get-inline-src-block-matches)
1732 (name (if on-lob-line
1733 (mapconcat #'identity
(butlast (org-babel-lob-get-info)) "")
1734 (nth 4 (or info
(org-babel-get-src-block-info 'light
)))))
1735 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1737 (when head
(goto-char head
))
1738 (org-with-wide-buffer
1740 found
;; was there a result (before we potentially insert one)
1745 ;; - return t if it is found, else return nil
1746 ;; - if it does not need to be rebuilt, then don't set end
1747 ;; - if it does need to be rebuilt then do set end
1748 name
(setq beg
(org-babel-find-named-result name
))
1750 (when (and hash
(not (string= hash
(match-string 5))))
1751 (goto-char beg
) (setq end beg
) ;; beginning of result
1753 (delete-region end
(org-babel-result-end)) nil
)))
1756 ;; - return t if it is found, else return nil
1757 ;; - if it is found, and the hash doesn't match, delete and set end
1758 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1759 (progn (end-of-line 1)
1760 (if (eobp) (insert "\n") (forward-char 1))
1763 (progn ;; unnamed results line already exists
1764 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1765 (beginning-of-line 1)
1767 (concat org-babel-result-regexp
"\n")))
1768 (let ((this-hash (match-string 5)))
1770 ;; must remove and rebuild if hash!=old-hash
1771 (if (and hash
(not (string= hash this-hash
)))
1775 end
(org-babel-result-end)))
1776 (setq end nil
)))))))))))
1777 (if (not (and insert end
)) found
1780 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1782 (when (wholenump indent
) (make-string indent ?
))
1783 "#+" org-babel-results-keyword
1785 (if org-babel-hash-show-time
1787 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash
"]")
1788 (concat "["hash
"]")))
1790 (when name
(concat " " name
)) "\n"))
1791 (unless beg
(insert "\n") (backward-char))
1792 (beginning-of-line 0)
1793 (if hash
(org-babel-hide-hash))
1796 (defvar org-block-regexp
)
1797 (defun org-babel-read-result ()
1798 "Read the result at `point' into emacs-lisp."
1799 (let ((case-fold-search t
) result-string
)
1801 ((org-at-table-p) (org-babel-read-table))
1802 ((org-at-item-p) (org-babel-read-list))
1803 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1804 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1805 ((looking-at "^[ \t]*: ")
1808 (mapconcat (lambda (line)
1809 (if (and (> (length line
) 1)
1810 (string-match "^[ \t]*: \\(.+\\)" line
))
1811 (match-string 1 line
)
1815 (point) (org-babel-result-end)) "[\r\n]+")
1817 (or (org-babel-number-p result-string
) result-string
))
1818 ((looking-at org-babel-result-regexp
)
1819 (save-excursion (forward-line 1) (org-babel-read-result))))))
1821 (defun org-babel-read-table ()
1822 "Read the table at `point' into emacs-lisp."
1823 (mapcar (lambda (row)
1824 (if (and (symbolp row
) (equal row
'hline
)) row
1825 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
)) row
)))
1826 (org-table-to-lisp)))
1828 (defun org-babel-read-list ()
1829 "Read the list at `point' into emacs-lisp."
1830 (mapcar (lambda (el) (org-babel-read el
'inhibit-lisp-eval
))
1831 (mapcar #'cadr
(cdr (org-list-parse-list)))))
1833 (defvar org-link-types-re
)
1834 (defun org-babel-read-link ()
1835 "Read the link at `point' into emacs-lisp.
1836 If the path of the link is a file path it is expanded using
1837 `expand-file-name'."
1838 (let* ((case-fold-search t
)
1839 (raw (and (looking-at org-bracket-link-regexp
)
1840 (org-no-properties (match-string 1))))
1841 (type (and (string-match org-link-types-re raw
)
1842 (match-string 1 raw
))))
1844 ((not type
) (expand-file-name raw
))
1845 ((string= type
"file")
1846 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1847 (expand-file-name (match-string 2 raw
))))
1850 (defun org-babel-format-result (result &optional sep
)
1851 "Format RESULT for writing to file."
1852 (let ((echo-res (lambda (r) (if (stringp r
) r
(format "%S" r
)))))
1856 result
(list :sep
(or sep
"\t") :fmt echo-res
))
1858 (funcall echo-res result
))))
1860 (defun org-babel-insert-result
1861 (result &optional result-params info hash indent lang
)
1862 "Insert RESULT into the current buffer.
1863 By default RESULT is inserted after the end of the
1864 current source block. With optional argument RESULT-PARAMS
1865 controls insertion of results in the org-mode file.
1866 RESULT-PARAMS can take the following values:
1868 replace - (default option) insert results after the source block
1869 replacing any previously inserted results
1871 silent -- no results are inserted into the Org-mode buffer but
1872 the results are echoed to the minibuffer and are
1873 ingested by Emacs (a potentially time consuming
1876 file ---- the results are interpreted as a file path, and are
1877 inserted into the buffer using the Org-mode file syntax
1879 list ---- the results are interpreted as an Org-mode list.
1881 raw ----- results are added directly to the Org-mode file. This
1882 is a good option if you code block will output org-mode
1885 drawer -- results are added directly to the Org-mode file as with
1886 \"raw\", but are wrapped in a RESULTS drawer, allowing
1887 them to later be replaced or removed automatically.
1889 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
1890 They are not comma-escaped when inserted, but Org syntax
1891 here will be discarded when exporting the file.
1893 html ---- results are added inside of a #+BEGIN_HTML block. This
1894 is a good option if you code block will output html
1897 latex --- results are added inside of a #+BEGIN_LATEX block.
1898 This is a good option if you code block will output
1899 latex formatted text.
1901 code ---- the results are extracted in the syntax of the source
1902 code of the language being evaluated and are added
1903 inside of a #+BEGIN_SRC block with the source-code
1904 language set appropriately. Note this relies on the
1905 optional LANG argument."
1906 (if (stringp result
)
1908 (setq result
(org-no-properties result
))
1909 (when (member "file" result-params
)
1910 (setq result
(org-babel-result-to-file
1911 result
(when (assoc :file-desc
(nth 2 info
))
1912 (or (cdr (assoc :file-desc
(nth 2 info
)))
1914 (unless (listp result
) (setq result
(format "%S" result
))))
1915 (if (and result-params
(member "silent" result-params
))
1917 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1922 (when (or (org-babel-get-inline-src-block-matches)
1923 (org-babel-get-lob-one-liner-matches))
1924 (goto-char (match-end 0))
1925 (insert (if (listp result
) "\n" " "))
1927 (existing-result (unless inlinep
1928 (org-babel-where-is-src-block-result
1929 t info hash indent
)))
1931 (cdr (assoc :results_switches
(nth 2 info
))))
1932 (visible-beg (copy-marker (point-min)))
1933 (visible-end (copy-marker (point-max)))
1934 ;; When results exist outside of the current visible
1935 ;; region of the buffer, be sure to widen buffer to
1937 (outside-scope-p (and existing-result
1938 (or (> visible-beg existing-result
)
1939 (<= visible-end existing-result
))))
1941 (when (and (stringp result
) ; ensure results end in a newline
1943 (> (length result
) 0)
1944 (not (or (string-equal (substring result -
1) "\n")
1945 (string-equal (substring result -
1) "\r"))))
1946 (setq result
(concat result
"\n")))
1949 (when outside-scope-p
(widen))
1950 (if (not existing-result
)
1951 (setq beg
(or inlinep
(point)))
1952 (goto-char existing-result
)
1954 (re-search-forward "#" nil t
)
1955 (setq indent
(- (current-column) 1)))
1959 ((member "replace" result-params
)
1960 (delete-region (point) (org-babel-result-end)))
1961 ((member "append" result-params
)
1962 (goto-char (org-babel-result-end)) (setq beg
(point-marker)))
1963 ((member "prepend" result-params
)))) ; already there
1964 (setq results-switches
1965 (if results-switches
(concat " " results-switches
) ""))
1966 (let ((wrap (lambda (start finish
&optional no-escape
)
1967 (goto-char end
) (insert (concat finish
"\n"))
1968 (goto-char beg
) (insert (concat start
"\n"))
1970 (org-escape-code-in-region (point) end
))
1971 (goto-char end
) (goto-char (point-at-eol))
1972 (setq end
(point-marker))))
1973 (proper-list-p (lambda (it) (and (listp it
) (null (cdr (last it
)))))))
1974 ;; insert results based on type
1976 ;; do nothing for an empty result
1978 ;; insert a list if preferred
1979 ((member "list" result-params
)
1982 (org-list-to-generic
1985 (lambda (el) (list nil
(if (stringp el
) el
(format "%S" el
))))
1986 (if (listp result
) result
(list result
))))
1987 '(:splicep nil
:istart
"- " :iend
"\n")))
1989 ;; assume the result is a table if it's not a string
1990 ((funcall proper-list-p result
)
1992 (insert (concat (orgtbl-to-orgtbl
1993 (if (or (eq 'hline
(car result
))
1994 (and (listp (car result
))
1995 (listp (cdr (car result
)))))
1996 result
(list result
))
1997 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1998 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1999 ((and (listp result
) (not (funcall proper-list-p result
)))
2000 (insert (format "%s\n" result
)))
2001 ((member "file" result-params
)
2002 (when inlinep
(goto-char inlinep
))
2004 (t (goto-char beg
) (insert result
)))
2005 (when (funcall proper-list-p result
) (goto-char (org-table-end)))
2006 (setq end
(point-marker))
2007 ;; possibly wrap result
2009 ((assoc :wrap
(nth 2 info
))
2010 (let ((name (or (cdr (assoc :wrap
(nth 2 info
))) "RESULTS")))
2011 (funcall wrap
(concat "#+BEGIN_" name
)
2012 (concat "#+END_" (car (org-split-string name
))))))
2013 ((member "html" result-params
)
2014 (funcall wrap
"#+BEGIN_HTML" "#+END_HTML"))
2015 ((member "latex" result-params
)
2016 (funcall wrap
"#+BEGIN_LaTeX" "#+END_LaTeX"))
2017 ((member "org" result-params
)
2018 (funcall wrap
"#+BEGIN_SRC org" "#+END_SRC"))
2019 ((member "code" result-params
)
2020 (funcall wrap
(format "#+BEGIN_SRC %s%s" (or lang
"none") results-switches
)
2022 ((member "raw" result-params
)
2023 (goto-char beg
) (if (org-at-table-p) (org-cycle)))
2024 ((or (member "drawer" result-params
)
2025 ;; Stay backward compatible with <7.9.2
2026 (member "wrap" result-params
))
2027 (funcall wrap
":RESULTS:" ":END:" 'no-escape
))
2028 ((and (not (funcall proper-list-p result
))
2029 (not (member "file" result-params
)))
2030 (org-babel-examplize-region beg end results-switches
)
2031 (setq end
(point)))))
2032 ;; possibly indent the results to match the #+results line
2033 (when (and (not inlinep
) (numberp indent
) indent
(> indent
0)
2034 ;; in this case `table-align' does the work for us
2035 (not (and (listp result
)
2036 (member "append" result-params
))))
2037 (indent-rigidly beg end indent
))
2039 (if (member "value" result-params
)
2040 (message "Code block returned no value.")
2041 (message "Code block produced no output."))
2042 (message "Code block evaluation complete.")))
2043 (when outside-scope-p
(narrow-to-region visible-beg visible-end
))
2044 (set-marker visible-beg nil
)
2045 (set-marker visible-end nil
))))))
2047 (defun org-babel-remove-result (&optional info
)
2048 "Remove the result of the current source block."
2050 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
2052 (setq start
(- location
1))
2054 (goto-char location
) (forward-line 1)
2055 (delete-region start
(org-babel-result-end))))))
2057 (defun org-babel-result-end ()
2058 "Return the point at the end of the current set of results."
2061 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2062 ((org-at-item-p) (let* ((struct (org-list-struct))
2063 (prvs (org-list-prevs-alist struct
)))
2064 (org-list-get-list-end (point-at-bol) struct prvs
)))
2065 ((let ((case-fold-search t
)) (looking-at "^\\([ \t]*\\):results:"))
2066 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2067 (forward-char 1) (point)))
2069 (let ((case-fold-search t
))
2070 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2071 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2074 (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
2078 (defun org-babel-result-to-file (result &optional description
)
2079 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2080 If the `default-directory' is different from the containing
2081 file's directory then expand relative links."
2082 (when (stringp result
)
2083 (format "[[file:%s]%s]"
2084 (if (and default-directory
2086 (not (string= (expand-file-name default-directory
)
2088 (file-name-directory buffer-file-name
)))))
2089 (expand-file-name result default-directory
)
2091 (if description
(concat "[" description
"]") ""))))
2093 (defvar org-babel-capitalize-examplize-region-markers nil
2094 "Make true to capitalize begin/end example markers inserted by code blocks.")
2096 (defun org-babel-examplize-region (beg end
&optional results-switches
)
2097 "Comment out region using the inline '==' or ': ' org example quote."
2099 (let ((chars-between (lambda (b e
)
2100 (not (string-match "^[\\s]*$" (buffer-substring b e
)))))
2101 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2102 (upcase str
) str
))))
2103 (if (or (funcall chars-between
(save-excursion (goto-char beg
) (point-at-bol)) beg
)
2104 (funcall chars-between end
(save-excursion (goto-char end
) (point-at-eol))))
2107 (insert (format "=%s=" (prog1 (buffer-substring beg end
)
2108 (delete-region beg end
)))))
2109 (let ((size (count-lines beg end
)))
2111 (cond ((= size
0)) ; do nothing for an empty result
2112 ((< size org-babel-min-lines-for-block-output
)
2115 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2118 (insert (if results-switches
2120 (funcall maybe-cap
"#+begin_example")
2122 (funcall maybe-cap
"#+begin_example\n")))
2123 (if (markerp end
) (goto-char end
) (forward-char (- end beg
)))
2124 (insert (funcall maybe-cap
"#+end_example\n")))))))))
2126 (defun org-babel-update-block-body (new-body)
2127 "Update the body of the current code block to NEW-BODY."
2128 (if (not (org-babel-where-is-src-block-head))
2129 (error "Not in a source block")
2131 (replace-match (concat (org-babel-trim new-body
) "\n") nil t nil
5))
2132 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2134 (defun org-babel-merge-params (&rest plists
)
2135 "Combine all parameter association lists in PLISTS.
2136 Later elements of PLISTS override the values of previous elements.
2137 This takes into account some special considerations for certain
2138 parameters when merging lists."
2139 (let* ((results-exclusive-groups
2140 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2141 (cdr (assoc 'results org-babel-common-header-args-w-values
))))
2142 (exports-exclusive-groups
2143 (mapcar (lambda (group) (mapcar #'symbol-name group
))
2144 (cdr (assoc 'exports org-babel-common-header-args-w-values
))))
2146 (e-merge (lambda (exclusive-groups &rest result-params
)
2147 ;; maintain exclusivity of mutually exclusive parameters
2149 (mapc (lambda (new-params)
2150 (mapc (lambda (new-param)
2151 (mapc (lambda (exclusive-group)
2152 (when (member new-param exclusive-group
)
2153 (mapcar (lambda (excluded-param)
2160 (setq output
(org-uniquify
2161 (cons new-param output
))))
2165 params results exports tangle noweb cache vars shebang comments padline
)
2173 (let ((name (if (listp (cdr pair
))
2175 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2177 (intern (match-string 1 (cdr pair
)))))))
2181 (if (member name
(mapcar #'car vars
))
2185 (unless (equal (car p
) name
) p
))
2188 (list (cons name pair
))))
2189 ;; if no name is given and we already have named variables
2190 ;; then assign to named variables in order
2191 (if (and vars
(nth variable-index vars
))
2192 (prog1 (setf (cddr (nth variable-index vars
))
2193 (concat (symbol-name
2194 (car (nth variable-index vars
)))
2196 (incf variable-index
))
2197 (error "Variable \"%s\" must be assigned a default value"
2200 (setq results
(funcall e-merge results-exclusive-groups
2203 (let ((r (cdr pair
)))
2204 (if (stringp r
) r
(eval r
)))))))
2207 (setq results
(funcall e-merge results-exclusive-groups
2209 (unless (or (member "both" exports
)
2210 (member "none" exports
)
2211 (member "code" exports
))
2212 (setq exports
(funcall e-merge exports-exclusive-groups
2213 exports
'("results"))))
2214 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
2216 (setq exports
(funcall e-merge exports-exclusive-groups
2217 exports
(split-string (cdr pair
)))))
2218 (:tangle
;; take the latest -- always overwrite
2219 (setq tangle
(or (list (cdr pair
)) tangle
)))
2221 (setq noweb
(funcall e-merge
2222 '(("yes" "no" "tangle" "no-export"
2223 "strip-export" "eval"))
2225 (split-string (or (cdr pair
) "")))))
2227 (setq cache
(funcall e-merge
'(("yes" "no")) cache
2228 (split-string (or (cdr pair
) "")))))
2230 (setq padline
(funcall e-merge
'(("yes" "no")) padline
2231 (split-string (or (cdr pair
) "")))))
2232 (:shebang
;; take the latest -- always overwrite
2233 (setq shebang
(or (list (cdr pair
)) shebang
)))
2235 (setq comments
(funcall e-merge
'(("yes" "no")) comments
2236 (split-string (or (cdr pair
) "")))))
2237 (t ;; replace: this covers e.g. :session
2238 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
2241 (setq vars
(reverse vars
))
2242 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
2245 (let ((key (intern (concat ":" (symbol-name hd
))))
2247 (setf params
(cons (cons key
(mapconcat 'identity val
" ")) params
))))
2248 '(results exports tangle noweb padline cache shebang comments
))
2251 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2252 "Set to true to use regular expressions to expand noweb references.
2253 This results in much faster noweb reference expansion but does
2254 not properly allow code blocks to inherit the \":noweb-ref\"
2255 header argument from buffer or subtree wide properties.")
2257 (defun org-babel-noweb-p (params context
)
2258 "Check if PARAMS require expansion in CONTEXT.
2259 CONTEXT may be one of :tangle, :export or :eval."
2261 (intersect (lambda (as bs
)
2263 (if (member (car as
) bs
)
2265 (funcall intersect
(cdr as
) bs
))))))
2266 (funcall intersect
(case context
2267 (:tangle
'("yes" "tangle" "no-export" "strip-export"))
2268 (:eval
'("yes" "no-export" "strip-export" "eval"))
2270 (split-string (or (cdr (assoc :noweb params
)) "")))))
2272 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
2273 "Expand Noweb references in the body of the current source code block.
2275 For example the following reference would be replaced with the
2276 body of the source-code block named 'example-block'.
2280 Note that any text preceding the <<foo>> construct on a line will
2281 be interposed between the lines of the replacement text. So for
2282 example if <<foo>> is placed behind a comment, then the entire
2283 replacement text will also be commented.
2285 This function must be called from inside of the buffer containing
2286 the source-code block which holds BODY.
2288 In addition the following syntax can be used to insert the
2289 results of evaluating the source-code block named 'example-block'.
2293 Any optional arguments can be passed to example-block by placing
2294 the arguments inside the parenthesis following the convention
2295 defined by `org-babel-lob'. For example
2297 <<example-block(a=9)>>
2299 would set the value of argument \"a\" equal to \"9\". Note that
2300 these arguments are not evaluated in the current source-code
2301 block but are passed literally to the \"example-block\"."
2302 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
2303 (info (or info
(org-babel-get-src-block-info)))
2306 (ob-nww-start org-babel-noweb-wrap-start
)
2307 (ob-nww-end org-babel-noweb-wrap-end
)
2308 (comment (string= "noweb" (cdr (assoc :comments
(nth 2 info
)))))
2309 (rx-prefix (concat "\\(" org-babel-src-name-regexp
"\\|"
2310 ":noweb-ref[ \t]+" "\\)"))
2312 (nb-add (lambda (text) (setq new-body
(concat new-body text
))))
2313 (c-wrap (lambda (text)
2315 (funcall (intern (concat lang
"-mode")))
2316 (comment-region (point) (progn (insert text
) (point)))
2317 (org-babel-trim (buffer-string)))))
2318 index source-name evaluate prefix blocks-in-buffer
)
2320 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start
)
2321 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end
)
2322 (insert body
) (goto-char (point-min))
2323 (setq index
(point))
2324 (while (and (re-search-forward (org-babel-noweb-wrap) nil t
))
2325 (save-match-data (setf source-name
(match-string 1)))
2326 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
2329 (buffer-substring (match-beginning 0)
2331 (beginning-of-line 1) (point)))))
2332 ;; add interval to new-body (removing noweb reference)
2333 (goto-char (match-beginning 0))
2334 (funcall nb-add
(buffer-substring index
(point)))
2335 (goto-char (match-end 0))
2336 (setq index
(point))
2338 (with-current-buffer parent-buffer
2341 (mapconcat ;; interpose PREFIX between every line
2345 (let ((raw (org-babel-ref-resolve source-name
)))
2346 (if (stringp raw
) raw
(format "%S" raw
)))
2348 ;; retrieve from the library of babel
2349 (nth 2 (assoc (intern source-name
)
2350 org-babel-library-of-babel
))
2351 ;; return the contents of headlines literally
2353 (when (org-babel-ref-goto-headline-id source-name
)
2354 (org-babel-ref-headline-body)))
2355 ;; find the expansion of reference in this buffer
2356 (let ((rx (concat rx-prefix source-name
"[ \t\n]"))
2359 (goto-char (point-min))
2360 (if org-babel-use-quick-and-dirty-noweb-expansion
2361 (while (re-search-forward rx nil t
)
2362 (let* ((i (org-babel-get-src-block-info 'light
))
2363 (body (org-babel-expand-noweb-references i
))
2364 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2368 (concat (funcall c-wrap
(car cs
)) "\n"
2370 (funcall c-wrap
(cadr cs
))))
2371 (org-babel-tangle-comment-links i
))
2373 (setq expansion
(cons sep
(cons full expansion
)))))
2374 (org-babel-map-src-blocks nil
2375 (let ((i (org-babel-get-src-block-info 'light
)))
2376 (when (equal (or (cdr (assoc :noweb-ref
(nth 2 i
)))
2379 (let* ((body (org-babel-expand-noweb-references i
))
2380 (sep (or (cdr (assoc :noweb-sep
(nth 2 i
)))
2384 (concat (funcall c-wrap
(car cs
)) "\n"
2386 (funcall c-wrap
(cadr cs
))))
2387 (org-babel-tangle-comment-links i
))
2390 (cons sep
(cons full expansion
)))))))))
2392 (mapconcat #'identity
(nreverse (cdr expansion
)) "")))
2393 ;; possibly raise an error if named block doesn't exist
2394 (if (member lang org-babel-noweb-error-langs
)
2396 (org-babel-noweb-wrap source-name
)
2397 "could not be resolved (see "
2398 "`org-babel-noweb-error-langs')"))
2400 "[\n\r]") (concat "\n" prefix
))))))
2401 (funcall nb-add
(buffer-substring index
(point-max))))
2404 (defun org-babel-script-escape (str &optional force
)
2405 "Safely convert tables into elisp lists."
2406 (let (in-single in-double out
)
2407 ((lambda (escaped) (condition-case nil
(org-babel-read escaped
) (error escaped
)))
2411 (or (and (string-equal "[" (substring str
0 1))
2412 (string-equal "]" (substring str -
1)))
2413 (and (string-equal "{" (substring str
0 1))
2414 (string-equal "}" (substring str -
1)))
2415 (and (string-equal "(" (substring str
0 1))
2416 (string-equal ")" (substring str -
1))))))
2426 (91 (if (or in-double in-single
) ; [
2429 (93 (if (or in-double in-single
) ; ]
2432 (123 (if (or in-double in-single
) ; {
2435 (125 (if (or in-double in-single
) ; }
2438 (44 (if (or in-double in-single
) ; ,
2439 (cons 44 out
) (cons 32 out
)))
2440 (39 (if in-double
; '
2442 (setq in-single
(not in-single
)) (cons 34 out
)))
2443 (34 (if in-single
; "
2444 (append (list 34 32) out
)
2445 (setq in-double
(not in-double
)) (cons 34 out
)))
2446 (t (cons ch out
)))))
2447 (string-to-list str
))
2448 (apply #'string
(reverse out
)))))
2451 (defun org-babel-read (cell &optional inhibit-lisp-eval
)
2452 "Convert the string value of CELL to a number if appropriate.
2453 Otherwise if cell looks like lisp (meaning it starts with a
2454 \"(\", \"'\", \"`\" or a \"[\") then read it as lisp, otherwise
2455 return it unmodified as a string. Optional argument NO-LISP-EVAL
2456 inhibits lisp evaluation for situations in which is it not
2458 (if (and (stringp cell
) (not (equal cell
"")))
2459 (or (org-babel-number-p cell
)
2460 (if (and (not inhibit-lisp-eval
)
2461 (member (substring cell
0 1) '("(" "'" "`" "[")))
2463 (if (string= (substring cell
0 1) "\"")
2465 (progn (set-text-properties 0 (length cell
) nil cell
) cell
))))
2468 (defun org-babel-number-p (string)
2469 "If STRING represents a number return its value."
2470 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
2471 (= (length (substring string
(match-beginning 0)
2474 (string-to-number string
)))
2476 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
2477 "Read the results located at FILE-NAME into an elisp table.
2478 If the table is trivial, then return it as a scalar."
2480 (save-window-excursion
2484 (org-table-import file-name separator
)
2485 (delete-file file-name
)
2486 (setq result
(mapcar (lambda (row)
2487 (mapcar #'org-babel-string-read row
))
2488 (org-table-to-lisp))))
2489 (error (message "Error reading results: %s" err
) nil
)))
2490 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
2491 (if (consp (car result
))
2492 (if (null (cdr (car result
)))
2498 (defun org-babel-string-read (cell)
2499 "Strip nested \"s from around strings."
2500 (org-babel-read (or (and (stringp cell
)
2501 (string-match "\\\"\\(.+\\)\\\"" cell
)
2502 (match-string 1 cell
))
2505 (defun org-babel-reverse-string (string)
2506 "Return the reverse of STRING."
2507 (apply 'string
(reverse (string-to-list string
))))
2509 (defun org-babel-chomp (string &optional regexp
)
2510 "Strip trailing spaces and carriage returns from STRING.
2511 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2512 overwritten by specifying a regexp as a second argument."
2513 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
2514 (while (and (> (length string
) 0)
2515 (string-match regexp
(substring string -
1)))
2516 (setq string
(substring string
0 -
1)))
2519 (defun org-babel-trim (string &optional regexp
)
2520 "Strip leading and trailing spaces and carriage returns from STRING.
2521 Like `org-babel-chomp' only it runs on both the front and back
2523 (org-babel-chomp (org-babel-reverse-string
2524 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
2527 (defvar org-babel-org-babel-call-process-region-original nil
)
2528 (defun org-babel-tramp-handle-call-process-region
2529 (start end program
&optional delete buffer display
&rest args
)
2530 "Use Tramp to handle `call-process-region'.
2531 Fixes a bug in `tramp-handle-call-process-region'."
2532 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
2533 (let ((tmpfile (tramp-compat-make-temp-file "")))
2534 (write-region start end tmpfile
)
2535 (when delete
(delete-region start end
))
2537 ;; (apply 'call-process program tmpfile buffer display args)
2539 (apply 'process-file program tmpfile buffer display args
)
2540 (delete-file tmpfile
)))
2541 ;; org-babel-call-process-region-original is the original emacs
2542 ;; definition. It is in scope from the let binding in
2543 ;; org-babel-execute-src-block
2544 (apply org-babel-call-process-region-original
2545 start end program delete buffer display args
)))
2547 (defun org-babel-local-file-name (file)
2548 "Return the local name component of FILE."
2549 (if (file-remote-p file
)
2551 (with-parsed-tramp-file-name file nil
2555 (defun org-babel-process-file-name (name &optional no-quote-p
)
2556 "Prepare NAME to be used in an external process.
2557 If NAME specifies a remote location, the remote portion of the
2558 name is removed, since in that case the process will be executing
2559 remotely. The file name is then processed by `expand-file-name'.
2560 Unless second argument NO-QUOTE-P is non-nil, the file name is
2561 additionally processed by `shell-quote-argument'"
2562 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
2563 (expand-file-name (org-babel-local-file-name name
))))
2565 (defvar org-babel-temporary-directory
)
2566 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
2567 (defvar org-babel-temporary-directory
2568 (or (and (boundp 'org-babel-temporary-directory
)
2569 (file-exists-p org-babel-temporary-directory
)
2570 org-babel-temporary-directory
)
2571 (make-temp-file "babel-" t
))
2572 "Directory to hold temporary files created to execute code blocks.
2573 Used by `org-babel-temp-file'. This directory will be removed on
2576 (defmacro org-babel-result-cond
(result-params scalar-form
&rest table-forms
)
2577 "Call the code to parse raw string results according to RESULT-PARAMS."
2579 (debug (form form
&rest form
)))
2580 `(unless (member "none" ,result-params
)
2581 (if (or (member "scalar" ,result-params
)
2582 (member "verbatim" ,result-params
)
2583 (member "html" ,result-params
)
2584 (member "code" ,result-params
)
2585 (member "pp" ,result-params
)
2586 (and (member "output" ,result-params
)
2587 (not (member "table" ,result-params
))))
2591 (defun org-babel-temp-file (prefix &optional suffix
)
2592 "Create a temporary file in the `org-babel-temporary-directory'.
2593 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2594 value of `temporary-file-directory' temporarily set to the value
2595 of `org-babel-temporary-directory'."
2596 (let ((temporary-file-directory
2597 (if (file-remote-p default-directory
)
2598 (concat (file-remote-p default-directory
) "/tmp")
2599 (or (and (boundp 'org-babel-temporary-directory
)
2600 (file-exists-p org-babel-temporary-directory
)
2601 org-babel-temporary-directory
)
2602 temporary-file-directory
))))
2603 (make-temp-file prefix nil suffix
)))
2605 (defun org-babel-remove-temporary-directory ()
2606 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2607 (when (and (boundp 'org-babel-temporary-directory
)
2608 (file-exists-p org-babel-temporary-directory
))
2609 ;; taken from `delete-directory' in files.el
2612 (mapc (lambda (file)
2613 ;; This test is equivalent to
2614 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2615 ;; but more efficient
2616 (if (eq t
(car (file-attributes file
)))
2617 (delete-directory file
)
2618 (delete-file file
)))
2619 ;; We do not want to delete "." and "..".
2620 (directory-files org-babel-temporary-directory
'full
2621 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2622 (delete-directory org-babel-temporary-directory
))
2624 (message "Failed to remove temporary Org-babel directory %s"
2625 (if (boundp 'org-babel-temporary-directory
)
2626 org-babel-temporary-directory
2627 "[directory not defined]"))))))
2629 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
2634 ;; generated-autoload-file: "org-loaddefs.el"
2637 ;;; ob-core.el ends here