Fix `org-confirm-babel-evaluate' with `org-sbe'
[org-mode.git] / lisp / ob-core.el
blob00f968a0a7d3ea8032ee690b6482e08b365617ff
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 <http://www.gnu.org/licenses/>.
25 ;;; Code:
26 (require 'cl-lib)
27 (require 'ob-eval)
28 (require 'org-macs)
29 (require 'org-compat)
31 (defconst org-babel-exeext
32 (if (memq system-type '(windows-nt cygwin))
33 ".exe"
34 nil))
36 (defvar org-babel-library-of-babel)
37 (defvar org-edit-src-content-indentation)
38 (defvar org-src-lang-modes)
39 (defvar org-src-preserve-indentation)
41 (declare-function org-at-item-p "org-list" ())
42 (declare-function org-at-table-p "org" (&optional table-type))
43 (declare-function org-babel-lob-execute-maybe "ob-lob" ())
44 (declare-function org-babel-ref-goto-headline-id "ob-ref" (id))
45 (declare-function org-babel-ref-headline-body "ob-ref" ())
46 (declare-function org-babel-ref-parse "ob-ref" (assignment))
47 (declare-function org-babel-ref-resolve "ob-ref" (ref))
48 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
49 (declare-function org-babel-tangle-comment-links "ob-tangle" (&optional info))
50 (declare-function org-completing-read "org" (&rest args))
51 (declare-function org-current-level "org" ())
52 (declare-function org-cycle "org" (&optional arg))
53 (declare-function org-do-remove-indentation "org" (&optional n))
54 (declare-function org-edit-src-code "org-src" (&optional code edit-buffer-name))
55 (declare-function org-edit-src-exit "org-src" ())
56 (declare-function org-element-at-point "org-element" ())
57 (declare-function org-element-context "org-element" (&optional element))
58 (declare-function org-element-normalize-string "org-element" (s))
59 (declare-function org-element-property "org-element" (property element))
60 (declare-function org-element-type "org-element" (element))
61 (declare-function org-entry-get "org" (pom property &optional inherit literal-nil))
62 (declare-function org-escape-code-in-region "org-src" (beg end))
63 (declare-function org-get-indentation "org" (&optional line))
64 (declare-function org-get-indentation "org" (&optional line))
65 (declare-function org-in-regexp "org" (regexp &optional nlines visually))
66 (declare-function org-indent-line "org" ())
67 (declare-function org-list-get-list-end "org-list" (item struct prevs))
68 (declare-function org-list-prevs-alist "org-list" (struct))
69 (declare-function org-list-struct "org-list" ())
70 (declare-function org-list-to-generic "org-list" (LIST PARAMS))
71 (declare-function org-list-to-lisp "org-list" (&optional delete))
72 (declare-function org-macro-escape-arguments "org-macro" (&rest args))
73 (declare-function org-make-options-regexp "org" (kwds &optional extra))
74 (declare-function org-mark-ring-push "org" (&optional pos buffer))
75 (declare-function org-narrow-to-subtree "org" ())
76 (declare-function org-next-block "org" (arg &optional backward block-regexp))
77 (declare-function org-number-sequence "org-compat" (from &optional to inc))
78 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
79 (declare-function org-outline-overlay-data "org" (&optional use-markers))
80 (declare-function org-previous-block "org" (arg &optional block-regexp))
81 (declare-function org-remove-indentation "org" (code &optional n))
82 (declare-function org-reverse-string "org" (string))
83 (declare-function org-set-outline-overlay-data "org" (data))
84 (declare-function org-show-context "org" (&optional key))
85 (declare-function org-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 (when file (find-file file))
1769 (save-excursion
1770 (goto-char (point-min))
1771 (let* ((re (org-babel-named-src-block-regexp-for-name))
1772 (names (and (looking-at re)
1773 (list (match-string-no-properties 9)))))
1774 (while (ignore-errors (org-next-block 1 nil re))
1775 (push (match-string-no-properties 9) names))
1776 names)))
1778 ;;;###autoload
1779 (defun org-babel-goto-named-result (name)
1780 "Go to a named result."
1781 (interactive
1782 (let ((completion-ignore-case t))
1783 (list (completing-read "Source-block name: "
1784 (org-babel-result-names) nil t))))
1785 (let ((point (org-babel-find-named-result name)))
1786 (if point
1787 ;; taken from `org-open-at-point'
1788 (progn (goto-char point) (org-show-context))
1789 (message "result `%s' not found in this buffer" name))))
1791 (defun org-babel-find-named-result (name)
1792 "Find a named result.
1793 Return the location of the result named NAME in the current
1794 buffer or nil if no such result exists."
1795 (save-excursion
1796 (goto-char (point-min))
1797 (let ((case-fold-search t)
1798 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1799 org-babel-results-keyword
1800 (regexp-quote name))))
1801 (catch :found
1802 (while (re-search-forward re nil t)
1803 (let ((element (org-element-at-point)))
1804 (when (or (eq (org-element-type element) 'keyword)
1805 (< (point)
1806 (org-element-property :post-affiliated element)))
1807 (throw :found (line-beginning-position)))))))))
1809 (defun org-babel-result-names (&optional file)
1810 "Returns the names of results in FILE or the current buffer."
1811 (save-excursion
1812 (when file (find-file file)) (goto-char (point-min))
1813 (let ((case-fold-search t) names)
1814 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1815 (setq names (cons (match-string-no-properties 9) names)))
1816 names)))
1818 ;;;###autoload
1819 (defun org-babel-next-src-block (&optional arg)
1820 "Jump to the next source block.
1821 With optional prefix argument ARG, jump forward ARG many source blocks."
1822 (interactive "p")
1823 (org-next-block arg nil org-babel-src-block-regexp))
1825 ;;;###autoload
1826 (defun org-babel-previous-src-block (&optional arg)
1827 "Jump to the previous source block.
1828 With optional prefix argument ARG, jump backward ARG many source blocks."
1829 (interactive "p")
1830 (org-previous-block arg org-babel-src-block-regexp))
1832 (defvar org-babel-load-languages)
1834 ;;;###autoload
1835 (defun org-babel-mark-block ()
1836 "Mark current src block."
1837 (interactive)
1838 (let ((head (org-babel-where-is-src-block-head)))
1839 (when head
1840 (save-excursion
1841 (goto-char head)
1842 (looking-at org-babel-src-block-regexp))
1843 (push-mark (match-end 5) nil t)
1844 (goto-char (match-beginning 5)))))
1846 (defun org-babel-demarcate-block (&optional arg)
1847 "Wrap or split the code in the region or on the point.
1848 When called from inside of a code block the current block is
1849 split. When called from outside of a code block a new code block
1850 is created. In both cases if the region is demarcated and if the
1851 region is not active then the point is demarcated."
1852 (interactive "P")
1853 (let* ((info (org-babel-get-src-block-info 'light))
1854 (start (org-babel-where-is-src-block-head))
1855 (block (and start (match-string 0)))
1856 (headers (and start (match-string 4)))
1857 (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
1858 (lower-case-p (and block
1859 (let (case-fold-search)
1860 (string-match-p "#\\+begin_src" block)))))
1861 (if info
1862 (mapc
1863 (lambda (place)
1864 (save-excursion
1865 (goto-char place)
1866 (let ((lang (nth 0 info))
1867 (indent (make-string (org-get-indentation) ?\s)))
1868 (when (string-match "^[[:space:]]*$"
1869 (buffer-substring (point-at-bol)
1870 (point-at-eol)))
1871 (delete-region (point-at-bol) (point-at-eol)))
1872 (insert (concat
1873 (if (looking-at "^") "" "\n")
1874 indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")
1875 (if arg stars indent) "\n"
1876 indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1877 lang
1878 (if (> (length headers) 1)
1879 (concat " " headers) headers)
1880 (if (looking-at "[\n\r]")
1882 (concat "\n" (make-string (current-column) ? )))))))
1883 (move-end-of-line 2))
1884 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1885 (let ((start (point))
1886 (lang (completing-read
1887 "Lang: "
1888 (mapcar #'symbol-name
1889 (delete-dups
1890 (append (mapcar #'car org-babel-load-languages)
1891 (mapcar (lambda (el) (intern (car el)))
1892 org-src-lang-modes))))))
1893 (body (delete-and-extract-region
1894 (if (org-region-active-p) (mark) (point)) (point))))
1895 (insert (concat (if (looking-at "^") "" "\n")
1896 (if arg (concat stars "\n") "")
1897 (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1898 lang "\n"
1899 body
1900 (if (or (= (length body) 0)
1901 (string-suffix-p "\r" body)
1902 (string-suffix-p "\n" body)) "" "\n")
1903 (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")))
1904 (goto-char start) (move-end-of-line 1)))))
1906 (defun org-babel--insert-results-keyword (name hash)
1907 "Insert RESULTS keyword with NAME value at point.
1908 If NAME is nil, results are anonymous. HASH is a string used as
1909 the results hash, or nil. Leave point before the keyword."
1910 (save-excursion (insert "\n")) ;open line to indent.
1911 (org-indent-line)
1912 (delete-char 1)
1913 (insert (concat "#+" org-babel-results-keyword
1914 (cond ((not hash) nil)
1915 (org-babel-hash-show-time
1916 (format "[%s %s]"
1917 (format-time-string "<%F %T>")
1918 hash))
1919 (t (format "[%s]" hash)))
1921 (when name (concat " " name))
1922 "\n"))
1923 ;; Make sure results are going to be followed by at least one blank
1924 ;; line so they do not get merged with the next element, e.g.,
1926 ;; #+results:
1927 ;; : 1
1929 ;; : fixed-width area, unrelated to the above.
1930 (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
1931 (beginning-of-line 0)
1932 (when hash (org-babel-hide-hash)))
1934 (defun org-babel--clear-results-maybe (hash)
1935 "Clear results when hash doesn't match HASH.
1937 When results hash does not match HASH, remove RESULTS keyword at
1938 point, along with related contents. Do nothing if HASH is nil.
1940 Return a non-nil value if results were cleared. In this case,
1941 leave point where new results should be inserted."
1942 (when hash
1943 (looking-at org-babel-result-regexp)
1944 (unless (string= (match-string 1) hash)
1945 (let* ((e (org-element-at-point))
1946 (post (copy-marker (org-element-property :post-affiliated e))))
1947 ;; Delete contents.
1948 (delete-region post
1949 (save-excursion
1950 (goto-char (org-element-property :end e))
1951 (skip-chars-backward " \t\n")
1952 (line-beginning-position 2)))
1953 ;; Delete RESULT keyword. However, if RESULTS keyword is
1954 ;; orphaned, ignore this part. The deletion above already
1955 ;; took care of it.
1956 (unless (= (point) post)
1957 (delete-region (line-beginning-position)
1958 (line-beginning-position 2)))
1959 (goto-char post)
1960 (set-marker post nil)
1961 t))))
1963 (defun org-babel-where-is-src-block-result (&optional insert _info hash)
1964 "Find where the current source block results begin.
1966 Return the point at the beginning of the result of the current
1967 source block, specifically at the beginning of the results line.
1969 If no result exists for this block return nil, unless optional
1970 argument INSERT is non-nil. In this case, create a results line
1971 following the source block and return the position at its
1972 beginning. In the case of inline code, remove the results part
1973 instead.
1975 If optional argument HASH is a string, remove contents related to
1976 RESULTS keyword if its hash is different. Then update the latter
1977 to HASH."
1978 (let ((context (org-element-context)))
1979 (catch :found
1980 (org-with-wide-buffer
1981 (pcase (org-element-type context)
1982 ((or `inline-babel-call `inline-src-block)
1983 ;; Results for inline objects are located right after them.
1984 ;; There is no RESULTS line to insert either.
1985 (let ((limit (org-element-property
1986 :contents-end (org-element-property :parent context))))
1987 (goto-char (org-element-property :end context))
1988 (skip-chars-forward " \t\n" limit)
1989 (throw :found
1990 (and
1991 (< (point) limit)
1992 (let ((result (org-element-context)))
1993 (and (eq (org-element-type result) 'macro)
1994 (string= (org-element-property :key result)
1995 "results")
1996 (if (not insert) (point)
1997 (delete-region
1998 (point)
1999 (progn
2000 (goto-char (org-element-property :end result))
2001 (skip-chars-backward " \t")
2002 (point)))
2003 (point))))))))
2004 ((or `babel-call `src-block)
2005 (let* ((name (org-element-property :name context))
2006 (named-results (and name (org-babel-find-named-result name))))
2007 (goto-char (or named-results (org-element-property :end context)))
2008 (cond
2009 ;; Existing results named after the current source.
2010 (named-results
2011 (when (org-babel--clear-results-maybe hash)
2012 (org-babel--insert-results-keyword name hash))
2013 (throw :found (point)))
2014 ;; Named results expect but none to be found.
2015 (name)
2016 ;; No possible anonymous results at the very end of
2017 ;; buffer or outside CONTEXT parent.
2018 ((eq (point)
2019 (or (org-element-property
2020 :contents-end (org-element-property :parent context))
2021 (point-max))))
2022 ;; Check if next element is an anonymous result below
2023 ;; the current block.
2024 ((let* ((next (org-element-at-point))
2025 (end (save-excursion
2026 (goto-char
2027 (org-element-property :post-affiliated next))
2028 (line-end-position)))
2029 (empty-result-re (concat org-babel-result-regexp "$"))
2030 (case-fold-search t))
2031 (re-search-forward empty-result-re end t))
2032 (beginning-of-line)
2033 (when (org-babel--clear-results-maybe hash)
2034 (org-babel--insert-results-keyword nil hash))
2035 (throw :found (point))))))
2036 ;; Ignore other elements.
2037 (_ (throw :found nil))))
2038 ;; No result found. Insert a RESULTS keyword below element, if
2039 ;; appropriate. In this case, ensure there is an empty line
2040 ;; after the previous element.
2041 (when insert
2042 (save-excursion
2043 (goto-char (min (org-element-property :end context) (point-max)))
2044 (skip-chars-backward " \t\n")
2045 (forward-line)
2046 (unless (bolp) (insert "\n"))
2047 (insert "\n")
2048 (org-babel--insert-results-keyword
2049 (org-element-property :name context) hash)
2050 (point))))))
2052 (defun org-babel-read-element (element)
2053 "Read ELEMENT into emacs-lisp.
2054 Return nil if ELEMENT cannot be read."
2055 (org-with-wide-buffer
2056 (goto-char (org-element-property :post-affiliated element))
2057 (pcase (org-element-type element)
2058 (`fixed-width
2059 (let ((v (org-trim (org-element-property :value element))))
2060 (or (org-babel--string-to-number v) v)))
2061 (`table (org-babel-read-table))
2062 (`plain-list (org-babel-read-list))
2063 (`example-block
2064 (let ((v (org-element-property :value element)))
2065 (if (or org-src-preserve-indentation
2066 (org-element-property :preserve-indent element))
2068 (org-remove-indentation v))))
2069 (`export-block
2070 (org-remove-indentation (org-element-property :value element)))
2071 (`paragraph
2072 ;; Treat paragraphs containing a single link specially.
2073 (skip-chars-forward " \t")
2074 (if (and (looking-at org-bracket-link-regexp)
2075 (save-excursion
2076 (goto-char (match-end 0))
2077 (skip-chars-forward " \r\t\n")
2078 (<= (org-element-property :end element)
2079 (point))))
2080 (org-babel-read-link)
2081 (buffer-substring-no-properties
2082 (org-element-property :contents-begin element)
2083 (org-element-property :contents-end element))))
2084 ((or `center-block `quote-block `verse-block `special-block)
2085 (org-remove-indentation
2086 (buffer-substring-no-properties
2087 (org-element-property :contents-begin element)
2088 (org-element-property :contents-end element))))
2089 (_ nil))))
2091 (defun org-babel-read-result ()
2092 "Read the result at point into emacs-lisp."
2093 (and (not (save-excursion
2094 (beginning-of-line)
2095 (looking-at-p "[ \t]*$")))
2096 (org-babel-read-element (org-element-at-point))))
2098 (defun org-babel-read-table ()
2099 "Read the table at point into emacs-lisp."
2100 (mapcar (lambda (row)
2101 (if (and (symbolp row) (equal row 'hline)) row
2102 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
2103 (org-table-to-lisp)))
2105 (defun org-babel-read-list ()
2106 "Read the list at point into emacs-lisp."
2107 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2108 (cdr (org-list-to-lisp))))
2110 (defvar org-link-types-re)
2111 (defun org-babel-read-link ()
2112 "Read the link at point into emacs-lisp.
2113 If the path of the link is a file path it is expanded using
2114 `expand-file-name'."
2115 (let* ((case-fold-search t)
2116 (raw (and (looking-at org-bracket-link-regexp)
2117 (org-no-properties (match-string 1))))
2118 (type (and (string-match org-link-types-re raw)
2119 (match-string 1 raw))))
2120 (cond
2121 ((not type) (expand-file-name raw))
2122 ((string= type "file")
2123 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
2124 (expand-file-name (match-string 2 raw))))
2125 (t raw))))
2127 (defun org-babel-format-result (result &optional sep)
2128 "Format RESULT for writing to file."
2129 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
2130 (if (listp result)
2131 ;; table result
2132 (orgtbl-to-generic
2133 result (list :sep (or sep "\t") :fmt echo-res))
2134 ;; scalar result
2135 (funcall echo-res result))))
2137 (defun org-babel-insert-result (result &optional result-params info hash lang)
2138 "Insert RESULT into the current buffer.
2140 By default RESULT is inserted after the end of the current source
2141 block. The RESULT of an inline source block usually will be
2142 wrapped inside a `results' macro and placed on the same line as
2143 the inline source block. The macro is stripped upon export.
2144 Multiline and non-scalar RESULTS from inline source blocks are
2145 not allowed. With optional argument RESULT-PARAMS controls
2146 insertion of results in the Org mode file. RESULT-PARAMS can
2147 take the following values:
2149 replace - (default option) insert results after the source block
2150 or inline source block replacing any previously
2151 inserted results.
2153 silent -- no results are inserted into the Org buffer but
2154 the results are echoed to the minibuffer and are
2155 ingested by Emacs (a potentially time consuming
2156 process).
2158 file ---- the results are interpreted as a file path, and are
2159 inserted into the buffer using the Org file syntax.
2161 list ---- the results are interpreted as an Org list.
2163 raw ----- results are added directly to the Org file. This is
2164 a good option if you code block will output Org
2165 formatted text.
2167 drawer -- results are added directly to the Org file as with
2168 \"raw\", but are wrapped in a RESULTS drawer or results
2169 macro, allowing them to later be replaced or removed
2170 automatically.
2172 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2173 org\" block depending on whether the current source block is
2174 inline or not. They are not comma-escaped when inserted,
2175 but Org syntax here will be discarded when exporting the
2176 file.
2178 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2179 or html export snippet depending on whether the current
2180 source block is inline or not. This is a good option
2181 if your code block will output html formatted text.
2183 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2184 block or latex export snippet depending on whether the
2185 current source block is inline or not. This is a good
2186 option if your code block will output latex formatted
2187 text.
2189 code ---- the results are extracted in the syntax of the source
2190 code of the language being evaluated and are added
2191 inside of a source block with the source-code language
2192 set appropriately. Also, source block inlining is
2193 preserved in this case. Note this relies on the
2194 optional LANG argument.
2196 list ---- the results are rendered as a list. This option not
2197 allowed for inline src blocks.
2199 table --- the results are rendered as a table. This option not
2200 allowed for inline src blocks.
2202 INFO may provide the values of these header arguments (in the
2203 `header-arguments-alist' see the docstring for
2204 `org-babel-get-src-block-info'):
2206 :file --- the name of the file to which output should be written.
2208 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2209 using the argument supplied to specify the export block
2210 or snippet type."
2211 (cond ((stringp result)
2212 (setq result (org-no-properties result))
2213 (when (member "file" result-params)
2214 (setq result (org-babel-result-to-file
2215 result (when (assq :file-desc (nth 2 info))
2216 (or (cdr (assq :file-desc (nth 2 info)))
2217 result))))))
2218 ((listp result))
2219 (t (setq result (format "%S" result))))
2220 (if (and result-params (member "silent" result-params))
2221 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2222 result)
2223 (let ((inline (let ((context (org-element-context)))
2224 (and (memq (org-element-type context)
2225 '(inline-babel-call inline-src-block))
2226 context))))
2227 (when inline
2228 (let ((warning
2229 (or (and (member "table" result-params) "`:results table'")
2230 (and (listp result) "list result")
2231 (and (string-match-p "\n." result) "multiline result")
2232 (and (member "list" result-params) "`:results list'"))))
2233 (when warning
2234 (user-error "Inline error: %s cannot be used" warning))))
2235 (save-excursion
2236 (let* ((visible-beg (point-min-marker))
2237 (visible-end (copy-marker (point-max) t))
2238 (inline (let ((context (org-element-context)))
2239 (and (memq (org-element-type context)
2240 '(inline-babel-call inline-src-block))
2241 context)))
2242 (existing-result (org-babel-where-is-src-block-result t nil hash))
2243 (results-switches (cdr (assq :results_switches (nth 2 info))))
2244 ;; When results exist outside of the current visible
2245 ;; region of the buffer, be sure to widen buffer to
2246 ;; update them.
2247 (outside-scope (and existing-result
2248 (buffer-narrowed-p)
2249 (or (> visible-beg existing-result)
2250 (<= visible-end existing-result))))
2251 beg end indent)
2252 ;; Ensure non-inline results end in a newline.
2253 (when (and (org-string-nw-p result)
2254 (not inline)
2255 (not (string-equal (substring result -1) "\n")))
2256 (setq result (concat result "\n")))
2257 (unwind-protect
2258 (progn
2259 (when outside-scope (widen))
2260 (if existing-result (goto-char existing-result)
2261 (goto-char (org-element-property :end inline))
2262 (skip-chars-backward " \t"))
2263 (unless inline
2264 (setq indent (org-get-indentation))
2265 (forward-line 1))
2266 (setq beg (point))
2267 (cond
2268 (inline
2269 ;; Make sure new results are separated from the
2270 ;; source code by one space.
2271 (unless existing-result
2272 (insert " ")
2273 (setq beg (point))))
2274 ((member "replace" result-params)
2275 (delete-region (point) (org-babel-result-end)))
2276 ((member "append" result-params)
2277 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2278 ((member "prepend" result-params))) ; already there
2279 (setq results-switches
2280 (if results-switches (concat " " results-switches) ""))
2281 (let ((wrap
2282 (lambda (start finish &optional no-escape no-newlines
2283 inline-start inline-finish)
2284 (when inline
2285 (setq start inline-start)
2286 (setq finish inline-finish)
2287 (setq no-newlines t))
2288 (let ((before-finish (marker-position end)))
2289 (goto-char end)
2290 (insert (concat finish (unless no-newlines "\n")))
2291 (goto-char beg)
2292 (insert (concat start (unless no-newlines "\n")))
2293 (unless no-escape
2294 (org-escape-code-in-region
2295 (min (point) before-finish) before-finish))
2296 (goto-char end))))
2297 (tabulablep
2298 (lambda (r)
2299 ;; Non-nil when result R can be turned into
2300 ;; a table.
2301 (and (listp r)
2302 (null (cdr (last r)))
2303 (cl-every
2304 (lambda (e) (or (atom e) (null (cdr (last e)))))
2305 result)))))
2306 ;; insert results based on type
2307 (cond
2308 ;; Do nothing for an empty result.
2309 ((null result))
2310 ;; Insert a list if preferred.
2311 ((member "list" result-params)
2312 (insert
2313 (org-trim
2314 (org-list-to-generic
2315 (cons 'unordered
2316 (mapcar
2317 (lambda (e)
2318 (list (if (stringp e) e (format "%S" e))))
2319 (if (listp result) result
2320 (split-string result "\n" t))))
2321 '(:splicep nil :istart "- " :iend "\n")))
2322 "\n"))
2323 ;; Try hard to print RESULT as a table. Give up if
2324 ;; it contains an improper list.
2325 ((funcall tabulablep result)
2326 (goto-char beg)
2327 (insert (concat (orgtbl-to-orgtbl
2328 (if (cl-every
2329 (lambda (e)
2330 (or (eq e 'hline) (listp e)))
2331 result)
2332 result
2333 (list result))
2334 nil)
2335 "\n"))
2336 (goto-char beg)
2337 (when (org-at-table-p) (org-table-align))
2338 (goto-char (org-table-end)))
2339 ;; Print verbatim a list that cannot be turned into
2340 ;; a table.
2341 ((listp result) (insert (format "%s\n" result)))
2342 ((member "file" result-params)
2343 (when inline
2344 (setq result (org-macro-escape-arguments result)))
2345 (insert result))
2346 ((and inline (not (member "raw" result-params)))
2347 (insert (org-macro-escape-arguments
2348 (org-babel-chomp result "\n"))))
2349 (t (goto-char beg) (insert result)))
2350 (setq end (copy-marker (point) t))
2351 ;; possibly wrap result
2352 (cond
2353 ((assq :wrap (nth 2 info))
2354 (let ((name (or (cdr (assq :wrap (nth 2 info))) "RESULTS")))
2355 (funcall wrap (concat "#+BEGIN_" name)
2356 (concat "#+END_" (car (split-string name)))
2357 nil nil (concat "{{{results(@@" name ":") "@@)}}}")))
2358 ((member "html" result-params)
2359 (funcall wrap "#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2360 "{{{results(@@html:" "@@)}}}"))
2361 ((member "latex" result-params)
2362 (funcall wrap "#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2363 "{{{results(@@latex:" "@@)}}}"))
2364 ((member "org" result-params)
2365 (goto-char beg) (when (org-at-table-p) (org-cycle))
2366 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC" nil nil
2367 "{{{results(src_org{" "})}}}"))
2368 ((member "code" result-params)
2369 (let ((lang (or lang "none")))
2370 (funcall wrap (format "#+BEGIN_SRC %s%s" lang results-switches)
2371 "#+END_SRC" nil nil
2372 (format "{{{results(src_%s[%s]{" lang results-switches)
2373 "})}}}")))
2374 ((member "raw" result-params)
2375 (goto-char beg) (when (org-at-table-p) (org-cycle)))
2376 ((or (member "drawer" result-params)
2377 ;; Stay backward compatible with <7.9.2
2378 (member "wrap" result-params))
2379 (goto-char beg) (when (org-at-table-p) (org-cycle))
2380 (funcall wrap ":RESULTS:" ":END:" 'no-escape nil
2381 "{{{results(" ")}}}"))
2382 ((and inline (member "file" result-params))
2383 (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
2384 ((and (not (funcall tabulablep result))
2385 (not (member "file" result-params)))
2386 (let ((org-babel-inline-result-wrap
2387 ;; Hard code {{{results(...)}}} on top of
2388 ;; customization.
2389 (format "{{{results(%s)}}}"
2390 org-babel-inline-result-wrap)))
2391 (org-babel-examplify-region
2392 beg end results-switches inline)))))
2393 ;; Possibly indent results in par with #+results line.
2394 (when (and (not inline) (numberp indent) (> indent 0)
2395 ;; In this case `table-align' does the work
2396 ;; for us.
2397 (not (and (listp result)
2398 (member "append" result-params))))
2399 (indent-rigidly beg end indent))
2400 (if (null result)
2401 (if (member "value" result-params)
2402 (message "Code block returned no value.")
2403 (message "Code block produced no output."))
2404 (message "Code block evaluation complete.")))
2405 (set-marker end nil)
2406 (when outside-scope (narrow-to-region visible-beg visible-end))
2407 (set-marker visible-beg nil)
2408 (set-marker visible-end nil)))))))
2410 (defun org-babel-remove-result (&optional info keep-keyword)
2411 "Remove the result of the current source block."
2412 (interactive)
2413 (let ((location (org-babel-where-is-src-block-result nil info)))
2414 (when location
2415 (save-excursion
2416 (goto-char location)
2417 (when (looking-at (concat org-babel-result-regexp ".*$"))
2418 (delete-region
2419 (if keep-keyword (1+ (match-end 0)) (1- (match-beginning 0)))
2420 (progn (forward-line 1) (org-babel-result-end))))))))
2422 (defun org-babel-remove-inline-result (&optional datum)
2423 "Remove the result of the current inline-src-block or babel call.
2424 The result must be wrapped in a `results' macro to be removed.
2425 Leading white space is trimmed."
2426 (interactive)
2427 (let* ((el (or datum (org-element-context))))
2428 (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
2429 (org-with-wide-buffer
2430 (goto-char (org-element-property :end el))
2431 (skip-chars-backward " \t")
2432 (let ((result (save-excursion
2433 (skip-chars-forward
2434 " \t\n"
2435 (org-element-property
2436 :contents-end (org-element-property :parent el)))
2437 (org-element-context))))
2438 (when (and (eq (org-element-type result) 'macro)
2439 (string= (org-element-property :key result) "results"))
2440 (delete-region ; And leading whitespace.
2441 (point)
2442 (progn (goto-char (org-element-property :end result))
2443 (skip-chars-backward " \t\n")
2444 (point)))))))))
2446 (defun org-babel-remove-result-one-or-many (x)
2447 "Remove the result of the current source block.
2448 If called with a prefix argument, remove all result blocks
2449 in the buffer."
2450 (interactive "P")
2451 (if x
2452 (org-babel-map-src-blocks nil (org-babel-remove-result))
2453 (org-babel-remove-result)))
2455 (defun org-babel-result-end ()
2456 "Return the point at the end of the current set of results."
2457 (save-excursion
2458 (cond
2459 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2460 ((org-at-item-p) (let* ((struct (org-list-struct))
2461 (prvs (org-list-prevs-alist struct)))
2462 (org-list-get-list-end (point-at-bol) struct prvs)))
2463 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2464 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2465 (forward-char 1) (point)))
2467 (let ((case-fold-search t))
2468 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2469 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2470 nil t)
2471 (forward-char 1))
2472 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2473 (forward-line 1))))
2474 (point)))))
2476 (defun org-babel-result-to-file (result &optional description)
2477 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2478 If the `default-directory' is different from the containing
2479 file's directory then expand relative links."
2480 (when (stringp result)
2481 (format "[[file:%s]%s]"
2482 (if (and default-directory
2483 buffer-file-name
2484 (not (string= (expand-file-name default-directory)
2485 (expand-file-name
2486 (file-name-directory buffer-file-name)))))
2487 (expand-file-name result default-directory)
2488 result)
2489 (if description (concat "[" description "]") ""))))
2491 (defun org-babel-examplify-region (beg end &optional results-switches inline)
2492 "Comment out region using the inline `==' or `: ' org example quote."
2493 (interactive "*r")
2494 (let ((maybe-cap
2495 (lambda (str)
2496 (if org-babel-uppercase-example-markers (upcase str) str))))
2497 (if inline
2498 (save-excursion
2499 (goto-char beg)
2500 (insert (format org-babel-inline-result-wrap
2501 (delete-and-extract-region beg end))))
2502 (let ((size (count-lines beg end)))
2503 (save-excursion
2504 (cond ((= size 0)) ; do nothing for an empty result
2505 ((< size org-babel-min-lines-for-block-output)
2506 (goto-char beg)
2507 (dotimes (_ size)
2508 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2510 (goto-char beg)
2511 (insert (if results-switches
2512 (format "%s%s\n"
2513 (funcall maybe-cap "#+begin_example")
2514 results-switches)
2515 (funcall maybe-cap "#+begin_example\n")))
2516 (let ((p (point)))
2517 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2518 (org-escape-code-in-region p (point)))
2519 (insert (funcall maybe-cap "#+end_example\n")))))))))
2521 (defun org-babel-update-block-body (new-body)
2522 "Update the body of the current code block to NEW-BODY."
2523 (let ((element (org-element-at-point)))
2524 (unless (eq (org-element-type element) 'src-block)
2525 (error "Not in a source block"))
2526 (goto-char (org-babel-where-is-src-block-head element))
2527 (let* ((ind (org-get-indentation))
2528 (body-start (line-beginning-position 2))
2529 (body (org-element-normalize-string
2530 (if (or org-src-preserve-indentation
2531 (org-element-property :preserve-indent element))
2532 new-body
2533 (with-temp-buffer
2534 (insert (org-remove-indentation new-body))
2535 (indent-rigidly
2536 (point-min)
2537 (point-max)
2538 (+ ind org-edit-src-content-indentation))
2539 (buffer-string))))))
2540 (delete-region body-start
2541 (org-with-wide-buffer
2542 (goto-char (org-element-property :end element))
2543 (skip-chars-backward " \t\n")
2544 (line-beginning-position)))
2545 (goto-char body-start)
2546 (insert body))))
2548 (defun org-babel-merge-params (&rest plists)
2549 "Combine all parameter association lists in PLISTS.
2550 Later elements of PLISTS override the values of previous elements.
2551 This takes into account some special considerations for certain
2552 parameters when merging lists."
2553 (let* ((results-exclusive-groups
2554 (mapcar (lambda (group) (mapcar #'symbol-name group))
2555 (cdr (assq 'results org-babel-common-header-args-w-values))))
2556 (exports-exclusive-groups
2557 (mapcar (lambda (group) (mapcar #'symbol-name group))
2558 (cdr (assq 'exports org-babel-common-header-args-w-values))))
2559 (merge
2560 (lambda (exclusive-groups &rest result-params)
2561 ;; Maintain exclusivity of mutually exclusive parameters,
2562 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2563 ;; RESULT-PARAMS.
2564 (let (output)
2565 (dolist (new-params result-params (delete-dups output))
2566 (dolist (new-param new-params)
2567 (dolist (exclusive-group exclusive-groups)
2568 (when (member new-param exclusive-group)
2569 (setq output (cl-remove-if
2570 (lambda (o) (member o exclusive-group))
2571 output))))
2572 (push new-param output))))))
2573 (variable-index 0) ;Handle positional arguments.
2574 clearnames
2575 params ;Final parameters list.
2576 ;; Some keywords accept multiple values. We need to treat
2577 ;; them specially.
2578 vars results exports)
2579 (dolist (plist plists)
2580 (dolist (pair plist)
2581 (pcase pair
2582 (`(:var . ,value)
2583 (let ((name (cond
2584 ((listp value) (car value))
2585 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
2586 (intern (match-string 1 value)))
2587 (t nil))))
2588 (cond
2589 (name
2590 (setq vars
2591 (append (if (not (assoc name vars)) vars
2592 (push name clearnames)
2593 (cl-remove-if (lambda (p) (equal name (car p)))
2594 vars))
2595 (list (cons name pair)))))
2596 ((and vars (nth variable-index vars))
2597 ;; If no name is given and we already have named
2598 ;; variables then assign to named variables in order.
2599 (let ((name (car (nth variable-index vars))))
2600 ;; Clear out colnames and rownames for replace vars.
2601 (push name clearnames)
2602 (setf (cddr (nth variable-index vars))
2603 (concat (symbol-name name) "=" value))
2604 (cl-incf variable-index)))
2605 (t (error "Variable \"%s\" must be assigned a default value"
2606 (cdr pair))))))
2607 (`(:results . ,value)
2608 (setq results (funcall merge
2609 results-exclusive-groups
2610 results
2611 (split-string
2612 (if (stringp value) value (eval value t))))))
2613 (`(,(or :file :file-ext) . ,value)
2614 ;; `:file' and `:file-ext' are regular keywords but they
2615 ;; imply a "file" `:results' and a "results" `:exports'.
2616 (when value
2617 (setq results
2618 (funcall merge results-exclusive-groups results '("file")))
2619 (unless (or (member "both" exports)
2620 (member "none" exports)
2621 (member "code" exports))
2622 (setq exports
2623 (funcall merge
2624 exports-exclusive-groups exports '("results"))))
2625 (push pair params)))
2626 (`(:exports . ,value)
2627 (setq exports (funcall merge
2628 exports-exclusive-groups
2629 exports
2630 (split-string (or value "")))))
2631 ;; Regular keywords: any value overwrites the previous one.
2632 (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
2633 ;; Handle `:var' and clear out colnames and rownames for replaced
2634 ;; variables.
2635 (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars)
2636 params))
2637 (dolist (name clearnames)
2638 (dolist (param '(:colname-names :rowname-names))
2639 (when (assq param params)
2640 (setf (cdr (assq param params))
2641 (cl-remove-if (lambda (pair) (equal name (car pair)))
2642 (cdr (assq param params))))
2643 (setq params
2644 (cl-remove-if (lambda (pair) (and (equal (car pair) param)
2645 (null (cdr pair))))
2646 params)))))
2647 ;; Handle other special keywords, which accept multiple values.
2648 (setq params (nconc (list (cons :results (mapconcat #'identity results " "))
2649 (cons :exports (mapconcat #'identity exports " ")))
2650 params))
2651 ;; Return merged params.
2652 params))
2654 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2655 "Set to true to use regular expressions to expand noweb references.
2656 This results in much faster noweb reference expansion but does
2657 not properly allow code blocks to inherit the \":noweb-ref\"
2658 header argument from buffer or subtree wide properties.")
2660 (defun org-babel-noweb-p (params context)
2661 "Check if PARAMS require expansion in CONTEXT.
2662 CONTEXT may be one of :tangle, :export or :eval."
2663 (let ((allowed-values (cl-case context
2664 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2665 (:eval '("yes" "no-export" "strip-export" "eval"))
2666 (:export '("yes")))))
2667 (cl-some (lambda (v) (member v allowed-values))
2668 (split-string (or (cdr (assq :noweb params)) "")))))
2670 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2671 "Expand Noweb references in the body of the current source code block.
2673 For example the following reference would be replaced with the
2674 body of the source-code block named `example-block'.
2676 <<example-block>>
2678 Note that any text preceding the <<foo>> construct on a line will
2679 be interposed between the lines of the replacement text. So for
2680 example if <<foo>> is placed behind a comment, then the entire
2681 replacement text will also be commented.
2683 This function must be called from inside of the buffer containing
2684 the source-code block which holds BODY.
2686 In addition the following syntax can be used to insert the
2687 results of evaluating the source-code block named `example-block'.
2689 <<example-block()>>
2691 Any optional arguments can be passed to example-block by placing
2692 the arguments inside the parenthesis following the convention
2693 defined by `org-babel-lob'. For example
2695 <<example-block(a=9)>>
2697 would set the value of argument \"a\" equal to \"9\". Note that
2698 these arguments are not evaluated in the current source-code
2699 block but are passed literally to the \"example-block\"."
2700 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2701 (info (or info (org-babel-get-src-block-info 'light)))
2702 (lang (nth 0 info))
2703 (body (nth 1 info))
2704 (ob-nww-start org-babel-noweb-wrap-start)
2705 (ob-nww-end org-babel-noweb-wrap-end)
2706 (comment (string= "noweb" (cdr (assq :comments (nth 2 info)))))
2707 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2708 ":noweb-ref[ \t]+" "\\)"))
2709 (new-body "")
2710 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2711 (c-wrap (lambda (text)
2712 (with-temp-buffer
2713 (funcall (intern (concat lang "-mode")))
2714 (comment-region (point) (progn (insert text) (point)))
2715 (org-trim (buffer-string)))))
2716 index source-name evaluate prefix)
2717 (with-temp-buffer
2718 (setq-local org-babel-noweb-wrap-start ob-nww-start)
2719 (setq-local org-babel-noweb-wrap-end ob-nww-end)
2720 (insert body) (goto-char (point-min))
2721 (setq index (point))
2722 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2723 (save-match-data (setf source-name (match-string 1)))
2724 (save-match-data (setq evaluate (string-match "(.*)" source-name)))
2725 (save-match-data
2726 (setq prefix
2727 (buffer-substring (match-beginning 0)
2728 (save-excursion
2729 (beginning-of-line 1) (point)))))
2730 ;; add interval to new-body (removing noweb reference)
2731 (goto-char (match-beginning 0))
2732 (funcall nb-add (buffer-substring index (point)))
2733 (goto-char (match-end 0))
2734 (setq index (point))
2735 (funcall
2736 nb-add
2737 (with-current-buffer parent-buffer
2738 (save-restriction
2739 (widen)
2740 (mapconcat ;; Interpose PREFIX between every line.
2741 #'identity
2742 (split-string
2743 (if evaluate
2744 (let ((raw (org-babel-ref-resolve source-name)))
2745 (if (stringp raw) raw (format "%S" raw)))
2747 ;; Retrieve from the library of babel.
2748 (nth 2 (assoc (intern source-name)
2749 org-babel-library-of-babel))
2750 ;; Return the contents of headlines literally.
2751 (save-excursion
2752 (when (org-babel-ref-goto-headline-id source-name)
2753 (org-babel-ref-headline-body)))
2754 ;; Find the expansion of reference in this buffer.
2755 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2756 expansion)
2757 (save-excursion
2758 (goto-char (point-min))
2759 (if org-babel-use-quick-and-dirty-noweb-expansion
2760 (while (re-search-forward rx nil t)
2761 (let* ((i (org-babel-get-src-block-info 'light))
2762 (body (org-babel-expand-noweb-references i))
2763 (sep (or (cdr (assq :noweb-sep (nth 2 i)))
2764 "\n"))
2765 (full (if comment
2766 (let ((cs (org-babel-tangle-comment-links i)))
2767 (concat (funcall c-wrap (car cs)) "\n"
2768 body "\n"
2769 (funcall c-wrap (cadr cs))))
2770 body)))
2771 (setq expansion (cons sep (cons full expansion)))))
2772 (org-babel-map-src-blocks nil
2773 (let ((i (org-babel-get-src-block-info 'light)))
2774 (when (equal (or (cdr (assq :noweb-ref (nth 2 i)))
2775 (nth 4 i))
2776 source-name)
2777 (let* ((body (org-babel-expand-noweb-references i))
2778 (sep (or (cdr (assq :noweb-sep (nth 2 i)))
2779 "\n"))
2780 (full (if comment
2781 (let ((cs (org-babel-tangle-comment-links i)))
2782 (concat (funcall c-wrap (car cs)) "\n"
2783 body "\n"
2784 (funcall c-wrap (cadr cs))))
2785 body)))
2786 (setq expansion
2787 (cons sep (cons full expansion)))))))))
2788 (and expansion
2789 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2790 ;; Possibly raise an error if named block doesn't exist.
2791 (if (or org-babel-noweb-error-all-langs
2792 (member lang org-babel-noweb-error-langs))
2793 (error "%s" (concat
2794 (org-babel-noweb-wrap source-name)
2795 "could not be resolved (see "
2796 "`org-babel-noweb-error-langs')"))
2797 "")))
2798 "[\n\r]") (concat "\n" prefix))))))
2799 (funcall nb-add (buffer-substring index (point-max))))
2800 new-body))
2802 (defun org-babel--script-escape-inner (str)
2803 (let (in-single in-double backslash out)
2804 (mapc
2805 (lambda (ch)
2806 (setq
2808 (if backslash
2809 (progn
2810 (setq backslash nil)
2811 (cond
2812 ((and in-single (eq ch ?'))
2813 ;; Escaped single quote inside single quoted string:
2814 ;; emit just a single quote, since we've changed the
2815 ;; outer quotes to double.
2816 (cons ch out))
2817 ((eq ch ?\")
2818 ;; Escaped double quote
2819 (if in-single
2820 ;; This should be interpreted as backslash+quote,
2821 ;; not an escape. Emit a three backslashes
2822 ;; followed by a quote (because one layer of
2823 ;; quoting will be stripped by `org-babel-read').
2824 (append (list ch ?\\ ?\\ ?\\) out)
2825 ;; Otherwise we are in a double-quoted string. Emit
2826 ;; a single escaped quote
2827 (append (list ch ?\\) out)))
2828 ((eq ch ?\\)
2829 ;; Escaped backslash: emit a single escaped backslash
2830 (append (list ?\\ ?\\) out))
2831 ;; Other: emit a quoted backslash followed by whatever
2832 ;; the character was (because one layer of quoting will
2833 ;; be stripped by `org-babel-read').
2834 (t (append (list ch ?\\ ?\\) out))))
2835 (cl-case ch
2836 (?\[ (if (or in-double in-single)
2837 (cons ?\[ out)
2838 (cons ?\( out)))
2839 (?\] (if (or in-double in-single)
2840 (cons ?\] out)
2841 (cons ?\) out)))
2842 (?\{ (if (or in-double in-single)
2843 (cons ?\{ out)
2844 (cons ?\( out)))
2845 (?\} (if (or in-double in-single)
2846 (cons ?\} out)
2847 (cons ?\) out)))
2848 (?, (if (or in-double in-single)
2849 (cons ?, out) (cons ?\s out)))
2850 (?\' (if in-double
2851 (cons ?\' out)
2852 (setq in-single (not in-single)) (cons ?\" out)))
2853 (?\" (if in-single
2854 (append (list ?\" ?\\) out)
2855 (setq in-double (not in-double)) (cons ?\" out)))
2856 (?\\ (unless (or in-single in-double)
2857 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2858 (setq backslash t)
2859 out)
2860 (t (cons ch out))))))
2861 (string-to-list str))
2862 (when (or in-single in-double)
2863 (error "Unterminated string in `org-babel-script-escape'"))
2864 (apply #'string (reverse out))))
2866 (defun org-babel-script-escape (str &optional force)
2867 "Safely convert tables into elisp lists."
2868 (unless (stringp str)
2869 (error "`org-babel-script-escape' expects a string"))
2870 (let ((escaped
2871 (cond
2872 ((and (> (length str) 2)
2873 (or (and (string-equal "[" (substring str 0 1))
2874 (string-equal "]" (substring str -1)))
2875 (and (string-equal "{" (substring str 0 1))
2876 (string-equal "}" (substring str -1)))
2877 (and (string-equal "(" (substring str 0 1))
2878 (string-equal ")" (substring str -1)))))
2880 (concat "'" (org-babel--script-escape-inner str)))
2881 ((or force
2882 (and (> (length str) 2)
2883 (or (and (string-equal "'" (substring str 0 1))
2884 (string-equal "'" (substring str -1)))
2885 ;; We need to pass double-quoted strings
2886 ;; through the backslash-twiddling bits, even
2887 ;; though we don't need to change their
2888 ;; delimiters.
2889 (and (string-equal "\"" (substring str 0 1))
2890 (string-equal "\"" (substring str -1))))))
2891 (org-babel--script-escape-inner str))
2892 (t str))))
2893 (condition-case nil (org-babel-read escaped) (error escaped))))
2895 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2896 "Convert the string value of CELL to a number if appropriate.
2897 Otherwise if CELL looks like lisp (meaning it starts with a
2898 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2899 lisp, otherwise return it unmodified as a string. Optional
2900 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2901 situations in which is it not appropriate."
2902 (cond ((not (org-string-nw-p cell)) cell)
2903 ((org-babel--string-to-number cell))
2904 ((and (not inhibit-lisp-eval)
2905 (or (memq (string-to-char cell) '(?\( ?' ?` ?\[))
2906 (string= cell "*this*")))
2907 (eval (read cell) t))
2908 ((eq (string-to-char cell) ?\") (read cell))
2909 (t (org-no-properties cell))))
2911 (defun org-babel--string-to-number (string)
2912 "If STRING represents a number return its value.
2913 Otherwise return nil."
2914 (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string)
2915 (string-to-number string)))
2917 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2918 "Read the results located at FILE-NAME into an elisp table.
2919 If the table is trivial, then return it as a scalar."
2920 (let (result)
2921 (save-window-excursion
2922 (with-temp-buffer
2923 (condition-case err
2924 (progn
2925 (org-table-import file-name separator)
2926 (delete-file file-name)
2927 (setq result (mapcar (lambda (row)
2928 (mapcar #'org-babel-string-read row))
2929 (org-table-to-lisp))))
2930 (error (message "Error reading results: %s" err) nil)))
2931 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2932 (if (consp (car result))
2933 (if (null (cdr (car result)))
2934 (caar result)
2935 result)
2936 (car result))
2937 result))))
2939 (defun org-babel-string-read (cell)
2940 "Strip nested \"s from around strings."
2941 (org-babel-read (or (and (stringp cell)
2942 (string-match "\\\"\\(.+\\)\\\"" cell)
2943 (match-string 1 cell))
2944 cell) t))
2946 (defun org-babel-chomp (string &optional regexp)
2947 "Strip a trailing space or carriage return from STRING.
2948 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2949 can be specified as the REGEXP argument."
2950 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2951 (while (and (> (length string) 0)
2952 (string-match regexp (substring string -1)))
2953 (setq string (substring string 0 -1)))
2954 string))
2956 (defun org-babel-process-file-name (name &optional no-quote-p)
2957 "Prepare NAME to be used in an external process.
2958 If NAME specifies a remote location, the remote portion of the
2959 name is removed, since in that case the process will be executing
2960 remotely. The file name is then processed by `expand-file-name'.
2961 Unless second argument NO-QUOTE-P is non-nil, the file name is
2962 additionally processed by `shell-quote-argument'"
2963 (let ((f (org-babel-local-file-name (expand-file-name name))))
2964 (if no-quote-p f (shell-quote-argument f))))
2966 (defvar org-babel-temporary-directory)
2967 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2968 (defvar org-babel-temporary-directory
2969 (or (and (boundp 'org-babel-temporary-directory)
2970 (file-exists-p org-babel-temporary-directory)
2971 org-babel-temporary-directory)
2972 (make-temp-file "babel-" t))
2973 "Directory to hold temporary files created to execute code blocks.
2974 Used by `org-babel-temp-file'. This directory will be removed on
2975 Emacs shutdown."))
2977 (defcustom org-babel-remote-temporary-directory "/tmp/"
2978 "Directory to hold temporary files on remote hosts."
2979 :group 'org-babel
2980 :type 'string)
2982 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2983 "Call the code to parse raw string results according to RESULT-PARAMS."
2984 (declare (indent 1)
2985 (debug (form form &rest form)))
2986 (org-with-gensyms (params)
2987 `(let ((,params ,result-params))
2988 (unless (member "none" ,params)
2989 (if (or (member "scalar" ,params)
2990 (member "verbatim" ,params)
2991 (member "html" ,params)
2992 (member "code" ,params)
2993 (member "pp" ,params)
2994 (member "file" ,params)
2995 (and (or (member "output" ,params)
2996 (member "raw" ,params)
2997 (member "org" ,params)
2998 (member "drawer" ,params))
2999 (not (member "table" ,params))))
3000 ,scalar-form
3001 ,@table-forms)))))
3002 (def-edebug-spec org-babel-result-cond (form form body))
3004 (defun org-babel-temp-file (prefix &optional suffix)
3005 "Create a temporary file in the `org-babel-temporary-directory'.
3006 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3007 value of `temporary-file-directory' temporarily set to the value
3008 of `org-babel-temporary-directory'."
3009 (if (file-remote-p default-directory)
3010 (let ((prefix
3011 (concat (file-remote-p default-directory)
3012 (expand-file-name
3013 prefix org-babel-remote-temporary-directory))))
3014 (make-temp-file prefix nil suffix))
3015 (let ((temporary-file-directory
3016 (or (and (boundp 'org-babel-temporary-directory)
3017 (file-exists-p org-babel-temporary-directory)
3018 org-babel-temporary-directory)
3019 temporary-file-directory)))
3020 (make-temp-file prefix nil suffix))))
3022 (defun org-babel-remove-temporary-directory ()
3023 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3024 (when (and (boundp 'org-babel-temporary-directory)
3025 (file-exists-p org-babel-temporary-directory))
3026 ;; taken from `delete-directory' in files.el
3027 (condition-case nil
3028 (progn
3029 (mapc (lambda (file)
3030 ;; This test is equivalent to
3031 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3032 ;; but more efficient
3033 (if (eq t (car (file-attributes file)))
3034 (delete-directory file)
3035 (delete-file file)))
3036 ;; We do not want to delete "." and "..".
3037 (directory-files org-babel-temporary-directory 'full
3038 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3039 (delete-directory org-babel-temporary-directory))
3040 (error
3041 (message "Failed to remove temporary Org-babel directory %s"
3042 (if (boundp 'org-babel-temporary-directory)
3043 org-babel-temporary-directory
3044 "[directory not defined]"))))))
3046 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
3048 (defun org-babel-one-header-arg-safe-p (pair safe-list)
3049 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3051 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3052 (and (consp pair)
3053 (keywordp (car pair))
3054 (stringp (cdr pair))
3056 (memq (car pair) safe-list)
3057 (let ((entry (assq (car pair) safe-list)))
3058 (and entry
3059 (consp entry)
3060 (cond ((functionp (cdr entry))
3061 (funcall (cdr entry) (cdr pair)))
3062 ((listp (cdr entry))
3063 (member (cdr pair) (cdr entry)))
3064 (t nil)))))))
3066 (defun org-babel-generate-file-param (src-name params)
3067 "Calculate the filename for source block results.
3069 The directory is calculated from the :output-dir property of the
3070 source block; if not specified, use the current directory.
3072 If the source block has a #+NAME and the :file parameter does not
3073 contain any period characters, then the :file parameter is
3074 treated as an extension, and the output file name is the
3075 concatenation of the directory (as calculated above), the block
3076 name, a period, and the parameter value as a file extension.
3077 Otherwise, the :file parameter is treated as a full file name,
3078 and the output file name is the directory (as calculated above)
3079 plus the parameter value."
3080 (let* ((file-cons (assq :file params))
3081 (file-ext-cons (assq :file-ext params))
3082 (file-ext (cdr-safe file-ext-cons))
3083 (dir (cdr-safe (assq :output-dir params)))
3084 fname)
3085 ;; create the output-dir if it does not exist
3086 (when dir
3087 (make-directory dir t))
3088 (if file-cons
3089 ;; :file given; add :output-dir if given
3090 (when dir
3091 (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
3092 ;; :file not given; compute from name and :file-ext if possible
3093 (when (and src-name file-ext)
3094 (if dir
3095 (setq fname (concat (file-name-as-directory (or dir ""))
3096 src-name "." file-ext))
3097 (setq fname (concat src-name "." file-ext)))
3098 (setq params (cons (cons :file fname) params))))
3099 params))
3101 (defun org-babel-graphical-output-file (params)
3102 "File where a babel block should send graphical output, per PARAMS.
3103 Return nil if no graphical output is expected. Raise an error if
3104 the output file is ill-defined."
3105 (let ((file (cdr (assq :file params))))
3106 (cond (file (and (member "graphics" (cdr (assq :result-params params)))
3107 file))
3108 ((assq :file-ext params)
3109 (user-error ":file-ext given but no :file generated; did you forget \
3110 to name a block?"))
3111 (t (user-error "No :file header argument given; cannot create \
3112 graphical result")))))
3114 (defun org-babel-make-language-alias (new old)
3115 "Make source blocks of type NEW aliases for those of type OLD.
3117 NEW and OLD should be strings. This function should be called
3118 after the babel API for OLD-type source blocks is fully defined.
3120 Callers of this function will probably want to add an entry to
3121 `org-src-lang-modes' as well."
3122 (dolist (fn '("execute" "expand-body" "prep-session"
3123 "variable-assignments" "load-session"))
3124 (let ((sym (intern-soft (concat "org-babel-" fn ":" old))))
3125 (when (and sym (fboundp sym))
3126 (defalias (intern (concat "org-babel-" fn ":" new)) sym))))
3127 ;; Technically we don't need a `dolist' for just one variable, but
3128 ;; we keep it for symmetry/ease of future expansion.
3129 (dolist (var '("default-header-args"))
3130 (let ((sym (intern-soft (concat "org-babel-" var ":" old))))
3131 (when (and sym (boundp sym))
3132 (defvaralias (intern (concat "org-babel-" var ":" new)) sym)))))
3134 (defun org-babel-strip-quotes (string)
3135 "Strip \\\"s from around a string, if applicable."
3136 (org-unbracket-string "\"" "\"" string))
3138 (provide 'ob-core)
3140 ;; Local variables:
3141 ;; generated-autoload-file: "org-loaddefs.el"
3142 ;; End:
3144 ;;; ob-core.el ends here