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