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