* ob-vbnet.el: Org-babel functions for VB.Net evaluation
[org-mode/org-tableheadings.git] / lisp / ob-core.el
blob8bc07dd85d14c63f5f36b534c693530ac794922b
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 (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 (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 (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 ;; header arguments specified with the header-args property at
1416 ;; point of call.
1417 (org-babel-parse-header-arguments
1418 (org-entry-get org-babel-current-src-block-location
1419 "header-args"
1420 'inherit))
1421 (and lang ; language-specific header arguments at point of call
1422 (org-babel-parse-header-arguments
1423 (org-entry-get org-babel-current-src-block-location
1424 (concat "header-args:" lang)
1425 'inherit))))))
1427 (defun org-babel-balanced-split (string alts)
1428 "Split STRING on instances of ALTS.
1429 ALTS is a cons of two character options where each option may be
1430 either the numeric code of a single character or a list of
1431 character alternatives. For example to split on balanced
1432 instances of \"[ \t]:\" set ALTS to ((32 9) . 58)."
1433 (let* ((matches (lambda (ch spec) (if (listp spec) (member ch spec) (equal spec ch))))
1434 (matched (lambda (ch last)
1435 (if (consp alts)
1436 (and (funcall matches ch (cdr alts))
1437 (funcall matches last (car alts)))
1438 (funcall matches ch alts))))
1439 (balance 0) (last 0)
1440 quote partial lst)
1441 (mapc (lambda (ch) ; split on [], (), "" balanced instances of [ \t]:
1442 (setq balance (+ balance
1443 (cond ((or (equal 91 ch) (equal 40 ch)) 1)
1444 ((or (equal 93 ch) (equal 41 ch)) -1)
1445 (t 0))))
1446 (when (and (equal 34 ch) (not (equal 92 last)))
1447 (setq quote (not quote)))
1448 (setq partial (cons ch partial))
1449 (when (and (= balance 0) (not quote) (funcall matched ch last))
1450 (setq lst (cons (apply #'string (nreverse
1451 (if (consp alts)
1452 (cddr partial)
1453 (cdr partial))))
1454 lst))
1455 (setq partial nil))
1456 (setq last ch))
1457 (string-to-list string))
1458 (nreverse (cons (apply #'string (nreverse partial)) lst))))
1460 (defun org-babel-join-splits-near-ch (ch list)
1461 "Join splits where \"=\" is on either end of the split."
1462 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1463 (first= (lambda (str) (= ch (aref str 0)))))
1464 (reverse
1465 (cl-reduce (lambda (acc el)
1466 (let ((head (car acc)))
1467 (if (and head (or (funcall last= head) (funcall first= el)))
1468 (cons (concat head el) (cdr acc))
1469 (cons el acc))))
1470 list :initial-value nil))))
1472 (defun org-babel-parse-header-arguments (arg-string)
1473 "Parse a string of header arguments returning an alist."
1474 (when (> (length arg-string) 0)
1475 (org-babel-parse-multiple-vars
1476 (delq nil
1477 (mapcar
1478 (lambda (arg)
1479 (if (string-match
1480 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1481 arg)
1482 (cons (intern (match-string 1 arg))
1483 (org-babel-read (org-babel-chomp (match-string 2 arg))))
1484 (cons (intern (org-babel-chomp arg)) nil)))
1485 (let ((raw (org-babel-balanced-split arg-string '((32 9) . 58))))
1486 (cons (car raw) (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
1488 (defun org-babel-parse-multiple-vars (header-arguments)
1489 "Expand multiple variable assignments behind a single :var keyword.
1491 This allows expression of multiple variables with one :var as
1492 shown below.
1494 #+PROPERTY: var foo=1, bar=2"
1495 (let (results)
1496 (mapc (lambda (pair)
1497 (if (eq (car pair) :var)
1498 (mapcar (lambda (v) (push (cons :var (org-trim v)) results))
1499 (org-babel-join-splits-near-ch
1500 61 (org-babel-balanced-split (cdr pair) 32)))
1501 (push pair results)))
1502 header-arguments)
1503 (nreverse results)))
1505 (defun org-babel-process-params (params)
1506 "Expand variables in PARAMS and add summary parameters."
1507 (let* ((processed-vars (mapcar (lambda (el)
1508 (if (consp el)
1510 (org-babel-ref-parse el)))
1511 (org-babel--get-vars params)))
1512 (vars-and-names (if (and (assoc :colname-names params)
1513 (assoc :rowname-names params))
1514 (list processed-vars)
1515 (org-babel-disassemble-tables
1516 processed-vars
1517 (cdr (assoc :hlines params))
1518 (cdr (assoc :colnames params))
1519 (cdr (assoc :rownames params)))))
1520 (raw-result (or (cdr (assoc :results params)) ""))
1521 (result-params (delete-dups
1522 (append
1523 (split-string (if (stringp raw-result)
1524 raw-result
1525 (eval raw-result t)))
1526 (cdr (assoc :result-params params))))))
1527 (append
1528 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1529 (list
1530 (cons :colname-names (or (cdr (assoc :colname-names params))
1531 (cadr vars-and-names)))
1532 (cons :rowname-names (or (cdr (assoc :rowname-names params))
1533 (caddr vars-and-names)))
1534 (cons :result-params result-params)
1535 (cons :result-type (cond ((member "output" result-params) 'output)
1536 ((member "value" result-params) 'value)
1537 (t 'value))))
1538 (cl-remove-if
1539 (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params
1540 :result-type :var)))
1541 params))))
1543 ;; row and column names
1544 (defun org-babel-del-hlines (table)
1545 "Remove all `hline's from TABLE."
1546 (remq 'hline table))
1548 (defun org-babel-get-colnames (table)
1549 "Return the column names of TABLE.
1550 Return a cons cell, the `car' of which contains the TABLE less
1551 colnames, and the `cdr' of which contains a list of the column
1552 names."
1553 (if (equal 'hline (nth 1 table))
1554 (cons (cddr table) (car table))
1555 (cons (cdr table) (car table))))
1557 (defun org-babel-get-rownames (table)
1558 "Return the row names of TABLE.
1559 Return a cons cell, the `car' of which contains the TABLE less
1560 rownames, and the `cdr' of which contains a list of the rownames.
1561 Note: this function removes any hlines in TABLE."
1562 (let* ((table (org-babel-del-hlines table))
1563 (rownames (funcall (lambda ()
1564 (let ((tp table))
1565 (mapcar
1566 (lambda (_row)
1567 (prog1
1568 (pop (car tp))
1569 (setq tp (cdr tp))))
1570 table))))))
1571 (cons table rownames)))
1573 (defun org-babel-put-colnames (table colnames)
1574 "Add COLNAMES to TABLE if they exist."
1575 (if colnames (apply 'list colnames 'hline table) table))
1577 (defun org-babel-put-rownames (table rownames)
1578 "Add ROWNAMES to TABLE if they exist."
1579 (if rownames
1580 (mapcar (lambda (row)
1581 (if (listp row)
1582 (cons (or (pop rownames) "") row)
1583 row)) table)
1584 table))
1586 (defun org-babel-pick-name (names selector)
1587 "Select one out of an alist of row or column names.
1588 SELECTOR can be either a list of names in which case those names
1589 will be returned directly, or an index into the list NAMES in
1590 which case the indexed names will be return."
1591 (if (listp selector)
1592 selector
1593 (when names
1594 (if (and selector (symbolp selector) (not (equal t selector)))
1595 (cdr (assoc selector names))
1596 (if (integerp selector)
1597 (nth (- selector 1) names)
1598 (cdr (car (last names))))))))
1600 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1601 "Parse tables for further processing.
1602 Process the variables in VARS according to the HLINES,
1603 ROWNAMES and COLNAMES header arguments. Return a list consisting
1604 of the vars, cnames and rnames."
1605 (let (cnames rnames)
1606 (list
1607 (mapcar
1608 (lambda (var)
1609 (when (listp (cdr var))
1610 (when (and (not (equal colnames "no"))
1611 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
1612 (not (member 'hline (cddr (cdr var)))))))
1613 (let ((both (org-babel-get-colnames (cdr var))))
1614 (setq cnames (cons (cons (car var) (cdr both))
1615 cnames))
1616 (setq var (cons (car var) (car both)))))
1617 (when (and rownames (not (equal rownames "no")))
1618 (let ((both (org-babel-get-rownames (cdr var))))
1619 (setq rnames (cons (cons (car var) (cdr both))
1620 rnames))
1621 (setq var (cons (car var) (car both)))))
1622 (when (and hlines (not (equal hlines "yes")))
1623 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1624 var)
1625 vars)
1626 (reverse cnames) (reverse rnames))))
1628 (defun org-babel-reassemble-table (table colnames rownames)
1629 "Add column and row names to a table.
1630 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1631 to the table for reinsertion to org-mode."
1632 (if (listp table)
1633 (let ((table (if (and rownames (= (length table) (length rownames)))
1634 (org-babel-put-rownames table rownames) table)))
1635 (if (and colnames (listp (car table)) (= (length (car table))
1636 (length colnames)))
1637 (org-babel-put-colnames table colnames) table))
1638 table))
1640 (defun org-babel-where-is-src-block-head (&optional src-block)
1641 "Find where the current source block begins.
1643 If optional argument SRC-BLOCK is `src-block' type element, find
1644 its current beginning instead.
1646 Return the point at the beginning of the current source block.
1647 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1648 match-data relatively to `org-babel-src-block-regexp', which see.
1649 If the point is not on a source block then return nil."
1650 (let ((element (or src-block (org-element-at-point))))
1651 (when (eq (org-element-type element) 'src-block)
1652 (let ((end (org-element-property :end element)))
1653 (org-with-wide-buffer
1654 ;; Ensure point is not on a blank line after the block.
1655 (beginning-of-line)
1656 (skip-chars-forward " \r\t\n" end)
1657 (when (< (point) end)
1658 (prog1 (goto-char (org-element-property :post-affiliated element))
1659 (looking-at org-babel-src-block-regexp))))))))
1661 ;;;###autoload
1662 (defun org-babel-goto-src-block-head ()
1663 "Go to the beginning of the current code block."
1664 (interactive)
1665 (let ((head (org-babel-where-is-src-block-head)))
1666 (if head (goto-char head) (error "Not currently in a code block"))))
1668 ;;;###autoload
1669 (defun org-babel-goto-named-src-block (name)
1670 "Go to a named source-code block."
1671 (interactive
1672 (let ((completion-ignore-case t)
1673 (case-fold-search t)
1674 (all-block-names (org-babel-src-block-names)))
1675 (list (completing-read
1676 "source-block name: " all-block-names nil t
1677 (let* ((context (org-element-context))
1678 (type (org-element-type context))
1679 (noweb-ref
1680 (and (memq type '(inline-src-block src-block))
1681 (org-in-regexp (org-babel-noweb-wrap)))))
1682 (cond
1683 (noweb-ref
1684 (buffer-substring
1685 (+ (car noweb-ref) (length org-babel-noweb-wrap-start))
1686 (- (cdr noweb-ref) (length org-babel-noweb-wrap-end))))
1687 ((memq type '(babel-call inline-babel-call)) ;#+CALL:
1688 (org-element-property :call context))
1689 ((car (org-element-property :results context))) ;#+RESULTS:
1690 ((let ((symbol (thing-at-point 'symbol))) ;Symbol.
1691 (and symbol
1692 (member-ignore-case symbol all-block-names)
1693 symbol)))
1694 (t "")))))))
1695 (let ((point (org-babel-find-named-block name)))
1696 (if point
1697 ;; Taken from `org-open-at-point'.
1698 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1699 (message "source-code block `%s' not found in this buffer" name))))
1701 (defun org-babel-find-named-block (name)
1702 "Find a named source-code block.
1703 Return the location of the source block identified by source
1704 NAME, or nil if no such block exists. Set match data according
1705 to `org-babel-named-src-block-regexp'."
1706 (save-excursion
1707 (goto-char (point-min))
1708 (ignore-errors
1709 (org-next-block 1 nil (org-babel-named-src-block-regexp-for-name name)))))
1711 (defun org-babel-src-block-names (&optional file)
1712 "Returns the names of source blocks in FILE or the current buffer."
1713 (when file (find-file file))
1714 (save-excursion
1715 (goto-char (point-min))
1716 (let ((re (org-babel-named-src-block-regexp-for-name))
1717 names)
1718 (while (ignore-errors (org-next-block 1 nil re))
1719 (push (match-string-no-properties 9) names))
1720 names)))
1722 ;;;###autoload
1723 (defun org-babel-goto-named-result (name)
1724 "Go to a named result."
1725 (interactive
1726 (let ((completion-ignore-case t))
1727 (list (completing-read "Source-block name: "
1728 (org-babel-result-names) nil t))))
1729 (let ((point (org-babel-find-named-result name)))
1730 (if point
1731 ;; taken from `org-open-at-point'
1732 (progn (goto-char point) (org-show-context))
1733 (message "result `%s' not found in this buffer" name))))
1735 (defun org-babel-find-named-result (name)
1736 "Find a named result.
1737 Return the location of the result named NAME in the current
1738 buffer or nil if no such result exists."
1739 (save-excursion
1740 (goto-char (point-min))
1741 (let ((case-fold-search t)
1742 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1743 org-babel-results-keyword
1744 (regexp-quote name))))
1745 (catch :found
1746 (while (re-search-forward re nil t)
1747 (let ((element (org-element-at-point)))
1748 (when (or (eq (org-element-type element) 'keyword)
1749 (< (point)
1750 (org-element-property :post-affiliated element)))
1751 (throw :found (line-beginning-position)))))))))
1753 (defun org-babel-result-names (&optional file)
1754 "Returns the names of results in FILE or the current buffer."
1755 (save-excursion
1756 (when file (find-file file)) (goto-char (point-min))
1757 (let ((case-fold-search t) names)
1758 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1759 (setq names (cons (match-string-no-properties 9) names)))
1760 names)))
1762 ;;;###autoload
1763 (defun org-babel-next-src-block (&optional arg)
1764 "Jump to the next source block.
1765 With optional prefix argument ARG, jump forward ARG many source blocks."
1766 (interactive "p")
1767 (org-next-block arg nil org-babel-src-block-regexp))
1769 ;;;###autoload
1770 (defun org-babel-previous-src-block (&optional arg)
1771 "Jump to the previous source block.
1772 With optional prefix argument ARG, jump backward ARG many source blocks."
1773 (interactive "p")
1774 (org-previous-block arg org-babel-src-block-regexp))
1776 (defvar org-babel-load-languages)
1778 ;;;###autoload
1779 (defun org-babel-mark-block ()
1780 "Mark current src block."
1781 (interactive)
1782 (let ((head (org-babel-where-is-src-block-head)))
1783 (when head
1784 (save-excursion
1785 (goto-char head)
1786 (looking-at org-babel-src-block-regexp))
1787 (push-mark (match-end 5) nil t)
1788 (goto-char (match-beginning 5)))))
1790 (defun org-babel-demarcate-block (&optional arg)
1791 "Wrap or split the code in the region or on the point.
1792 When called from inside of a code block the current block is
1793 split. When called from outside of a code block a new code block
1794 is created. In both cases if the region is demarcated and if the
1795 region is not active then the point is demarcated."
1796 (interactive "P")
1797 (let* ((info (org-babel-get-src-block-info 'light))
1798 (start (org-babel-where-is-src-block-head))
1799 (block (and start (match-string 0)))
1800 (headers (and start (match-string 4)))
1801 (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
1802 (lower-case-p (and block
1803 (let (case-fold-search)
1804 (org-string-match-p "#\\+begin_src" block)))))
1805 (if info
1806 (mapc
1807 (lambda (place)
1808 (save-excursion
1809 (goto-char place)
1810 (let ((lang (nth 0 info))
1811 (indent (make-string (org-get-indentation) ?\s)))
1812 (when (string-match "^[[:space:]]*$"
1813 (buffer-substring (point-at-bol)
1814 (point-at-eol)))
1815 (delete-region (point-at-bol) (point-at-eol)))
1816 (insert (concat
1817 (if (looking-at "^") "" "\n")
1818 indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")
1819 (if arg stars indent) "\n"
1820 indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1821 lang
1822 (if (> (length headers) 1)
1823 (concat " " headers) headers)
1824 (if (looking-at "[\n\r]")
1826 (concat "\n" (make-string (current-column) ? )))))))
1827 (move-end-of-line 2))
1828 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1829 (let ((start (point))
1830 (lang (completing-read
1831 "Lang: "
1832 (mapcar #'symbol-name
1833 (delete-dups
1834 (append (mapcar #'car org-babel-load-languages)
1835 (mapcar (lambda (el) (intern (car el)))
1836 org-src-lang-modes))))))
1837 (body (delete-and-extract-region
1838 (if (org-region-active-p) (mark) (point)) (point))))
1839 (insert (concat (if (looking-at "^") "" "\n")
1840 (if arg (concat stars "\n") "")
1841 (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1842 lang "\n"
1843 body
1844 (if (or (= (length body) 0)
1845 (string-match "[\r\n]$" body)) "" "\n")
1846 (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")))
1847 (goto-char start) (move-end-of-line 1)))))
1849 (defun org-babel--insert-results-keyword (name hash)
1850 "Insert RESULTS keyword with NAME value at point.
1851 If NAME is nil, results are anonymous. HASH is a string used as
1852 the results hash, or nil. Leave point before the keyword."
1853 (save-excursion (insert "\n")) ;open line to indent.
1854 (org-indent-line)
1855 (delete-char 1)
1856 (insert (concat "#+" org-babel-results-keyword
1857 (cond ((not hash) nil)
1858 (org-babel-hash-show-time
1859 (format "[%s %s]"
1860 (format-time-string "<%Y-%m-%d %H:%M:%S>")
1861 hash))
1862 (t (format "[%s]" hash)))
1864 (when name (concat " " name))
1865 "\n\n"))
1866 (beginning-of-line -1)
1867 (when hash (org-babel-hide-hash)))
1869 (defun org-babel--clear-results-maybe (hash)
1870 "Clear results when hash doesn't match HASH.
1872 When results hash does not match HASH, remove RESULTS keyword at
1873 point, along with related contents. Do nothing if HASH is nil.
1875 Return a non-nil value if results were cleared. In this case,
1876 leave point where new results should be inserted."
1877 (when hash
1878 (looking-at org-babel-result-regexp)
1879 (unless (string= (match-string 1) hash)
1880 (let* ((e (org-element-at-point))
1881 (post (copy-marker (org-element-property :post-affiliated e))))
1882 ;; Delete contents.
1883 (delete-region post
1884 (save-excursion
1885 (goto-char (org-element-property :end e))
1886 (skip-chars-backward " \t\n")
1887 (line-beginning-position 2)))
1888 ;; Delete RESULT keyword. However, if RESULTS keyword is
1889 ;; orphaned, ignore this part. The deletion above already
1890 ;; took care of it.
1891 (unless (= (point) post)
1892 (delete-region (line-beginning-position)
1893 (line-beginning-position 2)))
1894 (goto-char post)
1895 (set-marker post nil)))
1898 (defun org-babel-where-is-src-block-result (&optional insert _info hash)
1899 "Find where the current source block results begin.
1901 Return the point at the beginning of the result of the current
1902 source block, specifically at the beginning of the results line.
1904 If no result exists for this block return nil, unless optional
1905 argument INSERT is non-nil. In this case, create a results line
1906 following the source block and return the position at its
1907 beginning. In the case of inline code, remove the results part
1908 instead.
1910 If optional argument HASH is a string, remove contents related to
1911 RESULTS keyword if its hash is different. Then update the latter
1912 to HASH."
1913 (let ((context (org-element-context)))
1914 (catch :found
1915 (org-with-wide-buffer
1916 (pcase (org-element-type context)
1917 ((or `inline-babel-call `inline-src-block)
1918 ;; Results for inline objects are located right after them.
1919 ;; There is no RESULTS line to insert either.
1920 (let ((limit (org-element-property
1921 :contents-end (org-element-property :parent context))))
1922 (goto-char (org-element-property :end context))
1923 (skip-chars-forward " \t\n" limit)
1924 (throw :found
1925 (and
1926 (< (point) limit)
1927 (let ((result (org-element-context)))
1928 (and (eq (org-element-type result) 'macro)
1929 (string= (org-element-property :key result)
1930 "results")
1931 (if (not insert) (point)
1932 (delete-region
1933 (point)
1934 (progn
1935 (goto-char (org-element-property :end result))
1936 (skip-chars-backward " \t")
1937 (point)))
1938 (point))))))))
1939 ((or `babel-call `src-block)
1940 (let* ((name (org-element-property :name context))
1941 (named-results (and name (org-babel-find-named-result name))))
1942 (goto-char (or named-results (org-element-property :end context)))
1943 (cond
1944 ;; Existing results named after the current source.
1945 (named-results
1946 (when (org-babel--clear-results-maybe hash)
1947 (org-babel--insert-results-keyword name hash))
1948 (throw :found (point)))
1949 ;; Named results expect but none to be found.
1950 (name)
1951 ;; No possible anonymous results at the very end of
1952 ;; buffer or outside CONTEXT parent.
1953 ((eq (point)
1954 (or (org-element-property
1955 :contents-end (org-element-property :parent context))
1956 (point-max))))
1957 ;; Check if next element is an anonymous result below
1958 ;; the current block.
1959 ((let* ((next (org-element-at-point))
1960 (end (save-excursion
1961 (goto-char
1962 (org-element-property :post-affiliated next))
1963 (line-end-position)))
1964 (empty-result-re (concat org-babel-result-regexp "$"))
1965 (case-fold-search t))
1966 (re-search-forward empty-result-re end t))
1967 (beginning-of-line)
1968 (when (org-babel--clear-results-maybe hash)
1969 (org-babel--insert-results-keyword nil hash))
1970 (throw :found (point))))))
1971 ;; Ignore other elements.
1972 (_ (throw :found nil))))
1973 ;; No result found. Insert a RESULTS keyword below element, if
1974 ;; appropriate. In this case, ensure there is an empty line
1975 ;; after the previous element.
1976 (when insert
1977 (save-excursion
1978 (goto-char (min (org-element-property :end context) (point-max)))
1979 (skip-chars-backward " \t\n")
1980 (forward-line)
1981 (cond ((not (bolp)) (insert "\n\n"))
1982 ((or (eobp)
1983 (= (org-element-property :post-blank context) 0))
1984 (insert "\n"))
1985 (t (forward-line)))
1986 (org-babel--insert-results-keyword
1987 (org-element-property :name context) hash)
1988 (point))))))
1990 (defun org-babel-read-element (element)
1991 "Read ELEMENT into emacs-lisp.
1992 Return nil if ELEMENT cannot be read."
1993 (org-with-wide-buffer
1994 (goto-char (org-element-property :post-affiliated element))
1995 (pcase (org-element-type element)
1996 (`fixed-width
1997 (let ((v (org-trim (org-element-property :value element))))
1998 (or (org-babel-number-p v) v)))
1999 (`table (org-babel-read-table))
2000 (`plain-list (org-babel-read-list))
2001 (`example-block
2002 (let ((v (org-element-property :value element)))
2003 (if (or org-src-preserve-indentation
2004 (org-element-property :preserve-indent element))
2006 (org-remove-indentation v))))
2007 (`export-block
2008 (org-remove-indentation (org-element-property :value element)))
2009 (`paragraph
2010 ;; Treat paragraphs containing a single link specially.
2011 (skip-chars-forward " \t")
2012 (if (and (looking-at org-bracket-link-regexp)
2013 (save-excursion
2014 (goto-char (match-end 0))
2015 (skip-chars-forward " \r\t\n")
2016 (<= (org-element-property :end element)
2017 (point))))
2018 (org-babel-read-link)
2019 (buffer-substring-no-properties
2020 (org-element-property :contents-begin element)
2021 (org-element-property :contents-end element))))
2022 ((or `center-block `quote-block `verse-block `special-block)
2023 (org-remove-indentation
2024 (buffer-substring-no-properties
2025 (org-element-property :contents-begin element)
2026 (org-element-property :contents-end element))))
2027 (_ nil))))
2029 (defun org-babel-read-result ()
2030 "Read the result at point into emacs-lisp."
2031 (and (not (save-excursion
2032 (beginning-of-line)
2033 (looking-at-p "[ \t]*$")))
2034 (org-babel-read-element (org-element-at-point))))
2036 (defun org-babel-read-table ()
2037 "Read the table at point into emacs-lisp."
2038 (mapcar (lambda (row)
2039 (if (and (symbolp row) (equal row 'hline)) row
2040 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
2041 (org-table-to-lisp)))
2043 (defun org-babel-read-list ()
2044 "Read the list at point into emacs-lisp."
2045 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2046 (cdr (org-list-to-lisp))))
2048 (defvar org-link-types-re)
2049 (defun org-babel-read-link ()
2050 "Read the link at point into emacs-lisp.
2051 If the path of the link is a file path it is expanded using
2052 `expand-file-name'."
2053 (let* ((case-fold-search t)
2054 (raw (and (looking-at org-bracket-link-regexp)
2055 (org-no-properties (match-string 1))))
2056 (type (and (string-match org-link-types-re raw)
2057 (match-string 1 raw))))
2058 (cond
2059 ((not type) (expand-file-name raw))
2060 ((string= type "file")
2061 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
2062 (expand-file-name (match-string 2 raw))))
2063 (t raw))))
2065 (defun org-babel-format-result (result &optional sep)
2066 "Format RESULT for writing to file."
2067 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
2068 (if (listp result)
2069 ;; table result
2070 (orgtbl-to-generic
2071 result (list :sep (or sep "\t") :fmt echo-res))
2072 ;; scalar result
2073 (funcall echo-res result))))
2075 (defun org-babel-insert-result (result &optional result-params info hash lang)
2076 "Insert RESULT into the current buffer.
2078 By default RESULT is inserted after the end of the current source
2079 block. The RESULT of an inline source block usually will be
2080 wrapped inside a `results' macro and placed on the same line as
2081 the inline source block. The macro is stripped upon export.
2082 Multiline and non-scalar RESULTS from inline source blocks are
2083 not allowed. With optional argument RESULT-PARAMS controls
2084 insertion of results in the Org mode file. RESULT-PARAMS can
2085 take the following values:
2087 replace - (default option) insert results after the source block
2088 or inline source block replacing any previously
2089 inserted results.
2091 silent -- no results are inserted into the Org-mode buffer but
2092 the results are echoed to the minibuffer and are
2093 ingested by Emacs (a potentially time consuming
2094 process).
2096 file ---- the results are interpreted as a file path, and are
2097 inserted into the buffer using the Org-mode file syntax.
2099 list ---- the results are interpreted as an Org-mode list.
2101 raw ----- results are added directly to the Org-mode file. This
2102 is a good option if you code block will output org-mode
2103 formatted text.
2105 drawer -- results are added directly to the Org-mode file as with
2106 \"raw\", but are wrapped in a RESULTS drawer or results
2107 macro, allowing them to later be replaced or removed
2108 automatically.
2110 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2111 org\" block depending on whether the current source block is
2112 inline or not. They are not comma-escaped when inserted,
2113 but Org syntax here will be discarded when exporting the
2114 file.
2116 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2117 or html export snippet depending on whether the current
2118 source block is inline or not. This is a good option
2119 if your code block will output html formatted text.
2121 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2122 block or latex export snippet depending on whether the
2123 current source block is inline or not. This is a good
2124 option if your code block will output latex formatted
2125 text.
2127 code ---- the results are extracted in the syntax of the source
2128 code of the language being evaluated and are added
2129 inside of a source block with the source-code language
2130 set appropriately. Also, source block inlining is
2131 preserved in this case. Note this relies on the
2132 optional LANG argument.
2134 list ---- the results are rendered as a list. This option not
2135 allowed for inline src blocks.
2137 table --- the results are rendered as a table. This option not
2138 allowed for inline src blocks.
2140 INFO may provide the values of these header arguments (in the
2141 `header-arguments-alist' see the docstring for
2142 `org-babel-get-src-block-info'):
2144 :file --- the name of the file to which output should be written.
2146 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2147 using the argument supplied to specify the export block
2148 or snippet type."
2149 (cond ((stringp result)
2150 (setq result (org-no-properties result))
2151 (when (member "file" result-params)
2152 (setq result (org-babel-result-to-file
2153 result (when (assoc :file-desc (nth 2 info))
2154 (or (cdr (assoc :file-desc (nth 2 info)))
2155 result))))))
2156 ((listp result))
2157 (t (setq result (format "%S" result))))
2158 (if (and result-params (member "silent" result-params))
2159 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2160 result)
2161 (let ((inline (let ((context (org-element-context)))
2162 (and (memq (org-element-type context)
2163 '(inline-babel-call inline-src-block))
2164 context))))
2165 (when inline
2166 (let ((warning
2167 (or (and (member "table" result-params) "`:results table'")
2168 (and (listp result) "list result")
2169 (and (string-match-p "\n." result) "multiline result")
2170 (and (member "list" result-params) "`:results list'"))))
2171 (when warning
2172 (user-error "Inline error: %s cannot be used" warning))))
2173 (save-excursion
2174 (let* ((visible-beg (point-min-marker))
2175 (visible-end (copy-marker (point-max) t))
2176 (inline (let ((context (org-element-context)))
2177 (and (memq (org-element-type context)
2178 '(inline-babel-call inline-src-block))
2179 context)))
2180 (existing-result (org-babel-where-is-src-block-result t nil hash))
2181 (results-switches (cdr (assq :results_switches (nth 2 info))))
2182 ;; When results exist outside of the current visible
2183 ;; region of the buffer, be sure to widen buffer to
2184 ;; update them.
2185 (outside-scope (and existing-result
2186 (buffer-narrowed-p)
2187 (or (> visible-beg existing-result)
2188 (<= visible-end existing-result))))
2189 beg end indent)
2190 ;; Ensure non-inline results end in a newline.
2191 (when (and (org-string-nw-p result)
2192 (not inline)
2193 (not (string-equal (substring result -1) "\n")))
2194 (setq result (concat result "\n")))
2195 (unwind-protect
2196 (progn
2197 (when outside-scope (widen))
2198 (if existing-result (goto-char existing-result)
2199 (goto-char (org-element-property :end inline))
2200 (skip-chars-backward " \t"))
2201 (unless inline
2202 (setq indent (org-get-indentation))
2203 (forward-line 1))
2204 (setq beg (point))
2205 (cond
2206 (inline
2207 ;; Make sure new results are separated from the
2208 ;; source code by one space.
2209 (unless existing-result
2210 (insert " ")
2211 (setq beg (point))))
2212 ((member "replace" result-params)
2213 (delete-region (point) (org-babel-result-end)))
2214 ((member "append" result-params)
2215 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2216 ((member "prepend" result-params))) ; already there
2217 (setq results-switches
2218 (if results-switches (concat " " results-switches) ""))
2219 (let ((wrap (lambda (start finish &optional no-escape no-newlines
2220 inline-start inline-finish)
2221 (when inline
2222 (setq start inline-start)
2223 (setq finish inline-finish)
2224 (setq no-newlines t))
2225 (goto-char end)
2226 (insert (concat finish (unless no-newlines "\n")))
2227 (goto-char beg)
2228 (insert (concat start (unless no-newlines "\n")))
2229 (unless no-escape
2230 (org-escape-code-in-region (min (point) end) end))
2231 (goto-char end)
2232 (unless no-newlines (goto-char (point-at-eol)))
2233 (setq end (point-marker))))
2234 (tabulablep
2235 (lambda (r)
2236 ;; Non-nil when result R can be turned into
2237 ;; a table.
2238 (and (listp r)
2239 (null (cdr (last r)))
2240 (cl-every
2241 (lambda (e) (or (atom e) (null (cdr (last e)))))
2242 result)))))
2243 ;; insert results based on type
2244 (cond
2245 ;; Do nothing for an empty result.
2246 ((null result))
2247 ;; Insert a list if preferred.
2248 ((member "list" result-params)
2249 (insert
2250 (org-trim
2251 (org-list-to-generic
2252 (cons 'unordered
2253 (mapcar
2254 (lambda (e)
2255 (list (if (stringp e) e (format "%S" e))))
2256 (if (listp result) result
2257 (split-string result "\n" t))))
2258 '(:splicep nil :istart "- " :iend "\n")))
2259 "\n"))
2260 ;; Try hard to print RESULT as a table. Give up if
2261 ;; it contains an improper list.
2262 ((funcall tabulablep result)
2263 (goto-char beg)
2264 (insert (concat (orgtbl-to-orgtbl
2265 (if (cl-every
2266 (lambda (e)
2267 (or (eq e 'hline) (listp e)))
2268 result)
2269 result
2270 (list result))
2271 nil)
2272 "\n"))
2273 (goto-char beg)
2274 (when (org-at-table-p) (org-table-align))
2275 (goto-char (org-table-end)))
2276 ;; Print verbatim a list that cannot be turned into
2277 ;; a table.
2278 ((listp result) (insert (format "%s\n" result)))
2279 ((member "file" result-params)
2280 (when inline
2281 (setq result (org-macro-escape-arguments result)))
2282 (insert result))
2283 ((and inline (not (member "raw" result-params)))
2284 (insert (org-macro-escape-arguments
2285 (org-babel-chomp result "\n"))))
2286 (t (goto-char beg) (insert result)))
2287 (setq end (point-marker))
2288 ;; possibly wrap result
2289 (cond
2290 ((assoc :wrap (nth 2 info))
2291 (let ((name (or (cdr (assoc :wrap (nth 2 info))) "RESULTS")))
2292 (funcall wrap (concat "#+BEGIN_" name)
2293 (concat "#+END_" (car (org-split-string name)))
2294 nil nil (concat "{{{results(@@" name ":") "@@)}}}")))
2295 ((member "html" result-params)
2296 (funcall wrap "#+BEGIN_EXPORT html" "#+END_EXPORT" nil nil
2297 "{{{results(@@html:" "@@)}}}"))
2298 ((member "latex" result-params)
2299 (funcall wrap "#+BEGIN_EXPORT latex" "#+END_EXPORT" nil nil
2300 "{{{results(@@latex:" "@@)}}}"))
2301 ((member "org" result-params)
2302 (goto-char beg) (if (org-at-table-p) (org-cycle))
2303 (funcall wrap "#+BEGIN_SRC org" "#+END_SRC" nil nil
2304 "{{{results(src_org{" "})}}}"))
2305 ((member "code" result-params)
2306 (let ((lang (or lang "none")))
2307 (funcall wrap (format "#+BEGIN_SRC %s%s" lang results-switches)
2308 "#+END_SRC" nil nil
2309 (format "{{{results(src_%s[%s]{" lang results-switches)
2310 "})}}}")))
2311 ((member "raw" result-params)
2312 (goto-char beg) (if (org-at-table-p) (org-cycle)))
2313 ((or (member "drawer" result-params)
2314 ;; Stay backward compatible with <7.9.2
2315 (member "wrap" result-params))
2316 (goto-char beg) (if (org-at-table-p) (org-cycle))
2317 (funcall wrap ":RESULTS:" ":END:" 'no-escape nil
2318 "{{{results(" ")}}}"))
2319 ((and inline (member "file" result-params))
2320 (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
2321 ((and (not (funcall tabulablep result))
2322 (not (member "file" result-params)))
2323 (let ((org-babel-inline-result-wrap
2324 ;; Hard code {{{results(...)}}} on top of customization.
2325 (format "{{{results(%s)}}}"
2326 org-babel-inline-result-wrap)))
2327 (org-babel-examplify-region beg end results-switches inline)
2328 (setq end (point))))))
2329 ;; Possibly indent results in par with #+results line.
2330 (when (and (not inline) (numberp indent) (> indent 0)
2331 ;; In this case `table-align' does the work
2332 ;; for us.
2333 (not (and (listp result)
2334 (member "append" result-params))))
2335 (indent-rigidly beg end indent))
2336 (if (null result)
2337 (if (member "value" result-params)
2338 (message "Code block returned no value.")
2339 (message "Code block produced no output."))
2340 (message "Code block evaluation complete.")))
2341 (when outside-scope (narrow-to-region visible-beg visible-end))
2342 (set-marker visible-beg nil)
2343 (set-marker visible-end nil)))))))
2345 (defun org-babel-remove-result (&optional info keep-keyword)
2346 "Remove the result of the current source block."
2347 (interactive)
2348 (let ((location (org-babel-where-is-src-block-result nil info)))
2349 (when location
2350 (save-excursion
2351 (goto-char location)
2352 (when (looking-at (concat org-babel-result-regexp ".*$"))
2353 (delete-region
2354 (if keep-keyword (1+ (match-end 0)) (1- (match-beginning 0)))
2355 (progn (forward-line 1) (org-babel-result-end))))))))
2357 (defun org-babel-remove-inline-result (&optional datum)
2358 "Remove the result of the current inline-src-block or babel call.
2359 The result must be wrapped in a `results' macro to be removed.
2360 Leading white space is trimmed."
2361 (interactive)
2362 (let* ((el (or datum (org-element-context))))
2363 (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
2364 (org-with-wide-buffer
2365 (goto-char (org-element-property :end el))
2366 (skip-chars-backward " \t")
2367 (let ((result (save-excursion
2368 (skip-chars-forward
2369 " \t\n"
2370 (org-element-property
2371 :contents-end (org-element-property :parent el)))
2372 (org-element-context))))
2373 (when (and (eq (org-element-type result) 'macro)
2374 (string= (org-element-property :key result) "results"))
2375 (delete-region ; And leading whitespace.
2376 (point)
2377 (progn (goto-char (org-element-property :end result))
2378 (skip-chars-backward " \t\n")
2379 (point)))))))))
2381 (defun org-babel-remove-result-one-or-many (x)
2382 "Remove the result of the current source block.
2383 If called with a prefix argument, remove all result blocks
2384 in the buffer."
2385 (interactive "P")
2386 (if x
2387 (org-babel-map-src-blocks nil (org-babel-remove-result))
2388 (org-babel-remove-result)))
2390 (defun org-babel-result-end ()
2391 "Return the point at the end of the current set of results."
2392 (save-excursion
2393 (cond
2394 ((org-at-table-p) (progn (goto-char (org-table-end)) (point)))
2395 ((org-at-item-p) (let* ((struct (org-list-struct))
2396 (prvs (org-list-prevs-alist struct)))
2397 (org-list-get-list-end (point-at-bol) struct prvs)))
2398 ((let ((case-fold-search t)) (looking-at "^\\([ \t]*\\):results:"))
2399 (progn (re-search-forward (concat "^" (match-string 1) ":END:"))
2400 (forward-char 1) (point)))
2402 (let ((case-fold-search t))
2403 (if (looking-at (concat "[ \t]*#\\+begin_\\([^ \t\n\r]+\\)"))
2404 (progn (re-search-forward (concat "[ \t]*#\\+end_" (match-string 1))
2405 nil t)
2406 (forward-char 1))
2407 (while (looking-at "[ \t]*\\(: \\|:$\\|\\[\\[\\)")
2408 (forward-line 1))))
2409 (point)))))
2411 (defun org-babel-result-to-file (result &optional description)
2412 "Convert RESULT into an `org-mode' link with optional DESCRIPTION.
2413 If the `default-directory' is different from the containing
2414 file's directory then expand relative links."
2415 (when (stringp result)
2416 (format "[[file:%s]%s]"
2417 (if (and default-directory
2418 buffer-file-name
2419 (not (string= (expand-file-name default-directory)
2420 (expand-file-name
2421 (file-name-directory buffer-file-name)))))
2422 (expand-file-name result default-directory)
2423 result)
2424 (if description (concat "[" description "]") ""))))
2426 (defvar org-babel-capitalize-example-region-markers nil
2427 "Make true to capitalize begin/end example markers inserted by code blocks.")
2429 (defun org-babel-examplify-region (beg end &optional results-switches inline)
2430 "Comment out region using the inline `==' or `: ' org example quote."
2431 (interactive "*r")
2432 (let ((maybe-cap
2433 (lambda (str)
2434 (if org-babel-capitalize-example-region-markers (upcase str) str))))
2435 (if inline
2436 (save-excursion
2437 (goto-char beg)
2438 (insert (format org-babel-inline-result-wrap
2439 (delete-and-extract-region beg end))))
2440 (let ((size (count-lines beg end)))
2441 (save-excursion
2442 (cond ((= size 0)) ; do nothing for an empty result
2443 ((< size org-babel-min-lines-for-block-output)
2444 (goto-char beg)
2445 (dotimes (_ size)
2446 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2448 (goto-char beg)
2449 (insert (if results-switches
2450 (format "%s%s\n"
2451 (funcall maybe-cap "#+begin_example")
2452 results-switches)
2453 (funcall maybe-cap "#+begin_example\n")))
2454 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2455 (insert (funcall maybe-cap "#+end_example\n")))))))))
2457 (defun org-babel-update-block-body (new-body)
2458 "Update the body of the current code block to NEW-BODY."
2459 (let ((element (org-element-at-point)))
2460 (unless (eq (org-element-type element) 'src-block)
2461 (error "Not in a source block"))
2462 (goto-char (org-babel-where-is-src-block-head element))
2463 (let* ((ind (org-get-indentation))
2464 (body-start (line-beginning-position 2))
2465 (body (org-element-normalize-string
2466 (if (or org-src-preserve-indentation
2467 (org-element-property :preserve-indent element))
2468 new-body
2469 (with-temp-buffer
2470 (insert (org-remove-indentation new-body))
2471 (indent-rigidly
2472 (point-min)
2473 (point-max)
2474 (+ ind org-edit-src-content-indentation))
2475 (buffer-string))))))
2476 (delete-region body-start
2477 (org-with-wide-buffer
2478 (goto-char (org-element-property :end element))
2479 (skip-chars-backward " \t\n")
2480 (line-beginning-position)))
2481 (goto-char body-start)
2482 (insert body))))
2484 (defun org-babel-merge-params (&rest plists)
2485 "Combine all parameter association lists in PLISTS.
2486 Later elements of PLISTS override the values of previous elements.
2487 This takes into account some special considerations for certain
2488 parameters when merging lists."
2489 (let* ((results-exclusive-groups
2490 (mapcar (lambda (group) (mapcar #'symbol-name group))
2491 (cdr (assoc 'results org-babel-common-header-args-w-values))))
2492 (exports-exclusive-groups
2493 (mapcar (lambda (group) (mapcar #'symbol-name group))
2494 (cdr (assoc 'exports org-babel-common-header-args-w-values))))
2495 (merge
2496 (lambda (exclusive-groups &rest result-params)
2497 ;; Maintain exclusivity of mutually exclusive parameters,
2498 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2499 ;; RESULT-PARAMS.
2500 (let (output)
2501 (dolist (new-params result-params (delete-dups output))
2502 (dolist (new-param new-params)
2503 (dolist (exclusive-group exclusive-groups)
2504 (when (member new-param exclusive-group)
2505 (setq output (cl-remove-if
2506 (lambda (o) (member o exclusive-group))
2507 output))))
2508 (push new-param output))))))
2509 (variable-index 0) ;Handle positional arguments.
2510 clearnames
2511 params ;Final parameters list.
2512 ;; Some keywords accept multiple values. We need to treat
2513 ;; them specially.
2514 vars results exports)
2515 (dolist (plist plists)
2516 (dolist (pair plist)
2517 (pcase pair
2518 (`(:var . ,value)
2519 (let ((name (cond
2520 ((listp value) (car value))
2521 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
2522 (intern (match-string 1 value)))
2523 (t nil))))
2524 (cond
2525 (name
2526 (setq vars
2527 (append (if (not (assoc name vars)) vars
2528 (push name clearnames)
2529 (cl-remove-if (lambda (p) (equal name (car p)))
2530 vars))
2531 (list (cons name pair)))))
2532 ((and vars (nth variable-index vars))
2533 ;; If no name is given and we already have named
2534 ;; variables then assign to named variables in order.
2535 (let ((name (car (nth variable-index vars))))
2536 ;; Clear out colnames and rownames for replace vars.
2537 (push name clearnames)
2538 (setf (cddr (nth variable-index vars))
2539 (concat (symbol-name name) "=" value))
2540 (cl-incf variable-index)))
2541 (t (error "Variable \"%s\" must be assigned a default value"
2542 (cdr pair))))))
2543 (`(:results . ,value)
2544 (setq results (funcall merge
2545 results-exclusive-groups
2546 results
2547 (split-string
2548 (if (stringp value) value (eval value t))))))
2549 (`(,(or :file :file-ext) . ,value)
2550 ;; `:file' and `:file-ext' are regular keywords but they
2551 ;; imply a "file" `:results' and a "results" `:exports'.
2552 (when value
2553 (setq results
2554 (funcall merge results-exclusive-groups results '("file")))
2555 (unless (or (member "both" exports)
2556 (member "none" exports)
2557 (member "code" exports))
2558 (setq exports
2559 (funcall merge
2560 exports-exclusive-groups exports '("results"))))
2561 (push pair params)))
2562 (`(:exports . ,value)
2563 (setq exports (funcall merge
2564 exports-exclusive-groups
2565 exports
2566 (split-string (or value "")))))
2567 ;; Regular keywords: any value overwrites the previous one.
2568 (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
2569 ;; Handle `:var' and clear out colnames and rownames for replaced
2570 ;; variables.
2571 (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars)
2572 params))
2573 (dolist (name clearnames)
2574 (dolist (param '(:colname-names :rowname-names))
2575 (when (assq param params)
2576 (setf (cdr (assq param params))
2577 (cl-remove-if (lambda (pair) (equal name (car pair)))
2578 (cdr (assq param params))))
2579 (setq params
2580 (cl-remove-if (lambda (pair) (and (equal (car pair) param)
2581 (null (cdr pair))))
2582 params)))))
2583 ;; Handle other special keywords, which accept multiple values.
2584 (setq params (nconc (list (cons :results (mapconcat #'identity results " "))
2585 (cons :exports (mapconcat #'identity exports " ")))
2586 params))
2587 ;; Return merged params.
2588 params))
2590 (defvar org-babel-use-quick-and-dirty-noweb-expansion nil
2591 "Set to true to use regular expressions to expand noweb references.
2592 This results in much faster noweb reference expansion but does
2593 not properly allow code blocks to inherit the \":noweb-ref\"
2594 header argument from buffer or subtree wide properties.")
2596 (defun org-babel-noweb-p (params context)
2597 "Check if PARAMS require expansion in CONTEXT.
2598 CONTEXT may be one of :tangle, :export or :eval."
2599 (let ((allowed-values (cl-case context
2600 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2601 (:eval '("yes" "no-export" "strip-export" "eval"))
2602 (:export '("yes")))))
2603 (cl-some (lambda (v) (member v allowed-values))
2604 (split-string (or (cdr (assq :noweb params)) "")))))
2606 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2607 "Expand Noweb references in the body of the current source code block.
2609 For example the following reference would be replaced with the
2610 body of the source-code block named `example-block'.
2612 <<example-block>>
2614 Note that any text preceding the <<foo>> construct on a line will
2615 be interposed between the lines of the replacement text. So for
2616 example if <<foo>> is placed behind a comment, then the entire
2617 replacement text will also be commented.
2619 This function must be called from inside of the buffer containing
2620 the source-code block which holds BODY.
2622 In addition the following syntax can be used to insert the
2623 results of evaluating the source-code block named `example-block'.
2625 <<example-block()>>
2627 Any optional arguments can be passed to example-block by placing
2628 the arguments inside the parenthesis following the convention
2629 defined by `org-babel-lob'. For example
2631 <<example-block(a=9)>>
2633 would set the value of argument \"a\" equal to \"9\". Note that
2634 these arguments are not evaluated in the current source-code
2635 block but are passed literally to the \"example-block\"."
2636 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2637 (info (or info (org-babel-get-src-block-info 'light)))
2638 (lang (nth 0 info))
2639 (body (nth 1 info))
2640 (ob-nww-start org-babel-noweb-wrap-start)
2641 (ob-nww-end org-babel-noweb-wrap-end)
2642 (comment (string= "noweb" (cdr (assoc :comments (nth 2 info)))))
2643 (rx-prefix (concat "\\(" org-babel-src-name-regexp "\\|"
2644 ":noweb-ref[ \t]+" "\\)"))
2645 (new-body "")
2646 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2647 (c-wrap (lambda (text)
2648 (with-temp-buffer
2649 (funcall (intern (concat lang "-mode")))
2650 (comment-region (point) (progn (insert text) (point)))
2651 (org-trim (buffer-string)))))
2652 index source-name evaluate prefix)
2653 (with-temp-buffer
2654 (setq-local org-babel-noweb-wrap-start ob-nww-start)
2655 (setq-local org-babel-noweb-wrap-end ob-nww-end)
2656 (insert body) (goto-char (point-min))
2657 (setq index (point))
2658 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2659 (save-match-data (setf source-name (match-string 1)))
2660 (save-match-data (setq evaluate (string-match "(.*)" source-name)))
2661 (save-match-data
2662 (setq prefix
2663 (buffer-substring (match-beginning 0)
2664 (save-excursion
2665 (beginning-of-line 1) (point)))))
2666 ;; add interval to new-body (removing noweb reference)
2667 (goto-char (match-beginning 0))
2668 (funcall nb-add (buffer-substring index (point)))
2669 (goto-char (match-end 0))
2670 (setq index (point))
2671 (funcall
2672 nb-add
2673 (with-current-buffer parent-buffer
2674 (save-restriction
2675 (widen)
2676 (mapconcat ;; Interpose PREFIX between every line.
2677 #'identity
2678 (split-string
2679 (if evaluate
2680 (let ((raw (org-babel-ref-resolve source-name)))
2681 (if (stringp raw) raw (format "%S" raw)))
2683 ;; Retrieve from the library of babel.
2684 (nth 2 (assoc (intern source-name)
2685 org-babel-library-of-babel))
2686 ;; Return the contents of headlines literally.
2687 (save-excursion
2688 (when (org-babel-ref-goto-headline-id source-name)
2689 (org-babel-ref-headline-body)))
2690 ;; Find the expansion of reference in this buffer.
2691 (let ((rx (concat rx-prefix source-name "[ \t\n]"))
2692 expansion)
2693 (save-excursion
2694 (goto-char (point-min))
2695 (if org-babel-use-quick-and-dirty-noweb-expansion
2696 (while (re-search-forward rx nil t)
2697 (let* ((i (org-babel-get-src-block-info 'light))
2698 (body (org-babel-expand-noweb-references i))
2699 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2700 "\n"))
2701 (full (if comment
2702 (let ((cs (org-babel-tangle-comment-links i)))
2703 (concat (funcall c-wrap (car cs)) "\n"
2704 body "\n"
2705 (funcall c-wrap (cadr cs))))
2706 body)))
2707 (setq expansion (cons sep (cons full expansion)))))
2708 (org-babel-map-src-blocks nil
2709 (let ((i (org-babel-get-src-block-info 'light)))
2710 (when (equal (or (cdr (assoc :noweb-ref (nth 2 i)))
2711 (nth 4 i))
2712 source-name)
2713 (let* ((body (org-babel-expand-noweb-references i))
2714 (sep (or (cdr (assoc :noweb-sep (nth 2 i)))
2715 "\n"))
2716 (full (if comment
2717 (let ((cs (org-babel-tangle-comment-links i)))
2718 (concat (funcall c-wrap (car cs)) "\n"
2719 body "\n"
2720 (funcall c-wrap (cadr cs))))
2721 body)))
2722 (setq expansion
2723 (cons sep (cons full expansion)))))))))
2724 (and expansion
2725 (mapconcat #'identity (nreverse (cdr expansion)) "")))
2726 ;; Possibly raise an error if named block doesn't exist.
2727 (if (or org-babel-noweb-error-all-langs
2728 (member lang org-babel-noweb-error-langs))
2729 (error "%s" (concat
2730 (org-babel-noweb-wrap source-name)
2731 "could not be resolved (see "
2732 "`org-babel-noweb-error-langs')"))
2733 "")))
2734 "[\n\r]") (concat "\n" prefix))))))
2735 (funcall nb-add (buffer-substring index (point-max))))
2736 new-body))
2738 (defun org-babel--script-escape-inner (str)
2739 (let (in-single in-double backslash out)
2740 (mapc
2741 (lambda (ch)
2742 (setq
2744 (if backslash
2745 (progn
2746 (setq backslash nil)
2747 (cond
2748 ((and in-single (eq ch ?'))
2749 ;; Escaped single quote inside single quoted string:
2750 ;; emit just a single quote, since we've changed the
2751 ;; outer quotes to double.
2752 (cons ch out))
2753 ((eq ch ?\")
2754 ;; Escaped double quote
2755 (if in-single
2756 ;; This should be interpreted as backslash+quote,
2757 ;; not an escape. Emit a three backslashes
2758 ;; followed by a quote (because one layer of
2759 ;; quoting will be stripped by `org-babel-read').
2760 (append (list ch ?\\ ?\\ ?\\) out)
2761 ;; Otherwise we are in a double-quoted string. Emit
2762 ;; a single escaped quote
2763 (append (list ch ?\\) out)))
2764 ((eq ch ?\\)
2765 ;; Escaped backslash: emit a single escaped backslash
2766 (append (list ?\\ ?\\) out))
2767 ;; Other: emit a quoted backslash followed by whatever
2768 ;; the character was (because one layer of quoting will
2769 ;; be stripped by `org-babel-read').
2770 (t (append (list ch ?\\ ?\\) out))))
2771 (cl-case ch
2772 (?\[ (if (or in-double in-single)
2773 (cons ?\[ out)
2774 (cons ?\( out)))
2775 (?\] (if (or in-double in-single)
2776 (cons ?\] out)
2777 (cons ?\) out)))
2778 (?\{ (if (or in-double in-single)
2779 (cons ?\{ out)
2780 (cons ?\( out)))
2781 (?\} (if (or in-double in-single)
2782 (cons ?\} out)
2783 (cons ?\) out)))
2784 (?, (if (or in-double in-single)
2785 (cons ?, out) (cons ?\s out)))
2786 (?\' (if in-double
2787 (cons ?\' out)
2788 (setq in-single (not in-single)) (cons ?\" out)))
2789 (?\" (if in-single
2790 (append (list ?\" ?\\) out)
2791 (setq in-double (not in-double)) (cons ?\" out)))
2792 (?\\ (unless (or in-single in-double)
2793 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2794 (setq backslash t)
2795 out)
2796 (t (cons ch out))))))
2797 (string-to-list str))
2798 (when (or in-single in-double)
2799 (error "Unterminated string in `org-babel-script-escape'"))
2800 (apply #'string (reverse out))))
2802 (defun org-babel-script-escape (str &optional force)
2803 "Safely convert tables into elisp lists."
2804 (unless (stringp str)
2805 (error "`org-babel-script-escape' expects a string"))
2806 (let ((escaped
2807 (cond
2808 ((and (> (length str) 2)
2809 (or (and (string-equal "[" (substring str 0 1))
2810 (string-equal "]" (substring str -1)))
2811 (and (string-equal "{" (substring str 0 1))
2812 (string-equal "}" (substring str -1)))
2813 (and (string-equal "(" (substring str 0 1))
2814 (string-equal ")" (substring str -1)))))
2816 (concat "'" (org-babel--script-escape-inner str)))
2817 ((or force
2818 (and (> (length str) 2)
2819 (or (and (string-equal "'" (substring str 0 1))
2820 (string-equal "'" (substring str -1)))
2821 ;; We need to pass double-quoted strings
2822 ;; through the backslash-twiddling bits, even
2823 ;; though we don't need to change their
2824 ;; delimiters.
2825 (and (string-equal "\"" (substring str 0 1))
2826 (string-equal "\"" (substring str -1))))))
2827 (org-babel--script-escape-inner str))
2828 (t str))))
2829 (condition-case nil (org-babel-read escaped) (error escaped))))
2831 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2832 "Convert the string value of CELL to a number if appropriate.
2833 Otherwise if CELL looks like lisp (meaning it starts with a
2834 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2835 lisp, otherwise return it unmodified as a string. Optional
2836 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2837 situations in which is it not appropriate."
2838 (if (and (stringp cell) (not (equal cell "")))
2839 (or (org-babel-number-p cell)
2840 (if (and (not inhibit-lisp-eval)
2841 (or (member (substring cell 0 1) '("(" "'" "`" "["))
2842 (string= cell "*this*")))
2843 (eval (read cell) t)
2844 (if (string= (substring cell 0 1) "\"")
2845 (read cell)
2846 (progn (set-text-properties 0 (length cell) nil cell) cell))))
2847 cell))
2849 (defun org-babel-number-p (string)
2850 "If STRING represents a number return its value."
2851 (if (and (string-match "[0-9]+" string)
2852 (string-match "^-?[0-9]*\\.?[0-9]*$" string)
2853 (= (length (substring string (match-beginning 0)
2854 (match-end 0)))
2855 (length string)))
2856 (string-to-number string)))
2858 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2859 "Read the results located at FILE-NAME into an elisp table.
2860 If the table is trivial, then return it as a scalar."
2861 (let (result)
2862 (save-window-excursion
2863 (with-temp-buffer
2864 (condition-case err
2865 (progn
2866 (org-table-import file-name separator)
2867 (delete-file file-name)
2868 (setq result (mapcar (lambda (row)
2869 (mapcar #'org-babel-string-read row))
2870 (org-table-to-lisp))))
2871 (error (message "Error reading results: %s" err) nil)))
2872 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2873 (if (consp (car result))
2874 (if (null (cdr (car result)))
2875 (caar result)
2876 result)
2877 (car result))
2878 result))))
2880 (defun org-babel-string-read (cell)
2881 "Strip nested \"s from around strings."
2882 (org-babel-read (or (and (stringp cell)
2883 (string-match "\\\"\\(.+\\)\\\"" cell)
2884 (match-string 1 cell))
2885 cell) t))
2887 (defun org-babel-chomp (string &optional regexp)
2888 "Strip a trailing space or carriage return from STRING.
2889 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2890 can be specified as the REGEXP argument."
2891 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2892 (while (and (> (length string) 0)
2893 (string-match regexp (substring string -1)))
2894 (setq string (substring string 0 -1)))
2895 string))
2897 (defun org-babel-local-file-name (file)
2898 "Return the local name component of FILE."
2899 (or (file-remote-p file 'localname) file))
2901 (defun org-babel-process-file-name (name &optional no-quote-p)
2902 "Prepare NAME to be used in an external process.
2903 If NAME specifies a remote location, the remote portion of the
2904 name is removed, since in that case the process will be executing
2905 remotely. The file name is then processed by `expand-file-name'.
2906 Unless second argument NO-QUOTE-P is non-nil, the file name is
2907 additionally processed by `shell-quote-argument'"
2908 (let ((f (org-babel-local-file-name (expand-file-name name))))
2909 (if no-quote-p f (shell-quote-argument f))))
2911 (defvar org-babel-temporary-directory)
2912 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2913 (defvar org-babel-temporary-directory
2914 (or (and (boundp 'org-babel-temporary-directory)
2915 (file-exists-p org-babel-temporary-directory)
2916 org-babel-temporary-directory)
2917 (make-temp-file "babel-" t))
2918 "Directory to hold temporary files created to execute code blocks.
2919 Used by `org-babel-temp-file'. This directory will be removed on
2920 Emacs shutdown."))
2922 (defcustom org-babel-remote-temporary-directory "/tmp/"
2923 "Directory to hold temporary files on remote hosts."
2924 :group 'org-babel
2925 :type 'string)
2927 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
2928 "Call the code to parse raw string results according to RESULT-PARAMS."
2929 (declare (indent 1)
2930 (debug (form form &rest form)))
2931 (org-with-gensyms (params)
2932 `(let ((,params ,result-params))
2933 (unless (member "none" ,params)
2934 (if (or (member "scalar" ,params)
2935 (member "verbatim" ,params)
2936 (member "html" ,params)
2937 (member "code" ,params)
2938 (member "pp" ,params)
2939 (member "file" ,params)
2940 (and (or (member "output" ,params)
2941 (member "raw" ,params)
2942 (member "org" ,params)
2943 (member "drawer" ,params))
2944 (not (member "table" ,params))))
2945 ,scalar-form
2946 ,@table-forms)))))
2947 (def-edebug-spec org-babel-result-cond (form form body))
2949 (defun org-babel-temp-file (prefix &optional suffix)
2950 "Create a temporary file in the `org-babel-temporary-directory'.
2951 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
2952 value of `temporary-file-directory' temporarily set to the value
2953 of `org-babel-temporary-directory'."
2954 (if (file-remote-p default-directory)
2955 (let ((prefix
2956 (concat (file-remote-p default-directory)
2957 (expand-file-name
2958 prefix org-babel-remote-temporary-directory))))
2959 (make-temp-file prefix nil suffix))
2960 (let ((temporary-file-directory
2961 (or (and (boundp 'org-babel-temporary-directory)
2962 (file-exists-p org-babel-temporary-directory)
2963 org-babel-temporary-directory)
2964 temporary-file-directory)))
2965 (make-temp-file prefix nil suffix))))
2967 (defun org-babel-remove-temporary-directory ()
2968 "Remove `org-babel-temporary-directory' on Emacs shutdown."
2969 (when (and (boundp 'org-babel-temporary-directory)
2970 (file-exists-p org-babel-temporary-directory))
2971 ;; taken from `delete-directory' in files.el
2972 (condition-case nil
2973 (progn
2974 (mapc (lambda (file)
2975 ;; This test is equivalent to
2976 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
2977 ;; but more efficient
2978 (if (eq t (car (file-attributes file)))
2979 (delete-directory file)
2980 (delete-file file)))
2981 ;; We do not want to delete "." and "..".
2982 (directory-files org-babel-temporary-directory 'full
2983 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
2984 (delete-directory org-babel-temporary-directory))
2985 (error
2986 (message "Failed to remove temporary Org-babel directory %s"
2987 (if (boundp 'org-babel-temporary-directory)
2988 org-babel-temporary-directory
2989 "[directory not defined]"))))))
2991 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
2993 (defun org-babel-one-header-arg-safe-p (pair safe-list)
2994 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
2996 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
2997 (and (consp pair)
2998 (keywordp (car pair))
2999 (stringp (cdr pair))
3001 (memq (car pair) safe-list)
3002 (let ((entry (assq (car pair) safe-list)))
3003 (and entry
3004 (consp entry)
3005 (cond ((functionp (cdr entry))
3006 (funcall (cdr entry) (cdr pair)))
3007 ((listp (cdr entry))
3008 (member (cdr pair) (cdr entry)))
3009 (t nil)))))))
3011 (defun org-babel-generate-file-param (src-name params)
3012 "Calculate the filename for source block results.
3014 The directory is calculated from the :output-dir property of the
3015 source block; if not specified, use the current directory.
3017 If the source block has a #+NAME and the :file parameter does not
3018 contain any period characters, then the :file parameter is
3019 treated as an extension, and the output file name is the
3020 concatenation of the directory (as calculated above), the block
3021 name, a period, and the parameter value as a file extension.
3022 Otherwise, the :file parameter is treated as a full file name,
3023 and the output file name is the directory (as calculated above)
3024 plus the parameter value."
3025 (let* ((file-cons (assq :file params))
3026 (file-ext-cons (assq :file-ext params))
3027 (file-ext (cdr-safe file-ext-cons))
3028 (dir (cdr-safe (assq :output-dir params)))
3029 fname)
3030 ;; create the output-dir if it does not exist
3031 (when dir
3032 (make-directory dir t))
3033 (if file-cons
3034 ;; :file given; add :output-dir if given
3035 (when dir
3036 (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
3037 ;; :file not given; compute from name and :file-ext if possible
3038 (when (and src-name file-ext)
3039 (if dir
3040 (setq fname (concat (file-name-as-directory (or dir ""))
3041 src-name "." file-ext))
3042 (setq fname (concat src-name "." file-ext)))
3043 (setq params (cons (cons :file fname) params))))
3044 params))
3046 (defun org-babel-graphical-output-file (params)
3047 "File where a babel block should send graphical output, per PARAMS.
3048 Return nil if no graphical output is expected. Raise an error if
3049 the output file is ill-defined."
3050 (let ((file (cdr (assq :file params))))
3051 (cond (file (and (member "graphics" (cdr (assq :result-params params)))
3052 file))
3053 ((assq :file-ext params)
3054 (user-error ":file-ext given but no :file generated; did you forget \
3055 to name a block?"))
3056 (t (user-error "No :file header argument given; cannot create \
3057 graphical result")))))
3059 (defun org-babel-make-language-alias (new old)
3060 "Make source blocks of type NEW aliases for those of type OLD.
3062 NEW and OLD should be strings. This function should be called
3063 after the babel API for OLD-type source blocks is fully defined.
3065 Callers of this function will probably want to add an entry to
3066 `org-src-lang-modes' as well."
3067 (dolist (fn '("execute" "expand-body" "prep-session"
3068 "variable-assignments" "load-session"))
3069 (let ((sym (intern-soft (concat "org-babel-" fn ":" old))))
3070 (when (and sym (fboundp sym))
3071 (defalias (intern (concat "org-babel-" fn ":" new)) sym))))
3072 ;; Technically we don't need a `dolist' for just one variable, but
3073 ;; we keep it for symmetry/ease of future expansion.
3074 (dolist (var '("default-header-args"))
3075 (let ((sym (intern-soft (concat "org-babel-" var ":" old))))
3076 (when (and sym (boundp sym))
3077 (defvaralias (intern (concat "org-babel-" var ":" new)) sym)))))
3079 (provide 'ob-core)
3081 ;; Local variables:
3082 ;; generated-autoload-file: "org-loaddefs.el"
3083 ;; End:
3085 ;;; ob-core.el ends here