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