1 ;;; ob-core.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009-2016 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 ;; dynamically scoped for tramp
37 (defvar org-babel-call-process-region-original nil)
38 (defvar org-src-lang-modes)
39 (defvar org-babel-library-of-babel)
40 (declare-function show-all "outline" ())
41 (declare-function org-every "org" (pred seq))
42 (declare-function org-reduce "org" (CL-FUNC CL-SEQ &rest CL-KEYS))
43 (declare-function org-mark-ring-push "org" (&optional pos buffer))
44 (declare-function tramp-compat-make-temp-file "tramp-compat"
45 (filename &optional dir-flag))
46 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
47 (declare-function tramp-file-name-user "tramp" (vec))
48 (declare-function tramp-file-name-host "tramp" (vec))
49 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body))
50 (declare-function org-icompleting-read "org" (&rest args))
51 (declare-function org-edit-src-code "org-src"
52 (&optional context code edit-buffer-name quietp))
53 (declare-function org-edit-src-exit "org-src" (&optional context))
54 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
55 (declare-function org-save-outline-visibility "org-macs" (use-markers &rest body))
56 (declare-function org-outline-overlay-data "org" (&optional use-markers))
57 (declare-function org-set-outline-overlay-data "org" (data))
58 (declare-function org-narrow-to-subtree "org" ())
59 (declare-function org-split-string "org" (string &optional separators))
60 (declare-function org-entry-get "org"
61 (pom property &optional inherit literal-nil))
62 (declare-function org-make-options-regexp "org" (kwds &optional extra))
63 (declare-function org-do-remove-indentation "org" (&optional n))
64 (declare-function org-next-block "org" (arg &optional backward block-regexp))
65 (declare-function org-previous-block "org" (arg &optional block-regexp))
66 (declare-function org-show-context "org" (&optional key))
67 (declare-function org-at-table-p "org" (&optional table-type))
68 (declare-function org-cycle "org" (&optional arg))
69 (declare-function org-uniquify "org" (list))
70 (declare-function org-current-level "org" ())
71 (declare-function org-table-import "org-table" (file arg))
72 (declare-function org-add-hook "org-compat"
73 (hook function &optional append local))
74 (declare-function org-table-align "org-table" ())
75 (declare-function org-table-end "org-table" (&optional table-type))
76 (declare-function orgtbl-to-generic "org-table" (table params))
77 (declare-function orgtbl-to-orgtbl "org-table" (table params))
78 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
79 (declare-function org-babel-lob-get-info "ob-lob" nil)
80 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
81 (declare-function org-babel-ref-parse "ob-ref" (assignment))
82 (declare-function org-babel-ref-resolve "ob-ref" (ref))
83 (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
84 (declare-function org-babel-ref-headline-body "ob-ref" ())
85 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
86 (declare-function org-number-sequence "org-compat" (from &optional to inc))
87 (declare-function org-at-item-p "org-list" ())
88 (declare-function org-list-parse-list "org-list" (&optional delete))
89 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
90 (declare-function org-list-struct "org-list" ())
91 (declare-function org-list-prevs-alist "org-list" (struct))
92 (declare-function org-list-get-list-end "org-list" (item struct prevs))
93 (declare-function org-remove-if "org" (predicate seq))
94 (declare-function org-completing-read "org" (&rest args))
95 (declare-function org-escape-code-in-region "org-src" (beg end))
96 (declare-function org-unescape-code-in-string "org-src" (s))
97 (declare-function org-table-to-lisp "org-table" (&optional txt))
98 (declare-function org-reverse-string "org" (string))
99 (declare-function org-element-context "org-element" (&optional ELEMENT))
101 (defgroup org-babel nil
102 "Code block evaluation and management in `org-mode' documents."
106 (defcustom org-confirm-babel-evaluate t
107 "Confirm before evaluation.
108 Require confirmation before interactively evaluating code
109 blocks in Org-mode buffers. The default value of this variable
110 is t, meaning confirmation is required for any code block
111 evaluation. This variable can be set to nil to inhibit any
112 future confirmation requests. This variable can also be set to a
113 function which takes two arguments the language of the code block
114 and the body of the code block. Such a function should then
115 return a non-nil value if the user should be prompted for
116 execution or nil if no prompt is required.
118 Warning: Disabling confirmation may result in accidental
119 evaluation of potentially harmful code. It may be advisable
120 remove code block execution from C-c C-c as further protection
121 against accidental code block evaluation. The
122 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
123 remove code block execution from the C-c C-c keybinding."
126 :type '(choice boolean function))
127 ;; don't allow this variable to be changed through file settings
128 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
130 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
131 "Remove code block evaluation from the C-c C-c key binding."
136 (defcustom org-babel-results-keyword "RESULTS"
137 "Keyword used to name results generated by code blocks.
138 Should be either RESULTS or NAME however any capitalization may
142 :package-version '(Org . "8.0")
145 (defcustom org-babel-noweb-wrap-start "<<"
146 "String used to begin a noweb reference in a code block.
147 See also `org-babel-noweb-wrap-end'."
151 (defcustom org-babel-noweb-wrap-end ">>"
152 "String used to end a noweb reference in a code block.
153 See also `org-babel-noweb-wrap-start'."
157 (defcustom org-babel-inline-result-wrap "=%s="
158 "Format string used to wrap inline results.
159 This string must include a \"%s\" which will be replaced by the results."
163 (defun org-babel-noweb-wrap (&optional regexp)
164 (concat org-babel-noweb-wrap-start
165 (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
166 org-babel-noweb-wrap-end))
168 (defvar org-babel-src-name-regexp
169 "^[ \t]*#\\+name:[ \t]*"
170 "Regular expression used to match a source name line.")
172 (defvar org-babel-multi-line-header-regexp
173 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
174 "Regular expression used to match multi-line header arguments.")
176 (defvar org-babel-src-name-w-name-regexp
177 (concat org-babel-src-name-regexp
179 org-babel-multi-line-header-regexp
181 "\\([^ ()\f\t\n\r\v]+\\)")
182 "Regular expression matching source name lines with a name.")
184 (defvar org-babel-src-block-regexp
186 ;; (1) indentation (2) lang
187 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
189 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
190 ;; (4) header arguments
193 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
194 "Regexp used to identify code blocks.")
196 (defvar org-babel-inline-src-block-regexp
198 ;; (1) replacement target (2) lang
199 "\\(?:^\\|[^-[:alnum:]]\\)\\(src_\\([^ \f\t\n\r\v]+\\)"
200 ;; (3,4) (unused, headers)
201 "\\(\\|\\[\\(.*?\\)\\]\\)"
203 "{\\([^\f\n\r\v]+?\\)}\\)")
204 "Regexp used to identify inline src-blocks.")
206 (defun org-babel-get-header (params key &optional others)
207 "Select only header argument of type KEY from a list.
208 Optional argument OTHERS indicates that only the header that do
209 not match KEY should be returned."
212 (lambda (p) (when (funcall (if others #'not #'identity) (eq (car p) key)) p))
215 (defun org-babel-get-inline-src-block-matches()
216 "Set match data if within body of an inline source block.
217 Returns non-nil if match-data set"
218 (let ((src-at-0-p (save-excursion
219 (beginning-of-line 1)
220 (string= "src" (thing-at-point 'word))))
221 (first-line-p (= (line-beginning-position) (point-min)))
223 (let ((search-for (cond ((and src-at-0-p first-line-p "src_"))
224 (first-line-p "[[:punct:] \t]src_")
225 (t "[[:punct:] \f\t\n\r\v]src_")))
226 (lower-limit (if first-line-p
228 (- (point-at-bol) 1))))
230 (when (or (and src-at-0-p (bobp))
231 (and (re-search-forward "}" (point-at-eol) t)
232 (re-search-backward search-for lower-limit t)
234 (when (looking-at org-babel-inline-src-block-regexp)
237 (defvar org-babel-inline-lob-one-liner-regexp)
238 (defun org-babel-get-lob-one-liner-matches()
239 "Set match data if on line of an lob one liner.
240 Returns non-nil if match-data set"
242 (unless (= (point) (point-at-bol)) ;; move before inline block
243 (re-search-backward "[ \f\t\n\r\v]" nil t))
244 (if (looking-at org-babel-inline-lob-one-liner-regexp)
248 (defun org-babel-get-src-block-info (&optional light)
249 "Get information on the current source block.
251 Optional argument LIGHT does not resolve remote variable
252 references; a process which could likely result in the execution
253 of other code blocks.
256 (language body header-arguments-alist switches name indent block-head)."
257 (let ((case-fold-search t) head info name indent)
259 (if (setq head (org-babel-where-is-src-block-head))
262 (setq info (org-babel-parse-src-block-match))
263 (setq indent (car (last info)))
264 (setq info (butlast info))
265 (while (and (forward-line -1)
266 (looking-at org-babel-multi-line-header-regexp))
268 (org-babel-merge-params
270 (org-babel-parse-header-arguments (match-string 1)))))
271 (when (looking-at org-babel-src-name-w-name-regexp)
272 (setq name (org-no-properties (match-string 3)))))
273 ;; inline source block
274 (when (org-babel-get-inline-src-block-matches)
275 (setq info (org-babel-parse-inline-src-block-match))))
276 ;; resolve variable references and add summary parameters
277 (when (and info (not light))
278 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
279 (when info (append info (list name indent head)))))
281 (defvar org-current-export-file) ; dynamically bound
282 (defmacro org-babel-check-confirm-evaluate (info &rest body)
283 "Evaluate BODY with special execution confirmation variables set.
285 Specifically; NOEVAL will indicate if evaluation is allowed,
286 QUERY will indicate if a user query is required, CODE-BLOCK will
287 hold the language of the code block, and BLOCK-NAME will hold the
288 name of the code block."
289 (declare (indent defun))
291 (lang block-body headers name eval eval-no export eval-no-export)
292 `(let* ((,lang (nth 0 ,info))
293 (,block-body (nth 1 ,info))
294 (,headers (nth 2 ,info))
295 (,name (nth 4 ,info))
296 (,eval (or (cdr (assoc :eval ,headers))
297 (when (assoc :noeval ,headers) "no")))
298 (,eval-no (or (equal ,eval "no")
299 (equal ,eval "never")))
300 (,export (org-bound-and-true-p org-current-export-file))
301 (,eval-no-export (and ,export (or (equal ,eval "no-export")
302 (equal ,eval "never-export"))))
303 (noeval (or ,eval-no ,eval-no-export))
304 (query (or (equal ,eval "query")
305 (and ,export (equal ,eval "query-export"))
306 (if (functionp org-confirm-babel-evaluate)
307 (funcall org-confirm-babel-evaluate
309 org-confirm-babel-evaluate)))
310 (code-block (if ,info (format " %s " ,lang) " "))
311 (block-name (if ,name (format " (%s) " ,name) " ")))
312 ;; Silence byte-compiler is `body' doesn't use those vars.
313 (ignore noeval query)
316 (defsubst org-babel-check-evaluate (info)
317 "Check if code block INFO should be evaluated.
318 Do not query the user."
319 (org-babel-check-confirm-evaluate info
321 (message "Evaluation of this%scode-block%sis disabled."
322 code-block block-name)))))
324 ;; dynamically scoped for asynchronous export
325 (defvar org-babel-confirm-evaluate-answer-no)
327 (defsubst org-babel-confirm-evaluate (info)
328 "Confirm evaluation of the code block INFO.
330 If the variable `org-babel-confirm-evaluate-answer-no' is bound
331 to a non-nil value, auto-answer with \"no\".
333 This query can also be suppressed by setting the value of
334 `org-confirm-babel-evaluate' to nil, in which case all future
335 interactive code block evaluations will proceed without any
336 confirmation from the user.
338 Note disabling confirmation may result in accidental evaluation
339 of potentially harmful code."
340 (org-babel-check-confirm-evaluate info
343 (and (not (org-bound-and-true-p
344 org-babel-confirm-evaluate-answer-no))
346 (format "Evaluate this%scode block%son your system? "
347 code-block block-name)))
348 (message "Evaluation of this%scode-block%sis aborted."
349 code-block block-name))))))
352 (defun org-babel-execute-safely-maybe ()
353 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
354 (org-babel-execute-maybe)))
356 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
359 (defun org-babel-execute-maybe ()
361 (or (org-babel-execute-src-block-maybe)
362 (org-babel-lob-execute-maybe)))
364 (defmacro org-babel-when-in-src-block (&rest body)
365 "Execute BODY if point is in a source block and return t.
367 Otherwise do nothing and return nil."
368 `(if (or (org-babel-where-is-src-block-head)
369 (org-babel-get-inline-src-block-matches))
375 (defun org-babel-execute-src-block-maybe ()
376 "Conditionally execute a source block.
377 Detect if this is context for a Babel src-block and if so
378 then run `org-babel-execute-src-block'."
380 (org-babel-when-in-src-block
381 (org-babel-eval-wipe-error-buffer)
382 (org-babel-execute-src-block current-prefix-arg)))
385 (defun org-babel-view-src-block-info ()
386 "Display information on the current source block.
387 This includes header arguments, language and name, and is largely
388 a window into the `org-babel-get-src-block-info' function."
390 (let ((info (org-babel-get-src-block-info 'light))
391 (full (lambda (it) (> (length it) 0)))
392 (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
394 (with-help-window (help-buffer)
395 (let ((name (nth 4 info))
397 (switches (nth 3 info))
398 (header-args (nth 2 info)))
399 (when name (funcall printf "Name: %s\n" name))
400 (when lang (funcall printf "Lang: %s\n" lang))
401 (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
402 (funcall printf "Header Arguments:\n")
403 (dolist (pair (sort header-args
404 (lambda (a b) (string< (symbol-name (car a))
405 (symbol-name (car b))))))
406 (when (funcall full (cdr pair))
407 (funcall printf "\t%S%s\t%s\n"
409 (if (> (length (format "%S" (car pair))) 7) "" "\t")
413 (defun org-babel-expand-src-block-maybe ()
414 "Conditionally expand a source block.
415 Detect if this is context for a org-babel src-block and if so
416 then run `org-babel-expand-src-block'."
418 (org-babel-when-in-src-block
419 (org-babel-expand-src-block current-prefix-arg)))
422 (defun org-babel-load-in-session-maybe ()
423 "Conditionally load a source block in a session.
424 Detect if this is context for a org-babel src-block and if so
425 then run `org-babel-load-in-session'."
427 (org-babel-when-in-src-block
428 (org-babel-load-in-session current-prefix-arg)))
430 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
433 (defun org-babel-pop-to-session-maybe ()
434 "Conditionally pop to a session.
435 Detect if this is context for a org-babel src-block and if so
436 then run `org-babel-switch-to-session'."
438 (org-babel-when-in-src-block
439 (org-babel-switch-to-session current-prefix-arg)))
441 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
443 (defconst org-babel-common-header-args-w-values
444 '((cache . ((no yes)))
446 (colnames . ((nil no yes)))
447 (comments . ((no link yes org both noweb)))
449 (eval . ((never query)))
450 (exports . ((code results both none)))
454 (hlines . ((no yes)))
455 (mkdirp . ((yes no)))
458 (noweb . ((yes no tangle no-export strip-export)))
461 (padline . ((yes no)))
464 (results . ((file list vector table scalar verbatim)
465 (raw html latex org code pp drawer)
466 (replace silent none append prepend)
468 (rownames . ((no yes)))
472 (tangle . ((tangle yes no :any)))
473 (tangle-mode . ((#o755 #o555 #o444 :any)))
477 (defconst org-babel-header-arg-names
478 (mapcar #'car org-babel-common-header-args-w-values)
479 "Common header arguments used by org-babel.
480 Note that individual languages may define their own language
481 specific header arguments as well.")
483 (defvar org-babel-default-header-args
484 '((:session . "none") (:results . "replace") (:exports . "code")
485 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
486 "Default arguments to use when evaluating a source block.")
488 (defvar org-babel-default-inline-header-args
489 '((:session . "none") (:results . "replace") (:exports . "results"))
490 "Default arguments to use when evaluating an inline source block.")
492 (defvar org-babel-data-names '("tblname" "results" "name"))
494 (defvar org-babel-result-regexp
495 (concat "^[ \t]*#\\+"
496 (regexp-opt org-babel-data-names t)
498 ;; FIXME The string below is `org-ts-regexp'
499 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>"
500 " \\)?\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*")
501 "Regular expression used to match result lines.
502 If the results are associated with a hash key then the hash will
503 be saved in the second match data.")
505 (defvar org-babel-result-w-name-regexp
506 (concat org-babel-result-regexp
507 "\\([^ ()\f\t\n\r\v]+\\)\\((\\(.*\\))\\|\\)"))
509 (defvar org-babel-min-lines-for-block-output 10
510 "The minimum number of lines for block output.
511 If number of lines of output is equal to or exceeds this
512 value, the output is placed in a #+begin_example...#+end_example
513 block. Otherwise the output is marked as literal by inserting
514 colons at the starts of the lines. This variable only takes
515 effect if the :results output option is in effect.")
517 (defvar org-babel-noweb-error-langs nil
518 "Languages for which Babel will raise literate programming errors.
519 List of languages for which errors should be raised when the
520 source code block satisfying a noweb reference in this language
521 can not be resolved.")
523 (defvar org-babel-hash-show 4
524 "Number of initial characters to show of a hidden results hash.")
526 (defvar org-babel-hash-show-time nil
527 "Non-nil means show the time the code block was evaluated in the result hash.")
529 (defvar org-babel-after-execute-hook nil
530 "Hook for functions to be called after `org-babel-execute-src-block'")
532 (defun org-babel-named-src-block-regexp-for-name (name)
533 "This generates a regexp used to match a src block named NAME."
534 (concat org-babel-src-name-regexp (regexp-quote name)
535 "[ \t(]*[\r\n]\\(?:^#.*[\r\n]\\)*"
536 (substring org-babel-src-block-regexp 1)))
538 (defun org-babel-named-data-regexp-for-name (name)
539 "This generates a regexp used to match data named NAME."
540 (concat org-babel-result-regexp (regexp-quote name) "\\([ \t]\\|$\\)"))
543 (defvar call-process-region)
544 (defvar org-babel-current-src-block-location nil
545 "Marker pointing to the src block currently being executed.
546 This may also point to a call line or an inline code block. If
547 multiple blocks are being executed (e.g., in chained execution
548 through use of the :var header argument) this marker points to
549 the outer-most code block.")
554 (defun org-babel-execute-src-block (&optional arg info params)
555 "Execute the current source code block.
556 Insert the results of execution into the buffer. Source code
557 execution and the collection and formatting of results can be
558 controlled through a variety of header arguments.
560 With prefix argument ARG, force re-execution even if an existing
561 result cached in the buffer would otherwise have been returned.
563 Optionally supply a value for INFO in the form returned by
564 `org-babel-get-src-block-info'.
566 Optionally supply a value for PARAMS which will be merged with
567 the header arguments specified at the front of the source code
570 (let* ((org-babel-current-src-block-location
571 (or org-babel-current-src-block-location
573 (org-babel-where-is-src-block-head)))
576 (org-babel-get-src-block-info)))
577 (merged-params (org-babel-merge-params (nth 2 info) params)))
578 (when (org-babel-check-evaluate
579 (let ((i info)) (setf (nth 2 i) merged-params) i))
580 (let* ((params (if params
581 (org-babel-process-params merged-params)
583 (cachep (and (not arg) (cdr (assoc :cache params))
584 (string= "yes" (cdr (assoc :cache params)))))
585 (new-hash (when cachep (org-babel-sha1-hash info)))
586 (old-hash (when cachep (org-babel-current-result-hash)))
587 (cache-current-p (and (not arg) new-hash
588 (equal new-hash old-hash))))
591 (save-excursion ;; return cached result
592 (goto-char (org-babel-where-is-src-block-result nil info))
593 (end-of-line 1) (forward-char 1)
594 (let ((result (org-babel-read-result)))
595 (message (replace-regexp-in-string
596 "%" "%%" (format "%S" result)))
598 ((org-babel-confirm-evaluate
599 (let ((i info)) (setf (nth 2 i) merged-params) i))
600 (let* ((lang (nth 0 info))
601 (result-params (cdr (assoc :result-params params)))
602 (body (setf (nth 1 info)
603 (if (org-babel-noweb-p params :eval)
604 (org-babel-expand-noweb-references info)
606 (dir (cdr (assoc :dir params)))
608 (or (and dir (file-name-as-directory (expand-file-name dir)))
610 (org-babel-call-process-region-original ;; for tramp handler
611 (or (org-bound-and-true-p
612 org-babel-call-process-region-original)
613 (symbol-function 'call-process-region)))
614 (indent (nth 5 info))
617 (let ((call-process-region
619 (apply 'org-babel-tramp-handle-call-process-region
623 (let ((f (intern (concat "org-babel-execute:" f))))
624 (when (fboundp f) f)))))
626 (or (funcall lang-check lang)
629 (cdr (assoc lang org-src-lang-modes))))
630 (error "No org-babel-execute function for %s!"
632 (message "executing %s code block%s..."
634 (if (nth 4 info) (format " (%s)" (nth 4 info)) ""))
635 (if (member "none" result-params)
637 (funcall cmd body params)
638 (message "result silenced")
641 (let ((result (funcall cmd body params)))
642 (if (and (eq (cdr (assoc :result-type params))
644 (or (member "vector" result-params)
645 (member "table" result-params))
646 (not (listp result)))
647 (list (list result)) result)))
648 ;; If non-empty result and :file then write to :file.
649 (when (cdr (assoc :file params))
651 (with-temp-file (cdr (assoc :file params))
653 (org-babel-format-result
654 result (cdr (assoc :sep (nth 2 info)))))))
655 (setq result (cdr (assoc :file params))))
656 ;; Possibly perform post process provided its appropriate.
657 (when (cdr (assoc :post params))
658 (let ((*this* (if (cdr (assoc :file params))
659 (org-babel-result-to-file
660 (cdr (assoc :file params))
661 (when (assoc :file-desc params)
662 (or (cdr (assoc :file-desc params))
665 (setq result (org-babel-ref-resolve
666 (cdr (assoc :post params))))
667 (when (cdr (assoc :file params))
669 (remove "file" result-params)))))
670 (org-babel-insert-result
671 result result-params info new-hash indent lang))
672 (run-hooks 'org-babel-after-execute-hook)
674 (setq call-process-region
675 'org-babel-call-process-region-original)))))))))
677 (defun org-babel-expand-body:generic (body params &optional var-lines)
678 "Expand BODY with PARAMS.
679 Expand a block of code with org-babel according to its header
680 arguments. This generic implementation of body expansion is
681 called for languages which have not defined their own specific
682 org-babel-expand-body:lang function."
683 (let ((pro (cdr (assoc :prologue params)))
684 (epi (cdr (assoc :epilogue params))))
685 (mapconcat #'identity
686 (append (when pro (list pro))
689 (when epi (list epi)))
693 (defun org-babel-expand-src-block (&optional _arg info params)
694 "Expand the current source code block.
695 Expand according to the source code block's header
696 arguments and pop open the results in a preview buffer."
698 (let* ((info (or info (org-babel-get-src-block-info)))
700 (params (setf (nth 2 info)
701 (sort (org-babel-merge-params (nth 2 info) params)
702 (lambda (el1 el2) (string< (symbol-name (car el1))
703 (symbol-name (car el2)))))))
704 (body (setf (nth 1 info)
705 (if (org-babel-noweb-p params :eval)
706 (org-babel-expand-noweb-references info) (nth 1 info))))
707 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
708 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
711 (if (fboundp expand-cmd) (funcall expand-cmd body params)
712 (org-babel-expand-body:generic
713 body params (and (fboundp assignments-cmd)
714 (funcall assignments-cmd params))))))
715 (if (org-called-interactively-p 'any)
718 (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
721 (defun org-babel-edit-distance (s1 s2)
722 "Return the edit (levenshtein) distance between strings S1 S2."
723 (let* ((l1 (length s1))
725 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
726 (number-sequence 1 (1+ l1)))))
727 (in (lambda (i j) (aref (aref dist i) j))))
728 (setf (aref (aref dist 0) 0) 0)
729 (dolist (j (number-sequence 1 l2))
730 (setf (aref (aref dist 0) j) j))
731 (dolist (i (number-sequence 1 l1))
732 (setf (aref (aref dist i) 0) i)
733 (dolist (j (number-sequence 1 l2))
734 (setf (aref (aref dist i) j)
736 (1+ (funcall in (1- i) j))
737 (1+ (funcall in i (1- j)))
738 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
739 (funcall in (1- i) (1- j)))))))
742 (defun org-babel-combine-header-arg-lists (original &rest others)
743 "Combine a number of lists of header argument names and arguments."
744 (let ((results (copy-sequence original)))
745 (dolist (new-list others)
746 (dolist (arg-pair new-list)
747 (let ((header (car arg-pair)))
749 (cons arg-pair (org-remove-if
750 (lambda (pair) (equal header (car pair)))
755 (defun org-babel-check-src-block ()
756 "Check for misspelled header arguments in the current code block."
758 ;; TODO: report malformed code block
759 ;; TODO: report incompatible combinations of header arguments
760 ;; TODO: report uninitialized variables
761 (let ((too-close 2) ;; <- control closeness to report potential match
762 (names (mapcar #'symbol-name org-babel-header-arg-names)))
763 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
764 (and (org-babel-where-is-src-block-head)
765 (org-babel-parse-header-arguments
767 (match-string 4))))))
769 (when (and (not (string= header name))
770 (<= (org-babel-edit-distance header name) too-close)
771 (not (member header names)))
772 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
774 (message "No suspicious header arguments found.")))
777 (defun org-babel-insert-header-arg ()
778 "Insert a header argument selecting from lists of common args and values."
780 (let* ((lang (car (org-babel-get-src-block-info 'light)))
781 (lang-headers (intern (concat "org-babel-header-args:" lang)))
782 (headers (org-babel-combine-header-arg-lists
783 org-babel-common-header-args-w-values
784 (when (boundp lang-headers) (eval lang-headers))))
785 (arg (org-icompleting-read
788 (lambda (header-spec) (symbol-name (car header-spec)))
791 (let ((vals (cdr (assoc (intern arg) headers))))
797 (read-from-minibuffer "value: "))
801 (let ((arg (org-icompleting-read
803 (cons "default" (mapcar #'symbol-name group)))))
804 (if (and arg (not (string= "default" arg)))
809 ;; Add support for completing-read insertion of header arguments after ":"
810 (defun org-babel-header-arg-expand ()
811 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
812 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
813 (org-babel-enter-header-arg-w-completion (match-string 2))))
815 (defun org-babel-enter-header-arg-w-completion (&optional lang)
816 "Insert header argument appropriate for LANG with completion."
817 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
818 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var)))
819 (headers-w-values (org-babel-combine-header-arg-lists
820 org-babel-common-header-args-w-values lang-headers))
821 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
822 (header (org-completing-read "Header Arg: " headers))
823 (args (cdr (assoc (intern header) headers-w-values)))
824 (arg (when (and args (listp args))
826 (format "%s: " header)
827 (mapcar #'symbol-name (apply #'append args))))))
828 (insert (concat header " " (or arg "")))
831 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
834 (defun org-babel-load-in-session (&optional _arg info)
835 "Load the body of the current source-code block.
836 Evaluate the header arguments for the source block before
837 entering the session. After loading the body this pops open the
840 (let* ((info (or info (org-babel-get-src-block-info)))
842 (params (nth 2 info))
844 (user-error "No src code block at point")
846 (if (org-babel-noweb-p params :eval)
847 (org-babel-expand-noweb-references info)
849 (session (cdr (assoc :session params)))
850 (dir (cdr (assoc :dir params)))
852 (or (and dir (file-name-as-directory dir)) default-directory))
853 (cmd (intern (concat "org-babel-load-session:" lang))))
854 (unless (fboundp cmd)
855 (error "No org-babel-load-session function for %s!" lang))
856 (pop-to-buffer (funcall cmd session body params))
860 (defun org-babel-initiate-session (&optional arg info)
861 "Initiate session for current code block.
862 If called with a prefix argument then resolve any variable
863 references in the header arguments and assign these variables in
864 the session. Copy the body of the code block to the kill ring."
866 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
869 (params (nth 2 info))
870 (session (cdr (assoc :session params)))
871 (dir (cdr (assoc :dir params)))
873 (or (and dir (file-name-as-directory dir)) default-directory))
874 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
875 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
876 (if (and (stringp session) (string= session "none"))
877 (error "This block is not using a session!"))
878 (unless (fboundp init-cmd)
879 (error "No org-babel-initiate-session function for %s!" lang))
880 (with-temp-buffer (insert (org-babel-trim body))
881 (copy-region-as-kill (point-min) (point-max)))
883 (unless (fboundp prep-cmd)
884 (error "No org-babel-prep-session function for %s!" lang))
885 (funcall prep-cmd session params))
886 (funcall init-cmd session params)))
889 (defun org-babel-switch-to-session (&optional arg info)
890 "Switch to the session of the current code block.
891 Uses `org-babel-initiate-session' to start the session. If called
892 with a prefix argument then this is passed on to
893 `org-babel-initiate-session'."
895 (pop-to-buffer (org-babel-initiate-session arg info))
898 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
900 (defvar org-src-window-setup)
903 (defun org-babel-switch-to-session-with-code (&optional arg _info)
904 "Switch to code buffer and display session."
908 (let ((other-window-buffer (window-buffer (next-window))))
909 (set-window-buffer (next-window) (current-buffer))
910 (set-window-buffer (selected-window) other-window-buffer))
912 (info (org-babel-get-src-block-info))
913 (org-src-window-setup 'reorganize-frame))
915 (org-babel-switch-to-session arg info))
917 (funcall swap-windows)))
919 (defmacro org-babel-do-in-edit-buffer (&rest body)
920 "Evaluate BODY in edit buffer if there is a code block at point.
921 Return t if a code block was found at point, nil otherwise."
922 `(let ((org-src-window-setup 'switch-invisibly))
923 (when (and (org-babel-where-is-src-block-head)
924 (org-edit-src-code nil nil nil))
925 (unwind-protect (progn ,@body)
926 (if (org-bound-and-true-p org-edit-src-from-org-mode)
927 (org-edit-src-exit)))
929 (def-edebug-spec org-babel-do-in-edit-buffer (body))
931 (defun org-babel-do-key-sequence-in-edit-buffer (key)
932 "Read key sequence and execute the command in edit buffer.
933 Enter a key sequence to be executed in the language major-mode
934 edit buffer. For example, TAB will alter the contents of the
935 Org-mode code block according to the effect of TAB in the
936 language major-mode buffer. For languages that support
937 interactive sessions, this can be used to send code from the Org
938 buffer to the session for evaluation using the native major-mode
939 evaluation mechanisms."
940 (interactive "kEnter key-sequence to execute in edit buffer: ")
941 (org-babel-do-in-edit-buffer
943 (key-binding (or key (read-key-sequence nil))))))
945 (defvar org-bracket-link-regexp)
947 (defun org-babel-active-location-p ()
948 (memq (car (save-match-data (org-element-context)))
949 '(babel-call inline-babel-call inline-src-block src-block)))
952 (defun org-babel-open-src-block-result (&optional re-run)
953 "If `point' is on a src block then open the results of the
954 source code block, otherwise return nil. With optional prefix
955 argument RE-RUN the source-code block is evaluated even if
956 results already exist."
958 (let ((info (org-babel-get-src-block-info 'light)))
961 ;; go to the results, if there aren't any then run the block
962 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
963 (progn (org-babel-execute-src-block)
964 (org-babel-where-is-src-block-result))))
966 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
968 (if (looking-at org-bracket-link-regexp)
971 (let ((r (org-babel-format-result
972 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
973 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
974 (delete-region (point-min) (point-max))
979 (defmacro org-babel-map-src-blocks (file &rest body)
980 "Evaluate BODY forms on each source-block in FILE.
981 If FILE is nil evaluate BODY forms on source blocks in current
982 buffer. During evaluation of BODY the following local variables
983 are set relative to the currently matched code block.
985 full-block ------- string holding the entirety of the code block
986 beg-block -------- point at the beginning of the code block
987 end-block -------- point at the end of the matched code block
988 lang ------------- string holding the language of the code block
989 beg-lang --------- point at the beginning of the lang
990 end-lang --------- point at the end of the lang
991 switches --------- string holding the switches
992 beg-switches ----- point at the beginning of the switches
993 end-switches ----- point at the end of the switches
994 header-args ------ string holding the header-args
995 beg-header-args -- point at the beginning of the header-args
996 end-header-args -- point at the end of the header-args
997 body ------------- string holding the body of the code block
998 beg-body --------- point at the beginning of the body
999 end-body --------- point at the end of the body"
1000 (declare (indent 1))
1001 (let ((tempvar (make-symbol "file")))
1002 `(let* ((,tempvar ,file)
1003 (visited-p (or (null ,tempvar)
1004 (get-file-buffer (expand-file-name ,tempvar))))
1005 (point (point)) to-be-removed)
1006 (save-window-excursion
1007 (when ,tempvar (find-file ,tempvar))
1008 (setq to-be-removed (current-buffer))
1009 (goto-char (point-min))
1010 (while (re-search-forward org-babel-src-block-regexp nil t)
1011 (when (org-babel-active-location-p)
1012 (goto-char (match-beginning 0))
1013 (let ((full-block (match-string 0))
1014 (beg-block (match-beginning 0))
1015 (end-block (match-end 0))
1016 (lang (match-string 2))
1017 (beg-lang (match-beginning 2))
1018 (end-lang (match-end 2))
1019 (switches (match-string 3))
1020 (beg-switches (match-beginning 3))
1021 (end-switches (match-end 3))
1022 (header-args (match-string 4))
1023 (beg-header-args (match-beginning 4))
1024 (end-header-args (match-end 4))
1025 (body (match-string 5))
1026 (beg-body (match-beginning 5))
1027 (end-body (match-end 5)))
1028 ;; Silence byte-compiler in case `body' doesn't use all
1030 (ignore full-block beg-block end-block lang
1031 beg-lang end-lang switches beg-switches
1032 end-switches header-args beg-header-args
1033 end-header-args body beg-body end-body)
1035 (goto-char end-block)))))
1036 (unless visited-p (kill-buffer to-be-removed))
1037 (goto-char point))))
1038 (def-edebug-spec org-babel-map-src-blocks (form body))
1041 (defmacro org-babel-map-inline-src-blocks (file &rest body)
1042 "Evaluate BODY forms on each inline source-block in FILE.
1043 If FILE is nil evaluate BODY forms on source blocks in current
1045 (declare (indent 1))
1046 (let ((tempvar (make-symbol "file")))
1047 `(let* ((,tempvar ,file)
1048 (visited-p (or (null ,tempvar)
1049 (get-file-buffer (expand-file-name ,tempvar))))
1050 (point (point)) to-be-removed)
1051 (save-window-excursion
1052 (when ,tempvar (find-file ,tempvar))
1053 (setq to-be-removed (current-buffer))
1054 (goto-char (point-min))
1055 (while (re-search-forward org-babel-inline-src-block-regexp nil t)
1056 (when (org-babel-active-location-p)
1057 (goto-char (match-beginning 1))
1058 (save-match-data ,@body))
1059 (goto-char (match-end 0))))
1060 (unless visited-p (kill-buffer to-be-removed))
1061 (goto-char point))))
1062 (def-edebug-spec org-babel-map-inline-src-blocks (form body))
1064 (defvar org-babel-lob-one-liner-regexp)
1067 (defmacro org-babel-map-call-lines (file &rest body)
1068 "Evaluate BODY forms on each call line in FILE.
1069 If FILE is nil evaluate BODY forms on source blocks in current
1071 (declare (indent 1))
1072 (let ((tempvar (make-symbol "file")))
1073 `(let* ((,tempvar ,file)
1074 (visited-p (or (null ,tempvar)
1075 (get-file-buffer (expand-file-name ,tempvar))))
1076 (point (point)) to-be-removed)
1077 (save-window-excursion
1078 (when ,tempvar (find-file ,tempvar))
1079 (setq to-be-removed (current-buffer))
1080 (goto-char (point-min))
1081 (while (re-search-forward org-babel-lob-one-liner-regexp nil t)
1082 (when (org-babel-active-location-p)
1083 (goto-char (match-beginning 1))
1084 (save-match-data ,@body))
1085 (goto-char (match-end 0))))
1086 (unless visited-p (kill-buffer to-be-removed))
1087 (goto-char point))))
1088 (def-edebug-spec org-babel-map-call-lines (form body))
1091 (defmacro org-babel-map-executables (file &rest body)
1092 (declare (indent 1))
1093 (let ((tempvar (make-symbol "file"))
1094 (rx (make-symbol "rx")))
1095 `(let* ((,tempvar ,file)
1096 (,rx (concat "\\(" org-babel-src-block-regexp
1097 "\\|" org-babel-inline-src-block-regexp
1098 "\\|" org-babel-lob-one-liner-regexp "\\)"))
1099 (visited-p (or (null ,tempvar)
1100 (get-file-buffer (expand-file-name ,tempvar))))
1101 (point (point)) to-be-removed)
1102 (save-window-excursion
1103 (when ,tempvar (find-file ,tempvar))
1104 (setq to-be-removed (current-buffer))
1105 (goto-char (point-min))
1106 (while (re-search-forward ,rx nil t)
1107 (when (org-babel-active-location-p)
1108 (goto-char (match-beginning 1))
1109 (when (looking-at org-babel-inline-src-block-regexp)
1111 (save-match-data ,@body))
1112 (goto-char (match-end 0))))
1113 (unless visited-p (kill-buffer to-be-removed))
1114 (goto-char point))))
1115 (def-edebug-spec org-babel-map-executables (form body))
1118 (defun org-babel-execute-buffer (&optional arg)
1119 "Execute source code blocks in a buffer.
1120 Call `org-babel-execute-src-block' on every source block in
1121 the current buffer."
1123 (org-babel-eval-wipe-error-buffer)
1124 (org-save-outline-visibility t
1125 (org-babel-map-executables nil
1126 (if (looking-at org-babel-lob-one-liner-regexp)
1127 (org-babel-lob-execute-maybe)
1128 (org-babel-execute-src-block arg)))))
1131 (defun org-babel-execute-subtree (&optional arg)
1132 "Execute source code blocks in a subtree.
1133 Call `org-babel-execute-src-block' on every source block in
1134 the current subtree."
1138 (org-narrow-to-subtree)
1139 (org-babel-execute-buffer arg)
1143 (defun org-babel-sha1-hash (&optional info)
1144 "Generate an sha1 hash based on the value of info."
1146 (let ((print-level nil)
1147 (info (or info (org-babel-get-src-block-info))))
1149 (sort (copy-sequence (nth 2 info))
1150 (lambda (a b) (string< (car a) (car b)))))
1151 (let* ((rm (lambda (lst)
1152 (dolist (p '("replace" "silent" "none"
1153 "append" "prepend"))
1154 (setq lst (remove p lst)))
1157 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1158 (copy-sequence (cdr arg))
1160 (when (and v (not (and (sequencep v)
1164 ((and (listp v) ; lists are sorted
1165 (member (car arg) '(:result-params)))
1166 (sort (funcall rm v) #'string<))
1167 ((and (stringp v) ; strings are sorted
1168 (member (car arg) '(:results :exports)))
1169 (mapconcat #'identity (sort (funcall rm (split-string v))
1172 (let* ((it (format "%s-%s"
1175 (delq nil (mapcar (lambda (arg)
1176 (let ((normalized (funcall norm arg)))
1178 (format "%S" normalized))))
1182 (when (org-called-interactively-p 'interactive) (message hash))
1185 (defun org-babel-current-result-hash ()
1186 "Return the current in-buffer hash."
1187 (org-babel-where-is-src-block-result)
1188 (org-no-properties (match-string 5)))
1190 (defun org-babel-set-current-result-hash (hash)
1191 "Set the current in-buffer hash to HASH."
1192 (org-babel-where-is-src-block-result)
1193 (save-excursion (goto-char (match-beginning 5))
1194 (mapc #'delete-overlay (overlays-at (point)))
1195 (forward-char org-babel-hash-show)
1196 (mapc #'delete-overlay (overlays-at (point)))
1197 (replace-match hash nil nil nil 5)
1198 (goto-char (point-at-bol))
1199 (org-babel-hide-hash)))
1201 (defun org-babel-hide-hash ()
1202 "Hide the hash in the current results line.
1203 Only the initial `org-babel-hash-show' characters of the hash
1204 will remain visible."
1205 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1207 (when (and (re-search-forward org-babel-result-regexp nil t)
1209 (let* ((start (match-beginning 5))
1210 (hide-start (+ org-babel-hash-show start))
1212 (hash (match-string 5))
1214 (setq ov1 (make-overlay start hide-start))
1215 (setq ov2 (make-overlay hide-start end))
1216 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1217 (overlay-put ov1 'babel-hash hash)))))
1219 (defun org-babel-hide-all-hashes ()
1220 "Hide the hash in the current buffer.
1221 Only the initial `org-babel-hash-show' characters of each hash
1222 will remain visible. This function should be called as part of
1223 the `org-mode-hook'."
1225 (while (and (not org-babel-hash-show-time)
1226 (re-search-forward org-babel-result-regexp nil t))
1227 (goto-char (match-beginning 0))
1228 (org-babel-hide-hash)
1229 (goto-char (match-end 0)))))
1230 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1232 (defun org-babel-hash-at-point (&optional point)
1233 "Return the value of the hash at POINT.
1234 The hash is also added as the last element of the kill ring.
1235 This can be called with C-c C-c."
1237 (let ((hash (car (delq nil (mapcar
1238 (lambda (ol) (overlay-get ol 'babel-hash))
1239 (overlays-at (or point (point))))))))
1240 (when hash (kill-new hash) (message hash))))
1241 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1243 (defun org-babel-result-hide-spec ()
1244 "Hide portions of results lines.
1245 Add `org-babel-hide-result' as an invisibility spec for hiding
1246 portions of results lines."
1247 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1248 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1250 (defvar org-babel-hide-result-overlays nil
1251 "Overlays hiding results.")
1253 (defun org-babel-result-hide-all ()
1254 "Fold all results in the current buffer."
1256 (org-babel-show-result-all)
1258 (while (re-search-forward org-babel-result-regexp nil t)
1259 (save-excursion (goto-char (match-beginning 0))
1260 (org-babel-hide-result-toggle-maybe)))))
1262 (defun org-babel-show-result-all ()
1263 "Unfold all results in the current buffer."
1264 (mapc 'delete-overlay org-babel-hide-result-overlays)
1265 (setq org-babel-hide-result-overlays nil))
1268 (defun org-babel-hide-result-toggle-maybe ()
1269 "Toggle visibility of result at point."
1271 (let ((case-fold-search t))
1273 (beginning-of-line 1)
1274 (looking-at org-babel-result-regexp))
1275 (progn (org-babel-hide-result-toggle)
1276 t) ;; to signal that we took action
1277 nil))) ;; to signal that we did not
1279 (defun org-babel-hide-result-toggle (&optional force)
1280 "Toggle the visibility of the current result."
1284 (if (re-search-forward org-babel-result-regexp nil t)
1285 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1287 (while (looking-at org-babel-multi-line-header-regexp)
1289 (goto-char (- (org-babel-result-end) 1)) (point)))
1291 (if (memq t (mapcar (lambda (overlay)
1292 (eq (overlay-get overlay 'invisible)
1293 'org-babel-hide-result))
1294 (overlays-at start)))
1295 (if (or (not force) (eq force 'off))
1297 (when (member ov org-babel-hide-result-overlays)
1298 (setq org-babel-hide-result-overlays
1299 (delq ov org-babel-hide-result-overlays)))
1300 (when (eq (overlay-get ov 'invisible)
1301 'org-babel-hide-result)
1302 (delete-overlay ov)))
1303 (overlays-at start)))
1304 (setq ov (make-overlay start end))
1305 (overlay-put ov 'invisible 'org-babel-hide-result)
1306 ;; make the block accessible to isearch
1308 ov 'isearch-open-invisible
1310 (when (member ov org-babel-hide-result-overlays)
1311 (setq org-babel-hide-result-overlays
1312 (delq ov org-babel-hide-result-overlays)))
1313 (when (eq (overlay-get ov 'invisible)
1314 'org-babel-hide-result)
1315 (delete-overlay ov))))
1316 (push ov org-babel-hide-result-overlays)))
1317 (error "Not looking at a result line"))))
1319 ;; org-tab-after-check-for-cycling-hook
1320 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1321 ;; Remove overlays when changing major mode
1322 (add-hook 'org-mode-hook
1323 (lambda () (org-add-hook 'change-major-mode-hook
1324 'org-babel-show-result-all 'append 'local)))
1326 (defvar org-file-properties)
1327 (defun org-babel-params-from-properties (&optional lang)
1328 "Retrieve parameters specified as properties.
1329 Return a list of association lists of source block params
1330 specified in the properties of the current outline entry."
1333 ;; DEPRECATED header arguments specified as separate property at
1334 ;; point of definition
1336 (org-babel-parse-multiple-vars
1339 (lambda (header-arg)
1340 (and (setq val (org-entry-get (point) header-arg t))
1341 (cons (intern (concat ":" header-arg))
1342 (org-babel-read val))))
1347 (org-babel-combine-header-arg-lists
1348 org-babel-common-header-args-w-values
1350 (setq sym (intern (concat "org-babel-header-args:" lang)))
1351 (and (boundp sym) (eval sym))))))))))
1352 ;; header arguments specified with the header-args property at
1354 (org-babel-parse-header-arguments
1355 (org-entry-get org-babel-current-src-block-location
1356 "header-args" 'inherit))
1357 (when lang ;; language-specific header arguments at point of call
1358 (org-babel-parse-header-arguments
1359 (org-entry-get org-babel-current-src-block-location
1360 (concat "header-args:" lang) 'inherit))))))
1362 (defvar org-src-preserve-indentation) ;; declare defcustom from org-src
1363 (defun org-babel-parse-src-block-match ()
1364 "Parse the results from a match of the `org-babel-src-block-regexp'."
1365 (let* ((block-indentation (length (match-string 1)))
1366 (lang (org-no-properties (match-string 2)))
1367 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
1368 (switches (match-string 3))
1369 (body (org-no-properties
1370 (let* ((body (match-string 5))
1371 (sub-length (- (length body) 1)))
1372 (if (and (> sub-length 0)
1373 (string= "\n" (substring body sub-length)))
1374 (substring body 0 sub-length)
1376 (preserve-indentation (or org-src-preserve-indentation
1378 (string-match "-i\\>" switches)))))
1380 ;; get block body less properties, protective commas, and indentation
1383 (insert (org-unescape-code-in-string body))
1384 (unless preserve-indentation (org-do-remove-indentation))
1386 (apply #'org-babel-merge-params
1387 org-babel-default-header-args
1388 (when (boundp lang-headers) (eval lang-headers))
1390 (org-babel-params-from-properties lang)
1391 (list (org-babel-parse-header-arguments
1392 (org-no-properties (or (match-string 4) ""))))))
1394 block-indentation)))
1396 (defun org-babel-parse-inline-src-block-match ()
1397 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
1398 (let* ((lang (org-no-properties (match-string 2)))
1399 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
1401 (org-unescape-code-in-string (org-no-properties (match-string 5)))
1402 (apply #'org-babel-merge-params
1403 org-babel-default-inline-header-args
1404 (if (boundp lang-headers) (eval lang-headers) nil)
1406 (org-babel-params-from-properties lang)
1407 (list (org-babel-parse-header-arguments
1408 (org-no-properties (or (match-string 4) "")))))))))
1410 (defun org-babel-balanced-split (string alts)
1411 "Split STRING on instances of ALTS.
1412 ALTS is a cons of two character options where each option may be
1413 either the numeric code of a single character or a list of
1414 character alternatives. For example to split on balanced
1415 instances of \"[ \t]:\" set ALTS to ((32 9) . 58)."
1416 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1417 (matched (lambda (ch last)
1419 (and (funcall matches ch (cdr alts))
1420 (funcall matches last (car alts)))
1421 (funcall matches ch alts))))
1422 (balance 0) (last 0)
1424 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1425 (setq balance (+ balance
1426 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1427 ((or (equal 93 ch) (equal 41 ch)) -1)
1429 (when (and (equal 34 ch) (not (equal 92 last)))
1430 (setq quote (not quote)))
1431 (setq partial (cons ch partial))
1432 (when (and (= balance 0) (not quote) (funcall matched ch last))
1433 (setq lst (cons (apply #'string (nreverse
1440 (string-to-list string))
1441 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1443 (defun org-babel-join-splits-near-ch (ch list)
1444 "Join splits where \"=\" is on either end of the split."
1445 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1446 (first= (lambda (str) (= ch (aref str 0)))))
1448 (org-reduce (lambda (acc el)
1449 (let ((head (car acc)))
1450 (if (and head (or (funcall last= head) (funcall first= el)))
1451 (cons (concat head el) (cdr acc))
1453 list :initial-value nil))))
1455 (defun org-babel-parse-header-arguments (arg-string)
1456 "Parse a string of header arguments returning an alist."
1457 (when (> (length arg-string) 0)
1458 (org-babel-parse-multiple-vars
1463 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1465 (cons (intern (match-string 1 arg))
1466 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1467 (cons (intern (org-babel-chomp arg)) nil)))
1468 (let ((raw (org-babel-balanced-split arg-string '((32 9) . 58))))
1469 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
1471 (defun org-babel-parse-multiple-vars (header-arguments)
1472 "Expand multiple variable assignments behind a single :var keyword.
1474 This allows expression of multiple variables with one :var as
1477 #+PROPERTY: var foo=1, bar=2"
1479 (mapc (lambda (pair)
1480 (if (eq (car pair) :var)
1481 (mapcar (lambda (v) (push (cons :var (org-babel-trim v)) results))
1482 (org-babel-join-splits-near-ch
1483 61 (org-babel-balanced-split (cdr pair) 32)))
1484 (push pair results)))
1486 (nreverse results)))
1488 (defun org-babel-process-params (params)
1489 "Expand variables in PARAMS and add summary parameters."
1490 (let* ((processed-vars (mapcar (lambda (el)
1491 (if (consp (cdr el))
1493 (org-babel-ref-parse (cdr el))))
1494 (org-babel-get-header params :var)))
1495 (vars-and-names (if (and (assoc :colname-names params)
1496 (assoc :rowname-names params))
1497 (list processed-vars)
1498 (org-babel-disassemble-tables
1500 (cdr (assoc :hlines params))
1501 (cdr (assoc :colnames params))
1502 (cdr (assoc :rownames params)))))
1503 (raw-result (or (cdr (assoc :results params)) ""))
1504 (result-params (append
1505 (split-string (if (stringp raw-result)
1508 (cdr (assoc :result-params params)))))
1510 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1512 (cons :colname-names (or (cdr (assoc :colname-names params))
1513 (cadr vars-and-names)))
1514 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1515 (caddr vars-and-names)))
1516 (cons :result-params result-params)
1517 (cons :result-type (cond ((member "output" result-params) 'output)
1518 ((member "value" result-params) 'value)
1520 (org-babel-get-header params :var 'other))))
1522 ;; row and column names
1523 (defun org-babel-del-hlines (table)
1524 "Remove all `hline's from TABLE."
1525 (remove 'hline table))
1527 (defun org-babel-get-colnames (table)
1528 "Return the column names of TABLE.
1529 Return a cons cell, the `car' of which contains the TABLE less
1530 colnames, and the `cdr' of which contains a list of the column
1532 (if (equal 'hline (nth 1 table))
1533 (cons (cddr table) (car table))
1534 (cons (cdr table) (car table))))
1536 (defun org-babel-get-rownames (table)
1537 "Return the row names of TABLE.
1538 Return a cons cell, the `car' of which contains the TABLE less
1539 rownames, and the `cdr' of which contains a list of the rownames.
1540 Note: this function removes any hlines in TABLE."
1541 (let* ((table (org-babel-del-hlines table))
1542 (rownames (funcall (lambda ()
1548 (setq tp (cdr tp))))
1550 (cons table rownames)))
1552 (defun org-babel-put-colnames (table colnames)
1553 "Add COLNAMES to TABLE if they exist."
1554 (if colnames (apply 'list colnames 'hline table) table))
1556 (defun org-babel-put-rownames (table rownames)
1557 "Add ROWNAMES to TABLE if they exist."
1559 (mapcar (lambda (row)
1561 (cons (or (pop rownames) "") row)
1565 (defun org-babel-pick-name (names selector)
1566 "Select one out of an alist of row or column names.
1567 SELECTOR can be either a list of names in which case those names
1568 will be returned directly, or an index into the list NAMES in
1569 which case the indexed names will be return."
1570 (if (listp selector)
1573 (if (and selector (symbolp selector) (not (equal t selector)))
1574 (cdr (assoc selector names))
1575 (if (integerp selector)
1576 (nth (- selector 1) names)
1577 (cdr (car (last names))))))))
1579 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1580 "Parse tables for further processing.
1581 Process the variables in VARS according to the HLINES,
1582 ROWNAMES and COLNAMES header arguments. Return a list consisting
1583 of the vars, cnames and rnames."
1584 (let (cnames rnames)
1588 (when (listp (cdr var))
1589 (when (and (not (equal colnames "no"))
1590 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1591 (not (member 'hline (cddr (cdr var)))))))
1592 (let ((both (org-babel-get-colnames (cdr var))))
1593 (setq cnames (cons (cons (car var) (cdr both))
1595 (setq var (cons (car var) (car both)))))
1596 (when (and rownames (not (equal rownames "no")))
1597 (let ((both (org-babel-get-rownames (cdr var))))
1598 (setq rnames (cons (cons (car var) (cdr both))
1600 (setq var (cons (car var) (car both)))))
1601 (when (and hlines (not (equal hlines "yes")))
1602 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1605 (reverse cnames) (reverse rnames))))
1607 (defun org-babel-reassemble-table (table colnames rownames)
1608 "Add column and row names to a table.
1609 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1610 to the table for reinsertion to org-mode."
1612 (let ((table (if (and rownames (= (length table) (length rownames)))
1613 (org-babel-put-rownames table rownames) table)))
1614 (if (and colnames (listp (car table)) (= (length (car table))
1616 (org-babel-put-colnames table colnames) table))
1619 (defun org-babel-where-is-src-block-head ()
1620 "Find where the current source block begins.
1621 Return the point at the beginning of the current source
1622 block. Specifically at the beginning of the #+BEGIN_SRC line.
1623 If the point is not on a source block then return nil."
1624 (let ((initial (point)) (case-fold-search t) top bottom)
1626 (save-excursion ;; on a source name line or a #+header line
1627 (beginning-of-line 1)
1628 (and (or (looking-at org-babel-src-name-regexp)
1629 (looking-at org-babel-multi-line-header-regexp))
1631 (while (and (forward-line 1)
1632 (or (looking-at org-babel-src-name-regexp)
1633 (looking-at org-babel-multi-line-header-regexp))))
1634 (looking-at org-babel-src-block-regexp))
1636 (save-excursion ;; on a #+begin_src line
1637 (beginning-of-line 1)
1638 (and (looking-at org-babel-src-block-regexp)
1640 (save-excursion ;; inside a src block
1642 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
1643 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
1644 (< top initial) (< initial bottom)
1645 (progn (goto-char top) (beginning-of-line 1)
1646 (looking-at org-babel-src-block-regexp))
1650 (defun org-babel-goto-src-block-head ()
1651 "Go to the beginning of the current code block."
1653 (let ((head (org-babel-where-is-src-block-head)))
1654 (if head (goto-char head) (error "Not currently in a code block"))))
1657 (defun org-babel-goto-named-src-block (name)
1658 "Go to a named source-code block."
1660 (let ((completion-ignore-case t)
1661 (case-fold-search t)
1662 (under-point (thing-at-point 'line)))
1663 (list (org-icompleting-read
1664 "source-block name: " (org-babel-src-block-names) nil t
1667 ((string-match (org-babel-noweb-wrap) under-point)
1668 (let ((block-name (match-string 1 under-point)))
1669 (string-match "[^(]*" block-name)
1670 (match-string 0 block-name)))
1672 ((string-match org-babel-lob-one-liner-regexp under-point)
1673 (let ((source-info (car (org-babel-lob-get-info))))
1674 (if (string-match "^\\([^\\[]+?\\)\\(\\[.*\\]\\)?(" source-info)
1675 (let ((source-name (match-string 1 source-info)))
1678 ((string-match (concat "#\\+" org-babel-results-keyword
1679 "\\:\s+\\([^\\(]*\\)") under-point)
1680 (match-string 1 under-point))
1682 ((and (thing-at-point 'symbol))
1683 (org-babel-find-named-block (thing-at-point 'symbol))
1684 (thing-at-point 'symbol))
1686 (let ((point (org-babel-find-named-block name)))
1688 ;; taken from `org-open-at-point'
1689 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1690 (message "source-code block `%s' not found in this buffer" name))))
1692 (defun org-babel-find-named-block (name)
1693 "Find a named source-code block.
1694 Return the location of the source block identified by source
1695 NAME, or nil if no such block exists. Set match data according to
1696 org-babel-named-src-block-regexp."
1698 (let ((case-fold-search t)
1699 (regexp (org-babel-named-src-block-regexp-for-name name)))
1700 (goto-char (point-min))
1701 (when (or (re-search-forward regexp nil t)
1702 (re-search-backward regexp nil t))
1703 (match-beginning 0)))))
1705 (defun org-babel-src-block-names (&optional file)
1706 "Returns the names of source blocks in FILE or the current buffer."
1708 (when file (find-file file)) (goto-char (point-min))
1709 (let ((case-fold-search t) names)
1710 (while (re-search-forward org-babel-src-name-w-name-regexp nil t)
1711 (setq names (cons (match-string 3) names)))
1715 (defun org-babel-goto-named-result (name)
1716 "Go to a named result."
1718 (let ((completion-ignore-case t))
1719 (list (org-icompleting-read "source-block name: "
1720 (org-babel-result-names) nil t))))
1721 (let ((point (org-babel-find-named-result name)))
1723 ;; taken from `org-open-at-point'
1724 (progn (goto-char point) (org-show-context))
1725 (message "result `%s' not found in this buffer" name))))
1727 (defun org-babel-find-named-result (name &optional point)
1728 "Find a named result.
1729 Return the location of the result named NAME in the current
1730 buffer or nil if no such result exists."
1732 (let ((case-fold-search t))
1733 (goto-char (or point (point-min)))
1734 (catch 'is-a-code-block
1735 (when (re-search-forward
1736 (concat org-babel-result-regexp
1737 "[ \t]" (regexp-quote name) "[ \t]*[\n\f\v\r]")
1739 (when (and (string= "name" (downcase (match-string 1)))
1740 (or (beginning-of-line 1)
1741 (looking-at org-babel-src-block-regexp)
1742 (looking-at org-babel-multi-line-header-regexp)
1743 (looking-at org-babel-lob-one-liner-regexp)))
1744 (throw 'is-a-code-block (org-babel-find-named-result name (point))))
1745 (beginning-of-line 0) (point))))))
1747 (defun org-babel-result-names (&optional file)
1748 "Returns the names of results in FILE or the current buffer."
1750 (when file (find-file file)) (goto-char (point-min))
1751 (let ((case-fold-search t) names)
1752 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1753 (setq names (cons (match-string 4) names)))
1757 (defun org-babel-next-src-block (&optional arg)
1758 "Jump to the next source block.
1759 With optional prefix argument ARG, jump forward ARG many source blocks."
1761 (org-next-block arg nil org-babel-src-block-regexp))
1764 (defun org-babel-previous-src-block (&optional arg)
1765 "Jump to the previous source block.
1766 With optional prefix argument ARG, jump backward ARG many source blocks."
1768 (org-previous-block arg org-babel-src-block-regexp))
1770 (defvar org-babel-load-languages)
1773 (defun org-babel-mark-block ()
1774 "Mark current src block."
1776 (let ((head (org-babel-where-is-src-block-head)))
1780 (looking-at org-babel-src-block-regexp))
1781 (push-mark (match-end 5) nil t)
1782 (goto-char (match-beginning 5)))))
1784 (defun org-babel-demarcate-block (&optional arg)
1785 "Wrap or split the code in the region or on the point.
1786 When called from inside of a code block the current block is
1787 split. When called from outside of a code block a new code block
1788 is created. In both cases if the region is demarcated and if the
1789 region is not active then the point is demarcated."
1791 (let ((info (org-babel-get-src-block-info 'light))
1792 (headers (progn (org-babel-where-is-src-block-head)
1794 (stars (concat (make-string (or (org-current-level) 1) ?*) " ")))
1800 (let ((lang (nth 0 info))
1801 (indent (make-string (nth 5 info) ? )))
1802 (when (string-match "^[[:space:]]*$"
1803 (buffer-substring (point-at-bol)
1805 (delete-region (point-at-bol) (point-at-eol)))
1807 (if (looking-at "^") "" "\n")
1808 indent "#+end_src\n"
1809 (if arg stars indent) "\n"
1810 indent "#+begin_src " lang
1811 (if (> (length headers) 1)
1812 (concat " " headers) headers)
1813 (if (looking-at "[\n\r]")
1815 (concat "\n" (make-string (current-column) ? )))))))
1816 (move-end-of-line 2))
1817 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1818 (let ((start (point))
1819 (lang (org-icompleting-read
1821 (mapcar #'symbol-name
1823 (append (mapcar #'car org-babel-load-languages)
1824 (mapcar (lambda (el) (intern (car el)))
1825 org-src-lang-modes))))))
1826 (body (delete-and-extract-region
1827 (if (org-region-active-p) (mark) (point)) (point))))
1828 (insert (concat (if (looking-at "^") "" "\n")
1829 (if arg (concat stars "\n") "")
1830 "#+begin_src " lang "\n"
1832 (if (or (= (length body) 0)
1833 (string-match "[\r\n]$" body)) "" "\n")
1835 (goto-char start) (move-end-of-line 1)))))
1837 (defvar org-babel-lob-one-liner-regexp)
1838 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
1839 "Find where the current source block results begin.
1840 Return the point at the beginning of the result of the current
1841 source block. Specifically at the beginning of the results line.
1842 If no result exists for this block then create a results line
1843 following the source block."
1845 (let* ((case-fold-search t)
1846 (on-lob-line (save-excursion
1847 (beginning-of-line 1)
1848 (looking-at org-babel-lob-one-liner-regexp)))
1849 (inlinep (when (org-babel-get-inline-src-block-matches)
1851 (name (nth 4 (or info (org-babel-get-src-block-info 'light))))
1852 (head (unless on-lob-line (org-babel-where-is-src-block-head)))
1854 (when head (goto-char head))
1855 (org-with-wide-buffer
1857 found ;; was there a result (before we potentially insert one)
1862 ;; - return t if it is found, else return nil
1863 ;; - if it does not need to be rebuilt, then don't set end
1864 ;; - if it does need to be rebuilt then do set end
1865 name (setq beg (org-babel-find-named-result name))
1867 (when (and hash (not (string= hash (match-string 5))))
1868 (goto-char beg) (setq end beg) ;; beginning of result
1870 (delete-region end (org-babel-result-end)) nil)))
1873 ;; - return t if it is found, else return nil
1874 ;; - if it is found, and the hash doesn't match, delete and set end
1875 (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
1876 (progn (end-of-line 1)
1877 (if (eobp) (insert "\n") (forward-char 1))
1881 (progn ;; unnamed results line already exists
1883 (while (re-search-forward "[^ \f\t\n\r\v]" nil t)
1884 (beginning-of-line 1)
1886 ((looking-at (concat org-babel-result-regexp "\n"))
1887 (throw 'non-comment t))
1888 ((looking-at "^[ \t]*#") (end-of-line 1))
1889 (t (throw 'non-comment nil))))))
1890 (let ((this-hash (match-string 5)))
1892 ;; must remove and rebuild if hash!=old-hash
1893 (if (and hash (not (string= hash this-hash)))
1897 end (org-babel-result-end)))
1898 (setq end nil)))))))))))
1899 (if (not (and insert end)) found
1902 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1904 (when (wholenump indent) (make-string indent ? ))
1905 "#+" org-babel-results-keyword
1907 (if org-babel-hash-show-time
1909 "["(format-time-string "<%Y-%m-%d %H:%M:%S>")" "hash"]")
1910 (concat "["hash"]")))
1912 (when name (concat " " name)) "\n"))
1913 (unless beg (insert "\n") (backward-char))
1914 (beginning-of-line 0)
1915 (if hash (org-babel-hide-hash))
1918 (defvar org-block-regexp)
1919 (defun org-babel-read-result ()
1920 "Read the result at `point' into emacs-lisp."
1921 (let ((case-fold-search t) result-string)
1923 ((org-at-table-p) (org-babel-read-table))
1924 ((org-at-item-p) (org-babel-read-list))
1925 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
1926 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
1927 ((or (looking-at "^[ \t]*: ") (looking-at "^[ \t]*:$"))
1930 (mapconcat (lambda (line)
1931 (or (and (> (length line) 1)
1932 (string-match "^[ \t]*: ?\\(.+\\)" line)
1933 (match-string 1 line))
1937 (point) (org-babel-result-end)) "[\r\n]+")
1939 (or (org-babel-number-p result-string) result-string))
1940 ((looking-at org-babel-result-regexp)
1941 (save-excursion (forward-line 1) (org-babel-read-result))))))
1943 (defun org-babel-read-table ()
1944 "Read the table at `point' into emacs-lisp."
1945 (mapcar (lambda (row)
1946 (if (and (symbolp row) (equal row 'hline)) row
1947 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
1948 (org-table-to-lisp)))
1950 (defun org-babel-read-list ()
1951 "Read the list at `point' into emacs-lisp."
1952 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
1953 (mapcar #'cadr (cdr (org-list-parse-list)))))
1955 (defvar org-link-types-re)
1956 (defun org-babel-read-link ()
1957 "Read the link at `point' into emacs-lisp.
1958 If the path of the link is a file path it is expanded using
1959 `expand-file-name'."
1960 (let* ((case-fold-search t)
1961 (raw (and (looking-at org-bracket-link-regexp)
1962 (org-no-properties (match-string 1))))
1963 (type (and (string-match org-link-types-re raw)
1964 (match-string 1 raw))))
1966 ((not type) (expand-file-name raw))
1967 ((string= type "file")
1968 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
1969 (expand-file-name (match-string 2 raw))))
1972 (defun org-babel-format-result (result &optional sep)
1973 "Format RESULT for writing to file."
1974 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
1978 result (list :sep (or sep "\t") :fmt echo-res))
1980 (funcall echo-res result))))
1982 (defun org-babel-insert-result
1983 (result &optional result-params info hash indent lang)
1984 "Insert RESULT into the current buffer.
1985 By default RESULT is inserted after the end of the
1986 current source block. With optional argument RESULT-PARAMS
1987 controls insertion of results in the org-mode file.
1988 RESULT-PARAMS can take the following values:
1990 replace - (default option) insert results after the source block
1991 replacing any previously inserted results
1993 silent -- no results are inserted into the Org-mode buffer but
1994 the results are echoed to the minibuffer and are
1995 ingested by Emacs (a potentially time consuming
1998 file ---- the results are interpreted as a file path, and are
1999 inserted into the buffer using the Org-mode file syntax
2001 list ---- the results are interpreted as an Org-mode list.
2003 raw ----- results are added directly to the Org-mode file. This
2004 is a good option if you code block will output org-mode
2007 drawer -- results are added directly to the Org-mode file as with
2008 \"raw\", but are wrapped in a RESULTS drawer, allowing
2009 them to later be replaced or removed automatically.
2011 org ----- results are added inside of a \"#+BEGIN_SRC org\" block.
2012 They are not comma-escaped when inserted, but Org syntax
2013 here will be discarded when exporting the file.
2015 html ---- results are added inside of a #+BEGIN_HTML block. This
2016 is a good option if you code block will output html
2019 latex --- results are added inside of a #+BEGIN_LATEX block.
2020 This is a good option if you code block will output
2021 latex formatted text.
2023 code ---- the results are extracted in the syntax of the source
2024 code of the language being evaluated and are added
2025 inside of a #+BEGIN_SRC block with the source-code
2026 language set appropriately. Note this relies on the
2027 optional LANG argument."
2028 (if (stringp result)
2030 (setq result (org-no-properties result))
2031 (when (member "file" result-params)
2032 (setq result (org-babel-result-to-file
2033 result (when (assoc :file-desc (nth 2 info))
2034 (or (cdr (assoc :file-desc (nth 2 info)))
2036 (unless (listp result) (setq result (format "%S" result))))
2037 (if (and result-params (member "silent" result-params))
2039 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2044 (when (or (org-babel-get-inline-src-block-matches)
2045 (org-babel-get-lob-one-liner-matches))
2046 (goto-char (match-end 0))
2047 (insert (if (listp result) "\n" " "))
2049 (existing-result (unless inlinep
2050 (org-babel-where-is-src-block-result
2051 t info hash indent)))
2053 (cdr (assoc :results_switches (nth 2 info))))
2054 (visible-beg (point-min-marker))
2055 (visible-end (point-max-marker))
2056 ;; When results exist outside of the current visible
2057 ;; region of the buffer, be sure to widen buffer to
2059 (outside-scope-p (and existing-result
2060 (or (> visible-beg existing-result)
2061 (<= visible-end existing-result))))
2063 (when (and (stringp result) ; ensure results end in a newline
2065 (> (length result) 0)
2066 (not (or (string-equal (substring result -1) "\n")
2067 (string-equal (substring result -1) "\r"))))
2068 (setq result (concat result "\n")))
2071 (when outside-scope-p (widen))
2072 (if (not existing-result)
2073 (setq beg (or inlinep (point)))
2074 (goto-char existing-result)
2076 (re-search-forward "#" nil t)
2077 (setq indent (- (current-column) 1)))
2081 ((member "replace" result-params)
2082 (delete-region (point) (org-babel-result-end)))
2083 ((member "append" result-params)
2084 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2085 ((member "prepend" result-params)))) ; already there
2086 (setq results-switches
2087 (if results-switches (concat " " results-switches) ""))
2088 (let ((wrap (lambda (start finish &optional no-escape)
2089 (goto-char end) (insert (concat finish "\n"))
2090 (goto-char beg) (insert (concat start "\n"))
2092 (org-escape-code-in-region (min (point) end) end))
2093 (goto-char end) (goto-char (point-at-eol))
2094 (setq end (point-marker))))
2095 (proper-list-p (lambda (it) (and (listp it) (null (cdr (last it)))))))
2096 ;; insert results based on type
2098 ;; do nothing for an empty result
2100 ;; insert a list if preferred
2101 ((member "list" result-params)
2104 (org-list-to-generic
2107 (lambda (el) (list nil (if (stringp el) el (format "%S" el))))
2108 (if (listp result) result (split-string result "\n" t))))
2109 '(:splicep nil :istart "- " :iend "\n")))
2111 ;; assume the result is a table if it's not a string
2112 ((funcall proper-list-p result)
2114 (insert (concat (orgtbl-to-orgtbl
2116 (lambda (el) (or (listp el) (eq el 'hline)))
2118 result (list result))
2119 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
2120 (goto-char beg) (when (org-at-table-p) (org-table-align)))
2121 ((and (listp result) (not (funcall proper-list-p result)))
2122 (insert (format "%s\n" result)))
2123 ((member "file" result-params)
2124 (when inlinep (goto-char inlinep))
2126 (t (goto-char beg) (insert result)))
2127 (when (funcall proper-list-p result) (goto-char (org-table-end)))
2128 (setq end (point-marker))
2129 ;; possibly wrap result
2131 ((assoc :wrap (nth 2 info))
2132 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2133 (funcall wrap (concat "#+BEGIN_" name)
2134 (concat "#+END_" (car (org-split-string name))))))
2135 ((member "html" result-params)
2136 (funcall wrap "#+BEGIN_HTML" "#+END_HTML"))
2137 ((member "latex" result-params)
2138 (funcall wrap "#+BEGIN_LaTeX" "#+END_LaTeX"))
2139 ((member "org" result-params)
2140 (goto-char beg) (if (org-at-table-p) (org-cycle))
2141 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC"))
2142 ((member "code" result-params)
2143 (funcall wrap (format "#+BEGIN_SRC %s%s" (or lang "none") results-switches)
2145 ((member "raw" result-params)
2146 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2147 ((or (member "drawer" result-params)
2148 ;; Stay backward compatible with <7.9.2
2149 (member "wrap" result-params))
2150 (goto-char beg) (if (org-at-table-p) (org-cycle))
2151 (funcall wrap ":RESULTS:" ":END:" 'no-escape))
2152 ((and (not (funcall proper-list-p result))
2153 (not (member "file" result-params)))
2154 (org-babel-examplize-region beg end results-switches)
2155 (setq end (point)))))
2156 ;; possibly indent the results to match the #+results line
2157 (when (and (not inlinep) (numberp indent) indent (> indent 0)
2158 ;; in this case `table-align' does the work for us
2159 (not (and (listp result)
2160 (member "append" result-params))))
2161 (indent-rigidly beg end indent))
2163 (if (member "value" result-params)
2164 (message "Code block returned no value.")
2165 (message "Code block produced no output."))
2166 (message "Code block evaluation complete.")))
2167 (when outside-scope-p (narrow-to-region visible-beg visible-end))
2168 (set-marker visible-beg nil)
2169 (set-marker visible-end nil))))))
2171 (defun org-babel-remove-result (&optional info)
2172 "Remove the result of the current source block."
2174 (let ((location (org-babel-where-is-src-block-result nil info)) start)
2176 (setq start (- location 1))
2178 (goto-char location) (forward-line 1)
2179 (delete-region start (org-babel-result-end))))))
2181 (defun org-babel-result-end ()
2182 "Return the point at the end of the current set of results."
2185 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2186 ((org-at-item-p) (let* ((struct (org-list-struct))
2187 (prvs (org-list-prevs-alist struct)))
2188 (org-list-get-list-end (point-at-bol) struct prvs)))
2189 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2190 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2191 (forward-char 1) (point)))
2193 (let ((case-fold-search t))
2194 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2195 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2198 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2202 (defun org-babel-result-to-file (result &optional description)
2203 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2204 If the `default-directory' is different from the containing
2205 file's directory then expand relative links."
2206 (when (stringp result)
2207 (format "[[file:%s]%s]"
2208 (if (and default-directory
2210 (not (string= (expand-file-name default-directory)
2212 (file-name-directory buffer-file-name)))))
2213 (expand-file-name result default-directory)
2215 (if description (concat "[" description "]") ""))))
2217 (defvar org-babel-capitalize-examplize-region-markers nil
2218 "Make true to capitalize begin/end example markers inserted by code blocks.")
2220 (defun org-babel-examplize-region (beg end &optional results-switches)
2221 "Comment out region using the inline `==' or `: ' org example quote."
2223 (let ((chars-between (lambda (b e)
2224 (not (string-match "^[\\s]*$" (buffer-substring b e)))))
2225 (maybe-cap (lambda (str) (if org-babel-capitalize-examplize-region-markers
2226 (upcase str) str))))
2227 (if (or (funcall chars-between (save-excursion (goto-char beg) (point-at-bol)) beg)
2228 (funcall chars-between end (save-excursion (goto-char end) (point-at-eol))))
2231 (insert (format org-babel-inline-result-wrap
2232 (prog1 (buffer-substring beg end)
2233 (delete-region beg end)))))
2234 (let ((size (count-lines beg end)))
2236 (cond ((= size 0)) ; do nothing for an empty result
2237 ((< size org-babel-min-lines-for-block-output)
2240 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2243 (insert (if results-switches
2245 (funcall maybe-cap "#+begin_example")
2247 (funcall maybe-cap "#+begin_example\n")))
2248 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2249 (insert (funcall maybe-cap "#+end_example\n")))))))))
2251 (defun org-babel-update-block-body (new-body)
2252 "Update the body of the current code block to NEW-BODY."
2253 (if (not (org-babel-where-is-src-block-head))
2254 (error "Not in a source block")
2256 (replace-match (concat (org-babel-trim new-body) "\n") nil t nil 5))
2257 (indent-rigidly (match-beginning 5) (match-end 5) 2)))
2259 (defun org-babel-merge-params (&rest plists)
2260 "Combine all parameter association lists in PLISTS.
2261 Later elements of PLISTS override the values of previous elements.
2262 This takes into account some special considerations for certain
2263 parameters when merging lists."
2264 (let* ((results-exclusive-groups
2265 (mapcar (lambda (group) (mapcar #'symbol-name group))
2266 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2267 (exports-exclusive-groups
2268 (mapcar (lambda (group) (mapcar #'symbol-name group))
2269 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2271 (e-merge (lambda (exclusive-groups &rest result-params)
2272 ;; maintain exclusivity of mutually exclusive parameters
2274 (mapc (lambda (new-params)
2275 (mapc (lambda (new-param)
2276 (mapc (lambda (exclusive-group)
2277 (when (member new-param exclusive-group)
2278 (mapcar (lambda (excluded-param)
2285 (setq output (org-uniquify
2286 (cons new-param output))))
2290 params results exports tangle noweb cache vars shebang comments padline
2299 (let ((name (if (listp (cdr pair))
2301 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
2303 (intern (match-string 1 (cdr pair)))))))
2307 (if (member name (mapcar #'car vars))
2309 (push name clearnames)
2313 (unless (equal (car p) name) p))
2316 (list (cons name pair))))
2317 ;; if no name is given and we already have named variables
2318 ;; then assign to named variables in order
2319 (if (and vars (nth variable-index vars))
2320 (let ((name (car (nth variable-index vars))))
2321 (push name clearnames) ; clear out colnames
2324 (prog1 (setf (cddr (nth variable-index vars))
2325 (concat (symbol-name name) "=" (cdr pair)))
2326 (incf variable-index)))
2327 (error "Variable \"%s\" must be assigned a default value"
2330 (setq results (funcall e-merge results-exclusive-groups
2333 (let ((r (cdr pair)))
2334 (if (stringp r) r (eval r)))))))
2337 (setq results (funcall e-merge results-exclusive-groups
2339 (unless (or (member "both" exports)
2340 (member "none" exports)
2341 (member "code" exports))
2342 (setq exports (funcall e-merge exports-exclusive-groups
2343 exports '("results"))))
2344 (setq params (cons pair (assq-delete-all (car pair) params)))))
2346 (setq exports (funcall e-merge exports-exclusive-groups
2347 exports (split-string (cdr pair)))))
2348 (:tangle ;; take the latest -- always overwrite
2349 (setq tangle (or (list (cdr pair)) tangle)))
2351 (setq noweb (funcall e-merge
2352 '(("yes" "no" "tangle" "no-export"
2353 "strip-export" "eval"))
2355 (split-string (or (cdr pair) "")))))
2357 (setq cache (funcall e-merge '(("yes" "no")) cache
2358 (split-string (or (cdr pair) "")))))
2360 (setq padline (funcall e-merge '(("yes" "no")) padline
2361 (split-string (or (cdr pair) "")))))
2362 (:shebang ;; take the latest -- always overwrite
2363 (setq shebang (or (list (cdr pair)) shebang)))
2365 (setq comments (funcall e-merge '(("yes" "no")) comments
2366 (split-string (or (cdr pair) "")))))
2367 (t ;; replace: this covers e.g. :session
2368 (setq params (cons pair (assq-delete-all (car pair) params))))))
2371 (setq vars (reverse vars))
2372 (while vars (setq params (cons (cons :var (cddr (pop vars))) params)))
2373 ;; clear out col-names and row-names for replaced variables
2378 (when (assoc param params)
2379 (setf (cdr (assoc param params))
2380 (org-remove-if (lambda (pair) (equal (car pair) name))
2381 (cdr (assoc param params))))
2382 (setf params (org-remove-if (lambda (pair) (and (equal (car pair) param)
2385 (list :colname-names :rowname-names)))
2389 (let ((key (intern (concat ":" (symbol-name hd))))
2391 (setf params (cons (cons key (mapconcat 'identity val " ")) params))))
2392 '(results exports tangle noweb padline cache shebang comments))
2395 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2396 "Set to true to use regular expressions to expand noweb references.
2397 This results in much faster noweb reference expansion but does
2398 not properly allow code blocks to inherit the \":noweb-ref\"
2399 header argument from buffer or subtree wide properties.")
2401 (defun org-babel-noweb-p (params context)
2402 "Check if PARAMS require expansion in CONTEXT.
2403 CONTEXT may be one of :tangle, :export or :eval."
2405 (intersect (lambda (as bs)
2407 (if (member (car as) bs)
2409 (funcall intersect (cdr as) bs))))))
2410 (funcall intersect (case context
2411 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2412 (:eval '("yes" "no-export" "strip-export" "eval"))
2414 (split-string (or (cdr (assoc :noweb params)) "")))))
2416 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2417 "Expand Noweb references in the body of the current source code block.
2419 For example the following reference would be replaced with the
2420 body of the source-code block named `example-block'.
2424 Note that any text preceding the <<foo>> construct on a line will
2425 be interposed between the lines of the replacement text. So for
2426 example if <<foo>> is placed behind a comment, then the entire
2427 replacement text will also be commented.
2429 This function must be called from inside of the buffer containing
2430 the source-code block which holds BODY.
2432 In addition the following syntax can be used to insert the
2433 results of evaluating the source-code block named `example-block'.
2437 Any optional arguments can be passed to example-block by placing
2438 the arguments inside the parenthesis following the convention
2439 defined by `org-babel-lob'. For example
2441 <<example-block(a=9)>>
2443 would set the value of argument \"a\" equal to \"9\". Note that
2444 these arguments are not evaluated in the current source-code
2445 block but are passed literally to the \"example-block\"."
2446 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2447 (info (or info (org-babel-get-src-block-info 'light)))
2450 (ob-nww-start org-babel-noweb-wrap-start)
2451 (ob-nww-end org-babel-noweb-wrap-end)
2452 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2453 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2454 ":noweb-ref[ \t]+" "\\)"))
2456 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2457 (c-wrap (lambda (text)
2459 (funcall (intern (concat lang "-mode")))
2460 (comment-region (point) (progn (insert text) (point)))
2461 (org-babel-trim (buffer-string)))))
2462 index source-name evaluate prefix)
2464 (org-set-local 'org-babel-noweb-wrap-start ob-nww-start)
2465 (org-set-local 'org-babel-noweb-wrap-end ob-nww-end)
2466 (insert body) (goto-char (point-min))
2467 (setq index (point))
2468 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2469 (save-match-data (setf source-name (match-string 1)))
2470 (save-match-data (setq evaluate (string-match "(.*)" source-name)))
2473 (buffer-substring (match-beginning 0)
2475 (beginning-of-line 1) (point)))))
2476 ;; add interval to new-body (removing noweb reference)
2477 (goto-char (match-beginning 0))
2478 (funcall nb-add (buffer-substring index (point)))
2479 (goto-char (match-end 0))
2480 (setq index (point))
2483 (with-current-buffer parent-buffer
2486 (mapconcat ;; Interpose PREFIX between every line.
2490 (let ((raw (org-babel-ref-resolve source-name)))
2491 (if (stringp raw) raw (format "%S" raw)))
2493 ;; Retrieve from the library of babel.
2494 (nth 2 (assoc (intern source-name)
2495 org-babel-library-of-babel))
2496 ;; Return the contents of headlines literally.
2498 (when (org-babel-ref-goto-headline-id source-name)
2499 (org-babel-ref-headline-body)))
2500 ;; Find the expansion of reference in this buffer.
2501 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2504 (goto-char (point-min))
2505 (if org-babel-use-quick-and-dirty-noweb-expansion
2506 (while (re-search-forward rx nil t)
2507 (let* ((i (org-babel-get-src-block-info 'light))
2508 (body (org-babel-expand-noweb-references i))
2509 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2512 (let ((cs (org-babel-tangle-comment-links i)))
2513 (concat (funcall c-wrap (car cs)) "\n"
2515 (funcall c-wrap (cadr cs))))
2517 (setq expansion (cons sep (cons full expansion)))))
2518 (org-babel-map-src-blocks nil
2519 (let ((i (org-babel-get-src-block-info 'light)))
2520 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2523 (let* ((body (org-babel-expand-noweb-references i))
2524 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2527 (let ((cs (org-babel-tangle-comment-links i)))
2528 (concat (funcall c-wrap (car cs)) "\n"
2530 (funcall c-wrap (cadr cs))))
2533 (cons sep (cons full expansion)))))))))
2535 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2536 ;; Possibly raise an error if named block doesn't exist.
2537 (if (member lang org-babel-noweb-error-langs)
2539 (org-babel-noweb-wrap source-name)
2540 "could not be resolved (see "
2541 "`org-babel-noweb-error-langs')"))
2543 "[\n\r]") (concat "\n" prefix))))))
2544 (funcall nb-add (buffer-substring index (point-max))))
2547 (defun org-babel-script-escape (str &optional force)
2548 "Safely convert tables into elisp lists."
2553 (or (and (string-equal "[" (substring str 0 1))
2554 (string-equal "]" (substring str -1)))
2555 (and (string-equal "{" (substring str 0 1))
2556 (string-equal "}" (substring str -1)))
2557 (and (string-equal "(" (substring str 0 1))
2558 (string-equal ")" (substring str -1))))))
2562 (let (in-single in-double out)
2568 (91 (if (or in-double in-single) ; [
2571 (93 (if (or in-double in-single) ; ]
2574 (123 (if (or in-double in-single) ; {
2577 (125 (if (or in-double in-single) ; }
2580 (44 (if (or in-double in-single) ; ,
2581 (cons 44 out) (cons 32 out)))
2582 (39 (if in-double ; '
2584 (setq in-single (not in-single)) (cons 34 out)))
2585 (34 (if in-single ; "
2586 (append (list 34 32) out)
2587 (setq in-double (not in-double)) (cons 34 out)))
2588 (t (cons ch out)))))
2589 (string-to-list str))
2590 (apply #'string (reverse out)))))
2592 (condition-case nil (org-babel-read escaped) (error escaped))))
2594 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2595 "Convert the string value of CELL to a number if appropriate.
2596 Otherwise if cell looks like lisp (meaning it starts with a
2597 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read it as lisp,
2598 otherwise return it unmodified as a string. Optional argument
2599 NO-LISP-EVAL inhibits lisp evaluation for situations in which is
2600 it not appropriate."
2601 (if (and (stringp cell) (not (equal cell "")))
2602 (or (org-babel-number-p cell)
2603 (if (and (not inhibit-lisp-eval)
2604 (or (member (substring cell 0 1) '("(" "'" "`" "["))
2605 (string= cell "*this*")))
2607 (if (string= (substring cell 0 1) "\"")
2609 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2612 (defun org-babel-number-p (string)
2613 "If STRING represents a number return its value."
2614 (if (and (string-match "[0-9]+" string)
2615 (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2616 (= (length (substring string (match-beginning 0)
2619 (string-to-number string)))
2621 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2622 "Read the results located at FILE-NAME into an elisp table.
2623 If the table is trivial, then return it as a scalar."
2625 (save-window-excursion
2629 (org-table-import file-name separator)
2630 (delete-file file-name)
2631 (setq result (mapcar (lambda (row)
2632 (mapcar #'org-babel-string-read row))
2633 (org-table-to-lisp))))
2634 (error (message "Error reading results: %s" err) nil)))
2635 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2636 (if (consp (car result))
2637 (if (null (cdr (car result)))
2643 (defun org-babel-string-read (cell)
2644 "Strip nested \"s from around strings."
2645 (org-babel-read (or (and (stringp cell)
2646 (string-match "\\\"\\(.+\\)\\\"" cell)
2647 (match-string 1 cell))
2650 (defun org-babel-chomp (string &optional regexp)
2651 "Strip trailing spaces and carriage returns from STRING.
2652 Default regexp used is \"[ \f\t\n\r\v]\" but can be
2653 overwritten by specifying a regexp as a second argument."
2654 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2655 (while (and (> (length string) 0)
2656 (string-match regexp (substring string -1)))
2657 (setq string (substring string 0 -1)))
2660 (defun org-babel-trim (string &optional regexp)
2661 "Strip leading and trailing spaces and carriage returns from STRING.
2662 Like `org-babel-chomp' only it runs on both the front and back
2664 (org-babel-chomp (org-reverse-string
2665 (org-babel-chomp (org-reverse-string string) regexp))
2668 (defun org-babel-tramp-handle-call-process-region
2669 (start end program &optional delete buffer display &rest args)
2670 "Use Tramp to handle `call-process-region'.
2671 Fixes a bug in `tramp-handle-call-process-region'."
2672 (if (and (featurep 'tramp) (file-remote-p default-directory))
2673 (let ((tmpfile (tramp-compat-make-temp-file "")))
2674 (write-region start end tmpfile)
2675 (when delete (delete-region start end))
2677 ;; (apply 'call-process program tmpfile buffer display args)
2679 (apply 'process-file program tmpfile buffer display args)
2680 (delete-file tmpfile)))
2681 ;; org-babel-call-process-region-original is the original emacs
2682 ;; definition. It is in scope from the let binding in
2683 ;; org-babel-execute-src-block
2684 (apply org-babel-call-process-region-original
2685 start end program delete buffer display args)))
2687 (defun org-babel-local-file-name (file)
2688 "Return the local name component of FILE."
2689 (if (file-remote-p file)
2691 (with-parsed-tramp-file-name file nil
2695 (defun org-babel-process-file-name (name &optional no-quote-p)
2696 "Prepare NAME to be used in an external process.
2697 If NAME specifies a remote location, the remote portion of the
2698 name is removed, since in that case the process will be executing
2699 remotely. The file name is then processed by `expand-file-name'.
2700 Unless second argument NO-QUOTE-P is non-nil, the file name is
2701 additionally processed by `shell-quote-argument'"
2702 (let ((f (expand-file-name (org-babel-local-file-name name))))
2703 (if no-quote-p f (shell-quote-argument f))))
2705 (defvar org-babel-temporary-directory)
2706 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2707 (defvar org-babel-temporary-directory
2708 (or (and (boundp 'org-babel-temporary-directory)
2709 (file-exists-p org-babel-temporary-directory)
2710 org-babel-temporary-directory)
2711 (make-temp-file "babel-" t))
2712 "Directory to hold temporary files created to execute code blocks.
2713 Used by `org-babel-temp-file'. This directory will be removed on
2716 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2717 "Call the code to parse raw string results according to RESULT-PARAMS."
2719 (debug (form form &rest form)))
2720 (org-with-gensyms (params)
2721 `(let ((,params ,result-params))
2722 (unless (member "none" ,params)
2723 (if (or (member "scalar" ,params)
2724 (member "verbatim" ,params)
2725 (member "html" ,params)
2726 (member "code" ,params)
2727 (member "pp" ,params)
2728 (and (or (member "output" ,params)
2729 (member "raw" ,params)
2730 (member "org" ,params)
2731 (member "drawer" ,params))
2732 (not (member "table" ,params))))
2735 (def-edebug-spec org-babel-result-cond (form form body))
2737 (defun org-babel-temp-file (prefix &optional suffix)
2738 "Create a temporary file in the `org-babel-temporary-directory'.
2739 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2740 value of `temporary-file-directory' temporarily set to the value
2741 of `org-babel-temporary-directory'."
2742 (if (file-remote-p default-directory)
2744 (concat (file-remote-p default-directory)
2745 (expand-file-name prefix temporary-file-directory))))
2746 (make-temp-file prefix nil suffix))
2747 (let ((temporary-file-directory
2748 (or (and (boundp 'org-babel-temporary-directory)
2749 (file-exists-p org-babel-temporary-directory)
2750 org-babel-temporary-directory)
2751 temporary-file-directory)))
2752 (make-temp-file prefix nil suffix))))
2754 (defun org-babel-remove-temporary-directory ()
2755 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2756 (when (and (boundp 'org-babel-temporary-directory)
2757 (file-exists-p org-babel-temporary-directory))
2758 ;; taken from `delete-directory' in files.el
2761 (mapc (lambda (file)
2762 ;; This test is equivalent to
2763 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2764 ;; but more efficient
2765 (if (eq t (car (file-attributes file)))
2766 (delete-directory file)
2767 (delete-file file)))
2768 ;; We do not want to delete "." and "..".
2769 (directory-files org-babel-temporary-directory 'full
2770 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2771 (delete-directory org-babel-temporary-directory))
2773 (message "Failed to remove temporary Org-babel directory %s"
2774 (if (boundp 'org-babel-temporary-directory)
2775 org-babel-temporary-directory
2776 "[directory not defined]"))))))
2778 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2783 ;; generated-autoload-file: "org-loaddefs.el"
2786 ;;; ob-core.el ends here