org-footnote: Silence byte-compiler
[org-mode/org-tableheadings.git] / lisp / ob-core.el
blob2f2a6f206bc0809fffcb12ffce5fd26d261775c1
1 ;;; ob-core.el --- Working with Code Blocks -*- lexical-binding: t; -*-
3 ;; Copyright (C) 2009-2016 Free Software Foundation, Inc.
5 ;; Authors: Eric Schulte
6 ;; Dan Davison
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/>.
25 ;;; Code:
26 (require 'cl-lib)
27 (require 'ob-eval)
28 (require 'org-macs)
29 (require 'org-compat)
31 (defconst org-babel-exeext
32 (if (memq system-type '(windows-nt cygwin))
33 ".exe"
34 nil))
36 (defvar org-babel-library-of-babel)
37 (defvar org-edit-src-content-indentation)
38 (defvar org-src-lang-modes)
39 (defvar org-src-preserve-indentation)
41 (declare-function org-at-item-p "org-list" ())
42 (declare-function org-at-table-p "org" (&optional table-type))
43 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
44 (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
45 (declare-function org-babel-ref-headline-body "ob-ref" ())
46 (declare-function org-babel-ref-parse "ob-ref" (assignment))
47 (declare-function org-babel-ref-resolve "ob-ref" (ref))
48 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
49 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
50 (declare-function org-completing-read "org" (&rest args))
51 (declare-function org-current-level "org" ())
52 (declare-function org-cycle "org" (&optional arg))
53 (declare-function org-do-remove-indentation "org" (&optional n))
54 (declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name))
55 (declare-function org-edit-src-exit "org-src" ())
56 (declare-function org-element-at-point "org-element" ())
57 (declare-function org-element-context "org-element" (&optional element))
58 (declare-function org-element-normalize-string "org-element" (s))
59 (declare-function org-element-property "org-element" (property element))
60 (declare-function org-element-type "org-element" (element))
61 (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
62 (declare-function org-escape-code-in-region "org-src" (beg end))
63 (declare-function org-get-indentation "org" (&optional line))
64 (declare-function org-get-indentation "org" (&optional line))
65 (declare-function org-in-regexp "org" (regexp &optional nlines visually))
66 (declare-function org-indent-line "org" ())
67 (declare-function org-list-get-list-end "org-list" (item struct prevs))
68 (declare-function org-list-prevs-alist "org-list" (struct))
69 (declare-function org-list-struct "org-list" ())
70 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
71 (declare-function org-list-to-lisp "org-list" (&optional delete))
72 (declare-function org-macro-escape-arguments "org-macro" (&rest args))
73 (declare-function org-make-options-regexp "org" (kwds &optional extra))
74 (declare-function org-mark-ring-push "org" (&optional pos buffer))
75 (declare-function org-narrow-to-subtree "org" ())
76 (declare-function org-next-block "org" (arg &optional backward block-regexp))
77 (declare-function org-number-sequence "org-compat" (from &optional to inc))
78 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
79 (declare-function org-outline-overlay-data "org" (&optional use-markers))
80 (declare-function org-previous-block "org" (arg &optional block-regexp))
81 (declare-function org-remove-indentation "org" (code &optional n))
82 (declare-function org-reverse-string "org" (string))
83 (declare-function org-set-outline-overlay-data "org" (data))
84 (declare-function org-show-context "org" (&optional key))
85 (declare-function org-split-string "org" (string &optional separators))
86 (declare-function org-src-coderef-format "org-src" (element))
87 (declare-function org-src-coderef-regexp "org-src" (fmt &optional label))
88 (declare-function org-table-align "org-table" ())
89 (declare-function org-table-end "org-table" (&optional table-type))
90 (declare-function org-table-import "org-table" (file arg))
91 (declare-function org-table-to-lisp "org-table" (&optional txt))
92 (declare-function org-trim "org" (s &optional keep-lead))
93 (declare-function org-unescape-code-in-string "org-src" (s))
94 (declare-function org-uniquify "org" (list))
95 (declare-function orgtbl-to-generic "org-table" (table params))
96 (declare-function orgtbl-to-orgtbl "org-table" (table params))
97 (declare-function outline-show-all "outline" ())
98 (declare-function tramp-compat-make-temp-file "tramp-compat" (filename &optional dir-flag))
99 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
100 (declare-function tramp-file-name-host "tramp" (vec))
101 (declare-function tramp-file-name-user "tramp" (vec))
102 (declare-function with-parsed-tramp-file-name "tramp" (filename var &rest body) t)
104 (defgroup org-babel nil
105 "Code block evaluation and management in `org-mode' documents."
106 :tag "Babel"
107 :group 'org)
109 (defcustom org-confirm-babel-evaluate t
110 "Confirm before evaluation.
111 \\<org-mode-map>\
112 Require confirmation before interactively evaluating code
113 blocks in Org buffers. The default value of this variable is t,
114 meaning confirmation is required for any code block evaluation.
115 This variable can be set to nil to inhibit any future
116 confirmation requests. This variable can also be set to a
117 function which takes two arguments the language of the code block
118 and the body of the code block. Such a function should then
119 return a non-nil value if the user should be prompted for
120 execution or nil if no prompt is required.
122 Warning: Disabling confirmation may result in accidental
123 evaluation of potentially harmful code. It may be advisable
124 remove code block execution from \\[org-ctrl-c-ctrl-c] \
125 as further protection
126 against accidental code block evaluation. The
127 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
128 remove code block execution from the \\[org-ctrl-c-ctrl-c] keybinding."
129 :group 'org-babel
130 :version "24.1"
131 :type '(choice boolean function))
132 ;; don't allow this variable to be changed through file settings
133 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
135 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
136 "\\<org-mode-map>\
137 Remove code block evaluation from the \\[org-ctrl-c-ctrl-c] key binding."
138 :group 'org-babel
139 :version "24.1"
140 :type 'boolean)
142 (defcustom org-babel-results-keyword "RESULTS"
143 "Keyword used to name results generated by code blocks.
144 It should be \"RESULTS\". However any capitalization may be
145 used."
146 :group 'org-babel
147 :version "24.4"
148 :package-version '(Org . "8.0")
149 :type 'string
150 :safe (lambda (v)
151 (and (stringp v)
152 (eq (compare-strings "RESULTS" nil nil v nil nil t)
153 t))))
155 (defcustom org-babel-noweb-wrap-start "<<"
156 "String used to begin a noweb reference in a code block.
157 See also `org-babel-noweb-wrap-end'."
158 :group 'org-babel
159 :type 'string)
161 (defcustom org-babel-noweb-wrap-end ">>"
162 "String used to end a noweb reference in a code block.
163 See also `org-babel-noweb-wrap-start'."
164 :group 'org-babel
165 :type 'string)
167 (defcustom org-babel-inline-result-wrap "=%s="
168 "Format string used to wrap inline results.
169 This string must include a \"%s\" which will be replaced by the results."
170 :group 'org-babel
171 :type 'string)
172 (put 'org-babel-inline-result-wrap
173 'safe-local-variable
174 (lambda (value)
175 (and (stringp value)
176 (string-match-p "%s" value))))
178 (defun org-babel-noweb-wrap (&optional regexp)
179 (concat org-babel-noweb-wrap-start
180 (or regexp "\\([^ \t\n].+?[^ \t]\\|[^ \t\n]\\)")
181 org-babel-noweb-wrap-end))
183 (defvar org-babel-src-name-regexp
184 "^[ \t]*#\\+name:[ \t]*"
185 "Regular expression used to match a source name line.")
187 (defvar org-babel-multi-line-header-regexp
188 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
189 "Regular expression used to match multi-line header arguments.")
191 (defvar org-babel-src-block-regexp
192 (concat
193 ;; (1) indentation (2) lang
194 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
195 ;; (3) switches
196 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
197 ;; (4) header arguments
198 "\\([^\n]*\\)\n"
199 ;; (5) body
200 "\\([^\000]*?\n\\)??[ \t]*#\\+end_src")
201 "Regexp used to identify code blocks.")
203 (defun org-babel--get-vars (params)
204 "Return the babel variable assignments in PARAMS.
206 PARAMS is a quasi-alist of header args, whcih may contain
207 multiple entries for the key `:var'. This function returns a
208 list of the cdr of all the `:var' entries."
209 (mapcar #'cdr
210 (cl-remove-if-not (lambda (x) (eq (car x) :var)) params)))
212 (defvar org-babel-exp-reference-buffer nil
213 "Buffer containing original contents of the exported buffer.
214 This is used by Babel to resolve references in source blocks.
215 Its value is dynamically bound during export.")
217 (defun org-babel-check-confirm-evaluate (info)
218 "Check whether INFO allows code block evaluation.
220 Returns nil if evaluation is disallowed, t if it is
221 unconditionally allowed, and the symbol `query' if the user
222 should be asked whether to allow evaluation."
223 (let* ((headers (nth 2 info))
224 (eval (or (cdr (assq :eval headers))
225 (when (assq :noeval headers) "no")))
226 (eval-no (member eval '("no" "never")))
227 (export org-babel-exp-reference-buffer)
228 (eval-no-export (and export (member eval '("no-export" "never-export"))))
229 (noeval (or eval-no eval-no-export))
230 (query (or (equal eval "query")
231 (and export (equal eval "query-export"))
232 (if (functionp org-confirm-babel-evaluate)
233 (save-excursion
234 (goto-char (nth 5 info))
235 (funcall org-confirm-babel-evaluate
236 ;; language, code block body
237 (nth 0 info) (nth 1 info)))
238 org-confirm-babel-evaluate))))
239 (cond
240 (noeval nil)
241 (query 'query)
242 (t t))))
244 (defun org-babel-check-evaluate (info)
245 "Check if code block INFO should be evaluated.
247 Do not query the user, but do display an informative message if
248 evaluation is blocked. Returns non-nil if evaluation is not blocked."
249 (let ((evalp (org-babel-check-confirm-evaluate info)))
250 (when (null evalp)
251 (message "Evaluation of this %s code-block%sis disabled."
252 (nth 0 info)
253 (let ((name (nth 4 info))) (if name (format " (%s) " name) ""))))
254 evalp))
256 ;; Dynamically scoped for asynchronous export.
257 (defvar org-babel-confirm-evaluate-answer-no)
259 (defun org-babel-confirm-evaluate (info)
260 "Confirm evaluation of the code block INFO.
262 This query can also be suppressed by setting the value of
263 `org-confirm-babel-evaluate' to nil, in which case all future
264 interactive code block evaluations will proceed without any
265 confirmation from the user.
267 Note disabling confirmation may result in accidental evaluation
268 of potentially harmful code.
270 The variable `org-babel-confirm-evaluate-answer-no' is used by
271 the async export process, which requires a non-interactive
272 environment, to override this check."
273 (let* ((evalp (org-babel-check-confirm-evaluate info))
274 (lang (nth 0 info))
275 (name (nth 4 info))
276 (name-string (if name (format " (%s) " name) " ")))
277 (pcase evalp
278 (`nil nil)
279 (`t t)
280 (`query (or
281 (and (not (bound-and-true-p
282 org-babel-confirm-evaluate-answer-no))
283 (yes-or-no-p
284 (format "Evaluate this %s code block%son your system? "
285 lang name-string)))
286 (progn
287 (message "Evaluation of this %s code-block%sis aborted."
288 lang name-string)
289 nil)))
290 (x (error "Unexpected value `%s' from `org-babel-check-confirm-evaluate'" x)))))
292 ;;;###autoload
293 (defun org-babel-execute-safely-maybe ()
294 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
295 (org-babel-execute-maybe)))
297 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-safely-maybe)
299 ;;;###autoload
300 (defun org-babel-execute-maybe ()
301 (interactive)
302 (or (org-babel-execute-src-block-maybe)
303 (org-babel-lob-execute-maybe)))
305 (defmacro org-babel-when-in-src-block (&rest body)
306 "Execute BODY if point is in a source block and return t.
308 Otherwise do nothing and return nil."
309 `(if (memq (org-element-type (org-element-context))
310 '(inline-src-block src-block))
311 (progn
312 ,@body
314 nil))
316 (defun org-babel-execute-src-block-maybe ()
317 "Conditionally execute a source block.
318 Detect if this is context for a Babel src-block and if so
319 then run `org-babel-execute-src-block'."
320 (interactive)
321 (org-babel-when-in-src-block
322 (org-babel-eval-wipe-error-buffer)
323 (org-babel-execute-src-block current-prefix-arg)))
325 ;;;###autoload
326 (defun org-babel-view-src-block-info ()
327 "Display information on the current source block.
328 This includes header arguments, language and name, and is largely
329 a window into the `org-babel-get-src-block-info' function."
330 (interactive)
331 (let ((info (org-babel-get-src-block-info 'light))
332 (full (lambda (it) (> (length it) 0)))
333 (printf (lambda (fmt &rest args) (princ (apply #'format fmt args)))))
334 (when info
335 (with-help-window (help-buffer)
336 (let ((name (nth 4 info))
337 (lang (nth 0 info))
338 (switches (nth 3 info))
339 (header-args (nth 2 info)))
340 (when name (funcall printf "Name: %s\n" name))
341 (when lang (funcall printf "Lang: %s\n" lang))
342 (funcall printf "Properties:\n")
343 (funcall printf "\t:header-args \t%s\n" (org-entry-get (point) "header-args" t))
344 (funcall printf "\t:header-args:%s \t%s\n" lang (org-entry-get (point) (concat "header-args:" lang) t))
346 (when (funcall full switches) (funcall printf "Switches: %s\n" switches))
347 (funcall printf "Header Arguments:\n")
348 (dolist (pair (sort header-args
349 (lambda (a b) (string< (symbol-name (car a))
350 (symbol-name (car b))))))
351 (when (funcall full (format "%s" (cdr pair)))
352 (funcall printf "\t%S%s\t%s\n"
353 (car pair)
354 (if (> (length (format "%S" (car pair))) 7) "" "\t")
355 (cdr pair)))))))))
357 ;;;###autoload
358 (defun org-babel-expand-src-block-maybe ()
359 "Conditionally expand a source block.
360 Detect if this is context for a org-babel src-block and if so
361 then run `org-babel-expand-src-block'."
362 (interactive)
363 (org-babel-when-in-src-block
364 (org-babel-expand-src-block current-prefix-arg)))
366 ;;;###autoload
367 (defun org-babel-load-in-session-maybe ()
368 "Conditionally load a source block in a session.
369 Detect if this is context for a org-babel src-block and if so
370 then run `org-babel-load-in-session'."
371 (interactive)
372 (org-babel-when-in-src-block
373 (org-babel-load-in-session current-prefix-arg)))
375 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
377 ;;;###autoload
378 (defun org-babel-pop-to-session-maybe ()
379 "Conditionally pop to a session.
380 Detect if this is context for a org-babel src-block and if so
381 then run `org-babel-switch-to-session'."
382 (interactive)
383 (org-babel-when-in-src-block
384 (org-babel-switch-to-session current-prefix-arg)))
386 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
388 (defconst org-babel-common-header-args-w-values
389 '((cache . ((no yes)))
390 (cmdline . :any)
391 (colnames . ((nil no yes)))
392 (comments . ((no link yes org both noweb)))
393 (dir . :any)
394 (eval . ((yes no no-export strip-export never-export eval never
395 query)))
396 (exports . ((code results both none)))
397 (epilogue . :any)
398 (file . :any)
399 (file-desc . :any)
400 (file-ext . :any)
401 (hlines . ((no yes)))
402 (mkdirp . ((yes no)))
403 (no-expand)
404 (noeval)
405 (noweb . ((yes no tangle no-export strip-export)))
406 (noweb-ref . :any)
407 (noweb-sep . :any)
408 (output-dir . :any)
409 (padline . ((yes no)))
410 (post . :any)
411 (prologue . :any)
412 (results . ((file list vector table scalar verbatim)
413 (raw html latex org code pp drawer)
414 (replace silent none append prepend)
415 (output value)))
416 (rownames . ((no yes)))
417 (sep . :any)
418 (session . :any)
419 (shebang . :any)
420 (tangle . ((tangle yes no :any)))
421 (tangle-mode . ((#o755 #o555 #o444 :any)))
422 (var . :any)
423 (wrap . :any)))
425 (defconst org-babel-header-arg-names
426 (mapcar #'car org-babel-common-header-args-w-values)
427 "Common header arguments used by org-babel.
428 Note that individual languages may define their own language
429 specific header arguments as well.")
431 (defconst org-babel-safe-header-args
432 '(:cache :colnames :comments :exports :epilogue :hlines :noeval
433 :noweb :noweb-ref :noweb-sep :padline :prologue :rownames
434 :sep :session :tangle :wrap
435 (:eval . ("never" "query"))
436 (:results . (lambda (str) (not (string-match "file" str)))))
437 "A list of safe header arguments for babel source blocks.
439 The list can have entries of the following forms:
440 - :ARG -> :ARG is always a safe header arg
441 - (:ARG . (VAL1 VAL2 ...)) -> :ARG is safe as a header arg if it is
442 `equal' to one of the VALs.
443 - (:ARG . FN) -> :ARG is safe as a header arg if the function FN
444 returns non-nil. FN is passed one
445 argument, the value of the header arg
446 (as a string).")
448 (defmacro org-babel-header-args-safe-fn (safe-list)
449 "Return a function that determines whether a list of header args are safe.
451 Intended usage is:
452 \(put \\='org-babel-default-header-args \\='safe-local-variable
453 (org-babel-header-args-safe-p org-babel-safe-header-args)
455 This allows org-babel languages to extend the list of safe values for
456 their `org-babel-default-header-args:foo' variable.
458 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
459 `(lambda (value)
460 (and (listp value)
461 (cl-every
462 (lambda (pair)
463 (and (consp pair)
464 (org-babel-one-header-arg-safe-p pair ,safe-list)))
465 value))))
467 (defvar org-babel-default-header-args
468 '((:session . "none") (:results . "replace") (:exports . "code")
469 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
470 "Default arguments to use when evaluating a source block.")
471 (put 'org-babel-default-header-args 'safe-local-variable
472 (org-babel-header-args-safe-fn org-babel-safe-header-args))
474 (defvar org-babel-default-inline-header-args
475 '((:session . "none") (:results . "replace")
476 (:exports . "results") (:hlines . "yes"))
477 "Default arguments to use when evaluating an inline source block.")
478 (put 'org-babel-default-inline-header-args 'safe-local-variable
479 (org-babel-header-args-safe-fn org-babel-safe-header-args))
481 (defconst org-babel-name-regexp
482 (format "^[ \t]*#\\+%s:[ \t]*"
483 ;; FIXME: TBLNAME is for backward compatibility.
484 (regexp-opt '("NAME" "TBLNAME")))
485 "Regexp matching a NAME keyword.")
487 (defconst org-babel-result-regexp
488 (format "^[ \t]*#\\+%s\\(?:\\[\\(?:%S\\)?\\([[:alnum:]]+\\)\\]\\)?:[ \t]*"
489 org-babel-results-keyword
490 "<\\([0-9]\\{4\\}-[0-9]\\{2\\}-[0-9]\\{2\\} ?[^\r\n>]*?\\)>")
491 "Regular expression used to match result lines.
492 If the results are associated with a hash key then the hash will
493 be saved in match group 1.")
495 (defconst org-babel-result-w-name-regexp
496 (concat org-babel-result-regexp "\\(?9:[^ \t\n\r\v\f]+\\)")
497 "Regexp matching a RESULTS keyword with a name.
498 Name is saved in match group 9.")
500 (defvar org-babel-min-lines-for-block-output 10
501 "The minimum number of lines for block output.
502 If number of lines of output is equal to or exceeds this
503 value, the output is placed in a #+begin_example...#+end_example
504 block. Otherwise the output is marked as literal by inserting
505 colons at the starts of the lines. This variable only takes
506 effect if the :results output option is in effect.")
508 (defvar org-babel-noweb-error-all-langs nil
509 "Raise errors when noweb references don't resolve.
510 Also see `org-babel-noweb-error-langs' to control noweb errors on
511 a language by language bases.")
513 (defvar org-babel-noweb-error-langs nil
514 "Languages for which Babel will raise literate programming errors.
515 List of languages for which errors should be raised when the
516 source code block satisfying a noweb reference in this language
517 can not be resolved. Also see `org-babel-noweb-error-all-langs'
518 to raise errors for all languages.")
520 (defvar org-babel-hash-show 4
521 "Number of initial characters to show of a hidden results hash.")
523 (defvar org-babel-hash-show-time nil
524 "Non-nil means show the time the code block was evaluated in the result hash.")
526 (defvar org-babel-after-execute-hook nil
527 "Hook for functions to be called after `org-babel-execute-src-block'")
529 (defun org-babel-named-src-block-regexp-for-name (&optional name)
530 "This generates a regexp used to match a src block named NAME.
531 If NAME is nil, match any name. Matched name is then put in
532 match group 9. Other match groups are defined in
533 `org-babel-src-block-regexp'."
534 (concat org-babel-src-name-regexp
535 (concat (if name (regexp-quote name) "\\(?9:.*?\\)") "[ \t]*" )
536 "\\(?:\n[ \t]*#\\+\\S-+:.*\\)*?"
537 "\n"
538 (substring org-babel-src-block-regexp 1)))
540 (defun org-babel-named-data-regexp-for-name (name)
541 "This generates a regexp used to match data named NAME."
542 (concat org-babel-name-regexp (regexp-quote name) "[ \t]*$"))
544 (defun org-babel--normalize-body (datum)
545 "Normalize body for element or object DATUM.
546 DATUM is a source block element or an inline source block object.
547 Remove final newline character and spurious indentation."
548 (let* ((value (org-element-property :value datum))
549 (body (if (string-suffix-p "\n" value)
550 (substring value 0 -1)
551 value)))
552 (cond ((eq (org-element-type datum) 'inline-src-block)
553 ;; Newline characters and indentation in an inline
554 ;; src-block are not meaningful, since they could come from
555 ;; some paragraph filling. Treat them as a white space.
556 (replace-regexp-in-string "\n[ \t]*" " " body))
557 ((or org-src-preserve-indentation
558 (org-element-property :preserve-indent datum))
559 body)
560 (t (org-remove-indentation body)))))
562 ;;; functions
563 (defvar org-babel-current-src-block-location nil
564 "Marker pointing to the src block currently being executed.
565 This may also point to a call line or an inline code block. If
566 multiple blocks are being executed (e.g., in chained execution
567 through use of the :var header argument) this marker points to
568 the outer-most code block.")
570 (defvar *this*)
572 (defun org-babel-get-src-block-info (&optional light datum)
573 "Extract information from a source block or inline source block.
575 Optional argument LIGHT does not resolve remote variable
576 references; a process which could likely result in the execution
577 of other code blocks.
579 By default, consider the block at point. However, when optional
580 argument DATUM is provided, extract information from that parsed
581 object instead.
583 Return nil if point is not on a source block. Otherwise, return
584 a list with the following pattern:
586 (language body arguments switches name start coderef)"
587 (let* ((datum (or datum (org-element-context)))
588 (type (org-element-type datum))
589 (inline (eq type 'inline-src-block)))
590 (when (memq type '(inline-src-block src-block))
591 (let* ((lang (org-element-property :language datum))
592 (lang-headers (intern
593 (concat "org-babel-default-header-args:" lang)))
594 (name (org-element-property :name datum))
595 (info
596 (list
597 lang
598 (org-babel--normalize-body datum)
599 (apply #'org-babel-merge-params
600 (if inline org-babel-default-inline-header-args
601 org-babel-default-header-args)
602 (and (boundp lang-headers) (eval lang-headers t))
603 (append
604 ;; If DATUM is provided, make sure we get node
605 ;; properties applicable to its location within
606 ;; the document.
607 (org-with-point-at (org-element-property :begin datum)
608 (org-babel-params-from-properties lang))
609 (mapcar #'org-babel-parse-header-arguments
610 (cons (org-element-property :parameters datum)
611 (org-element-property :header datum)))))
612 (or (org-element-property :switches datum) "")
613 name
614 (org-element-property (if inline :begin :post-affiliated)
615 datum)
616 (and (not inline) (org-src-coderef-format datum)))))
617 (unless light
618 (setf (nth 2 info) (org-babel-process-params (nth 2 info))))
619 (setf (nth 2 info) (org-babel-generate-file-param name (nth 2 info)))
620 info))))
622 ;;;###autoload
623 (defun org-babel-execute-src-block (&optional arg info params)
624 "Execute the current source code block.
625 Insert the results of execution into the buffer. Source code
626 execution and the collection and formatting of results can be
627 controlled through a variety of header arguments.
629 With prefix argument ARG, force re-execution even if an existing
630 result cached in the buffer would otherwise have been returned.
632 Optionally supply a value for INFO in the form returned by
633 `org-babel-get-src-block-info'.
635 Optionally supply a value for PARAMS which will be merged with
636 the header arguments specified at the front of the source code
637 block."
638 (interactive)
639 (let* ((org-babel-current-src-block-location
640 (or org-babel-current-src-block-location
641 (nth 5 info)
642 (org-babel-where-is-src-block-head)))
643 (info (if info (copy-tree info) (org-babel-get-src-block-info))))
644 ;; Merge PARAMS with INFO before considering source block
645 ;; evaluation since both could disagree.
646 (cl-callf org-babel-merge-params (nth 2 info) params)
647 (when (org-babel-check-evaluate info)
648 (cl-callf org-babel-process-params (nth 2 info))
649 (let* ((params (nth 2 info))
650 (cache (let ((c (cdr (assq :cache params))))
651 (and (not arg) c (string= "yes" c))))
652 (new-hash (and cache (org-babel-sha1-hash info)))
653 (old-hash (and cache (org-babel-current-result-hash)))
654 (current-cache (and new-hash (equal new-hash old-hash))))
655 (cond
656 (current-cache
657 (save-excursion ;Return cached result.
658 (goto-char (org-babel-where-is-src-block-result nil info))
659 (forward-line)
660 (skip-chars-forward " \t")
661 (let ((result (org-babel-read-result)))
662 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
663 result)))
664 ((org-babel-confirm-evaluate info)
665 (let* ((lang (nth 0 info))
666 (result-params (cdr (assq :result-params params)))
667 ;; Expand noweb references in BODY and remove any
668 ;; coderef.
669 (body
670 (let ((coderef (nth 6 info))
671 (expand
672 (if (org-babel-noweb-p params :eval)
673 (org-babel-expand-noweb-references info)
674 (nth 1 info))))
675 (if (not coderef) expand
676 (replace-regexp-in-string
677 (org-src-coderef-regexp coderef) "" expand nil nil 1))))
678 (dir (cdr (assq :dir params)))
679 (default-directory
680 (or (and dir (file-name-as-directory (expand-file-name dir)))
681 default-directory))
682 (cmd (intern (concat "org-babel-execute:" lang)))
683 result)
684 (unless (fboundp cmd)
685 (error "No org-babel-execute function for %s!" lang))
686 (message "executing %s code block%s..."
687 (capitalize lang)
688 (let ((name (nth 4 info)))
689 (if name (format " (%s)" name) "")))
690 (if (member "none" result-params)
691 (progn (funcall cmd body params)
692 (message "result silenced"))
693 (setq result
694 (let ((r (funcall cmd body params)))
695 (if (and (eq (cdr (assq :result-type params)) 'value)
696 (or (member "vector" result-params)
697 (member "table" result-params))
698 (not (listp r)))
699 (list (list r))
700 r)))
701 (let ((file (cdr (assq :file params))))
702 ;; If non-empty result and :file then write to :file.
703 (when file
704 (when result
705 (with-temp-file file
706 (insert (org-babel-format-result
707 result (cdr (assq :sep params))))))
708 (setq result file))
709 ;; Possibly perform post process provided its
710 ;; appropriate. Dynamically bind "*this*" to the
711 ;; actual results of the block.
712 (let ((post (cdr (assq :post params))))
713 (when post
714 (let ((*this* (if (not file) result
715 (org-babel-result-to-file
716 file
717 (let ((desc (assq :file-desc params)))
718 (and desc (or (cdr desc) result)))))))
719 (setq result (org-babel-ref-resolve post))
720 (when file
721 (setq result-params (remove "file" result-params))))))
722 (org-babel-insert-result
723 result result-params info new-hash lang)))
724 (run-hooks 'org-babel-after-execute-hook)
725 result)))))))
727 (defun org-babel-expand-body:generic (body params &optional var-lines)
728 "Expand BODY with PARAMS.
729 Expand a block of code with org-babel according to its header
730 arguments. This generic implementation of body expansion is
731 called for languages which have not defined their own specific
732 org-babel-expand-body:lang function."
733 (let ((pro (cdr (assoc :prologue params)))
734 (epi (cdr (assoc :epilogue params))))
735 (mapconcat #'identity
736 (append (when pro (list pro))
737 var-lines
738 (list body)
739 (when epi (list epi)))
740 "\n")))
742 ;;;###autoload
743 (defun org-babel-expand-src-block (&optional _arg info params)
744 "Expand the current source code block.
745 Expand according to the source code block's header
746 arguments and pop open the results in a preview buffer."
747 (interactive)
748 (let* ((info (or info (org-babel-get-src-block-info)))
749 (lang (nth 0 info))
750 (params (setf (nth 2 info)
751 (sort (org-babel-merge-params (nth 2 info) params)
752 (lambda (el1 el2) (string< (symbol-name (car el1))
753 (symbol-name (car el2)))))))
754 (body (setf (nth 1 info)
755 (if (org-babel-noweb-p params :eval)
756 (org-babel-expand-noweb-references info) (nth 1 info))))
757 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
758 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
759 lang)))
760 (expanded
761 (if (fboundp expand-cmd) (funcall expand-cmd body params)
762 (org-babel-expand-body:generic
763 body params (and (fboundp assignments-cmd)
764 (funcall assignments-cmd params))))))
765 (if (called-interactively-p 'any)
766 (org-edit-src-code
767 expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
768 expanded)))
770 (defun org-babel-edit-distance (s1 s2)
771 "Return the edit (levenshtein) distance between strings S1 S2."
772 (let* ((l1 (length s1))
773 (l2 (length s2))
774 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
775 (number-sequence 1 (1+ l1)))))
776 (in (lambda (i j) (aref (aref dist i) j))))
777 (setf (aref (aref dist 0) 0) 0)
778 (dolist (j (number-sequence 1 l2))
779 (setf (aref (aref dist 0) j) j))
780 (dolist (i (number-sequence 1 l1))
781 (setf (aref (aref dist i) 0) i)
782 (dolist (j (number-sequence 1 l2))
783 (setf (aref (aref dist i) j)
784 (min
785 (1+ (funcall in (1- i) j))
786 (1+ (funcall in i (1- j)))
787 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
788 (funcall in (1- i) (1- j)))))))
789 (funcall in l1 l2)))
791 (defun org-babel-combine-header-arg-lists (original &rest others)
792 "Combine a number of lists of header argument names and arguments."
793 (let ((results (copy-sequence original)))
794 (dolist (new-list others)
795 (dolist (arg-pair new-list)
796 (let ((header (car arg-pair)))
797 (setq results
798 (cons arg-pair (cl-remove-if
799 (lambda (pair) (equal header (car pair)))
800 results))))))
801 results))
803 ;;;###autoload
804 (defun org-babel-check-src-block ()
805 "Check for misspelled header arguments in the current code block."
806 (interactive)
807 ;; TODO: report malformed code block
808 ;; TODO: report incompatible combinations of header arguments
809 ;; TODO: report uninitialized variables
810 (let ((too-close 2) ;; <- control closeness to report potential match
811 (names (mapcar #'symbol-name org-babel-header-arg-names)))
812 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
813 (and (org-babel-where-is-src-block-head)
814 (org-babel-parse-header-arguments
815 (org-no-properties
816 (match-string 4))))))
817 (dolist (name names)
818 (when (and (not (string= header name))
819 (<= (org-babel-edit-distance header name) too-close)
820 (not (member header names)))
821 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
822 header name))))
823 (message "No suspicious header arguments found.")))
825 ;;;###autoload
826 (defun org-babel-insert-header-arg (&optional header-arg value)
827 "Insert a header argument selecting from lists of common args and values."
828 (interactive)
829 (let* ((info (org-babel-get-src-block-info 'light))
830 (lang (car info))
831 (begin (nth 5 info))
832 (lang-headers (intern (concat "org-babel-header-args:" lang)))
833 (headers (org-babel-combine-header-arg-lists
834 org-babel-common-header-args-w-values
835 (when (boundp lang-headers) (eval lang-headers t))))
836 (header-arg (or header-arg
837 (completing-read
838 "Header Arg: "
839 (mapcar
840 (lambda (header-spec) (symbol-name (car header-spec)))
841 headers))))
842 (vals (cdr (assoc (intern header-arg) headers)))
843 (value (or value
844 (cond
845 ((eq vals :any)
846 (read-from-minibuffer "value: "))
847 ((listp vals)
848 (mapconcat
849 (lambda (group)
850 (let ((arg (completing-read
851 "Value: "
852 (cons "default"
853 (mapcar #'symbol-name group)))))
854 (if (and arg (not (string= "default" arg)))
855 (concat arg " ")
856 "")))
857 vals ""))))))
858 (save-excursion
859 (goto-char begin)
860 (goto-char (point-at-eol))
861 (unless (= (char-before (point)) ?\ ) (insert " "))
862 (insert ":" header-arg) (when value (insert " " value)))))
864 ;; Add support for completing-read insertion of header arguments after ":"
865 (defun org-babel-header-arg-expand ()
866 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
867 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
868 (org-babel-enter-header-arg-w-completion (match-string 2))))
870 (defun org-babel-enter-header-arg-w-completion (&optional lang)
871 "Insert header argument appropriate for LANG with completion."
872 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
873 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var t)))
874 (headers-w-values (org-babel-combine-header-arg-lists
875 org-babel-common-header-args-w-values lang-headers))
876 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
877 (header (org-completing-read "Header Arg: " headers))
878 (args (cdr (assoc (intern header) headers-w-values)))
879 (arg (when (and args (listp args))
880 (org-completing-read
881 (format "%s: " header)
882 (mapcar #'symbol-name (apply #'append args))))))
883 (insert (concat header " " (or arg "")))
884 (cons header arg)))
886 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
888 ;;;###autoload
889 (defun org-babel-load-in-session (&optional _arg info)
890 "Load the body of the current source-code block.
891 Evaluate the header arguments for the source block before
892 entering the session. After loading the body this pops open the
893 session."
894 (interactive)
895 (let* ((info (or info (org-babel-get-src-block-info)))
896 (lang (nth 0 info))
897 (params (nth 2 info))
898 (body (if (not info)
899 (user-error "No src code block at point")
900 (setf (nth 1 info)
901 (if (org-babel-noweb-p params :eval)
902 (org-babel-expand-noweb-references info)
903 (nth 1 info)))))
904 (session (cdr (assoc :session params)))
905 (dir (cdr (assoc :dir params)))
906 (default-directory
907 (or (and dir (file-name-as-directory dir)) default-directory))
908 (cmd (intern (concat "org-babel-load-session:" lang))))
909 (unless (fboundp cmd)
910 (error "No org-babel-load-session function for %s!" lang))
911 (pop-to-buffer (funcall cmd session body params))
912 (end-of-line 1)))
914 ;;;###autoload
915 (defun org-babel-initiate-session (&optional arg info)
916 "Initiate session for current code block.
917 If called with a prefix argument then resolve any variable
918 references in the header arguments and assign these variables in
919 the session. Copy the body of the code block to the kill ring."
920 (interactive "P")
921 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
922 (lang (nth 0 info))
923 (body (nth 1 info))
924 (params (nth 2 info))
925 (session (cdr (assoc :session params)))
926 (dir (cdr (assoc :dir params)))
927 (default-directory
928 (or (and dir (file-name-as-directory dir)) default-directory))
929 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
930 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
931 (when (and (stringp session) (string= session "none"))
932 (error "This block is not using a session!"))
933 (unless (fboundp init-cmd)
934 (error "No org-babel-initiate-session function for %s!" lang))
935 (with-temp-buffer (insert (org-trim body))
936 (copy-region-as-kill (point-min) (point-max)))
937 (when arg
938 (unless (fboundp prep-cmd)
939 (error "No org-babel-prep-session function for %s!" lang))
940 (funcall prep-cmd session params))
941 (funcall init-cmd session params)))
943 ;;;###autoload
944 (defun org-babel-switch-to-session (&optional arg info)
945 "Switch to the session of the current code block.
946 Uses `org-babel-initiate-session' to start the session. If called
947 with a prefix argument then this is passed on to
948 `org-babel-initiate-session'."
949 (interactive "P")
950 (pop-to-buffer (org-babel-initiate-session arg info))
951 (end-of-line 1))
953 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
955 (defvar org-src-window-setup)
957 ;;;###autoload
958 (defun org-babel-switch-to-session-with-code (&optional arg _info)
959 "Switch to code buffer and display session."
960 (interactive "P")
961 (let ((swap-windows
962 (lambda ()
963 (let ((other-window-buffer (window-buffer (next-window))))
964 (set-window-buffer (next-window) (current-buffer))
965 (set-window-buffer (selected-window) other-window-buffer))
966 (other-window 1)))
967 (info (org-babel-get-src-block-info))
968 (org-src-window-setup 'reorganize-frame))
969 (save-excursion
970 (org-babel-switch-to-session arg info))
971 (org-edit-src-code)
972 (funcall swap-windows)))
974 ;;;###autoload
975 (defmacro org-babel-do-in-edit-buffer (&rest body)
976 "Evaluate BODY in edit buffer if there is a code block at point.
977 Return t if a code block was found at point, nil otherwise."
978 `(let ((org-src-window-setup 'switch-invisibly))
979 (when (and (org-babel-where-is-src-block-head)
980 (org-edit-src-code))
981 (unwind-protect (progn ,@body)
982 (org-edit-src-exit))
983 t)))
984 (def-edebug-spec org-babel-do-in-edit-buffer (body))
986 (defun org-babel-do-key-sequence-in-edit-buffer (key)
987 "Read key sequence and execute the command in edit buffer.
988 Enter a key sequence to be executed in the language major-mode
989 edit buffer. For example, TAB will alter the contents of the
990 Org code block according to the effect of TAB in the language
991 major mode buffer. For languages that support interactive
992 sessions, this can be used to send code from the Org buffer
993 to the session for evaluation using the native major mode
994 evaluation mechanisms."
995 (interactive "kEnter key-sequence to execute in edit buffer: ")
996 (org-babel-do-in-edit-buffer
997 (call-interactively
998 (key-binding (or key (read-key-sequence nil))))))
1000 (defvar org-bracket-link-regexp)
1002 (defun org-babel-active-location-p ()
1003 (memq (org-element-type (save-match-data (org-element-context)))
1004 '(babel-call inline-babel-call inline-src-block src-block)))
1006 ;;;###autoload
1007 (defun org-babel-open-src-block-result (&optional re-run)
1008 "If `point' is on a src block then open the results of the
1009 source code block, otherwise return nil. With optional prefix
1010 argument RE-RUN the source-code block is evaluated even if
1011 results already exist."
1012 (interactive "P")
1013 (let ((info (org-babel-get-src-block-info 'light)))
1014 (when info
1015 (save-excursion
1016 ;; go to the results, if there aren't any then run the block
1017 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
1018 (progn (org-babel-execute-src-block)
1019 (org-babel-where-is-src-block-result))))
1020 (end-of-line 1)
1021 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1022 ;; open the results
1023 (if (looking-at org-bracket-link-regexp)
1024 ;; file results
1025 (org-open-at-point)
1026 (let ((r (org-babel-format-result
1027 (org-babel-read-result) (cdr (assoc :sep (nth 2 info))))))
1028 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1029 (delete-region (point-min) (point-max))
1030 (insert r)))
1031 t))))
1033 ;;;###autoload
1034 (defmacro org-babel-map-src-blocks (file &rest body)
1035 "Evaluate BODY forms on each source-block in FILE.
1036 If FILE is nil evaluate BODY forms on source blocks in current
1037 buffer. During evaluation of BODY the following local variables
1038 are set relative to the currently matched code block.
1040 full-block ------- string holding the entirety of the code block
1041 beg-block -------- point at the beginning of the code block
1042 end-block -------- point at the end of the matched code block
1043 lang ------------- string holding the language of the code block
1044 beg-lang --------- point at the beginning of the lang
1045 end-lang --------- point at the end of the lang
1046 switches --------- string holding the switches
1047 beg-switches ----- point at the beginning of the switches
1048 end-switches ----- point at the end of the switches
1049 header-args ------ string holding the header-args
1050 beg-header-args -- point at the beginning of the header-args
1051 end-header-args -- point at the end of the header-args
1052 body ------------- string holding the body of the code block
1053 beg-body --------- point at the beginning of the body
1054 end-body --------- point at the end of the body"
1055 (declare (indent 1))
1056 (let ((tempvar (make-symbol "file")))
1057 `(let* ((case-fold-search t)
1058 (,tempvar ,file)
1059 (visited-p (or (null ,tempvar)
1060 (get-file-buffer (expand-file-name ,tempvar))))
1061 (point (point)) to-be-removed)
1062 (save-window-excursion
1063 (when ,tempvar (find-file ,tempvar))
1064 (setq to-be-removed (current-buffer))
1065 (goto-char (point-min))
1066 (while (re-search-forward org-babel-src-block-regexp nil t)
1067 (when (org-babel-active-location-p)
1068 (goto-char (match-beginning 0))
1069 (let ((full-block (match-string 0))
1070 (beg-block (match-beginning 0))
1071 (end-block (match-end 0))
1072 (lang (match-string 2))
1073 (beg-lang (match-beginning 2))
1074 (end-lang (match-end 2))
1075 (switches (match-string 3))
1076 (beg-switches (match-beginning 3))
1077 (end-switches (match-end 3))
1078 (header-args (match-string 4))
1079 (beg-header-args (match-beginning 4))
1080 (end-header-args (match-end 4))
1081 (body (match-string 5))
1082 (beg-body (match-beginning 5))
1083 (end-body (match-end 5)))
1084 ;; Silence byte-compiler in case `body' doesn't use all
1085 ;; those variables.
1086 (ignore full-block beg-block end-block lang
1087 beg-lang end-lang switches beg-switches
1088 end-switches header-args beg-header-args
1089 end-header-args body beg-body end-body)
1090 ,@body
1091 (goto-char end-block)))))
1092 (unless visited-p (kill-buffer to-be-removed))
1093 (goto-char point))))
1094 (def-edebug-spec org-babel-map-src-blocks (form body))
1096 ;;;###autoload
1097 (defmacro org-babel-map-inline-src-blocks (file &rest body)
1098 "Evaluate BODY forms on each inline source block in FILE.
1099 If FILE is nil evaluate BODY forms on source blocks in current
1100 buffer."
1101 (declare (indent 1) (debug (form body)))
1102 (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
1103 `(let* ((case-fold-search t)
1104 (,tempvar ,file)
1105 (,visitedp (or (null ,tempvar)
1106 (get-file-buffer (expand-file-name ,tempvar))))
1107 (,point (point))
1108 ,to-be-removed)
1109 (save-window-excursion
1110 (when ,tempvar (find-file ,tempvar))
1111 (setq ,to-be-removed (current-buffer))
1112 (goto-char (point-min))
1113 (while (re-search-forward "src_\\S-" nil t)
1114 (let ((,datum (save-match-data (org-element-context))))
1115 (when (eq (org-element-type ,datum) 'inline-src-block)
1116 (goto-char (match-beginning 0))
1117 (let ((,end (copy-marker (org-element-property :end ,datum))))
1118 ,@body
1119 (goto-char ,end)
1120 (set-marker ,end nil))))))
1121 (unless ,visitedp (kill-buffer ,to-be-removed))
1122 (goto-char ,point))))
1124 ;;;###autoload
1125 (defmacro org-babel-map-call-lines (file &rest body)
1126 "Evaluate BODY forms on each call line in FILE.
1127 If FILE is nil evaluate BODY forms on source blocks in current
1128 buffer."
1129 (declare (indent 1) (debug (form body)))
1130 (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
1131 `(let* ((case-fold-search t)
1132 (,tempvar ,file)
1133 (,visitedp (or (null ,tempvar)
1134 (get-file-buffer (expand-file-name ,tempvar))))
1135 (,point (point))
1136 ,to-be-removed)
1137 (save-window-excursion
1138 (when ,tempvar (find-file ,tempvar))
1139 (setq ,to-be-removed (current-buffer))
1140 (goto-char (point-min))
1141 (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t)
1142 (let ((,datum (save-match-data (org-element-context))))
1143 (when (memq (org-element-type ,datum)
1144 '(babel-call inline-babel-call))
1145 (goto-char (match-beginning 0))
1146 (let ((,end (copy-marker (org-element-property :end ,datum))))
1147 ,@body
1148 (goto-char ,end)
1149 (set-marker ,end nil))))))
1150 (unless ,visitedp (kill-buffer ,to-be-removed))
1151 (goto-char ,point))))
1153 ;;;###autoload
1154 (defmacro org-babel-map-executables (file &rest body)
1155 "Evaluate BODY forms on each active Babel code in FILE.
1156 If FILE is nil evaluate BODY forms on source blocks in current
1157 buffer."
1158 (declare (indent 1) (debug (form body)))
1159 (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
1160 `(let* ((case-fold-search t)
1161 (,tempvar ,file)
1162 (,visitedp (or (null ,tempvar)
1163 (get-file-buffer (expand-file-name ,tempvar))))
1164 (,point (point))
1165 ,to-be-removed)
1166 (save-window-excursion
1167 (when ,tempvar (find-file ,tempvar))
1168 (setq ,to-be-removed (current-buffer))
1169 (goto-char (point-min))
1170 (while (re-search-forward
1171 "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t)
1172 (let ((,datum (save-match-data (org-element-context))))
1173 (when (memq (org-element-type ,datum)
1174 '(babel-call inline-babel-call inline-src-block
1175 src-block))
1176 (goto-char (match-beginning 0))
1177 (let ((,end (copy-marker (org-element-property :end ,datum))))
1178 ,@body
1179 (goto-char ,end)
1180 (set-marker ,end nil))))))
1181 (unless ,visitedp (kill-buffer ,to-be-removed))
1182 (goto-char ,point))))
1184 ;;;###autoload
1185 (defun org-babel-execute-buffer (&optional arg)
1186 "Execute source code blocks in a buffer.
1187 Call `org-babel-execute-src-block' on every source block in
1188 the current buffer."
1189 (interactive "P")
1190 (org-babel-eval-wipe-error-buffer)
1191 (org-save-outline-visibility t
1192 (org-babel-map-executables nil
1193 (if (memq (org-element-type (org-element-context))
1194 '(babel-call inline-babel-call))
1195 (org-babel-lob-execute-maybe)
1196 (org-babel-execute-src-block arg)))))
1198 ;;;###autoload
1199 (defun org-babel-execute-subtree (&optional arg)
1200 "Execute source code blocks in a subtree.
1201 Call `org-babel-execute-src-block' on every source block in
1202 the current subtree."
1203 (interactive "P")
1204 (save-restriction
1205 (save-excursion
1206 (org-narrow-to-subtree)
1207 (org-babel-execute-buffer arg)
1208 (widen))))
1210 ;;;###autoload
1211 (defun org-babel-sha1-hash (&optional info)
1212 "Generate an sha1 hash based on the value of info."
1213 (interactive)
1214 (let ((print-level nil)
1215 (info (or info (org-babel-get-src-block-info))))
1216 (setf (nth 2 info)
1217 (sort (copy-sequence (nth 2 info))
1218 (lambda (a b) (string< (car a) (car b)))))
1219 (let* ((rm (lambda (lst)
1220 (dolist (p '("replace" "silent" "none"
1221 "append" "prepend"))
1222 (setq lst (remove p lst)))
1223 lst))
1224 (norm (lambda (arg)
1225 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1226 (copy-sequence (cdr arg))
1227 (cdr arg))))
1228 (when (and v (not (and (sequencep v)
1229 (not (consp v))
1230 (= (length v) 0))))
1231 (cond
1232 ((and (listp v) ; lists are sorted
1233 (member (car arg) '(:result-params)))
1234 (sort (funcall rm v) #'string<))
1235 ((and (stringp v) ; strings are sorted
1236 (member (car arg) '(:results :exports)))
1237 (mapconcat #'identity (sort (funcall rm (split-string v))
1238 #'string<) " "))
1239 (t v))))))
1240 ;; expanded body
1241 (lang (nth 0 info))
1242 (params (nth 2 info))
1243 (body (if (org-babel-noweb-p params :eval)
1244 (org-babel-expand-noweb-references info) (nth 1 info)))
1245 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
1246 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1247 lang)))
1248 (expanded
1249 (if (fboundp expand-cmd) (funcall expand-cmd body params)
1250 (org-babel-expand-body:generic
1251 body params (and (fboundp assignments-cmd)
1252 (funcall assignments-cmd params))))))
1253 (let* ((it (format "%s-%s"
1254 (mapconcat
1255 #'identity
1256 (delq nil (mapcar (lambda (arg)
1257 (let ((normalized (funcall norm arg)))
1258 (when normalized
1259 (format "%S" normalized))))
1260 (nth 2 info))) ":")
1261 expanded))
1262 (hash (sha1 it)))
1263 (when (called-interactively-p 'interactive) (message hash))
1264 hash))))
1266 (defun org-babel-current-result-hash (&optional info)
1267 "Return the current in-buffer hash."
1268 (let ((result (org-babel-where-is-src-block-result nil info)))
1269 (when result
1270 (org-with-wide-buffer
1271 (goto-char result)
1272 (looking-at org-babel-result-regexp)
1273 (match-string-no-properties 1)))))
1275 (defun org-babel-set-current-result-hash (hash info)
1276 "Set the current in-buffer hash to HASH."
1277 (org-with-wide-buffer
1278 (goto-char (org-babel-where-is-src-block-result nil info))
1279 (looking-at org-babel-result-regexp)
1280 (goto-char (match-beginning 1))
1281 (mapc #'delete-overlay (overlays-at (point)))
1282 (forward-char org-babel-hash-show)
1283 (mapc #'delete-overlay (overlays-at (point)))
1284 (replace-match hash nil nil nil 1)
1285 (beginning-of-line)
1286 (org-babel-hide-hash)))
1288 (defun org-babel-hide-hash ()
1289 "Hide the hash in the current results line.
1290 Only the initial `org-babel-hash-show' characters of the hash
1291 will remain visible."
1292 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1293 (save-excursion
1294 (when (and (re-search-forward org-babel-result-regexp nil t)
1295 (match-string 1))
1296 (let* ((start (match-beginning 1))
1297 (hide-start (+ org-babel-hash-show start))
1298 (end (match-end 1))
1299 (hash (match-string 1))
1300 ov1 ov2)
1301 (setq ov1 (make-overlay start hide-start))
1302 (setq ov2 (make-overlay hide-start end))
1303 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1304 (overlay-put ov1 'babel-hash hash)))))
1306 (defun org-babel-hide-all-hashes ()
1307 "Hide the hash in the current buffer.
1308 Only the initial `org-babel-hash-show' characters of each hash
1309 will remain visible. This function should be called as part of
1310 the `org-mode-hook'."
1311 (save-excursion
1312 (while (and (not org-babel-hash-show-time)
1313 (re-search-forward org-babel-result-regexp nil t))
1314 (goto-char (match-beginning 0))
1315 (org-babel-hide-hash)
1316 (goto-char (match-end 0)))))
1317 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1319 (defun org-babel-hash-at-point (&optional point)
1320 "Return the value of the hash at POINT.
1321 \\<org-mode-map>\
1322 The hash is also added as the last element of the kill ring.
1323 This can be called with \\[org-ctrl-c-ctrl-c]."
1324 (interactive)
1325 (let ((hash (car (delq nil (mapcar
1326 (lambda (ol) (overlay-get ol 'babel-hash))
1327 (overlays-at (or point (point))))))))
1328 (when hash (kill-new hash) (message hash))))
1329 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
1331 (defun org-babel-result-hide-spec ()
1332 "Hide portions of results lines.
1333 Add `org-babel-hide-result' as an invisibility spec for hiding
1334 portions of results lines."
1335 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1336 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1338 (defvar org-babel-hide-result-overlays nil
1339 "Overlays hiding results.")
1341 (defun org-babel-result-hide-all ()
1342 "Fold all results in the current buffer."
1343 (interactive)
1344 (org-babel-show-result-all)
1345 (save-excursion
1346 (while (re-search-forward org-babel-result-regexp nil t)
1347 (save-excursion (goto-char (match-beginning 0))
1348 (org-babel-hide-result-toggle-maybe)))))
1350 (defun org-babel-show-result-all ()
1351 "Unfold all results in the current buffer."
1352 (mapc 'delete-overlay org-babel-hide-result-overlays)
1353 (setq org-babel-hide-result-overlays nil))
1355 ;;;###autoload
1356 (defun org-babel-hide-result-toggle-maybe ()
1357 "Toggle visibility of result at point."
1358 (interactive)
1359 (let ((case-fold-search t))
1360 (if (save-excursion
1361 (beginning-of-line 1)
1362 (looking-at org-babel-result-regexp))
1363 (progn (org-babel-hide-result-toggle)
1364 t) ;; to signal that we took action
1365 nil))) ;; to signal that we did not
1367 (defun org-babel-hide-result-toggle (&optional force)
1368 "Toggle the visibility of the current result."
1369 (interactive)
1370 (save-excursion
1371 (beginning-of-line)
1372 (if (re-search-forward org-babel-result-regexp nil t)
1373 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1374 (end (progn
1375 (while (looking-at org-babel-multi-line-header-regexp)
1376 (forward-line 1))
1377 (goto-char (- (org-babel-result-end) 1)) (point)))
1379 (if (memq t (mapcar (lambda (overlay)
1380 (eq (overlay-get overlay 'invisible)
1381 'org-babel-hide-result))
1382 (overlays-at start)))
1383 (when (or (not force) (eq force 'off))
1384 (mapc (lambda (ov)
1385 (when (member ov org-babel-hide-result-overlays)
1386 (setq org-babel-hide-result-overlays
1387 (delq ov org-babel-hide-result-overlays)))
1388 (when (eq (overlay-get ov 'invisible)
1389 'org-babel-hide-result)
1390 (delete-overlay ov)))
1391 (overlays-at start)))
1392 (setq ov (make-overlay start end))
1393 (overlay-put ov 'invisible 'org-babel-hide-result)
1394 ;; make the block accessible to isearch
1395 (overlay-put
1396 ov 'isearch-open-invisible
1397 (lambda (ov)
1398 (when (member ov org-babel-hide-result-overlays)
1399 (setq org-babel-hide-result-overlays
1400 (delq ov org-babel-hide-result-overlays)))
1401 (when (eq (overlay-get ov 'invisible)
1402 'org-babel-hide-result)
1403 (delete-overlay ov))))
1404 (push ov org-babel-hide-result-overlays)))
1405 (error "Not looking at a result line"))))
1407 ;; org-tab-after-check-for-cycling-hook
1408 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1409 ;; Remove overlays when changing major mode
1410 (add-hook 'org-mode-hook
1411 (lambda () (add-hook 'change-major-mode-hook
1412 'org-babel-show-result-all 'append 'local)))
1414 (defvar org-file-properties)
1415 (defun org-babel-params-from-properties (&optional lang)
1416 "Retrieve parameters specified as properties.
1417 Return a list of association lists of source block params
1418 specified in the properties of the current outline entry."
1419 (save-match-data
1420 (list
1421 ;; header arguments specified with the header-args property at
1422 ;; point of call.
1423 (org-babel-parse-header-arguments
1424 (org-entry-get org-babel-current-src-block-location
1425 "header-args"
1426 'inherit))
1427 (and lang ; language-specific header arguments at point of call
1428 (org-babel-parse-header-arguments
1429 (org-entry-get org-babel-current-src-block-location
1430 (concat "header-args:" lang)
1431 'inherit))))))
1433 (defun org-babel-balanced-split (string alts)
1434 "Split STRING on instances of ALTS.
1435 ALTS is a cons of two character options where each option may be
1436 either the numeric code of a single character or a list of
1437 character alternatives. For example to split on balanced
1438 instances of \"[ \t]:\" set ALTS to ((32 9) . 58)."
1439 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1440 (matched (lambda (ch last)
1441 (if (consp alts)
1442 (and (funcall matches ch (cdr alts))
1443 (funcall matches last (car alts)))
1444 (funcall matches ch alts))))
1445 (balance 0) (last 0)
1446 quote partial lst)
1447 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1448 (setq balance (+ balance
1449 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1450 ((or (equal 93 ch) (equal 41 ch)) -1)
1451 (t 0))))
1452 (when (and (equal 34 ch) (not (equal 92 last)))
1453 (setq quote (not quote)))
1454 (setq partial (cons ch partial))
1455 (when (and (= balance 0) (not quote) (funcall matched ch last))
1456 (setq lst (cons (apply #'string (nreverse
1457 (if (consp alts)
1458 (cddr partial)
1459 (cdr partial))))
1460 lst))
1461 (setq partial nil))
1462 (setq last ch))
1463 (string-to-list string))
1464 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1466 (defun org-babel-join-splits-near-ch (ch list)
1467 "Join splits where \"=\" is on either end of the split."
1468 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1469 (first= (lambda (str) (= ch (aref str 0)))))
1470 (reverse
1471 (cl-reduce (lambda (acc el)
1472 (let ((head (car acc)))
1473 (if (and head (or (funcall last= head) (funcall first= el)))
1474 (cons (concat head el) (cdr acc))
1475 (cons el acc))))
1476 list :initial-value nil))))
1478 (defun org-babel-parse-header-arguments (arg-string)
1479 "Parse a string of header arguments returning an alist."
1480 (when (> (length arg-string) 0)
1481 (org-babel-parse-multiple-vars
1482 (delq nil
1483 (mapcar
1484 (lambda (arg)
1485 (if (string-match
1486 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1487 arg)
1488 (cons (intern (match-string 1 arg))
1489 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1490 (cons (intern (org-babel-chomp arg)) nil)))
1491 (let ((raw (org-babel-balanced-split arg-string '((32 9) . 58))))
1492 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
1494 (defun org-babel-parse-multiple-vars (header-arguments)
1495 "Expand multiple variable assignments behind a single :var keyword.
1497 This allows expression of multiple variables with one :var as
1498 shown below.
1500 #+PROPERTY: var foo=1, bar=2"
1501 (let (results)
1502 (mapc (lambda (pair)
1503 (if (eq (car pair) :var)
1504 (mapcar (lambda (v) (push (cons :var (org-trim v)) results))
1505 (org-babel-join-splits-near-ch
1506 61 (org-babel-balanced-split (cdr pair) 32)))
1507 (push pair results)))
1508 header-arguments)
1509 (nreverse results)))
1511 (defun org-babel-process-params (params)
1512 "Expand variables in PARAMS and add summary parameters."
1513 (let* ((processed-vars (mapcar (lambda (el)
1514 (if (consp el)
1516 (org-babel-ref-parse el)))
1517 (org-babel--get-vars params)))
1518 (vars-and-names (if (and (assoc :colname-names params)
1519 (assoc :rowname-names params))
1520 (list processed-vars)
1521 (org-babel-disassemble-tables
1522 processed-vars
1523 (cdr (assoc :hlines params))
1524 (cdr (assoc :colnames params))
1525 (cdr (assoc :rownames params)))))
1526 (raw-result (or (cdr (assoc :results params)) ""))
1527 (result-params (delete-dups
1528 (append
1529 (split-string (if (stringp raw-result)
1530 raw-result
1531 (eval raw-result t)))
1532 (cdr (assoc :result-params params))))))
1533 (append
1534 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1535 (list
1536 (cons :colname-names (or (cdr (assoc :colname-names params))
1537 (cadr vars-and-names)))
1538 (cons :rowname-names (or (cdr (assq :rowname-names params))
1539 (cl-caddr vars-and-names)))
1540 (cons :result-params result-params)
1541 (cons :result-type (cond ((member "output" result-params) 'output)
1542 ((member "value" result-params) 'value)
1543 (t 'value))))
1544 (cl-remove-if
1545 (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params
1546 :result-type :var)))
1547 params))))
1549 ;; row and column names
1550 (defun org-babel-del-hlines (table)
1551 "Remove all `hline's from TABLE."
1552 (remq 'hline table))
1554 (defun org-babel-get-colnames (table)
1555 "Return the column names of TABLE.
1556 Return a cons cell, the `car' of which contains the TABLE less
1557 colnames, and the `cdr' of which contains a list of the column
1558 names."
1559 (if (equal 'hline (nth 1 table))
1560 (cons (cddr table) (car table))
1561 (cons (cdr table) (car table))))
1563 (defun org-babel-get-rownames (table)
1564 "Return the row names of TABLE.
1565 Return a cons cell, the `car' of which contains the TABLE less
1566 rownames, and the `cdr' of which contains a list of the rownames.
1567 Note: this function removes any hlines in TABLE."
1568 (let* ((table (org-babel-del-hlines table))
1569 (rownames (funcall (lambda ()
1570 (let ((tp table))
1571 (mapcar
1572 (lambda (_row)
1573 (prog1
1574 (pop (car tp))
1575 (setq tp (cdr tp))))
1576 table))))))
1577 (cons table rownames)))
1579 (defun org-babel-put-colnames (table colnames)
1580 "Add COLNAMES to TABLE if they exist."
1581 (if colnames (apply 'list colnames 'hline table) table))
1583 (defun org-babel-put-rownames (table rownames)
1584 "Add ROWNAMES to TABLE if they exist."
1585 (if rownames
1586 (mapcar (lambda (row)
1587 (if (listp row)
1588 (cons (or (pop rownames) "") row)
1589 row)) table)
1590 table))
1592 (defun org-babel-pick-name (names selector)
1593 "Select one out of an alist of row or column names.
1594 SELECTOR can be either a list of names in which case those names
1595 will be returned directly, or an index into the list NAMES in
1596 which case the indexed names will be return."
1597 (if (listp selector)
1598 selector
1599 (when names
1600 (if (and selector (symbolp selector) (not (equal t selector)))
1601 (cdr (assoc selector names))
1602 (if (integerp selector)
1603 (nth (- selector 1) names)
1604 (cdr (car (last names))))))))
1606 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1607 "Parse tables for further processing.
1608 Process the variables in VARS according to the HLINES,
1609 ROWNAMES and COLNAMES header arguments. Return a list consisting
1610 of the vars, cnames and rnames."
1611 (let (cnames rnames)
1612 (list
1613 (mapcar
1614 (lambda (var)
1615 (when (listp (cdr var))
1616 (when (and (not (equal colnames "no"))
1617 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1618 (not (member 'hline (cddr (cdr var)))))))
1619 (let ((both (org-babel-get-colnames (cdr var))))
1620 (setq cnames (cons (cons (car var) (cdr both))
1621 cnames))
1622 (setq var (cons (car var) (car both)))))
1623 (when (and rownames (not (equal rownames "no")))
1624 (let ((both (org-babel-get-rownames (cdr var))))
1625 (setq rnames (cons (cons (car var) (cdr both))
1626 rnames))
1627 (setq var (cons (car var) (car both)))))
1628 (when (and hlines (not (equal hlines "yes")))
1629 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1630 var)
1631 vars)
1632 (reverse cnames) (reverse rnames))))
1634 (defun org-babel-reassemble-table (table colnames rownames)
1635 "Add column and row names to a table.
1636 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1637 to the table for reinsertion to org-mode."
1638 (if (listp table)
1639 (let ((table (if (and rownames (= (length table) (length rownames)))
1640 (org-babel-put-rownames table rownames) table)))
1641 (if (and colnames (listp (car table)) (= (length (car table))
1642 (length colnames)))
1643 (org-babel-put-colnames table colnames) table))
1644 table))
1646 (defun org-babel-where-is-src-block-head (&optional src-block)
1647 "Find where the current source block begins.
1649 If optional argument SRC-BLOCK is `src-block' type element, find
1650 its current beginning instead.
1652 Return the point at the beginning of the current source block.
1653 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1654 match-data relatively to `org-babel-src-block-regexp', which see.
1655 If the point is not on a source block then return nil."
1656 (let ((element (or src-block (org-element-at-point))))
1657 (when (eq (org-element-type element) 'src-block)
1658 (let ((end (org-element-property :end element)))
1659 (org-with-wide-buffer
1660 ;; Ensure point is not on a blank line after the block.
1661 (beginning-of-line)
1662 (skip-chars-forward " \r\t\n" end)
1663 (when (< (point) end)
1664 (prog1 (goto-char (org-element-property :post-affiliated element))
1665 (looking-at org-babel-src-block-regexp))))))))
1667 ;;;###autoload
1668 (defun org-babel-goto-src-block-head ()
1669 "Go to the beginning of the current code block."
1670 (interactive)
1671 (let ((head (org-babel-where-is-src-block-head)))
1672 (if head (goto-char head) (error "Not currently in a code block"))))
1674 ;;;###autoload
1675 (defun org-babel-goto-named-src-block (name)
1676 "Go to a named source-code block."
1677 (interactive
1678 (let ((completion-ignore-case t)
1679 (case-fold-search t)
1680 (all-block-names (org-babel-src-block-names)))
1681 (list (completing-read
1682 "source-block name: " all-block-names nil t
1683 (let* ((context (org-element-context))
1684 (type (org-element-type context))
1685 (noweb-ref
1686 (and (memq type '(inline-src-block src-block))
1687 (org-in-regexp (org-babel-noweb-wrap)))))
1688 (cond
1689 (noweb-ref
1690 (buffer-substring
1691 (+ (car noweb-ref) (length org-babel-noweb-wrap-start))
1692 (- (cdr noweb-ref) (length org-babel-noweb-wrap-end))))
1693 ((memq type '(babel-call inline-babel-call)) ;#+CALL:
1694 (org-element-property :call context))
1695 ((car (org-element-property :results context))) ;#+RESULTS:
1696 ((let ((symbol (thing-at-point 'symbol))) ;Symbol.
1697 (and symbol
1698 (member-ignore-case symbol all-block-names)
1699 symbol)))
1700 (t "")))))))
1701 (let ((point (org-babel-find-named-block name)))
1702 (if point
1703 ;; Taken from `org-open-at-point'.
1704 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1705 (message "source-code block `%s' not found in this buffer" name))))
1707 (defun org-babel-find-named-block (name)
1708 "Find a named source-code block.
1709 Return the location of the source block identified by source
1710 NAME, or nil if no such block exists. Set match data according
1711 to `org-babel-named-src-block-regexp'."
1712 (save-excursion
1713 (goto-char (point-min))
1714 (ignore-errors
1715 (org-next-block 1 nil (org-babel-named-src-block-regexp-for-name name)))))
1717 (defun org-babel-src-block-names (&optional file)
1718 "Returns the names of source blocks in FILE or the current buffer."
1719 (when file (find-file file))
1720 (save-excursion
1721 (goto-char (point-min))
1722 (let ((re (org-babel-named-src-block-regexp-for-name))
1723 names)
1724 (while (ignore-errors (org-next-block 1 nil re))
1725 (push (match-string-no-properties 9) names))
1726 names)))
1728 ;;;###autoload
1729 (defun org-babel-goto-named-result (name)
1730 "Go to a named result."
1731 (interactive
1732 (let ((completion-ignore-case t))
1733 (list (completing-read "Source-block name: "
1734 (org-babel-result-names) nil t))))
1735 (let ((point (org-babel-find-named-result name)))
1736 (if point
1737 ;; taken from `org-open-at-point'
1738 (progn (goto-char point) (org-show-context))
1739 (message "result `%s' not found in this buffer" name))))
1741 (defun org-babel-find-named-result (name)
1742 "Find a named result.
1743 Return the location of the result named NAME in the current
1744 buffer or nil if no such result exists."
1745 (save-excursion
1746 (goto-char (point-min))
1747 (let ((case-fold-search t)
1748 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1749 org-babel-results-keyword
1750 (regexp-quote name))))
1751 (catch :found
1752 (while (re-search-forward re nil t)
1753 (let ((element (org-element-at-point)))
1754 (when (or (eq (org-element-type element) 'keyword)
1755 (< (point)
1756 (org-element-property :post-affiliated element)))
1757 (throw :found (line-beginning-position)))))))))
1759 (defun org-babel-result-names (&optional file)
1760 "Returns the names of results in FILE or the current buffer."
1761 (save-excursion
1762 (when file (find-file file)) (goto-char (point-min))
1763 (let ((case-fold-search t) names)
1764 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1765 (setq names (cons (match-string-no-properties 9) names)))
1766 names)))
1768 ;;;###autoload
1769 (defun org-babel-next-src-block (&optional arg)
1770 "Jump to the next source block.
1771 With optional prefix argument ARG, jump forward ARG many source blocks."
1772 (interactive "p")
1773 (org-next-block arg nil org-babel-src-block-regexp))
1775 ;;;###autoload
1776 (defun org-babel-previous-src-block (&optional arg)
1777 "Jump to the previous source block.
1778 With optional prefix argument ARG, jump backward ARG many source blocks."
1779 (interactive "p")
1780 (org-previous-block arg org-babel-src-block-regexp))
1782 (defvar org-babel-load-languages)
1784 ;;;###autoload
1785 (defun org-babel-mark-block ()
1786 "Mark current src block."
1787 (interactive)
1788 (let ((head (org-babel-where-is-src-block-head)))
1789 (when head
1790 (save-excursion
1791 (goto-char head)
1792 (looking-at org-babel-src-block-regexp))
1793 (push-mark (match-end 5) nil t)
1794 (goto-char (match-beginning 5)))))
1796 (defun org-babel-demarcate-block (&optional arg)
1797 "Wrap or split the code in the region or on the point.
1798 When called from inside of a code block the current block is
1799 split. When called from outside of a code block a new code block
1800 is created. In both cases if the region is demarcated and if the
1801 region is not active then the point is demarcated."
1802 (interactive "P")
1803 (let* ((info (org-babel-get-src-block-info 'light))
1804 (start (org-babel-where-is-src-block-head))
1805 (block (and start (match-string 0)))
1806 (headers (and start (match-string 4)))
1807 (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
1808 (lower-case-p (and block
1809 (let (case-fold-search)
1810 (string-match-p "#\\+begin_src" block)))))
1811 (if info
1812 (mapc
1813 (lambda (place)
1814 (save-excursion
1815 (goto-char place)
1816 (let ((lang (nth 0 info))
1817 (indent (make-string (org-get-indentation) ?\s)))
1818 (when (string-match "^[[:space:]]*$"
1819 (buffer-substring (point-at-bol)
1820 (point-at-eol)))
1821 (delete-region (point-at-bol) (point-at-eol)))
1822 (insert (concat
1823 (if (looking-at "^") "" "\n")
1824 indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")
1825 (if arg stars indent) "\n"
1826 indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1827 lang
1828 (if (> (length headers) 1)
1829 (concat " " headers) headers)
1830 (if (looking-at "[\n\r]")
1832 (concat "\n" (make-string (current-column) ? )))))))
1833 (move-end-of-line 2))
1834 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1835 (let ((start (point))
1836 (lang (completing-read
1837 "Lang: "
1838 (mapcar #'symbol-name
1839 (delete-dups
1840 (append (mapcar #'car org-babel-load-languages)
1841 (mapcar (lambda (el) (intern (car el)))
1842 org-src-lang-modes))))))
1843 (body (delete-and-extract-region
1844 (if (org-region-active-p) (mark) (point)) (point))))
1845 (insert (concat (if (looking-at "^") "" "\n")
1846 (if arg (concat stars "\n") "")
1847 (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1848 lang "\n"
1849 body
1850 (if (or (= (length body) 0)
1851 (string-suffix-p "\r" body)
1852 (string-suffix-p "\n" body)) "" "\n")
1853 (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")))
1854 (goto-char start) (move-end-of-line 1)))))
1856 (defun org-babel--insert-results-keyword (name hash)
1857 "Insert RESULTS keyword with NAME value at point.
1858 If NAME is nil, results are anonymous. HASH is a string used as
1859 the results hash, or nil. Leave point before the keyword."
1860 (save-excursion (insert "\n")) ;open line to indent.
1861 (org-indent-line)
1862 (delete-char 1)
1863 (insert (concat "#+" org-babel-results-keyword
1864 (cond ((not hash) nil)
1865 (org-babel-hash-show-time
1866 (format "[%s %s]"
1867 (format-time-string "<%Y-%m-%d %H:%M:%S>")
1868 hash))
1869 (t (format "[%s]" hash)))
1871 (when name (concat " " name))
1872 "\n\n"))
1873 (beginning-of-line -1)
1874 (when hash (org-babel-hide-hash)))
1876 (defun org-babel--clear-results-maybe (hash)
1877 "Clear results when hash doesn't match HASH.
1879 When results hash does not match HASH, remove RESULTS keyword at
1880 point, along with related contents. Do nothing if HASH is nil.
1882 Return a non-nil value if results were cleared. In this case,
1883 leave point where new results should be inserted."
1884 (when hash
1885 (looking-at org-babel-result-regexp)
1886 (unless (string= (match-string 1) hash)
1887 (let* ((e (org-element-at-point))
1888 (post (copy-marker (org-element-property :post-affiliated e))))
1889 ;; Delete contents.
1890 (delete-region post
1891 (save-excursion
1892 (goto-char (org-element-property :end e))
1893 (skip-chars-backward " \t\n")
1894 (line-beginning-position 2)))
1895 ;; Delete RESULT keyword. However, if RESULTS keyword is
1896 ;; orphaned, ignore this part. The deletion above already
1897 ;; took care of it.
1898 (unless (= (point) post)
1899 (delete-region (line-beginning-position)
1900 (line-beginning-position 2)))
1901 (goto-char post)
1902 (set-marker post nil)))
1905 (defun org-babel-where-is-src-block-result (&optional insert _info hash)
1906 "Find where the current source block results begin.
1908 Return the point at the beginning of the result of the current
1909 source block, specifically at the beginning of the results line.
1911 If no result exists for this block return nil, unless optional
1912 argument INSERT is non-nil. In this case, create a results line
1913 following the source block and return the position at its
1914 beginning. In the case of inline code, remove the results part
1915 instead.
1917 If optional argument HASH is a string, remove contents related to
1918 RESULTS keyword if its hash is different. Then update the latter
1919 to HASH."
1920 (let ((context (org-element-context)))
1921 (catch :found
1922 (org-with-wide-buffer
1923 (pcase (org-element-type context)
1924 ((or `inline-babel-call `inline-src-block)
1925 ;; Results for inline objects are located right after them.
1926 ;; There is no RESULTS line to insert either.
1927 (let ((limit (org-element-property
1928 :contents-end (org-element-property :parent context))))
1929 (goto-char (org-element-property :end context))
1930 (skip-chars-forward " \t\n" limit)
1931 (throw :found
1932 (and
1933 (< (point) limit)
1934 (let ((result (org-element-context)))
1935 (and (eq (org-element-type result) 'macro)
1936 (string= (org-element-property :key result)
1937 "results")
1938 (if (not insert) (point)
1939 (delete-region
1940 (point)
1941 (progn
1942 (goto-char (org-element-property :end result))
1943 (skip-chars-backward " \t")
1944 (point)))
1945 (point))))))))
1946 ((or `babel-call `src-block)
1947 (let* ((name (org-element-property :name context))
1948 (named-results (and name (org-babel-find-named-result name))))
1949 (goto-char (or named-results (org-element-property :end context)))
1950 (cond
1951 ;; Existing results named after the current source.
1952 (named-results
1953 (when (org-babel--clear-results-maybe hash)
1954 (org-babel--insert-results-keyword name hash))
1955 (throw :found (point)))
1956 ;; Named results expect but none to be found.
1957 (name)
1958 ;; No possible anonymous results at the very end of
1959 ;; buffer or outside CONTEXT parent.
1960 ((eq (point)
1961 (or (org-element-property
1962 :contents-end (org-element-property :parent context))
1963 (point-max))))
1964 ;; Check if next element is an anonymous result below
1965 ;; the current block.
1966 ((let* ((next (org-element-at-point))
1967 (end (save-excursion
1968 (goto-char
1969 (org-element-property :post-affiliated next))
1970 (line-end-position)))
1971 (empty-result-re (concat org-babel-result-regexp "$"))
1972 (case-fold-search t))
1973 (re-search-forward empty-result-re end t))
1974 (beginning-of-line)
1975 (when (org-babel--clear-results-maybe hash)
1976 (org-babel--insert-results-keyword nil hash))
1977 (throw :found (point))))))
1978 ;; Ignore other elements.
1979 (_ (throw :found nil))))
1980 ;; No result found. Insert a RESULTS keyword below element, if
1981 ;; appropriate. In this case, ensure there is an empty line
1982 ;; after the previous element.
1983 (when insert
1984 (save-excursion
1985 (goto-char (min (org-element-property :end context) (point-max)))
1986 (skip-chars-backward " \t\n")
1987 (forward-line)
1988 (cond ((not (bolp)) (insert "\n\n"))
1989 ((or (eobp)
1990 (= (org-element-property :post-blank context) 0))
1991 (insert "\n"))
1992 (t (forward-line)))
1993 (org-babel--insert-results-keyword
1994 (org-element-property :name context) hash)
1995 (point))))))
1997 (defun org-babel-read-element (element)
1998 "Read ELEMENT into emacs-lisp.
1999 Return nil if ELEMENT cannot be read."
2000 (org-with-wide-buffer
2001 (goto-char (org-element-property :post-affiliated element))
2002 (pcase (org-element-type element)
2003 (`fixed-width
2004 (let ((v (org-trim (org-element-property :value element))))
2005 (or (org-babel--string-to-number v) v)))
2006 (`table (org-babel-read-table))
2007 (`plain-list (org-babel-read-list))
2008 (`example-block
2009 (let ((v (org-element-property :value element)))
2010 (if (or org-src-preserve-indentation
2011 (org-element-property :preserve-indent element))
2013 (org-remove-indentation v))))
2014 (`export-block
2015 (org-remove-indentation (org-element-property :value element)))
2016 (`paragraph
2017 ;; Treat paragraphs containing a single link specially.
2018 (skip-chars-forward " \t")
2019 (if (and (looking-at org-bracket-link-regexp)
2020 (save-excursion
2021 (goto-char (match-end 0))
2022 (skip-chars-forward " \r\t\n")
2023 (<= (org-element-property :end element)
2024 (point))))
2025 (org-babel-read-link)
2026 (buffer-substring-no-properties
2027 (org-element-property :contents-begin element)
2028 (org-element-property :contents-end element))))
2029 ((or `center-block `quote-block `verse-block `special-block)
2030 (org-remove-indentation
2031 (buffer-substring-no-properties
2032 (org-element-property :contents-begin element)
2033 (org-element-property :contents-end element))))
2034 (_ nil))))
2036 (defun org-babel-read-result ()
2037 "Read the result at point into emacs-lisp."
2038 (and (not (save-excursion
2039 (beginning-of-line)
2040 (looking-at-p "[ \t]*$")))
2041 (org-babel-read-element (org-element-at-point))))
2043 (defun org-babel-read-table ()
2044 "Read the table at point into emacs-lisp."
2045 (mapcar (lambda (row)
2046 (if (and (symbolp row) (equal row 'hline)) row
2047 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
2048 (org-table-to-lisp)))
2050 (defun org-babel-read-list ()
2051 "Read the list at point into emacs-lisp."
2052 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2053 (cdr (org-list-to-lisp))))
2055 (defvar org-link-types-re)
2056 (defun org-babel-read-link ()
2057 "Read the link at point into emacs-lisp.
2058 If the path of the link is a file path it is expanded using
2059 `expand-file-name'."
2060 (let* ((case-fold-search t)
2061 (raw (and (looking-at org-bracket-link-regexp)
2062 (org-no-properties (match-string 1))))
2063 (type (and (string-match org-link-types-re raw)
2064 (match-string 1 raw))))
2065 (cond
2066 ((not type) (expand-file-name raw))
2067 ((string= type "file")
2068 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
2069 (expand-file-name (match-string 2 raw))))
2070 (t raw))))
2072 (defun org-babel-format-result (result &optional sep)
2073 "Format RESULT for writing to file."
2074 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
2075 (if (listp result)
2076 ;; table result
2077 (orgtbl-to-generic
2078 result (list :sep (or sep "\t") :fmt echo-res))
2079 ;; scalar result
2080 (funcall echo-res result))))
2082 (defun org-babel-insert-result (result &optional result-params info hash lang)
2083 "Insert RESULT into the current buffer.
2085 By default RESULT is inserted after the end of the current source
2086 block. The RESULT of an inline source block usually will be
2087 wrapped inside a `results' macro and placed on the same line as
2088 the inline source block. The macro is stripped upon export.
2089 Multiline and non-scalar RESULTS from inline source blocks are
2090 not allowed. With optional argument RESULT-PARAMS controls
2091 insertion of results in the Org mode file. RESULT-PARAMS can
2092 take the following values:
2094 replace - (default option) insert results after the source block
2095 or inline source block replacing any previously
2096 inserted results.
2098 silent -- no results are inserted into the Org buffer but
2099 the results are echoed to the minibuffer and are
2100 ingested by Emacs (a potentially time consuming
2101 process).
2103 file ---- the results are interpreted as a file path, and are
2104 inserted into the buffer using the Org file syntax.
2106 list ---- the results are interpreted as an Org list.
2108 raw ----- results are added directly to the Org file. This is
2109 a good option if you code block will output Org
2110 formatted text.
2112 drawer -- results are added directly to the Org file as with
2113 \"raw\", but are wrapped in a RESULTS drawer or results
2114 macro, allowing them to later be replaced or removed
2115 automatically.
2117 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2118 org\" block depending on whether the current source block is
2119 inline or not. They are not comma-escaped when inserted,
2120 but Org syntax here will be discarded when exporting the
2121 file.
2123 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2124 or html export snippet depending on whether the current
2125 source block is inline or not. This is a good option
2126 if your code block will output html formatted text.
2128 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2129 block or latex export snippet depending on whether the
2130 current source block is inline or not. This is a good
2131 option if your code block will output latex formatted
2132 text.
2134 code ---- the results are extracted in the syntax of the source
2135 code of the language being evaluated and are added
2136 inside of a source block with the source-code language
2137 set appropriately. Also, source block inlining is
2138 preserved in this case. Note this relies on the
2139 optional LANG argument.
2141 list ---- the results are rendered as a list. This option not
2142 allowed for inline src blocks.
2144 table --- the results are rendered as a table. This option not
2145 allowed for inline src blocks.
2147 INFO may provide the values of these header arguments (in the
2148 `header-arguments-alist' see the docstring for
2149 `org-babel-get-src-block-info'):
2151 :file --- the name of the file to which output should be written.
2153 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2154 using the argument supplied to specify the export block
2155 or snippet type."
2156 (cond ((stringp result)
2157 (setq result (org-no-properties result))
2158 (when (member "file" result-params)
2159 (setq result (org-babel-result-to-file
2160 result (when (assoc :file-desc (nth 2 info))
2161 (or (cdr (assoc :file-desc (nth 2 info)))
2162 result))))))
2163 ((listp result))
2164 (t (setq result (format "%S" result))))
2165 (if (and result-params (member "silent" result-params))
2166 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2167 result)
2168 (let ((inline (let ((context (org-element-context)))
2169 (and (memq (org-element-type context)
2170 '(inline-babel-call inline-src-block))
2171 context))))
2172 (when inline
2173 (let ((warning
2174 (or (and (member "table" result-params) "`:results table'")
2175 (and (listp result) "list result")
2176 (and (string-match-p "\n." result) "multiline result")
2177 (and (member "list" result-params) "`:results list'"))))
2178 (when warning
2179 (user-error "Inline error: %s cannot be used" warning))))
2180 (save-excursion
2181 (let* ((visible-beg (point-min-marker))
2182 (visible-end (copy-marker (point-max) t))
2183 (inline (let ((context (org-element-context)))
2184 (and (memq (org-element-type context)
2185 '(inline-babel-call inline-src-block))
2186 context)))
2187 (existing-result (org-babel-where-is-src-block-result t nil hash))
2188 (results-switches (cdr (assq :results_switches (nth 2 info))))
2189 ;; When results exist outside of the current visible
2190 ;; region of the buffer, be sure to widen buffer to
2191 ;; update them.
2192 (outside-scope (and existing-result
2193 (buffer-narrowed-p)
2194 (or (> visible-beg existing-result)
2195 (<= visible-end existing-result))))
2196 beg end indent)
2197 ;; Ensure non-inline results end in a newline.
2198 (when (and (org-string-nw-p result)
2199 (not inline)
2200 (not (string-equal (substring result -1) "\n")))
2201 (setq result (concat result "\n")))
2202 (unwind-protect
2203 (progn
2204 (when outside-scope (widen))
2205 (if existing-result (goto-char existing-result)
2206 (goto-char (org-element-property :end inline))
2207 (skip-chars-backward " \t"))
2208 (unless inline
2209 (setq indent (org-get-indentation))
2210 (forward-line 1))
2211 (setq beg (point))
2212 (cond
2213 (inline
2214 ;; Make sure new results are separated from the
2215 ;; source code by one space.
2216 (unless existing-result
2217 (insert " ")
2218 (setq beg (point))))
2219 ((member "replace" result-params)
2220 (delete-region (point) (org-babel-result-end)))
2221 ((member "append" result-params)
2222 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2223 ((member "prepend" result-params))) ; already there
2224 (setq results-switches
2225 (if results-switches (concat " " results-switches) ""))
2226 (let ((wrap (lambda (start finish &optional no-escape no-newlines
2227 inline-start inline-finish)
2228 (when inline
2229 (setq start inline-start)
2230 (setq finish inline-finish)
2231 (setq no-newlines t))
2232 (goto-char end)
2233 (insert (concat finish (unless no-newlines "\n")))
2234 (goto-char beg)
2235 (insert (concat start (unless no-newlines "\n")))
2236 (unless no-escape
2237 (org-escape-code-in-region (min (point) end) end))
2238 (goto-char end)
2239 (unless no-newlines (goto-char (point-at-eol)))
2240 (setq end (point-marker))))
2241 (tabulablep
2242 (lambda (r)
2243 ;; Non-nil when result R can be turned into
2244 ;; a table.
2245 (and (listp r)
2246 (null (cdr (last r)))
2247 (cl-every
2248 (lambda (e) (or (atom e) (null (cdr (last e)))))
2249 result)))))
2250 ;; insert results based on type
2251 (cond
2252 ;; Do nothing for an empty result.
2253 ((null result))
2254 ;; Insert a list if preferred.
2255 ((member "list" result-params)
2256 (insert
2257 (org-trim
2258 (org-list-to-generic
2259 (cons 'unordered
2260 (mapcar
2261 (lambda (e)
2262 (list (if (stringp e) e (format "%S" e))))
2263 (if (listp result) result
2264 (split-string result "\n" t))))
2265 '(:splicep nil :istart "- " :iend "\n")))
2266 "\n"))
2267 ;; Try hard to print RESULT as a table. Give up if
2268 ;; it contains an improper list.
2269 ((funcall tabulablep result)
2270 (goto-char beg)
2271 (insert (concat (orgtbl-to-orgtbl
2272 (if (cl-every
2273 (lambda (e)
2274 (or (eq e 'hline) (listp e)))
2275 result)
2276 result
2277 (list result))
2278 nil)
2279 "\n"))
2280 (goto-char beg)
2281 (when (org-at-table-p) (org-table-align))
2282 (goto-char (org-table-end)))
2283 ;; Print verbatim a list that cannot be turned into
2284 ;; a table.
2285 ((listp result) (insert (format "%s\n" result)))
2286 ((member "file" result-params)
2287 (when inline
2288 (setq result (org-macro-escape-arguments result)))
2289 (insert result))
2290 ((and inline (not (member "raw" result-params)))
2291 (insert (org-macro-escape-arguments
2292 (org-babel-chomp result "\n"))))
2293 (t (goto-char beg) (insert result)))
2294 (setq end (point-marker))
2295 ;; possibly wrap result
2296 (cond
2297 ((assoc :wrap (nth 2 info))
2298 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2299 (funcall wrap (concat "#+BEGIN_" name)
2300 (concat "#+END_" (car (org-split-string name)))
2301 nil nil (concat "{{{results(@@" name ":") "@@)}}}")))
2302 ((member "html" result-params)
2303 (funcall wrap "#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2304 "{{{results(@@html:" "@@)}}}"))
2305 ((member "latex" result-params)
2306 (funcall wrap "#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2307 "{{{results(@@latex:" "@@)}}}"))
2308 ((member "org" result-params)
2309 (goto-char beg) (when (org-at-table-p) (org-cycle))
2310 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC" nil nil
2311 "{{{results(src_org{" "})}}}"))
2312 ((member "code" result-params)
2313 (let ((lang (or lang "none")))
2314 (funcall wrap (format "#+BEGIN_SRC %s%s" lang results-switches)
2315 "#+END_SRC" nil nil
2316 (format "{{{results(src_%s[%s]{" lang results-switches)
2317 "})}}}")))
2318 ((member "raw" result-params)
2319 (goto-char beg) (when (org-at-table-p) (org-cycle)))
2320 ((or (member "drawer" result-params)
2321 ;; Stay backward compatible with <7.9.2
2322 (member "wrap" result-params))
2323 (goto-char beg) (when (org-at-table-p) (org-cycle))
2324 (funcall wrap ":RESULTS:" ":END:" 'no-escape nil
2325 "{{{results(" ")}}}"))
2326 ((and inline (member "file" result-params))
2327 (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
2328 ((and (not (funcall tabulablep result))
2329 (not (member "file" result-params)))
2330 (let ((org-babel-inline-result-wrap
2331 ;; Hard code {{{results(...)}}} on top of customization.
2332 (format "{{{results(%s)}}}"
2333 org-babel-inline-result-wrap)))
2334 (org-babel-examplify-region beg end results-switches inline)
2335 (setq end (point))))))
2336 ;; Possibly indent results in par with #+results line.
2337 (when (and (not inline) (numberp indent) (> indent 0)
2338 ;; In this case `table-align' does the work
2339 ;; for us.
2340 (not (and (listp result)
2341 (member "append" result-params))))
2342 (indent-rigidly beg end indent))
2343 (if (null result)
2344 (if (member "value" result-params)
2345 (message "Code block returned no value.")
2346 (message "Code block produced no output."))
2347 (message "Code block evaluation complete.")))
2348 (when outside-scope (narrow-to-region visible-beg visible-end))
2349 (set-marker visible-beg nil)
2350 (set-marker visible-end nil)))))))
2352 (defun org-babel-remove-result (&optional info keep-keyword)
2353 "Remove the result of the current source block."
2354 (interactive)
2355 (let ((location (org-babel-where-is-src-block-result nil info)))
2356 (when location
2357 (save-excursion
2358 (goto-char location)
2359 (when (looking-at (concat org-babel-result-regexp ".*$"))
2360 (delete-region
2361 (if keep-keyword (1+ (match-end 0)) (1- (match-beginning 0)))
2362 (progn (forward-line 1) (org-babel-result-end))))))))
2364 (defun org-babel-remove-inline-result (&optional datum)
2365 "Remove the result of the current inline-src-block or babel call.
2366 The result must be wrapped in a `results' macro to be removed.
2367 Leading white space is trimmed."
2368 (interactive)
2369 (let* ((el (or datum (org-element-context))))
2370 (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
2371 (org-with-wide-buffer
2372 (goto-char (org-element-property :end el))
2373 (skip-chars-backward " \t")
2374 (let ((result (save-excursion
2375 (skip-chars-forward
2376 " \t\n"
2377 (org-element-property
2378 :contents-end (org-element-property :parent el)))
2379 (org-element-context))))
2380 (when (and (eq (org-element-type result) 'macro)
2381 (string= (org-element-property :key result) "results"))
2382 (delete-region ; And leading whitespace.
2383 (point)
2384 (progn (goto-char (org-element-property :end result))
2385 (skip-chars-backward " \t\n")
2386 (point)))))))))
2388 (defun org-babel-remove-result-one-or-many (x)
2389 "Remove the result of the current source block.
2390 If called with a prefix argument, remove all result blocks
2391 in the buffer."
2392 (interactive "P")
2393 (if x
2394 (org-babel-map-src-blocks nil (org-babel-remove-result))
2395 (org-babel-remove-result)))
2397 (defun org-babel-result-end ()
2398 "Return the point at the end of the current set of results."
2399 (save-excursion
2400 (cond
2401 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2402 ((org-at-item-p) (let* ((struct (org-list-struct))
2403 (prvs (org-list-prevs-alist struct)))
2404 (org-list-get-list-end (point-at-bol) struct prvs)))
2405 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2406 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2407 (forward-char 1) (point)))
2409 (let ((case-fold-search t))
2410 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2411 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2412 nil t)
2413 (forward-char 1))
2414 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2415 (forward-line 1))))
2416 (point)))))
2418 (defun org-babel-result-to-file (result &optional description)
2419 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2420 If the `default-directory' is different from the containing
2421 file's directory then expand relative links."
2422 (when (stringp result)
2423 (format "[[file:%s]%s]"
2424 (if (and default-directory
2425 buffer-file-name
2426 (not (string= (expand-file-name default-directory)
2427 (expand-file-name
2428 (file-name-directory buffer-file-name)))))
2429 (expand-file-name result default-directory)
2430 result)
2431 (if description (concat "[" description "]") ""))))
2433 (defvar org-babel-capitalize-example-region-markers nil
2434 "Make true to capitalize begin/end example markers inserted by code blocks.")
2436 (defun org-babel-examplify-region (beg end &optional results-switches inline)
2437 "Comment out region using the inline `==' or `: ' org example quote."
2438 (interactive "*r")
2439 (let ((maybe-cap
2440 (lambda (str)
2441 (if org-babel-capitalize-example-region-markers (upcase str) str))))
2442 (if inline
2443 (save-excursion
2444 (goto-char beg)
2445 (insert (format org-babel-inline-result-wrap
2446 (delete-and-extract-region beg end))))
2447 (let ((size (count-lines beg end)))
2448 (save-excursion
2449 (cond ((= size 0)) ; do nothing for an empty result
2450 ((< size org-babel-min-lines-for-block-output)
2451 (goto-char beg)
2452 (dotimes (_ size)
2453 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2455 (goto-char beg)
2456 (insert (if results-switches
2457 (format "%s%s\n"
2458 (funcall maybe-cap "#+begin_example")
2459 results-switches)
2460 (funcall maybe-cap "#+begin_example\n")))
2461 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2462 (insert (funcall maybe-cap "#+end_example\n")))))))))
2464 (defun org-babel-update-block-body (new-body)
2465 "Update the body of the current code block to NEW-BODY."
2466 (let ((element (org-element-at-point)))
2467 (unless (eq (org-element-type element) 'src-block)
2468 (error "Not in a source block"))
2469 (goto-char (org-babel-where-is-src-block-head element))
2470 (let* ((ind (org-get-indentation))
2471 (body-start (line-beginning-position 2))
2472 (body (org-element-normalize-string
2473 (if (or org-src-preserve-indentation
2474 (org-element-property :preserve-indent element))
2475 new-body
2476 (with-temp-buffer
2477 (insert (org-remove-indentation new-body))
2478 (indent-rigidly
2479 (point-min)
2480 (point-max)
2481 (+ ind org-edit-src-content-indentation))
2482 (buffer-string))))))
2483 (delete-region body-start
2484 (org-with-wide-buffer
2485 (goto-char (org-element-property :end element))
2486 (skip-chars-backward " \t\n")
2487 (line-beginning-position)))
2488 (goto-char body-start)
2489 (insert body))))
2491 (defun org-babel-merge-params (&rest plists)
2492 "Combine all parameter association lists in PLISTS.
2493 Later elements of PLISTS override the values of previous elements.
2494 This takes into account some special considerations for certain
2495 parameters when merging lists."
2496 (let* ((results-exclusive-groups
2497 (mapcar (lambda (group) (mapcar #'symbol-name group))
2498 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2499 (exports-exclusive-groups
2500 (mapcar (lambda (group) (mapcar #'symbol-name group))
2501 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2502 (merge
2503 (lambda (exclusive-groups &rest result-params)
2504 ;; Maintain exclusivity of mutually exclusive parameters,
2505 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2506 ;; RESULT-PARAMS.
2507 (let (output)
2508 (dolist (new-params result-params (delete-dups output))
2509 (dolist (new-param new-params)
2510 (dolist (exclusive-group exclusive-groups)
2511 (when (member new-param exclusive-group)
2512 (setq output (cl-remove-if
2513 (lambda (o) (member o exclusive-group))
2514 output))))
2515 (push new-param output))))))
2516 (variable-index 0) ;Handle positional arguments.
2517 clearnames
2518 params ;Final parameters list.
2519 ;; Some keywords accept multiple values. We need to treat
2520 ;; them specially.
2521 vars results exports)
2522 (dolist (plist plists)
2523 (dolist (pair plist)
2524 (pcase pair
2525 (`(:var . ,value)
2526 (let ((name (cond
2527 ((listp value) (car value))
2528 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
2529 (intern (match-string 1 value)))
2530 (t nil))))
2531 (cond
2532 (name
2533 (setq vars
2534 (append (if (not (assoc name vars)) vars
2535 (push name clearnames)
2536 (cl-remove-if (lambda (p) (equal name (car p)))
2537 vars))
2538 (list (cons name pair)))))
2539 ((and vars (nth variable-index vars))
2540 ;; If no name is given and we already have named
2541 ;; variables then assign to named variables in order.
2542 (let ((name (car (nth variable-index vars))))
2543 ;; Clear out colnames and rownames for replace vars.
2544 (push name clearnames)
2545 (setf (cddr (nth variable-index vars))
2546 (concat (symbol-name name) "=" value))
2547 (cl-incf variable-index)))
2548 (t (error "Variable \"%s\" must be assigned a default value"
2549 (cdr pair))))))
2550 (`(:results . ,value)
2551 (setq results (funcall merge
2552 results-exclusive-groups
2553 results
2554 (split-string
2555 (if (stringp value) value (eval value t))))))
2556 (`(,(or :file :file-ext) . ,value)
2557 ;; `:file' and `:file-ext' are regular keywords but they
2558 ;; imply a "file" `:results' and a "results" `:exports'.
2559 (when value
2560 (setq results
2561 (funcall merge results-exclusive-groups results '("file")))
2562 (unless (or (member "both" exports)
2563 (member "none" exports)
2564 (member "code" exports))
2565 (setq exports
2566 (funcall merge
2567 exports-exclusive-groups exports '("results"))))
2568 (push pair params)))
2569 (`(:exports . ,value)
2570 (setq exports (funcall merge
2571 exports-exclusive-groups
2572 exports
2573 (split-string (or value "")))))
2574 ;; Regular keywords: any value overwrites the previous one.
2575 (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
2576 ;; Handle `:var' and clear out colnames and rownames for replaced
2577 ;; variables.
2578 (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars)
2579 params))
2580 (dolist (name clearnames)
2581 (dolist (param '(:colname-names :rowname-names))
2582 (when (assq param params)
2583 (setf (cdr (assq param params))
2584 (cl-remove-if (lambda (pair) (equal name (car pair)))
2585 (cdr (assq param params))))
2586 (setq params
2587 (cl-remove-if (lambda (pair) (and (equal (car pair) param)
2588 (null (cdr pair))))
2589 params)))))
2590 ;; Handle other special keywords, which accept multiple values.
2591 (setq params (nconc (list (cons :results (mapconcat #'identity results " "))
2592 (cons :exports (mapconcat #'identity exports " ")))
2593 params))
2594 ;; Return merged params.
2595 params))
2597 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2598 "Set to true to use regular expressions to expand noweb references.
2599 This results in much faster noweb reference expansion but does
2600 not properly allow code blocks to inherit the \":noweb-ref\"
2601 header argument from buffer or subtree wide properties.")
2603 (defun org-babel-noweb-p (params context)
2604 "Check if PARAMS require expansion in CONTEXT.
2605 CONTEXT may be one of :tangle, :export or :eval."
2606 (let ((allowed-values (cl-case context
2607 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2608 (:eval '("yes" "no-export" "strip-export" "eval"))
2609 (:export '("yes")))))
2610 (cl-some (lambda (v) (member v allowed-values))
2611 (split-string (or (cdr (assq :noweb params)) "")))))
2613 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2614 "Expand Noweb references in the body of the current source code block.
2616 For example the following reference would be replaced with the
2617 body of the source-code block named `example-block'.
2619 <<example-block>>
2621 Note that any text preceding the <<foo>> construct on a line will
2622 be interposed between the lines of the replacement text. So for
2623 example if <<foo>> is placed behind a comment, then the entire
2624 replacement text will also be commented.
2626 This function must be called from inside of the buffer containing
2627 the source-code block which holds BODY.
2629 In addition the following syntax can be used to insert the
2630 results of evaluating the source-code block named `example-block'.
2632 <<example-block()>>
2634 Any optional arguments can be passed to example-block by placing
2635 the arguments inside the parenthesis following the convention
2636 defined by `org-babel-lob'. For example
2638 <<example-block(a=9)>>
2640 would set the value of argument \"a\" equal to \"9\". Note that
2641 these arguments are not evaluated in the current source-code
2642 block but are passed literally to the \"example-block\"."
2643 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2644 (info (or info (org-babel-get-src-block-info 'light)))
2645 (lang (nth 0 info))
2646 (body (nth 1 info))
2647 (ob-nww-start org-babel-noweb-wrap-start)
2648 (ob-nww-end org-babel-noweb-wrap-end)
2649 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2650 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2651 ":noweb-ref[ \t]+" "\\)"))
2652 (new-body "")
2653 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2654 (c-wrap (lambda (text)
2655 (with-temp-buffer
2656 (funcall (intern (concat lang "-mode")))
2657 (comment-region (point) (progn (insert text) (point)))
2658 (org-trim (buffer-string)))))
2659 index source-name evaluate prefix)
2660 (with-temp-buffer
2661 (setq-local org-babel-noweb-wrap-start ob-nww-start)
2662 (setq-local org-babel-noweb-wrap-end ob-nww-end)
2663 (insert body) (goto-char (point-min))
2664 (setq index (point))
2665 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2666 (save-match-data (setf source-name (match-string 1)))
2667 (save-match-data (setq evaluate (string-match "(.*)" source-name)))
2668 (save-match-data
2669 (setq prefix
2670 (buffer-substring (match-beginning 0)
2671 (save-excursion
2672 (beginning-of-line 1) (point)))))
2673 ;; add interval to new-body (removing noweb reference)
2674 (goto-char (match-beginning 0))
2675 (funcall nb-add (buffer-substring index (point)))
2676 (goto-char (match-end 0))
2677 (setq index (point))
2678 (funcall
2679 nb-add
2680 (with-current-buffer parent-buffer
2681 (save-restriction
2682 (widen)
2683 (mapconcat ;; Interpose PREFIX between every line.
2684 #'identity
2685 (split-string
2686 (if evaluate
2687 (let ((raw (org-babel-ref-resolve source-name)))
2688 (if (stringp raw) raw (format "%S" raw)))
2690 ;; Retrieve from the library of babel.
2691 (nth 2 (assoc (intern source-name)
2692 org-babel-library-of-babel))
2693 ;; Return the contents of headlines literally.
2694 (save-excursion
2695 (when (org-babel-ref-goto-headline-id source-name)
2696 (org-babel-ref-headline-body)))
2697 ;; Find the expansion of reference in this buffer.
2698 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2699 expansion)
2700 (save-excursion
2701 (goto-char (point-min))
2702 (if org-babel-use-quick-and-dirty-noweb-expansion
2703 (while (re-search-forward rx nil t)
2704 (let* ((i (org-babel-get-src-block-info 'light))
2705 (body (org-babel-expand-noweb-references i))
2706 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2707 "\n"))
2708 (full (if comment
2709 (let ((cs (org-babel-tangle-comment-links i)))
2710 (concat (funcall c-wrap (car cs)) "\n"
2711 body "\n"
2712 (funcall c-wrap (cadr cs))))
2713 body)))
2714 (setq expansion (cons sep (cons full expansion)))))
2715 (org-babel-map-src-blocks nil
2716 (let ((i (org-babel-get-src-block-info 'light)))
2717 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2718 (nth 4 i))
2719 source-name)
2720 (let* ((body (org-babel-expand-noweb-references i))
2721 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2722 "\n"))
2723 (full (if comment
2724 (let ((cs (org-babel-tangle-comment-links i)))
2725 (concat (funcall c-wrap (car cs)) "\n"
2726 body "\n"
2727 (funcall c-wrap (cadr cs))))
2728 body)))
2729 (setq expansion
2730 (cons sep (cons full expansion)))))))))
2731 (and expansion
2732 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2733 ;; Possibly raise an error if named block doesn't exist.
2734 (if (or org-babel-noweb-error-all-langs
2735 (member lang org-babel-noweb-error-langs))
2736 (error "%s" (concat
2737 (org-babel-noweb-wrap source-name)
2738 "could not be resolved (see "
2739 "`org-babel-noweb-error-langs')"))
2740 "")))
2741 "[\n\r]") (concat "\n" prefix))))))
2742 (funcall nb-add (buffer-substring index (point-max))))
2743 new-body))
2745 (defun org-babel--script-escape-inner (str)
2746 (let (in-single in-double backslash out)
2747 (mapc
2748 (lambda (ch)
2749 (setq
2751 (if backslash
2752 (progn
2753 (setq backslash nil)
2754 (cond
2755 ((and in-single (eq ch ?'))
2756 ;; Escaped single quote inside single quoted string:
2757 ;; emit just a single quote, since we've changed the
2758 ;; outer quotes to double.
2759 (cons ch out))
2760 ((eq ch ?\")
2761 ;; Escaped double quote
2762 (if in-single
2763 ;; This should be interpreted as backslash+quote,
2764 ;; not an escape. Emit a three backslashes
2765 ;; followed by a quote (because one layer of
2766 ;; quoting will be stripped by `org-babel-read').
2767 (append (list ch ?\\ ?\\ ?\\) out)
2768 ;; Otherwise we are in a double-quoted string. Emit
2769 ;; a single escaped quote
2770 (append (list ch ?\\) out)))
2771 ((eq ch ?\\)
2772 ;; Escaped backslash: emit a single escaped backslash
2773 (append (list ?\\ ?\\) out))
2774 ;; Other: emit a quoted backslash followed by whatever
2775 ;; the character was (because one layer of quoting will
2776 ;; be stripped by `org-babel-read').
2777 (t (append (list ch ?\\ ?\\) out))))
2778 (cl-case ch
2779 (?\[ (if (or in-double in-single)
2780 (cons ?\[ out)
2781 (cons ?\( out)))
2782 (?\] (if (or in-double in-single)
2783 (cons ?\] out)
2784 (cons ?\) out)))
2785 (?\{ (if (or in-double in-single)
2786 (cons ?\{ out)
2787 (cons ?\( out)))
2788 (?\} (if (or in-double in-single)
2789 (cons ?\} out)
2790 (cons ?\) out)))
2791 (?, (if (or in-double in-single)
2792 (cons ?, out) (cons ?\s out)))
2793 (?\' (if in-double
2794 (cons ?\' out)
2795 (setq in-single (not in-single)) (cons ?\" out)))
2796 (?\" (if in-single
2797 (append (list ?\" ?\\) out)
2798 (setq in-double (not in-double)) (cons ?\" out)))
2799 (?\\ (unless (or in-single in-double)
2800 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2801 (setq backslash t)
2802 out)
2803 (t (cons ch out))))))
2804 (string-to-list str))
2805 (when (or in-single in-double)
2806 (error "Unterminated string in `org-babel-script-escape'"))
2807 (apply #'string (reverse out))))
2809 (defun org-babel-script-escape (str &optional force)
2810 "Safely convert tables into elisp lists."
2811 (unless (stringp str)
2812 (error "`org-babel-script-escape' expects a string"))
2813 (let ((escaped
2814 (cond
2815 ((and (> (length str) 2)
2816 (or (and (string-equal "[" (substring str 0 1))
2817 (string-equal "]" (substring str -1)))
2818 (and (string-equal "{" (substring str 0 1))
2819 (string-equal "}" (substring str -1)))
2820 (and (string-equal "(" (substring str 0 1))
2821 (string-equal ")" (substring str -1)))))
2823 (concat "'" (org-babel--script-escape-inner str)))
2824 ((or force
2825 (and (> (length str) 2)
2826 (or (and (string-equal "'" (substring str 0 1))
2827 (string-equal "'" (substring str -1)))
2828 ;; We need to pass double-quoted strings
2829 ;; through the backslash-twiddling bits, even
2830 ;; though we don't need to change their
2831 ;; delimiters.
2832 (and (string-equal "\"" (substring str 0 1))
2833 (string-equal "\"" (substring str -1))))))
2834 (org-babel--script-escape-inner str))
2835 (t str))))
2836 (condition-case nil (org-babel-read escaped) (error escaped))))
2838 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2839 "Convert the string value of CELL to a number if appropriate.
2840 Otherwise if CELL looks like lisp (meaning it starts with a
2841 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2842 lisp, otherwise return it unmodified as a string. Optional
2843 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2844 situations in which is it not appropriate."
2845 (if (and (stringp cell) (not (equal cell "")))
2846 (or (org-babel--string-to-number cell)
2847 (if (and (not inhibit-lisp-eval)
2848 (or (member (substring cell 0 1) '("(" "'" "`" "["))
2849 (string= cell "*this*")))
2850 (eval (read cell) t)
2851 (if (string= (substring cell 0 1) "\"")
2852 (read cell)
2853 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2854 cell))
2856 (defun org-babel--string-to-number (string)
2857 "If STRING represents a number return its value.
2859 Otherwise return nil."
2860 (when (string-match "\\`-?[0-9]*\\.?[0-9]*\\'" string)
2861 (string-to-number string)))
2862 (define-obsolete-function-alias 'org-babel-number-p 'org-babel--string-to-number "Org 9.0")
2864 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2865 "Read the results located at FILE-NAME into an elisp table.
2866 If the table is trivial, then return it as a scalar."
2867 (let (result)
2868 (save-window-excursion
2869 (with-temp-buffer
2870 (condition-case err
2871 (progn
2872 (org-table-import file-name separator)
2873 (delete-file file-name)
2874 (setq result (mapcar (lambda (row)
2875 (mapcar #'org-babel-string-read row))
2876 (org-table-to-lisp))))
2877 (error (message "Error reading results: %s" err) nil)))
2878 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2879 (if (consp (car result))
2880 (if (null (cdr (car result)))
2881 (caar result)
2882 result)
2883 (car result))
2884 result))))
2886 (defun org-babel-string-read (cell)
2887 "Strip nested \"s from around strings."
2888 (org-babel-read (or (and (stringp cell)
2889 (string-match "\\\"\\(.+\\)\\\"" cell)
2890 (match-string 1 cell))
2891 cell) t))
2893 (defun org-babel-chomp (string &optional regexp)
2894 "Strip a trailing space or carriage return from STRING.
2895 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2896 can be specified as the REGEXP argument."
2897 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2898 (while (and (> (length string) 0)
2899 (string-match regexp (substring string -1)))
2900 (setq string (substring string 0 -1)))
2901 string))
2903 (defun org-babel-local-file-name (file)
2904 "Return the local name component of FILE."
2905 (or (file-remote-p file 'localname) file))
2907 (defun org-babel-process-file-name (name &optional no-quote-p)
2908 "Prepare NAME to be used in an external process.
2909 If NAME specifies a remote location, the remote portion of the
2910 name is removed, since in that case the process will be executing
2911 remotely. The file name is then processed by `expand-file-name'.
2912 Unless second argument NO-QUOTE-P is non-nil, the file name is
2913 additionally processed by `shell-quote-argument'"
2914 (let ((f (org-babel-local-file-name (expand-file-name name))))
2915 (if no-quote-p f (shell-quote-argument f))))
2917 (defvar org-babel-temporary-directory)
2918 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2919 (defvar org-babel-temporary-directory
2920 (or (and (boundp 'org-babel-temporary-directory)
2921 (file-exists-p org-babel-temporary-directory)
2922 org-babel-temporary-directory)
2923 (make-temp-file "babel-" t))
2924 "Directory to hold temporary files created to execute code blocks.
2925 Used by `org-babel-temp-file'. This directory will be removed on
2926 Emacs shutdown."))
2928 (defcustom org-babel-remote-temporary-directory "/tmp/"
2929 "Directory to hold temporary files on remote hosts."
2930 :group 'org-babel
2931 :type 'string)
2933 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2934 "Call the code to parse raw string results according to RESULT-PARAMS."
2935 (declare (indent 1)
2936 (debug (form form &rest form)))
2937 (org-with-gensyms (params)
2938 `(let ((,params ,result-params))
2939 (unless (member "none" ,params)
2940 (if (or (member "scalar" ,params)
2941 (member "verbatim" ,params)
2942 (member "html" ,params)
2943 (member "code" ,params)
2944 (member "pp" ,params)
2945 (member "file" ,params)
2946 (and (or (member "output" ,params)
2947 (member "raw" ,params)
2948 (member "org" ,params)
2949 (member "drawer" ,params))
2950 (not (member "table" ,params))))
2951 ,scalar-form
2952 ,@table-forms)))))
2953 (def-edebug-spec org-babel-result-cond (form form body))
2955 (defun org-babel-temp-file (prefix &optional suffix)
2956 "Create a temporary file in the `org-babel-temporary-directory'.
2957 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2958 value of `temporary-file-directory' temporarily set to the value
2959 of `org-babel-temporary-directory'."
2960 (if (file-remote-p default-directory)
2961 (let ((prefix
2962 (concat (file-remote-p default-directory)
2963 (expand-file-name
2964 prefix org-babel-remote-temporary-directory))))
2965 (make-temp-file prefix nil suffix))
2966 (let ((temporary-file-directory
2967 (or (and (boundp 'org-babel-temporary-directory)
2968 (file-exists-p org-babel-temporary-directory)
2969 org-babel-temporary-directory)
2970 temporary-file-directory)))
2971 (make-temp-file prefix nil suffix))))
2973 (defun org-babel-remove-temporary-directory ()
2974 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2975 (when (and (boundp 'org-babel-temporary-directory)
2976 (file-exists-p org-babel-temporary-directory))
2977 ;; taken from `delete-directory' in files.el
2978 (condition-case nil
2979 (progn
2980 (mapc (lambda (file)
2981 ;; This test is equivalent to
2982 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2983 ;; but more efficient
2984 (if (eq t (car (file-attributes file)))
2985 (delete-directory file)
2986 (delete-file file)))
2987 ;; We do not want to delete "." and "..".
2988 (directory-files org-babel-temporary-directory 'full
2989 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2990 (delete-directory org-babel-temporary-directory))
2991 (error
2992 (message "Failed to remove temporary Org-babel directory %s"
2993 (if (boundp 'org-babel-temporary-directory)
2994 org-babel-temporary-directory
2995 "[directory not defined]"))))))
2997 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2999 (defun org-babel-one-header-arg-safe-p (pair safe-list)
3000 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3002 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3003 (and (consp pair)
3004 (keywordp (car pair))
3005 (stringp (cdr pair))
3007 (memq (car pair) safe-list)
3008 (let ((entry (assq (car pair) safe-list)))
3009 (and entry
3010 (consp entry)
3011 (cond ((functionp (cdr entry))
3012 (funcall (cdr entry) (cdr pair)))
3013 ((listp (cdr entry))
3014 (member (cdr pair) (cdr entry)))
3015 (t nil)))))))
3017 (defun org-babel-generate-file-param (src-name params)
3018 "Calculate the filename for source block results.
3020 The directory is calculated from the :output-dir property of the
3021 source block; if not specified, use the current directory.
3023 If the source block has a #+NAME and the :file parameter does not
3024 contain any period characters, then the :file parameter is
3025 treated as an extension, and the output file name is the
3026 concatenation of the directory (as calculated above), the block
3027 name, a period, and the parameter value as a file extension.
3028 Otherwise, the :file parameter is treated as a full file name,
3029 and the output file name is the directory (as calculated above)
3030 plus the parameter value."
3031 (let* ((file-cons (assq :file params))
3032 (file-ext-cons (assq :file-ext params))
3033 (file-ext (cdr-safe file-ext-cons))
3034 (dir (cdr-safe (assq :output-dir params)))
3035 fname)
3036 ;; create the output-dir if it does not exist
3037 (when dir
3038 (make-directory dir t))
3039 (if file-cons
3040 ;; :file given; add :output-dir if given
3041 (when dir
3042 (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
3043 ;; :file not given; compute from name and :file-ext if possible
3044 (when (and src-name file-ext)
3045 (if dir
3046 (setq fname (concat (file-name-as-directory (or dir ""))
3047 src-name "." file-ext))
3048 (setq fname (concat src-name "." file-ext)))
3049 (setq params (cons (cons :file fname) params))))
3050 params))
3052 (defun org-babel-graphical-output-file (params)
3053 "File where a babel block should send graphical output, per PARAMS.
3054 Return nil if no graphical output is expected. Raise an error if
3055 the output file is ill-defined."
3056 (let ((file (cdr (assq :file params))))
3057 (cond (file (and (member "graphics" (cdr (assq :result-params params)))
3058 file))
3059 ((assq :file-ext params)
3060 (user-error ":file-ext given but no :file generated; did you forget \
3061 to name a block?"))
3062 (t (user-error "No :file header argument given; cannot create \
3063 graphical result")))))
3065 (defun org-babel-make-language-alias (new old)
3066 "Make source blocks of type NEW aliases for those of type OLD.
3068 NEW and OLD should be strings. This function should be called
3069 after the babel API for OLD-type source blocks is fully defined.
3071 Callers of this function will probably want to add an entry to
3072 `org-src-lang-modes' as well."
3073 (dolist (fn '("execute" "expand-body" "prep-session"
3074 "variable-assignments" "load-session"))
3075 (let ((sym (intern-soft (concat "org-babel-" fn ":" old))))
3076 (when (and sym (fboundp sym))
3077 (defalias (intern (concat "org-babel-" fn ":" new)) sym))))
3078 ;; Technically we don't need a `dolist' for just one variable, but
3079 ;; we keep it for symmetry/ease of future expansion.
3080 (dolist (var '("default-header-args"))
3081 (let ((sym (intern-soft (concat "org-babel-" var ":" old))))
3082 (when (and sym (boundp sym))
3083 (defvaralias (intern (concat "org-babel-" var ":" new)) sym)))))
3085 (defun org-babel-strip-quotes (string)
3086 "Strip \\\"s from around a string, if applicable."
3087 (org-unbracket-string "\"" "\"" string))
3089 (provide 'ob-core)
3091 ;; Local variables:
3092 ;; generated-autoload-file: "org-loaddefs.el"
3093 ;; End:
3095 ;;; ob-core.el ends here