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