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