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