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