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