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