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