ob-core: Fix failing tests.
[org-mode/org-tableheadings.git] / lisp / ob-core.el
blob129e17f627c1ceb4b93247d952f4beec04235778
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)
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 (let ((graphics?
710 (member "graphics" (cdr (assq :result-params params)))))
711 ;; Handle :results graphics :file case. Don't
712 ;; write result to file if result is graphics.
713 (when (and result (not graphics?))
714 (with-temp-file file
715 (insert (org-babel-format-result
716 result (cdr (assq :sep params)))))))
717 (setq result file))
718 ;; Possibly perform post process provided its
719 ;; appropriate. Dynamically bind "*this*" to the
720 ;; actual results of the block.
721 (let ((post (cdr (assq :post params))))
722 (when post
723 (let ((*this* (if (not file) result
724 (org-babel-result-to-file
725 file
726 (let ((desc (assq :file-desc params)))
727 (and desc (or (cdr desc) result)))))))
728 (setq result (org-babel-ref-resolve post))
729 (when file
730 (setq result-params (remove "file" result-params))))))
731 (org-babel-insert-result
732 result result-params info new-hash lang)))
733 (run-hooks 'org-babel-after-execute-hook)
734 result)))))))
736 (defun org-babel-expand-body:generic (body params &optional var-lines)
737 "Expand BODY with PARAMS.
738 Expand a block of code with org-babel according to its header
739 arguments. This generic implementation of body expansion is
740 called for languages which have not defined their own specific
741 org-babel-expand-body:lang function."
742 (let ((pro (cdr (assq :prologue params)))
743 (epi (cdr (assq :epilogue params))))
744 (mapconcat #'identity
745 (append (when pro (list pro))
746 var-lines
747 (list body)
748 (when epi (list epi)))
749 "\n")))
751 ;;;###autoload
752 (defun org-babel-expand-src-block (&optional _arg info params)
753 "Expand the current source code block.
754 Expand according to the source code block's header
755 arguments and pop open the results in a preview buffer."
756 (interactive)
757 (let* ((info (or info (org-babel-get-src-block-info)))
758 (lang (nth 0 info))
759 (params (setf (nth 2 info)
760 (sort (org-babel-merge-params (nth 2 info) params)
761 (lambda (el1 el2) (string< (symbol-name (car el1))
762 (symbol-name (car el2)))))))
763 (body (setf (nth 1 info)
764 (if (org-babel-noweb-p params :eval)
765 (org-babel-expand-noweb-references info) (nth 1 info))))
766 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
767 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
768 lang)))
769 (expanded
770 (if (fboundp expand-cmd) (funcall expand-cmd body params)
771 (org-babel-expand-body:generic
772 body params (and (fboundp assignments-cmd)
773 (funcall assignments-cmd params))))))
774 (if (called-interactively-p 'any)
775 (org-edit-src-code
776 expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))
777 expanded)))
779 (defun org-babel-edit-distance (s1 s2)
780 "Return the edit (levenshtein) distance between strings S1 S2."
781 (let* ((l1 (length s1))
782 (l2 (length s2))
783 (dist (vconcat (mapcar (lambda (_) (make-vector (1+ l2) nil))
784 (number-sequence 1 (1+ l1)))))
785 (in (lambda (i j) (aref (aref dist i) j))))
786 (setf (aref (aref dist 0) 0) 0)
787 (dolist (j (number-sequence 1 l2))
788 (setf (aref (aref dist 0) j) j))
789 (dolist (i (number-sequence 1 l1))
790 (setf (aref (aref dist i) 0) i)
791 (dolist (j (number-sequence 1 l2))
792 (setf (aref (aref dist i) j)
793 (min
794 (1+ (funcall in (1- i) j))
795 (1+ (funcall in i (1- j)))
796 (+ (if (equal (aref s1 (1- i)) (aref s2 (1- j))) 0 1)
797 (funcall in (1- i) (1- j)))))))
798 (funcall in l1 l2)))
800 (defun org-babel-combine-header-arg-lists (original &rest others)
801 "Combine a number of lists of header argument names and arguments."
802 (let ((results (copy-sequence original)))
803 (dolist (new-list others)
804 (dolist (arg-pair new-list)
805 (let ((header (car arg-pair)))
806 (setq results
807 (cons arg-pair (cl-remove-if
808 (lambda (pair) (equal header (car pair)))
809 results))))))
810 results))
812 ;;;###autoload
813 (defun org-babel-check-src-block ()
814 "Check for misspelled header arguments in the current code block."
815 (interactive)
816 ;; TODO: report malformed code block
817 ;; TODO: report incompatible combinations of header arguments
818 ;; TODO: report uninitialized variables
819 (let ((too-close 2) ;; <- control closeness to report potential match
820 (names (mapcar #'symbol-name org-babel-header-arg-names)))
821 (dolist (header (mapcar (lambda (arg) (substring (symbol-name (car arg)) 1))
822 (and (org-babel-where-is-src-block-head)
823 (org-babel-parse-header-arguments
824 (org-no-properties
825 (match-string 4))))))
826 (dolist (name names)
827 (when (and (not (string= header name))
828 (<= (org-babel-edit-distance header name) too-close)
829 (not (member header names)))
830 (error "Supplied header \"%S\" is suspiciously close to \"%S\""
831 header name))))
832 (message "No suspicious header arguments found.")))
834 ;;;###autoload
835 (defun org-babel-insert-header-arg (&optional header-arg value)
836 "Insert a header argument selecting from lists of common args and values."
837 (interactive)
838 (let* ((info (org-babel-get-src-block-info 'light))
839 (lang (car info))
840 (begin (nth 5 info))
841 (lang-headers (intern (concat "org-babel-header-args:" lang)))
842 (headers (org-babel-combine-header-arg-lists
843 org-babel-common-header-args-w-values
844 (when (boundp lang-headers) (eval lang-headers t))))
845 (header-arg (or header-arg
846 (completing-read
847 "Header Arg: "
848 (mapcar
849 (lambda (header-spec) (symbol-name (car header-spec)))
850 headers))))
851 (vals (cdr (assoc (intern header-arg) headers)))
852 (value (or value
853 (cond
854 ((eq vals :any)
855 (read-from-minibuffer "value: "))
856 ((listp vals)
857 (mapconcat
858 (lambda (group)
859 (let ((arg (completing-read
860 "Value: "
861 (cons "default"
862 (mapcar #'symbol-name group)))))
863 (if (and arg (not (string= "default" arg)))
864 (concat arg " ")
865 "")))
866 vals ""))))))
867 (save-excursion
868 (goto-char begin)
869 (goto-char (point-at-eol))
870 (unless (= (char-before (point)) ?\ ) (insert " "))
871 (insert ":" header-arg) (when value (insert " " value)))))
873 ;; Add support for completing-read insertion of header arguments after ":"
874 (defun org-babel-header-arg-expand ()
875 "Call `org-babel-enter-header-arg-w-completion' in appropriate contexts."
876 (when (and (equal (char-before) ?\:) (org-babel-where-is-src-block-head))
877 (org-babel-enter-header-arg-w-completion (match-string 2))))
879 (defun org-babel-enter-header-arg-w-completion (&optional lang)
880 "Insert header argument appropriate for LANG with completion."
881 (let* ((lang-headers-var (intern (concat "org-babel-header-args:" lang)))
882 (lang-headers (when (boundp lang-headers-var) (eval lang-headers-var t)))
883 (headers-w-values (org-babel-combine-header-arg-lists
884 org-babel-common-header-args-w-values lang-headers))
885 (headers (mapcar #'symbol-name (mapcar #'car headers-w-values)))
886 (header (org-completing-read "Header Arg: " headers))
887 (args (cdr (assoc (intern header) headers-w-values)))
888 (arg (when (and args (listp args))
889 (org-completing-read
890 (format "%s: " header)
891 (mapcar #'symbol-name (apply #'append args))))))
892 (insert (concat header " " (or arg "")))
893 (cons header arg)))
895 (add-hook 'org-tab-first-hook 'org-babel-header-arg-expand)
897 ;;;###autoload
898 (defun org-babel-load-in-session (&optional _arg info)
899 "Load the body of the current source-code block.
900 Evaluate the header arguments for the source block before
901 entering the session. After loading the body this pops open the
902 session."
903 (interactive)
904 (let* ((info (or info (org-babel-get-src-block-info)))
905 (lang (nth 0 info))
906 (params (nth 2 info))
907 (body (if (not info)
908 (user-error "No src code block at point")
909 (setf (nth 1 info)
910 (if (org-babel-noweb-p params :eval)
911 (org-babel-expand-noweb-references info)
912 (nth 1 info)))))
913 (session (cdr (assq :session params)))
914 (dir (cdr (assq :dir params)))
915 (default-directory
916 (or (and dir (file-name-as-directory dir)) default-directory))
917 (cmd (intern (concat "org-babel-load-session:" lang))))
918 (unless (fboundp cmd)
919 (error "No org-babel-load-session function for %s!" lang))
920 (pop-to-buffer (funcall cmd session body params))
921 (end-of-line 1)))
923 ;;;###autoload
924 (defun org-babel-initiate-session (&optional arg info)
925 "Initiate session for current code block.
926 If called with a prefix argument then resolve any variable
927 references in the header arguments and assign these variables in
928 the session. Copy the body of the code block to the kill ring."
929 (interactive "P")
930 (let* ((info (or info (org-babel-get-src-block-info (not arg))))
931 (lang (nth 0 info))
932 (body (nth 1 info))
933 (params (nth 2 info))
934 (session (cdr (assq :session params)))
935 (dir (cdr (assq :dir params)))
936 (default-directory
937 (or (and dir (file-name-as-directory dir)) default-directory))
938 (init-cmd (intern (format "org-babel-%s-initiate-session" lang)))
939 (prep-cmd (intern (concat "org-babel-prep-session:" lang))))
940 (when (and (stringp session) (string= session "none"))
941 (error "This block is not using a session!"))
942 (unless (fboundp init-cmd)
943 (error "No org-babel-initiate-session function for %s!" lang))
944 (with-temp-buffer (insert (org-trim body))
945 (copy-region-as-kill (point-min) (point-max)))
946 (when arg
947 (unless (fboundp prep-cmd)
948 (error "No org-babel-prep-session function for %s!" lang))
949 (funcall prep-cmd session params))
950 (funcall init-cmd session params)))
952 ;;;###autoload
953 (defun org-babel-switch-to-session (&optional arg info)
954 "Switch to the session of the current code block.
955 Uses `org-babel-initiate-session' to start the session. If called
956 with a prefix argument then this is passed on to
957 `org-babel-initiate-session'."
958 (interactive "P")
959 (pop-to-buffer (org-babel-initiate-session arg info))
960 (end-of-line 1))
962 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
964 (defvar org-src-window-setup)
966 ;;;###autoload
967 (defun org-babel-switch-to-session-with-code (&optional arg _info)
968 "Switch to code buffer and display session."
969 (interactive "P")
970 (let ((swap-windows
971 (lambda ()
972 (let ((other-window-buffer (window-buffer (next-window))))
973 (set-window-buffer (next-window) (current-buffer))
974 (set-window-buffer (selected-window) other-window-buffer))
975 (other-window 1)))
976 (info (org-babel-get-src-block-info))
977 (org-src-window-setup 'reorganize-frame))
978 (save-excursion
979 (org-babel-switch-to-session arg info))
980 (org-edit-src-code)
981 (funcall swap-windows)))
983 ;;;###autoload
984 (defmacro org-babel-do-in-edit-buffer (&rest body)
985 "Evaluate BODY in edit buffer if there is a code block at point.
986 Return t if a code block was found at point, nil otherwise."
987 (declare (debug (body)))
988 `(let* ((element (org-element-at-point))
989 ;; This function is not supposed to move point. However,
990 ;; `org-edit-src-code' always moves point back into the
991 ;; source block. It is problematic if the point was before
992 ;; the code, e.g., on block's opening line. In this case,
993 ;; we want to restore this location after executing BODY.
994 (outside-position
995 (and (<= (line-beginning-position)
996 (org-element-property :post-affiliated element))
997 (point-marker)))
998 (org-src-window-setup 'switch-invisibly))
999 (when (and (org-babel-where-is-src-block-head element)
1000 (org-edit-src-code))
1001 (unwind-protect (progn ,@body)
1002 (org-edit-src-exit)
1003 (when outside-position (goto-char outside-position)))
1004 t)))
1006 (defun org-babel-do-key-sequence-in-edit-buffer (key)
1007 "Read key sequence and execute the command in edit buffer.
1008 Enter a key sequence to be executed in the language major-mode
1009 edit buffer. For example, TAB will alter the contents of the
1010 Org code block according to the effect of TAB in the language
1011 major mode buffer. For languages that support interactive
1012 sessions, this can be used to send code from the Org buffer
1013 to the session for evaluation using the native major mode
1014 evaluation mechanisms."
1015 (interactive "kEnter key-sequence to execute in edit buffer: ")
1016 (org-babel-do-in-edit-buffer
1017 (call-interactively
1018 (key-binding (or key (read-key-sequence nil))))))
1020 (defvar org-bracket-link-regexp)
1022 (defun org-babel-active-location-p ()
1023 (memq (org-element-type (save-match-data (org-element-context)))
1024 '(babel-call inline-babel-call inline-src-block src-block)))
1026 ;;;###autoload
1027 (defun org-babel-open-src-block-result (&optional re-run)
1028 "If `point' is on a src block then open the results of the
1029 source code block, otherwise return nil. With optional prefix
1030 argument RE-RUN the source-code block is evaluated even if
1031 results already exist."
1032 (interactive "P")
1033 (let ((info (org-babel-get-src-block-info 'light)))
1034 (when info
1035 (save-excursion
1036 ;; go to the results, if there aren't any then run the block
1037 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
1038 (progn (org-babel-execute-src-block)
1039 (org-babel-where-is-src-block-result))))
1040 (end-of-line 1)
1041 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
1042 ;; open the results
1043 (if (looking-at org-bracket-link-regexp)
1044 ;; file results
1045 (org-open-at-point)
1046 (let ((r (org-babel-format-result
1047 (org-babel-read-result) (cdr (assq :sep (nth 2 info))))))
1048 (pop-to-buffer (get-buffer-create "*Org-Babel Results*"))
1049 (delete-region (point-min) (point-max))
1050 (insert r)))
1051 t))))
1053 ;;;###autoload
1054 (defmacro org-babel-map-src-blocks (file &rest body)
1055 "Evaluate BODY forms on each source-block in FILE.
1056 If FILE is nil evaluate BODY forms on source blocks in current
1057 buffer. During evaluation of BODY the following local variables
1058 are set relative to the currently matched code block.
1060 full-block ------- string holding the entirety of the code block
1061 beg-block -------- point at the beginning of the code block
1062 end-block -------- point at the end of the matched code block
1063 lang ------------- string holding the language of the code block
1064 beg-lang --------- point at the beginning of the lang
1065 end-lang --------- point at the end of the lang
1066 switches --------- string holding the switches
1067 beg-switches ----- point at the beginning of the switches
1068 end-switches ----- point at the end of the switches
1069 header-args ------ string holding the header-args
1070 beg-header-args -- point at the beginning of the header-args
1071 end-header-args -- point at the end of the header-args
1072 body ------------- string holding the body of the code block
1073 beg-body --------- point at the beginning of the body
1074 end-body --------- point at the end of the body"
1075 (declare (indent 1))
1076 (let ((tempvar (make-symbol "file")))
1077 `(let* ((case-fold-search t)
1078 (,tempvar ,file)
1079 (visited-p (or (null ,tempvar)
1080 (get-file-buffer (expand-file-name ,tempvar))))
1081 (point (point)) to-be-removed)
1082 (save-window-excursion
1083 (when ,tempvar (find-file ,tempvar))
1084 (setq to-be-removed (current-buffer))
1085 (goto-char (point-min))
1086 (while (re-search-forward org-babel-src-block-regexp nil t)
1087 (when (org-babel-active-location-p)
1088 (goto-char (match-beginning 0))
1089 (let ((full-block (match-string 0))
1090 (beg-block (match-beginning 0))
1091 (end-block (match-end 0))
1092 (lang (match-string 2))
1093 (beg-lang (match-beginning 2))
1094 (end-lang (match-end 2))
1095 (switches (match-string 3))
1096 (beg-switches (match-beginning 3))
1097 (end-switches (match-end 3))
1098 (header-args (match-string 4))
1099 (beg-header-args (match-beginning 4))
1100 (end-header-args (match-end 4))
1101 (body (match-string 5))
1102 (beg-body (match-beginning 5))
1103 (end-body (match-end 5)))
1104 ;; Silence byte-compiler in case `body' doesn't use all
1105 ;; those variables.
1106 (ignore full-block beg-block end-block lang
1107 beg-lang end-lang switches beg-switches
1108 end-switches header-args beg-header-args
1109 end-header-args body beg-body end-body)
1110 ,@body
1111 (goto-char end-block)))))
1112 (unless visited-p (kill-buffer to-be-removed))
1113 (goto-char point))))
1114 (def-edebug-spec org-babel-map-src-blocks (form body))
1116 ;;;###autoload
1117 (defmacro org-babel-map-inline-src-blocks (file &rest body)
1118 "Evaluate BODY forms on each inline source block in FILE.
1119 If FILE is nil evaluate BODY forms on source blocks in current
1120 buffer."
1121 (declare (indent 1) (debug (form body)))
1122 (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
1123 `(let* ((case-fold-search t)
1124 (,tempvar ,file)
1125 (,visitedp (or (null ,tempvar)
1126 (get-file-buffer (expand-file-name ,tempvar))))
1127 (,point (point))
1128 ,to-be-removed)
1129 (save-window-excursion
1130 (when ,tempvar (find-file ,tempvar))
1131 (setq ,to-be-removed (current-buffer))
1132 (goto-char (point-min))
1133 (while (re-search-forward "src_\\S-" nil t)
1134 (let ((,datum (save-match-data (org-element-context))))
1135 (when (eq (org-element-type ,datum) 'inline-src-block)
1136 (goto-char (match-beginning 0))
1137 (let ((,end (copy-marker (org-element-property :end ,datum))))
1138 ,@body
1139 (goto-char ,end)
1140 (set-marker ,end nil))))))
1141 (unless ,visitedp (kill-buffer ,to-be-removed))
1142 (goto-char ,point))))
1144 ;;;###autoload
1145 (defmacro org-babel-map-call-lines (file &rest body)
1146 "Evaluate BODY forms on each call line in FILE.
1147 If FILE is nil evaluate BODY forms on source blocks in current
1148 buffer."
1149 (declare (indent 1) (debug (form body)))
1150 (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
1151 `(let* ((case-fold-search t)
1152 (,tempvar ,file)
1153 (,visitedp (or (null ,tempvar)
1154 (get-file-buffer (expand-file-name ,tempvar))))
1155 (,point (point))
1156 ,to-be-removed)
1157 (save-window-excursion
1158 (when ,tempvar (find-file ,tempvar))
1159 (setq ,to-be-removed (current-buffer))
1160 (goto-char (point-min))
1161 (while (re-search-forward "call_\\S-\\|^[ \t]*#\\+CALL:" nil t)
1162 (let ((,datum (save-match-data (org-element-context))))
1163 (when (memq (org-element-type ,datum)
1164 '(babel-call inline-babel-call))
1165 (goto-char (match-beginning 0))
1166 (let ((,end (copy-marker (org-element-property :end ,datum))))
1167 ,@body
1168 (goto-char ,end)
1169 (set-marker ,end nil))))))
1170 (unless ,visitedp (kill-buffer ,to-be-removed))
1171 (goto-char ,point))))
1173 ;;;###autoload
1174 (defmacro org-babel-map-executables (file &rest body)
1175 "Evaluate BODY forms on each active Babel code in FILE.
1176 If FILE is nil evaluate BODY forms on source blocks in current
1177 buffer."
1178 (declare (indent 1) (debug (form body)))
1179 (org-with-gensyms (datum end point tempvar to-be-removed visitedp)
1180 `(let* ((case-fold-search t)
1181 (,tempvar ,file)
1182 (,visitedp (or (null ,tempvar)
1183 (get-file-buffer (expand-file-name ,tempvar))))
1184 (,point (point))
1185 ,to-be-removed)
1186 (save-window-excursion
1187 (when ,tempvar (find-file ,tempvar))
1188 (setq ,to-be-removed (current-buffer))
1189 (goto-char (point-min))
1190 (while (re-search-forward
1191 "\\(call\\|src\\)_\\|^[ \t]*#\\+\\(BEGIN_SRC\\|CALL:\\)" nil t)
1192 (let ((,datum (save-match-data (org-element-context))))
1193 (when (memq (org-element-type ,datum)
1194 '(babel-call inline-babel-call inline-src-block
1195 src-block))
1196 (goto-char (match-beginning 0))
1197 (let ((,end (copy-marker (org-element-property :end ,datum))))
1198 ,@body
1199 (goto-char ,end)
1200 (set-marker ,end nil))))))
1201 (unless ,visitedp (kill-buffer ,to-be-removed))
1202 (goto-char ,point))))
1204 ;;;###autoload
1205 (defun org-babel-execute-buffer (&optional arg)
1206 "Execute source code blocks in a buffer.
1207 Call `org-babel-execute-src-block' on every source block in
1208 the current buffer."
1209 (interactive "P")
1210 (org-babel-eval-wipe-error-buffer)
1211 (org-save-outline-visibility t
1212 (org-babel-map-executables nil
1213 (if (memq (org-element-type (org-element-context))
1214 '(babel-call inline-babel-call))
1215 (org-babel-lob-execute-maybe)
1216 (org-babel-execute-src-block arg)))))
1218 ;;;###autoload
1219 (defun org-babel-execute-subtree (&optional arg)
1220 "Execute source code blocks in a subtree.
1221 Call `org-babel-execute-src-block' on every source block in
1222 the current subtree."
1223 (interactive "P")
1224 (save-restriction
1225 (save-excursion
1226 (org-narrow-to-subtree)
1227 (org-babel-execute-buffer arg)
1228 (widen))))
1230 ;;;###autoload
1231 (defun org-babel-sha1-hash (&optional info)
1232 "Generate an sha1 hash based on the value of info."
1233 (interactive)
1234 (let ((print-level nil)
1235 (info (or info (org-babel-get-src-block-info))))
1236 (setf (nth 2 info)
1237 (sort (copy-sequence (nth 2 info))
1238 (lambda (a b) (string< (car a) (car b)))))
1239 (let* ((rm (lambda (lst)
1240 (dolist (p '("replace" "silent" "none"
1241 "append" "prepend"))
1242 (setq lst (remove p lst)))
1243 lst))
1244 (norm (lambda (arg)
1245 (let ((v (if (and (listp (cdr arg)) (null (cddr arg)))
1246 (copy-sequence (cdr arg))
1247 (cdr arg))))
1248 (when (and v (not (and (sequencep v)
1249 (not (consp v))
1250 (= (length v) 0))))
1251 (cond
1252 ((and (listp v) ; lists are sorted
1253 (member (car arg) '(:result-params)))
1254 (sort (funcall rm v) #'string<))
1255 ((and (stringp v) ; strings are sorted
1256 (member (car arg) '(:results :exports)))
1257 (mapconcat #'identity (sort (funcall rm (split-string v))
1258 #'string<) " "))
1259 (t v))))))
1260 ;; expanded body
1261 (lang (nth 0 info))
1262 (params (nth 2 info))
1263 (body (if (org-babel-noweb-p params :eval)
1264 (org-babel-expand-noweb-references info) (nth 1 info)))
1265 (expand-cmd (intern (concat "org-babel-expand-body:" lang)))
1266 (assignments-cmd (intern (concat "org-babel-variable-assignments:"
1267 lang)))
1268 (expanded
1269 (if (fboundp expand-cmd) (funcall expand-cmd body params)
1270 (org-babel-expand-body:generic
1271 body params (and (fboundp assignments-cmd)
1272 (funcall assignments-cmd params))))))
1273 (let* ((it (format "%s-%s"
1274 (mapconcat
1275 #'identity
1276 (delq nil (mapcar (lambda (arg)
1277 (let ((normalized (funcall norm arg)))
1278 (when normalized
1279 (format "%S" normalized))))
1280 (nth 2 info))) ":")
1281 expanded))
1282 (hash (sha1 it)))
1283 (when (called-interactively-p 'interactive) (message hash))
1284 hash))))
1286 (defun org-babel-current-result-hash (&optional info)
1287 "Return the current in-buffer hash."
1288 (let ((result (org-babel-where-is-src-block-result nil info)))
1289 (when result
1290 (org-with-wide-buffer
1291 (goto-char result)
1292 (looking-at org-babel-result-regexp)
1293 (match-string-no-properties 1)))))
1295 (defun org-babel-set-current-result-hash (hash info)
1296 "Set the current in-buffer hash to HASH."
1297 (org-with-wide-buffer
1298 (goto-char (org-babel-where-is-src-block-result nil info))
1299 (looking-at org-babel-result-regexp)
1300 (goto-char (match-beginning 1))
1301 (mapc #'delete-overlay (overlays-at (point)))
1302 (forward-char org-babel-hash-show)
1303 (mapc #'delete-overlay (overlays-at (point)))
1304 (replace-match hash nil nil nil 1)
1305 (beginning-of-line)
1306 (org-babel-hide-hash)))
1308 (defun org-babel-hide-hash ()
1309 "Hide the hash in the current results line.
1310 Only the initial `org-babel-hash-show' characters of the hash
1311 will remain visible."
1312 (add-to-invisibility-spec '(org-babel-hide-hash . t))
1313 (save-excursion
1314 (when (and (re-search-forward org-babel-result-regexp nil t)
1315 (match-string 1))
1316 (let* ((start (match-beginning 1))
1317 (hide-start (+ org-babel-hash-show start))
1318 (end (match-end 1))
1319 (hash (match-string 1))
1320 ov1 ov2)
1321 (setq ov1 (make-overlay start hide-start))
1322 (setq ov2 (make-overlay hide-start end))
1323 (overlay-put ov2 'invisible 'org-babel-hide-hash)
1324 (overlay-put ov1 'babel-hash hash)))))
1326 (defun org-babel-hide-all-hashes ()
1327 "Hide the hash in the current buffer.
1328 Only the initial `org-babel-hash-show' characters of each hash
1329 will remain visible. This function should be called as part of
1330 the `org-mode-hook'."
1331 (save-excursion
1332 (while (and (not org-babel-hash-show-time)
1333 (re-search-forward org-babel-result-regexp nil t))
1334 (goto-char (match-beginning 0))
1335 (org-babel-hide-hash)
1336 (goto-char (match-end 0)))))
1337 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
1339 (defun org-babel-hash-at-point (&optional point)
1340 "Return the value of the hash at POINT.
1341 \\<org-mode-map>\
1342 The hash is also added as the last element of the kill ring.
1343 This can be called with `\\[org-ctrl-c-ctrl-c]'."
1344 (interactive)
1345 (let ((hash (car (delq nil (mapcar
1346 (lambda (ol) (overlay-get ol 'babel-hash))
1347 (overlays-at (or point (point))))))))
1348 (when hash (kill-new hash) (message hash))))
1350 (defun org-babel-result-hide-spec ()
1351 "Hide portions of results lines.
1352 Add `org-babel-hide-result' as an invisibility spec for hiding
1353 portions of results lines."
1354 (add-to-invisibility-spec '(org-babel-hide-result . t)))
1355 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
1357 (defvar org-babel-hide-result-overlays nil
1358 "Overlays hiding results.")
1360 (defun org-babel-result-hide-all ()
1361 "Fold all results in the current buffer."
1362 (interactive)
1363 (org-babel-show-result-all)
1364 (save-excursion
1365 (while (re-search-forward org-babel-result-regexp nil t)
1366 (save-excursion (goto-char (match-beginning 0))
1367 (org-babel-hide-result-toggle-maybe)))))
1369 (defun org-babel-show-result-all ()
1370 "Unfold all results in the current buffer."
1371 (mapc 'delete-overlay org-babel-hide-result-overlays)
1372 (setq org-babel-hide-result-overlays nil))
1374 ;;;###autoload
1375 (defun org-babel-hide-result-toggle-maybe ()
1376 "Toggle visibility of result at point."
1377 (interactive)
1378 (let ((case-fold-search t))
1379 (if (save-excursion
1380 (beginning-of-line 1)
1381 (looking-at org-babel-result-regexp))
1382 (progn (org-babel-hide-result-toggle)
1383 t) ;; to signal that we took action
1384 nil))) ;; to signal that we did not
1386 (defun org-babel-hide-result-toggle (&optional force)
1387 "Toggle the visibility of the current result."
1388 (interactive)
1389 (save-excursion
1390 (beginning-of-line)
1391 (if (re-search-forward org-babel-result-regexp nil t)
1392 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
1393 (end (progn
1394 (while (looking-at org-babel-multi-line-header-regexp)
1395 (forward-line 1))
1396 (goto-char (- (org-babel-result-end) 1)) (point)))
1398 (if (memq t (mapcar (lambda (overlay)
1399 (eq (overlay-get overlay 'invisible)
1400 'org-babel-hide-result))
1401 (overlays-at start)))
1402 (when (or (not force) (eq force 'off))
1403 (mapc (lambda (ov)
1404 (when (member ov org-babel-hide-result-overlays)
1405 (setq org-babel-hide-result-overlays
1406 (delq ov org-babel-hide-result-overlays)))
1407 (when (eq (overlay-get ov 'invisible)
1408 'org-babel-hide-result)
1409 (delete-overlay ov)))
1410 (overlays-at start)))
1411 (setq ov (make-overlay start end))
1412 (overlay-put ov 'invisible 'org-babel-hide-result)
1413 ;; make the block accessible to isearch
1414 (overlay-put
1415 ov 'isearch-open-invisible
1416 (lambda (ov)
1417 (when (member ov org-babel-hide-result-overlays)
1418 (setq org-babel-hide-result-overlays
1419 (delq ov org-babel-hide-result-overlays)))
1420 (when (eq (overlay-get ov 'invisible)
1421 'org-babel-hide-result)
1422 (delete-overlay ov))))
1423 (push ov org-babel-hide-result-overlays)))
1424 (error "Not looking at a result line"))))
1426 ;; org-tab-after-check-for-cycling-hook
1427 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
1428 ;; Remove overlays when changing major mode
1429 (add-hook 'org-mode-hook
1430 (lambda () (add-hook 'change-major-mode-hook
1431 'org-babel-show-result-all 'append 'local)))
1433 (defun org-babel-params-from-properties (&optional lang no-eval)
1434 "Retrieve source block parameters specified as properties.
1436 LANG is the language of the source block, as a string. When
1437 optional argument NO-EVAL is non-nil, do not evaluate Lisp values
1438 in parameters.
1440 Return a list of association lists of source block parameters
1441 specified in the properties of the current outline entry."
1442 (save-match-data
1443 (list
1444 ;; Header arguments specified with the header-args property at
1445 ;; point of call.
1446 (org-babel-parse-header-arguments
1447 (org-entry-get (point) "header-args" 'inherit)
1448 no-eval)
1449 ;; Language-specific header arguments at point of call.
1450 (and lang
1451 (org-babel-parse-header-arguments
1452 (org-entry-get (point) (concat "header-args:" lang) 'inherit)
1453 no-eval)))))
1455 (defun org-babel-balanced-split (string alts)
1456 "Split STRING on instances of ALTS.
1457 ALTS is a character, or cons of two character options where each
1458 option may be either the numeric code of a single character or
1459 a list of character alternatives. For example, to split on
1460 balanced instances of \"[ \t]:\", set ALTS to ((32 9) . 58)."
1461 (with-temp-buffer
1462 (insert string)
1463 (goto-char (point-min))
1464 (let ((splitp (lambda (past next)
1465 ;; Non-nil when there should be a split after NEXT
1466 ;; character. PAST is the character before NEXT.
1467 (pcase alts
1468 (`(,(and first (pred consp)) . ,(and second (pred consp)))
1469 (and (memq past first) (memq next second)))
1470 (`(,first . ,(and second (pred consp)))
1471 (and (eq past first) (memq next second)))
1472 (`(,(and first (pred consp)) . ,second)
1473 (and (memq past first) (eq next second)))
1474 (`(,first . ,second)
1475 (and (eq past first) (eq next second)))
1476 ((pred (eq next)) t)
1477 (_ nil))))
1478 (partial nil)
1479 (result nil))
1480 (while (not (eobp))
1481 (cond
1482 ((funcall splitp (char-before) (char-after))
1483 ;; There is a split after point. If ALTS is two-folds,
1484 ;; remove last parsed character as it belongs to ALTS.
1485 (when (consp alts) (pop partial))
1486 ;; Include elements parsed so far in RESULTS and flush
1487 ;; partial parsing.
1488 (when partial
1489 (push (apply #'string (nreverse partial)) result)
1490 (setq partial nil))
1491 (forward-char))
1492 ((memq (char-after) '(?\( ?\[))
1493 ;; Include everything between balanced brackets.
1494 (let* ((origin (point))
1495 (after (char-after))
1496 (openings (list after)))
1497 (forward-char)
1498 (while (and openings (re-search-forward "[]()]" nil t))
1499 (pcase (char-before)
1500 ((and match (or ?\[ ?\()) (push match openings))
1501 (?\] (when (eq ?\[ (car openings)) (pop openings)))
1502 (_ (when (eq ?\( (car openings)) (pop openings)))))
1503 (if (null openings)
1504 (setq partial
1505 (nconc (nreverse (string-to-list
1506 (buffer-substring origin (point))))
1507 partial))
1508 ;; Un-balanced bracket. Backtrack.
1509 (push after partial)
1510 (goto-char (1+ origin)))))
1511 ((and (eq ?\" (char-after)) (not (eq ?\\ (char-before))))
1512 ;; Include everything from current double quote to next
1513 ;; non-escaped double quote.
1514 (let ((origin (point)))
1515 (if (re-search-forward "[^\\]\"" nil t)
1516 (setq partial
1517 (nconc (nreverse (string-to-list
1518 (buffer-substring origin (point))))
1519 partial))
1520 ;; No closing double quote. Backtrack.
1521 (push ?\" partial)
1522 (forward-char))))
1523 (t (push (char-after) partial)
1524 (forward-char))))
1525 ;; Add pending parsing and return result.
1526 (when partial (push (apply #'string (nreverse partial)) result))
1527 (nreverse result))))
1529 (defun org-babel-join-splits-near-ch (ch list)
1530 "Join splits where \"=\" is on either end of the split."
1531 (let ((last= (lambda (str) (= ch (aref str (1- (length str))))))
1532 (first= (lambda (str) (= ch (aref str 0)))))
1533 (reverse
1534 (cl-reduce (lambda (acc el)
1535 (let ((head (car acc)))
1536 (if (and head (or (funcall last= head) (funcall first= el)))
1537 (cons (concat head el) (cdr acc))
1538 (cons el acc))))
1539 list :initial-value nil))))
1541 (defun org-babel-parse-header-arguments (string &optional no-eval)
1542 "Parse header arguments in STRING.
1543 When optional argument NO-EVAL is non-nil, do not evaluate Lisp
1544 in parameters. Return an alist."
1545 (when (org-string-nw-p string)
1546 (org-babel-parse-multiple-vars
1547 (delq nil
1548 (mapcar
1549 (lambda (arg)
1550 (if (string-match
1551 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
1552 arg)
1553 (cons (intern (match-string 1 arg))
1554 (org-babel-read (org-babel-chomp (match-string 2 arg))
1555 no-eval))
1556 (cons (intern (org-babel-chomp arg)) nil)))
1557 (let ((raw (org-babel-balanced-split string '((32 9) . 58))))
1558 (cons (car raw)
1559 (mapcar (lambda (r) (concat ":" r)) (cdr raw)))))))))
1561 (defun org-babel-parse-multiple-vars (header-arguments)
1562 "Expand multiple variable assignments behind a single :var keyword.
1564 This allows expression of multiple variables with one :var as
1565 shown below.
1567 #+PROPERTY: var foo=1, bar=2"
1568 (let (results)
1569 (mapc (lambda (pair)
1570 (if (eq (car pair) :var)
1571 (mapcar (lambda (v) (push (cons :var (org-trim v)) results))
1572 (org-babel-join-splits-near-ch
1573 61 (org-babel-balanced-split (cdr pair) 32)))
1574 (push pair results)))
1575 header-arguments)
1576 (nreverse results)))
1578 (defun org-babel-process-params (params)
1579 "Expand variables in PARAMS and add summary parameters."
1580 (let* ((processed-vars (mapcar (lambda (el)
1581 (if (consp el)
1583 (org-babel-ref-parse el)))
1584 (org-babel--get-vars params)))
1585 (vars-and-names (if (and (assq :colname-names params)
1586 (assq :rowname-names params))
1587 (list processed-vars)
1588 (org-babel-disassemble-tables
1589 processed-vars
1590 (cdr (assq :hlines params))
1591 (cdr (assq :colnames params))
1592 (cdr (assq :rownames params)))))
1593 (raw-result (or (cdr (assq :results params)) ""))
1594 (result-params (delete-dups
1595 (append
1596 (split-string (if (stringp raw-result)
1597 raw-result
1598 (eval raw-result t)))
1599 (cdr (assq :result-params params))))))
1600 (append
1601 (mapcar (lambda (var) (cons :var var)) (car vars-and-names))
1602 (list
1603 (cons :colname-names (or (cdr (assq :colname-names params))
1604 (cadr vars-and-names)))
1605 (cons :rowname-names (or (cdr (assq :rowname-names params))
1606 (cl-caddr vars-and-names)))
1607 (cons :result-params result-params)
1608 (cons :result-type (cond ((member "output" result-params) 'output)
1609 ((member "value" result-params) 'value)
1610 (t 'value))))
1611 (cl-remove-if
1612 (lambda (x) (memq (car x) '(:colname-names :rowname-names :result-params
1613 :result-type :var)))
1614 params))))
1616 ;; row and column names
1617 (defun org-babel-del-hlines (table)
1618 "Remove all `hline's from TABLE."
1619 (remq 'hline table))
1621 (defun org-babel-get-colnames (table)
1622 "Return the column names of TABLE.
1623 Return a cons cell, the `car' of which contains the TABLE less
1624 colnames, and the `cdr' of which contains a list of the column
1625 names."
1626 (if (eq 'hline (nth 1 table))
1627 (cons (cddr table) (car table))
1628 (cons (cdr table) (car table))))
1630 (defun org-babel-get-rownames (table)
1631 "Return the row names of TABLE.
1632 Return a cons cell, the `car' of which contains the TABLE less
1633 rownames, and the `cdr' of which contains a list of the rownames.
1634 Note: this function removes any hlines in TABLE."
1635 (let* ((table (org-babel-del-hlines table))
1636 (rownames (funcall (lambda ()
1637 (let ((tp table))
1638 (mapcar
1639 (lambda (_row)
1640 (prog1
1641 (pop (car tp))
1642 (setq tp (cdr tp))))
1643 table))))))
1644 (cons table rownames)))
1646 (defun org-babel-put-colnames (table colnames)
1647 "Add COLNAMES to TABLE if they exist."
1648 (if colnames (apply 'list colnames 'hline table) table))
1650 (defun org-babel-put-rownames (table rownames)
1651 "Add ROWNAMES to TABLE if they exist."
1652 (if rownames
1653 (mapcar (lambda (row)
1654 (if (listp row)
1655 (cons (or (pop rownames) "") row)
1656 row)) table)
1657 table))
1659 (defun org-babel-pick-name (names selector)
1660 "Select one out of an alist of row or column names.
1661 SELECTOR can be either a list of names in which case those names
1662 will be returned directly, or an index into the list NAMES in
1663 which case the indexed names will be return."
1664 (if (listp selector)
1665 selector
1666 (when names
1667 (if (and selector (symbolp selector) (not (equal t selector)))
1668 (cdr (assoc selector names))
1669 (if (integerp selector)
1670 (nth (- selector 1) names)
1671 (cdr (car (last names))))))))
1673 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
1674 "Parse tables for further processing.
1675 Process the variables in VARS according to the HLINES,
1676 ROWNAMES and COLNAMES header arguments. Return a list consisting
1677 of the vars, cnames and rnames."
1678 (let (cnames rnames)
1679 (list
1680 (mapcar
1681 (lambda (var)
1682 (when (listp (cdr var))
1683 (when (and (not (equal colnames "no"))
1684 (or colnames (and (eq (nth 1 (cdr var)) 'hline)
1685 (not (member 'hline (cddr (cdr var)))))))
1686 (let ((both (org-babel-get-colnames (cdr var))))
1687 (setq cnames (cons (cons (car var) (cdr both))
1688 cnames))
1689 (setq var (cons (car var) (car both)))))
1690 (when (and rownames (not (equal rownames "no")))
1691 (let ((both (org-babel-get-rownames (cdr var))))
1692 (setq rnames (cons (cons (car var) (cdr both))
1693 rnames))
1694 (setq var (cons (car var) (car both)))))
1695 (when (and hlines (not (equal hlines "yes")))
1696 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
1697 var)
1698 vars)
1699 (reverse cnames) (reverse rnames))))
1701 (defun org-babel-reassemble-table (table colnames rownames)
1702 "Add column and row names to a table.
1703 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1704 to the table for reinsertion to org-mode."
1705 (if (listp table)
1706 (let ((table (if (and rownames (= (length table) (length rownames)))
1707 (org-babel-put-rownames table rownames) table)))
1708 (if (and colnames (listp (car table)) (= (length (car table))
1709 (length colnames)))
1710 (org-babel-put-colnames table colnames) table))
1711 table))
1713 (defun org-babel-where-is-src-block-head (&optional src-block)
1714 "Find where the current source block begins.
1716 If optional argument SRC-BLOCK is `src-block' type element, find
1717 its current beginning instead.
1719 Return the point at the beginning of the current source block.
1720 Specifically at the beginning of the #+BEGIN_SRC line. Also set
1721 match-data relatively to `org-babel-src-block-regexp', which see.
1722 If the point is not on a source block then return nil."
1723 (let ((element (or src-block (org-element-at-point))))
1724 (when (eq (org-element-type element) 'src-block)
1725 (let ((end (org-element-property :end element)))
1726 (org-with-wide-buffer
1727 ;; Ensure point is not on a blank line after the block.
1728 (beginning-of-line)
1729 (skip-chars-forward " \r\t\n" end)
1730 (when (< (point) end)
1731 (prog1 (goto-char (org-element-property :post-affiliated element))
1732 (looking-at org-babel-src-block-regexp))))))))
1734 ;;;###autoload
1735 (defun org-babel-goto-src-block-head ()
1736 "Go to the beginning of the current code block."
1737 (interactive)
1738 (let ((head (org-babel-where-is-src-block-head)))
1739 (if head (goto-char head) (error "Not currently in a code block"))))
1741 ;;;###autoload
1742 (defun org-babel-goto-named-src-block (name)
1743 "Go to a named source-code block."
1744 (interactive
1745 (let ((completion-ignore-case t)
1746 (case-fold-search t)
1747 (all-block-names (org-babel-src-block-names)))
1748 (list (completing-read
1749 "source-block name: " all-block-names nil t
1750 (let* ((context (org-element-context))
1751 (type (org-element-type context))
1752 (noweb-ref
1753 (and (memq type '(inline-src-block src-block))
1754 (org-in-regexp (org-babel-noweb-wrap)))))
1755 (cond
1756 (noweb-ref
1757 (buffer-substring
1758 (+ (car noweb-ref) (length org-babel-noweb-wrap-start))
1759 (- (cdr noweb-ref) (length org-babel-noweb-wrap-end))))
1760 ((memq type '(babel-call inline-babel-call)) ;#+CALL:
1761 (org-element-property :call context))
1762 ((car (org-element-property :results context))) ;#+RESULTS:
1763 ((let ((symbol (thing-at-point 'symbol))) ;Symbol.
1764 (and symbol
1765 (member-ignore-case symbol all-block-names)
1766 symbol)))
1767 (t "")))))))
1768 (let ((point (org-babel-find-named-block name)))
1769 (if point
1770 ;; Taken from `org-open-at-point'.
1771 (progn (org-mark-ring-push) (goto-char point) (org-show-context))
1772 (message "source-code block `%s' not found in this buffer" name))))
1774 (defun org-babel-find-named-block (name)
1775 "Find a named source-code block.
1776 Return the location of the source block identified by source
1777 NAME, or nil if no such block exists. Set match data according
1778 to `org-babel-named-src-block-regexp'."
1779 (save-excursion
1780 (goto-char (point-min))
1781 (let ((regexp (org-babel-named-src-block-regexp-for-name name)))
1782 (or (and (looking-at regexp)
1783 (progn (goto-char (match-beginning 1))
1784 (line-beginning-position)))
1785 (ignore-errors (org-next-block 1 nil regexp))))))
1787 (defun org-babel-src-block-names (&optional file)
1788 "Returns the names of source blocks in FILE or the current buffer."
1789 (with-current-buffer (if file (find-file-noselect file) (current-buffer))
1790 (org-with-point-at 1
1791 (let ((regexp "^[ \t]*#\\+begin_src ")
1792 (case-fold-search t)
1793 (names nil))
1794 (while (re-search-forward regexp nil t)
1795 (let ((element (org-element-at-point)))
1796 (when (eq 'src-block (org-element-type element))
1797 (let ((name (org-element-property :name element)))
1798 (when name (push name names))))))
1799 names))))
1801 ;;;###autoload
1802 (defun org-babel-goto-named-result (name)
1803 "Go to a named result."
1804 (interactive
1805 (let ((completion-ignore-case t))
1806 (list (completing-read "Source-block name: "
1807 (org-babel-result-names) nil t))))
1808 (let ((point (org-babel-find-named-result name)))
1809 (if point
1810 ;; taken from `org-open-at-point'
1811 (progn (goto-char point) (org-show-context))
1812 (message "result `%s' not found in this buffer" name))))
1814 (defun org-babel-find-named-result (name)
1815 "Find a named result.
1816 Return the location of the result named NAME in the current
1817 buffer or nil if no such result exists."
1818 (save-excursion
1819 (goto-char (point-min))
1820 (let ((case-fold-search t)
1821 (re (format "^[ \t]*#\\+%s.*?:[ \t]*%s[ \t]*$"
1822 org-babel-results-keyword
1823 (regexp-quote name))))
1824 (catch :found
1825 (while (re-search-forward re nil t)
1826 (let ((element (org-element-at-point)))
1827 (when (or (eq (org-element-type element) 'keyword)
1828 (< (point)
1829 (org-element-property :post-affiliated element)))
1830 (throw :found (line-beginning-position)))))))))
1832 (defun org-babel-result-names (&optional file)
1833 "Returns the names of results in FILE or the current buffer."
1834 (save-excursion
1835 (when file (find-file file)) (goto-char (point-min))
1836 (let ((case-fold-search t) names)
1837 (while (re-search-forward org-babel-result-w-name-regexp nil t)
1838 (setq names (cons (match-string-no-properties 9) names)))
1839 names)))
1841 ;;;###autoload
1842 (defun org-babel-next-src-block (&optional arg)
1843 "Jump to the next source block.
1844 With optional prefix argument ARG, jump forward ARG many source blocks."
1845 (interactive "p")
1846 (org-next-block arg nil org-babel-src-block-regexp))
1848 ;;;###autoload
1849 (defun org-babel-previous-src-block (&optional arg)
1850 "Jump to the previous source block.
1851 With optional prefix argument ARG, jump backward ARG many source blocks."
1852 (interactive "p")
1853 (org-previous-block arg org-babel-src-block-regexp))
1855 (defvar org-babel-load-languages)
1857 ;;;###autoload
1858 (defun org-babel-mark-block ()
1859 "Mark current src block."
1860 (interactive)
1861 (let ((head (org-babel-where-is-src-block-head)))
1862 (when head
1863 (save-excursion
1864 (goto-char head)
1865 (looking-at org-babel-src-block-regexp))
1866 (push-mark (match-end 5) nil t)
1867 (goto-char (match-beginning 5)))))
1869 (defun org-babel-demarcate-block (&optional arg)
1870 "Wrap or split the code in the region or on the point.
1871 When called from inside of a code block the current block is
1872 split. When called from outside of a code block a new code block
1873 is created. In both cases if the region is demarcated and if the
1874 region is not active then the point is demarcated."
1875 (interactive "P")
1876 (let* ((info (org-babel-get-src-block-info 'light))
1877 (start (org-babel-where-is-src-block-head))
1878 (block (and start (match-string 0)))
1879 (headers (and start (match-string 4)))
1880 (stars (concat (make-string (or (org-current-level) 1) ?*) " "))
1881 (lower-case-p (and block
1882 (let (case-fold-search)
1883 (string-match-p "#\\+begin_src" block)))))
1884 (if info
1885 (mapc
1886 (lambda (place)
1887 (save-excursion
1888 (goto-char place)
1889 (let ((lang (nth 0 info))
1890 (indent (make-string (org-get-indentation) ?\s)))
1891 (when (string-match "^[[:space:]]*$"
1892 (buffer-substring (point-at-bol)
1893 (point-at-eol)))
1894 (delete-region (point-at-bol) (point-at-eol)))
1895 (insert (concat
1896 (if (looking-at "^") "" "\n")
1897 indent (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")
1898 (if arg stars indent) "\n"
1899 indent (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1900 lang
1901 (if (> (length headers) 1)
1902 (concat " " headers) headers)
1903 (if (looking-at "[\n\r]")
1905 (concat "\n" (make-string (current-column) ? )))))))
1906 (move-end-of-line 2))
1907 (sort (if (org-region-active-p) (list (mark) (point)) (list (point))) #'>))
1908 (let ((start (point))
1909 (lang (completing-read
1910 "Lang: "
1911 (mapcar #'symbol-name
1912 (delete-dups
1913 (append (mapcar #'car org-babel-load-languages)
1914 (mapcar (lambda (el) (intern (car el)))
1915 org-src-lang-modes))))))
1916 (body (delete-and-extract-region
1917 (if (org-region-active-p) (mark) (point)) (point))))
1918 (insert (concat (if (looking-at "^") "" "\n")
1919 (if arg (concat stars "\n") "")
1920 (funcall (if lower-case-p 'downcase 'upcase) "#+begin_src ")
1921 lang "\n"
1922 body
1923 (if (or (= (length body) 0)
1924 (string-suffix-p "\r" body)
1925 (string-suffix-p "\n" body)) "" "\n")
1926 (funcall (if lower-case-p 'downcase 'upcase) "#+end_src\n")))
1927 (goto-char start) (move-end-of-line 1)))))
1929 (defun org-babel--insert-results-keyword (name hash)
1930 "Insert RESULTS keyword with NAME value at point.
1931 If NAME is nil, results are anonymous. HASH is a string used as
1932 the results hash, or nil. Leave point before the keyword."
1933 (save-excursion (insert "\n")) ;open line to indent.
1934 (org-indent-line)
1935 (delete-char 1)
1936 (insert (concat "#+" org-babel-results-keyword
1937 (cond ((not hash) nil)
1938 (org-babel-hash-show-time
1939 (format "[%s %s]"
1940 (format-time-string "<%F %T>")
1941 hash))
1942 (t (format "[%s]" hash)))
1944 (when name (concat " " name))
1945 "\n"))
1946 ;; Make sure results are going to be followed by at least one blank
1947 ;; line so they do not get merged with the next element, e.g.,
1949 ;; #+results:
1950 ;; : 1
1952 ;; : fixed-width area, unrelated to the above.
1953 (unless (looking-at "^[ \t]*$") (save-excursion (insert "\n")))
1954 (beginning-of-line 0)
1955 (when hash (org-babel-hide-hash)))
1957 (defun org-babel--clear-results-maybe (hash)
1958 "Clear results when hash doesn't match HASH.
1960 When results hash does not match HASH, remove RESULTS keyword at
1961 point, along with related contents. Do nothing if HASH is nil.
1963 Return a non-nil value if results were cleared. In this case,
1964 leave point where new results should be inserted."
1965 (when hash
1966 (looking-at org-babel-result-regexp)
1967 (unless (string= (match-string 1) hash)
1968 (let* ((e (org-element-at-point))
1969 (post (copy-marker (org-element-property :post-affiliated e))))
1970 ;; Delete contents.
1971 (delete-region post
1972 (save-excursion
1973 (goto-char (org-element-property :end e))
1974 (skip-chars-backward " \t\n")
1975 (line-beginning-position 2)))
1976 ;; Delete RESULT keyword. However, if RESULTS keyword is
1977 ;; orphaned, ignore this part. The deletion above already
1978 ;; took care of it.
1979 (unless (= (point) post)
1980 (delete-region (line-beginning-position)
1981 (line-beginning-position 2)))
1982 (goto-char post)
1983 (set-marker post nil)
1984 t))))
1986 (defun org-babel-where-is-src-block-result (&optional insert _info hash)
1987 "Find where the current source block results begin.
1989 Return the point at the beginning of the result of the current
1990 source block, specifically at the beginning of the results line.
1992 If no result exists for this block return nil, unless optional
1993 argument INSERT is non-nil. In this case, create a results line
1994 following the source block and return the position at its
1995 beginning. In the case of inline code, remove the results part
1996 instead.
1998 If optional argument HASH is a string, remove contents related to
1999 RESULTS keyword if its hash is different. Then update the latter
2000 to HASH."
2001 (let ((context (org-element-context)))
2002 (catch :found
2003 (org-with-wide-buffer
2004 (pcase (org-element-type context)
2005 ((or `inline-babel-call `inline-src-block)
2006 ;; Results for inline objects are located right after them.
2007 ;; There is no RESULTS line to insert either.
2008 (let ((limit (org-element-property
2009 :contents-end (org-element-property :parent context))))
2010 (goto-char (org-element-property :end context))
2011 (skip-chars-forward " \t\n" limit)
2012 (throw :found
2013 (and
2014 (< (point) limit)
2015 (let ((result (org-element-context)))
2016 (and (eq (org-element-type result) 'macro)
2017 (string= (org-element-property :key result)
2018 "results")
2019 (if (not insert) (point)
2020 (delete-region
2021 (point)
2022 (progn
2023 (goto-char (org-element-property :end result))
2024 (skip-chars-backward " \t")
2025 (point)))
2026 (point))))))))
2027 ((or `babel-call `src-block)
2028 (let* ((name (org-element-property :name context))
2029 (named-results (and name (org-babel-find-named-result name))))
2030 (goto-char (or named-results (org-element-property :end context)))
2031 (cond
2032 ;; Existing results named after the current source.
2033 (named-results
2034 (when (org-babel--clear-results-maybe hash)
2035 (org-babel--insert-results-keyword name hash))
2036 (throw :found (point)))
2037 ;; Named results expect but none to be found.
2038 (name)
2039 ;; No possible anonymous results at the very end of
2040 ;; buffer or outside CONTEXT parent.
2041 ((eq (point)
2042 (or (org-element-property
2043 :contents-end (org-element-property :parent context))
2044 (point-max))))
2045 ;; Check if next element is an anonymous result below
2046 ;; the current block.
2047 ((let* ((next (org-element-at-point))
2048 (end (save-excursion
2049 (goto-char
2050 (org-element-property :post-affiliated next))
2051 (line-end-position)))
2052 (empty-result-re (concat org-babel-result-regexp "$"))
2053 (case-fold-search t))
2054 (re-search-forward empty-result-re end t))
2055 (beginning-of-line)
2056 (when (org-babel--clear-results-maybe hash)
2057 (org-babel--insert-results-keyword nil hash))
2058 (throw :found (point))))))
2059 ;; Ignore other elements.
2060 (_ (throw :found nil))))
2061 ;; No result found. Insert a RESULTS keyword below element, if
2062 ;; appropriate. In this case, ensure there is an empty line
2063 ;; after the previous element.
2064 (when insert
2065 (save-excursion
2066 (goto-char (min (org-element-property :end context) (point-max)))
2067 (skip-chars-backward " \t\n")
2068 (forward-line)
2069 (unless (bolp) (insert "\n"))
2070 (insert "\n")
2071 (org-babel--insert-results-keyword
2072 (org-element-property :name context) hash)
2073 (point))))))
2075 (defun org-babel-read-element (element)
2076 "Read ELEMENT into emacs-lisp.
2077 Return nil if ELEMENT cannot be read."
2078 (org-with-wide-buffer
2079 (goto-char (org-element-property :post-affiliated element))
2080 (pcase (org-element-type element)
2081 (`fixed-width
2082 (let ((v (org-trim (org-element-property :value element))))
2083 (or (org-babel--string-to-number v) v)))
2084 (`table (org-babel-read-table))
2085 (`plain-list (org-babel-read-list))
2086 (`example-block
2087 (let ((v (org-element-property :value element)))
2088 (if (or org-src-preserve-indentation
2089 (org-element-property :preserve-indent element))
2091 (org-remove-indentation v))))
2092 (`export-block
2093 (org-remove-indentation (org-element-property :value element)))
2094 (`paragraph
2095 ;; Treat paragraphs containing a single link specially.
2096 (skip-chars-forward " \t")
2097 (if (and (looking-at org-bracket-link-regexp)
2098 (save-excursion
2099 (goto-char (match-end 0))
2100 (skip-chars-forward " \r\t\n")
2101 (<= (org-element-property :end element)
2102 (point))))
2103 (org-babel-read-link)
2104 (buffer-substring-no-properties
2105 (org-element-property :contents-begin element)
2106 (org-element-property :contents-end element))))
2107 ((or `center-block `quote-block `verse-block `special-block)
2108 (org-remove-indentation
2109 (buffer-substring-no-properties
2110 (org-element-property :contents-begin element)
2111 (org-element-property :contents-end element))))
2112 (_ nil))))
2114 (defun org-babel-read-result ()
2115 "Read the result at point into emacs-lisp."
2116 (and (not (save-excursion
2117 (beginning-of-line)
2118 (looking-at-p "[ \t]*$")))
2119 (org-babel-read-element (org-element-at-point))))
2121 (defun org-babel-read-table ()
2122 "Read the table at point into emacs-lisp."
2123 (mapcar (lambda (row)
2124 (if (and (symbolp row) (equal row 'hline)) row
2125 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval)) row)))
2126 (org-table-to-lisp)))
2128 (defun org-babel-read-list ()
2129 "Read the list at point into emacs-lisp."
2130 (mapcar (lambda (el) (org-babel-read el 'inhibit-lisp-eval))
2131 (cdr (org-list-to-lisp))))
2133 (defvar org-link-types-re)
2134 (defun org-babel-read-link ()
2135 "Read the link at point into emacs-lisp.
2136 If the path of the link is a file path it is expanded using
2137 `expand-file-name'."
2138 (let* ((case-fold-search t)
2139 (raw (and (looking-at org-bracket-link-regexp)
2140 (org-no-properties (match-string 1))))
2141 (type (and (string-match org-link-types-re raw)
2142 (match-string 1 raw))))
2143 (cond
2144 ((not type) (expand-file-name raw))
2145 ((string= type "file")
2146 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
2147 (expand-file-name (match-string 2 raw))))
2148 (t raw))))
2150 (defun org-babel-format-result (result &optional sep)
2151 "Format RESULT for writing to file."
2152 (let ((echo-res (lambda (r) (if (stringp r) r (format "%S" r)))))
2153 (if (listp result)
2154 ;; table result
2155 (orgtbl-to-generic
2156 result (list :sep (or sep "\t") :fmt echo-res))
2157 ;; scalar result
2158 (funcall echo-res result))))
2160 (defun org-babel-insert-result (result &optional result-params info hash lang)
2161 "Insert RESULT into the current buffer.
2163 By default RESULT is inserted after the end of the current source
2164 block. The RESULT of an inline source block usually will be
2165 wrapped inside a `results' macro and placed on the same line as
2166 the inline source block. The macro is stripped upon export.
2167 Multiline and non-scalar RESULTS from inline source blocks are
2168 not allowed. With optional argument RESULT-PARAMS controls
2169 insertion of results in the Org mode file. RESULT-PARAMS can
2170 take the following values:
2172 replace - (default option) insert results after the source block
2173 or inline source block replacing any previously
2174 inserted results.
2176 silent -- no results are inserted into the Org buffer but
2177 the results are echoed to the minibuffer and are
2178 ingested by Emacs (a potentially time consuming
2179 process).
2181 file ---- the results are interpreted as a file path, and are
2182 inserted into the buffer using the Org file syntax.
2184 list ---- the results are interpreted as an Org list.
2186 raw ----- results are added directly to the Org file. This is
2187 a good option if you code block will output Org
2188 formatted text.
2190 drawer -- results are added directly to the Org file as with
2191 \"raw\", but are wrapped in a RESULTS drawer or results
2192 macro, allowing them to later be replaced or removed
2193 automatically.
2195 org ----- results are added inside of a \"src_org{}\" or \"#+BEGIN_SRC
2196 org\" block depending on whether the current source block is
2197 inline or not. They are not comma-escaped when inserted,
2198 but Org syntax here will be discarded when exporting the
2199 file.
2201 html ---- results are added inside of a #+BEGIN_EXPORT HTML block
2202 or html export snippet depending on whether the current
2203 source block is inline or not. This is a good option
2204 if your code block will output html formatted text.
2206 latex --- results are added inside of a #+BEGIN_EXPORT LATEX
2207 block or latex export snippet depending on whether the
2208 current source block is inline or not. This is a good
2209 option if your code block will output latex formatted
2210 text.
2212 code ---- the results are extracted in the syntax of the source
2213 code of the language being evaluated and are added
2214 inside of a source block with the source-code language
2215 set appropriately. Also, source block inlining is
2216 preserved in this case. Note this relies on the
2217 optional LANG argument.
2219 list ---- the results are rendered as a list. This option not
2220 allowed for inline src blocks.
2222 table --- the results are rendered as a table. This option not
2223 allowed for inline src blocks.
2225 INFO may provide the values of these header arguments (in the
2226 `header-arguments-alist' see the docstring for
2227 `org-babel-get-src-block-info'):
2229 :file --- the name of the file to which output should be written.
2231 :wrap --- the effect is similar to `latex' in RESULT-PARAMS but
2232 using the argument supplied to specify the export block
2233 or snippet type."
2234 (cond ((stringp result)
2235 (setq result (org-no-properties result))
2236 (when (member "file" result-params)
2237 (setq result (org-babel-result-to-file
2238 result (when (assq :file-desc (nth 2 info))
2239 (or (cdr (assq :file-desc (nth 2 info)))
2240 result))))))
2241 ((listp result))
2242 (t (setq result (format "%S" result))))
2243 (if (and result-params (member "silent" result-params))
2244 (progn (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
2245 result)
2246 (let ((inline (let ((context (org-element-context)))
2247 (and (memq (org-element-type context)
2248 '(inline-babel-call inline-src-block))
2249 context))))
2250 (when inline
2251 (let ((warning
2252 (or (and (member "table" result-params) "`:results table'")
2253 (and (listp result) "list result")
2254 (and (string-match-p "\n." result) "multiline result")
2255 (and (member "list" result-params) "`:results list'"))))
2256 (when warning
2257 (user-error "Inline error: %s cannot be used" warning))))
2258 (save-excursion
2259 (let* ((visible-beg (point-min-marker))
2260 (visible-end (copy-marker (point-max) t))
2261 (inline (let ((context (org-element-context)))
2262 (and (memq (org-element-type context)
2263 '(inline-babel-call inline-src-block))
2264 context)))
2265 (existing-result (org-babel-where-is-src-block-result t nil hash))
2266 (results-switches (cdr (assq :results_switches (nth 2 info))))
2267 ;; When results exist outside of the current visible
2268 ;; region of the buffer, be sure to widen buffer to
2269 ;; update them.
2270 (outside-scope (and existing-result
2271 (buffer-narrowed-p)
2272 (or (> visible-beg existing-result)
2273 (<= visible-end existing-result))))
2274 beg end indent)
2275 ;; Ensure non-inline results end in a newline.
2276 (when (and (org-string-nw-p result)
2277 (not inline)
2278 (not (string-equal (substring result -1) "\n")))
2279 (setq result (concat result "\n")))
2280 (unwind-protect
2281 (progn
2282 (when outside-scope (widen))
2283 (if existing-result (goto-char existing-result)
2284 (goto-char (org-element-property :end inline))
2285 (skip-chars-backward " \t"))
2286 (unless inline
2287 (setq indent (org-get-indentation))
2288 (forward-line 1))
2289 (setq beg (point))
2290 (cond
2291 (inline
2292 ;; Make sure new results are separated from the
2293 ;; source code by one space.
2294 (unless existing-result
2295 (insert " ")
2296 (setq beg (point))))
2297 ((member "replace" result-params)
2298 (delete-region (point) (org-babel-result-end)))
2299 ((member "append" result-params)
2300 (goto-char (org-babel-result-end)) (setq beg (point-marker)))
2301 ((member "prepend" result-params))) ; already there
2302 (setq results-switches
2303 (if results-switches (concat " " results-switches) ""))
2304 (let ((wrap
2305 (lambda (start finish &optional no-escape no-newlines
2306 inline-start inline-finish)
2307 (when inline
2308 (setq start inline-start)
2309 (setq finish inline-finish)
2310 (setq no-newlines t))
2311 (let ((before-finish (marker-position end)))
2312 (goto-char end)
2313 (insert (concat finish (unless no-newlines "\n")))
2314 (goto-char beg)
2315 (insert (concat start (unless no-newlines "\n")))
2316 (unless no-escape
2317 (org-escape-code-in-region
2318 (min (point) before-finish) before-finish))
2319 (goto-char end))))
2320 (tabulablep
2321 (lambda (r)
2322 ;; Non-nil when result R can be turned into
2323 ;; a table.
2324 (and (listp r)
2325 (null (cdr (last r)))
2326 (cl-every
2327 (lambda (e) (or (atom e) (null (cdr (last e)))))
2328 result)))))
2329 ;; insert results based on type
2330 (cond
2331 ;; Do nothing for an empty result.
2332 ((null result))
2333 ;; Insert a list if preferred.
2334 ((member "list" result-params)
2335 (insert
2336 (org-trim
2337 (org-list-to-generic
2338 (cons 'unordered
2339 (mapcar
2340 (lambda (e)
2341 (list (if (stringp e) e (format "%S" e))))
2342 (if (listp result) result
2343 (split-string result "\n" t))))
2344 '(:splicep nil :istart "- " :iend "\n")))
2345 "\n"))
2346 ;; Try hard to print RESULT as a table. Give up if
2347 ;; it contains an improper list.
2348 ((funcall tabulablep result)
2349 (goto-char beg)
2350 (insert (concat (orgtbl-to-orgtbl
2351 (if (cl-every
2352 (lambda (e)
2353 (or (eq e 'hline) (listp e)))
2354 result)
2355 result
2356 (list result))
2357 nil)
2358 "\n"))
2359 (goto-char beg)
2360 (when (org-at-table-p) (org-table-align))
2361 (goto-char (org-table-end)))
2362 ;; Print verbatim a list that cannot be turned into
2363 ;; a table.
2364 ((listp result) (insert (format "%s\n" result)))
2365 ((member "file" result-params)
2366 (when inline
2367 (setq result (org-macro-escape-arguments result)))
2368 (insert result))
2369 ((and inline (not (member "raw" result-params)))
2370 (insert (org-macro-escape-arguments
2371 (org-babel-chomp result "\n"))))
2372 (t (goto-char beg) (insert result)))
2373 (setq end (copy-marker (point) t))
2374 ;; possibly wrap result
2375 (cond
2376 ((assq :wrap (nth 2 info))
2377 (let ((name (or (cdr (assq :wrap (nth 2 info))) "results")))
2378 (funcall wrap (concat "#+begin_" name)
2379 (concat "#+end_" (car (split-string name)))
2380 nil nil (concat "{{{results(@@" name ":") "@@)}}}")))
2381 ((member "html" result-params)
2382 (funcall wrap "#+begin_export html" "#+end_export" nil nil
2383 "{{{results(@@html:" "@@)}}}"))
2384 ((member "latex" result-params)
2385 (funcall wrap "#+begin_export latex" "#+end_export" nil nil
2386 "{{{results(@@latex:" "@@)}}}"))
2387 ((member "org" result-params)
2388 (goto-char beg) (when (org-at-table-p) (org-cycle))
2389 (funcall wrap "#+begin_src org" "#+end_src" nil nil
2390 "{{{results(src_org{" "})}}}"))
2391 ((member "code" result-params)
2392 (let ((lang (or lang "none")))
2393 (funcall wrap (format "#+begin_src %s%s" lang results-switches)
2394 "#+end_src" nil nil
2395 (format "{{{results(src_%s[%s]{" lang results-switches)
2396 "})}}}")))
2397 ((member "raw" result-params)
2398 (goto-char beg) (when (org-at-table-p) (org-cycle)))
2399 ((or (member "drawer" result-params)
2400 ;; Stay backward compatible with <7.9.2
2401 (member "wrap" result-params))
2402 (goto-char beg) (when (org-at-table-p) (org-cycle))
2403 (funcall wrap ":results:" ":end:" 'no-escape nil
2404 "{{{results(" ")}}}"))
2405 ((and inline (member "file" result-params))
2406 (funcall wrap nil nil nil nil "{{{results(" ")}}}"))
2407 ((and (not (funcall tabulablep result))
2408 (not (member "file" result-params)))
2409 (let ((org-babel-inline-result-wrap
2410 ;; Hard code {{{results(...)}}} on top of
2411 ;; customization.
2412 (format "{{{results(%s)}}}"
2413 org-babel-inline-result-wrap)))
2414 (org-babel-examplify-region
2415 beg end results-switches inline)))))
2416 ;; Possibly indent results in par with #+results line.
2417 (when (and (not inline) (numberp indent) (> indent 0)
2418 ;; In this case `table-align' does the work
2419 ;; for us.
2420 (not (and (listp result)
2421 (member "append" result-params))))
2422 (indent-rigidly beg end indent))
2423 (if (null result)
2424 (if (member "value" result-params)
2425 (message "Code block returned no value.")
2426 (message "Code block produced no output."))
2427 (message "Code block evaluation complete.")))
2428 (set-marker end nil)
2429 (when outside-scope (narrow-to-region visible-beg visible-end))
2430 (set-marker visible-beg nil)
2431 (set-marker visible-end nil)))))))
2433 (defun org-babel-remove-result (&optional info keep-keyword)
2434 "Remove the result of the current source block."
2435 (interactive)
2436 (let ((location (org-babel-where-is-src-block-result nil info)))
2437 (when location
2438 (save-excursion
2439 (goto-char location)
2440 (when (looking-at (concat org-babel-result-regexp ".*$"))
2441 (delete-region
2442 (if keep-keyword (line-beginning-position 2)
2443 (save-excursion
2444 (skip-chars-backward " \r\t\n")
2445 (line-beginning-position 2)))
2446 (progn (forward-line) (org-babel-result-end))))))))
2448 (defun org-babel-remove-inline-result (&optional datum)
2449 "Remove the result of the current inline-src-block or babel call.
2450 The result must be wrapped in a `results' macro to be removed.
2451 Leading white space is trimmed."
2452 (interactive)
2453 (let* ((el (or datum (org-element-context))))
2454 (when (memq (org-element-type el) '(inline-src-block inline-babel-call))
2455 (org-with-wide-buffer
2456 (goto-char (org-element-property :end el))
2457 (skip-chars-backward " \t")
2458 (let ((result (save-excursion
2459 (skip-chars-forward
2460 " \t\n"
2461 (org-element-property
2462 :contents-end (org-element-property :parent el)))
2463 (org-element-context))))
2464 (when (and (eq (org-element-type result) 'macro)
2465 (string= (org-element-property :key result) "results"))
2466 (delete-region ; And leading whitespace.
2467 (point)
2468 (progn (goto-char (org-element-property :end result))
2469 (skip-chars-backward " \t\n")
2470 (point)))))))))
2472 (defun org-babel-remove-result-one-or-many (x)
2473 "Remove the result of the current source block.
2474 If called with a prefix argument, remove all result blocks
2475 in the buffer."
2476 (interactive "P")
2477 (if x
2478 (org-babel-map-src-blocks nil (org-babel-remove-result))
2479 (org-babel-remove-result)))
2481 (defun org-babel-result-end ()
2482 "Return the point at the end of the current set of results."
2483 (cond ((looking-at-p "^[ \t]*$") (point)) ;no result
2484 ((looking-at-p (format "^[ \t]*%s[ \t]*$" org-bracket-link-regexp))
2485 (line-beginning-position 2))
2487 (let ((element (org-element-at-point)))
2488 (if (memq (org-element-type element)
2489 ;; Possible results types.
2490 '(drawer example-block export-block fixed-width item
2491 plain-list src-block table))
2492 (save-excursion
2493 (goto-char (min (point-max) ;for narrowed buffers
2494 (org-element-property :end element)))
2495 (skip-chars-backward " \r\t\n")
2496 (line-beginning-position 2))
2497 (point))))))
2499 (defun org-babel-result-to-file (result &optional description)
2500 "Convert RESULT into an Org link with optional DESCRIPTION.
2501 If the `default-directory' is different from the containing
2502 file's directory then expand relative links."
2503 (when (stringp result)
2504 (let ((same-directory?
2505 (and buffer-file-name
2506 (not (string= (expand-file-name default-directory)
2507 (expand-file-name
2508 (file-name-directory buffer-file-name)))))))
2509 (format "[[file:%s]%s]"
2510 (if (and default-directory buffer-file-name same-directory?)
2511 (if (eq org-link-file-path-type 'adaptive)
2512 (file-relative-name
2513 (expand-file-name result default-directory)
2514 (file-name-directory (buffer-file-name)))
2515 (expand-file-name result default-directory))
2516 result)
2517 (if description (concat "[" description "]") "")))))
2519 (defun org-babel-examplify-region (beg end &optional results-switches inline)
2520 "Comment out region using the inline `==' or `: ' org example quote."
2521 (interactive "*r")
2522 (let ((maybe-cap
2523 (lambda (str)
2524 (if org-babel-uppercase-example-markers (upcase str) str))))
2525 (if inline
2526 (save-excursion
2527 (goto-char beg)
2528 (insert (format org-babel-inline-result-wrap
2529 (delete-and-extract-region beg end))))
2530 (let ((size (count-lines beg end)))
2531 (save-excursion
2532 (cond ((= size 0)) ; do nothing for an empty result
2533 ((< size org-babel-min-lines-for-block-output)
2534 (goto-char beg)
2535 (dotimes (_ size)
2536 (beginning-of-line 1) (insert ": ") (forward-line 1)))
2538 (goto-char beg)
2539 (insert (if results-switches
2540 (format "%s%s\n"
2541 (funcall maybe-cap "#+begin_example")
2542 results-switches)
2543 (funcall maybe-cap "#+begin_example\n")))
2544 (let ((p (point)))
2545 (if (markerp end) (goto-char end) (forward-char (- end beg)))
2546 (org-escape-code-in-region p (point)))
2547 (insert (funcall maybe-cap "#+end_example\n")))))))))
2549 (defun org-babel-update-block-body (new-body)
2550 "Update the body of the current code block to NEW-BODY."
2551 (let ((element (org-element-at-point)))
2552 (unless (eq (org-element-type element) 'src-block)
2553 (error "Not in a source block"))
2554 (goto-char (org-babel-where-is-src-block-head element))
2555 (let* ((ind (org-get-indentation))
2556 (body-start (line-beginning-position 2))
2557 (body (org-element-normalize-string
2558 (if (or org-src-preserve-indentation
2559 (org-element-property :preserve-indent element))
2560 new-body
2561 (with-temp-buffer
2562 (insert (org-remove-indentation new-body))
2563 (indent-rigidly
2564 (point-min)
2565 (point-max)
2566 (+ ind org-edit-src-content-indentation))
2567 (buffer-string))))))
2568 (delete-region body-start
2569 (org-with-wide-buffer
2570 (goto-char (org-element-property :end element))
2571 (skip-chars-backward " \t\n")
2572 (line-beginning-position)))
2573 (goto-char body-start)
2574 (insert body))))
2576 (defun org-babel-merge-params (&rest plists)
2577 "Combine all parameter association lists in PLISTS.
2578 Later elements of PLISTS override the values of previous elements.
2579 This takes into account some special considerations for certain
2580 parameters when merging lists."
2581 (let* ((results-exclusive-groups
2582 (mapcar (lambda (group) (mapcar #'symbol-name group))
2583 (cdr (assq 'results org-babel-common-header-args-w-values))))
2584 (exports-exclusive-groups
2585 (mapcar (lambda (group) (mapcar #'symbol-name group))
2586 (cdr (assq 'exports org-babel-common-header-args-w-values))))
2587 (merge
2588 (lambda (exclusive-groups &rest result-params)
2589 ;; Maintain exclusivity of mutually exclusive parameters,
2590 ;; as defined in EXCLUSIVE-GROUPS while merging lists in
2591 ;; RESULT-PARAMS.
2592 (let (output)
2593 (dolist (new-params result-params (delete-dups output))
2594 (dolist (new-param new-params)
2595 (dolist (exclusive-group exclusive-groups)
2596 (when (member new-param exclusive-group)
2597 (setq output (cl-remove-if
2598 (lambda (o) (member o exclusive-group))
2599 output))))
2600 (push new-param output))))))
2601 (variable-index 0) ;Handle positional arguments.
2602 clearnames
2603 params ;Final parameters list.
2604 ;; Some keywords accept multiple values. We need to treat
2605 ;; them specially.
2606 vars results exports)
2607 (dolist (plist plists)
2608 (dolist (pair plist)
2609 (pcase pair
2610 (`(:var . ,value)
2611 (let ((name (cond
2612 ((listp value) (car value))
2613 ((string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*=" value)
2614 (intern (match-string 1 value)))
2615 (t nil))))
2616 (cond
2617 (name
2618 (setq vars
2619 (append (if (not (assoc name vars)) vars
2620 (push name clearnames)
2621 (cl-remove-if (lambda (p) (equal name (car p)))
2622 vars))
2623 (list (cons name pair)))))
2624 ((and vars (nth variable-index vars))
2625 ;; If no name is given and we already have named
2626 ;; variables then assign to named variables in order.
2627 (let ((name (car (nth variable-index vars))))
2628 ;; Clear out colnames and rownames for replace vars.
2629 (push name clearnames)
2630 (setf (cddr (nth variable-index vars))
2631 (concat (symbol-name name) "=" value))
2632 (cl-incf variable-index)))
2633 (t (error "Variable \"%s\" must be assigned a default value"
2634 (cdr pair))))))
2635 (`(:results . ,value)
2636 (setq results (funcall merge
2637 results-exclusive-groups
2638 results
2639 (split-string
2640 (if (stringp value) value (eval value t))))))
2641 (`(,(or :file :file-ext) . ,value)
2642 ;; `:file' and `:file-ext' are regular keywords but they
2643 ;; imply a "file" `:results' and a "results" `:exports'.
2644 (when value
2645 (setq results
2646 (funcall merge results-exclusive-groups results '("file")))
2647 (unless (or (member "both" exports)
2648 (member "none" exports)
2649 (member "code" exports))
2650 (setq exports
2651 (funcall merge
2652 exports-exclusive-groups exports '("results"))))
2653 (push pair params)))
2654 (`(:exports . ,value)
2655 (setq exports (funcall merge
2656 exports-exclusive-groups
2657 exports
2658 (split-string (or value "")))))
2659 ;; Regular keywords: any value overwrites the previous one.
2660 (_ (setq params (cons pair (assq-delete-all (car pair) params)))))))
2661 ;; Handle `:var' and clear out colnames and rownames for replaced
2662 ;; variables.
2663 (setq params (nconc (mapcar (lambda (v) (cons :var (cddr v))) vars)
2664 params))
2665 (dolist (name clearnames)
2666 (dolist (param '(:colname-names :rowname-names))
2667 (when (assq param params)
2668 (setf (cdr (assq param params))
2669 (cl-remove-if (lambda (pair) (equal name (car pair)))
2670 (cdr (assq param params))))
2671 (setq params
2672 (cl-remove-if (lambda (pair) (and (equal (car pair) param)
2673 (null (cdr pair))))
2674 params)))))
2675 ;; Handle other special keywords, which accept multiple values.
2676 (setq params (nconc (list (cons :results (mapconcat #'identity results " "))
2677 (cons :exports (mapconcat #'identity exports " ")))
2678 params))
2679 ;; Return merged params.
2680 params))
2682 (defun org-babel-noweb-p (params context)
2683 "Check if PARAMS require expansion in CONTEXT.
2684 CONTEXT may be one of :tangle, :export or :eval."
2685 (let ((allowed-values (cl-case context
2686 (:tangle '("yes" "tangle" "no-export" "strip-export"))
2687 (:eval '("yes" "no-export" "strip-export" "eval"))
2688 (:export '("yes")))))
2689 (cl-some (lambda (v) (member v allowed-values))
2690 (split-string (or (cdr (assq :noweb params)) "")))))
2692 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
2693 "Expand Noweb references in the body of the current source code block.
2695 For example the following reference would be replaced with the
2696 body of the source-code block named `example-block'.
2698 <<example-block>>
2700 Note that any text preceding the <<foo>> construct on a line will
2701 be interposed between the lines of the replacement text. So for
2702 example if <<foo>> is placed behind a comment, then the entire
2703 replacement text will also be commented.
2705 This function must be called from inside of the buffer containing
2706 the source-code block which holds BODY.
2708 In addition the following syntax can be used to insert the
2709 results of evaluating the source-code block named `example-block'.
2711 <<example-block()>>
2713 Any optional arguments can be passed to example-block by placing
2714 the arguments inside the parenthesis following the convention
2715 defined by `org-babel-lob'. For example
2717 <<example-block(a=9)>>
2719 would set the value of argument \"a\" equal to \"9\". Note that
2720 these arguments are not evaluated in the current source-code
2721 block but are passed literally to the \"example-block\"."
2722 (let* ((parent-buffer (or parent-buffer (current-buffer)))
2723 (info (or info (org-babel-get-src-block-info 'light)))
2724 (lang (nth 0 info))
2725 (body (nth 1 info))
2726 (ob-nww-start org-babel-noweb-wrap-start)
2727 (ob-nww-end org-babel-noweb-wrap-end)
2728 (new-body "")
2729 (nb-add (lambda (text) (setq new-body (concat new-body text))))
2730 index source-name evaluate prefix)
2731 (with-temp-buffer
2732 (setq-local org-babel-noweb-wrap-start ob-nww-start)
2733 (setq-local org-babel-noweb-wrap-end ob-nww-end)
2734 (insert body) (goto-char (point-min))
2735 (setq index (point))
2736 (while (and (re-search-forward (org-babel-noweb-wrap) nil t))
2737 (save-match-data (setf source-name (match-string 1)))
2738 (save-match-data (setq evaluate (string-match "(.*)" source-name)))
2739 (save-match-data
2740 (setq prefix
2741 (buffer-substring (match-beginning 0)
2742 (save-excursion
2743 (beginning-of-line 1) (point)))))
2744 ;; add interval to new-body (removing noweb reference)
2745 (goto-char (match-beginning 0))
2746 (funcall nb-add (buffer-substring index (point)))
2747 (goto-char (match-end 0))
2748 (setq index (point))
2749 (funcall
2750 nb-add
2751 (with-current-buffer parent-buffer
2752 (save-restriction
2753 (widen)
2754 (mapconcat ;; Interpose PREFIX between every line.
2755 #'identity
2756 (split-string
2757 (if evaluate
2758 (let ((raw (org-babel-ref-resolve source-name)))
2759 (if (stringp raw) raw (format "%S" raw)))
2761 ;; Retrieve from the Library of Babel.
2762 (nth 2 (assoc-string source-name org-babel-library-of-babel))
2763 ;; Return the contents of headlines literally.
2764 (save-excursion
2765 (when (org-babel-ref-goto-headline-id source-name)
2766 (org-babel-ref-headline-body)))
2767 ;; Find the expansion of reference in this buffer.
2768 (save-excursion
2769 (goto-char (point-min))
2770 (let* ((name-regexp
2771 (org-babel-named-src-block-regexp-for-name
2772 source-name))
2773 (comment
2774 (string= "noweb"
2775 (cdr (assq :comments (nth 2 info)))))
2776 (c-wrap
2777 (lambda (s)
2778 ;; Comment, according to LANG mode,
2779 ;; string S. Return new string.
2780 (with-temp-buffer
2781 (funcall (intern (concat lang "-mode")))
2782 (comment-region (point)
2783 (progn (insert s) (point)))
2784 (org-trim (buffer-string)))))
2785 (expand-body
2786 (lambda (i)
2787 ;; Expand body of code blocked
2788 ;; represented by block info I.
2789 (let ((b (if (org-babel-noweb-p (nth 2 i) :eval)
2790 (org-babel-expand-noweb-references i)
2791 (nth 1 i))))
2792 (if (not comment) b
2793 (let ((cs (org-babel-tangle-comment-links i)))
2794 (concat (funcall c-wrap (car cs)) "\n"
2795 b "\n"
2796 (funcall c-wrap (cadr cs)))))))))
2797 (if (re-search-forward name-regexp nil t)
2798 ;; Found a source block named SOURCE-NAME.
2799 ;; Assume it is unique; do not look after
2800 ;; `:noweb-ref' header argument.
2801 (funcall expand-body
2802 (org-babel-get-src-block-info 'light))
2803 ;; Though luck. We go into the long process
2804 ;; of checking each source block and expand
2805 ;; those with a matching Noweb reference.
2806 (let ((expansion nil))
2807 (org-babel-map-src-blocks nil
2808 (let* ((info (org-babel-get-src-block-info 'light))
2809 (parameters (nth 2 info)))
2810 (when (equal source-name
2811 (cdr (assq :noweb-ref parameters)))
2812 (push (funcall expand-body info) expansion)
2813 (push (or (cdr (assq :noweb-sep parameters))
2814 "\n")
2815 expansion))))
2816 (when expansion
2817 (mapconcat #'identity
2818 (nreverse (cdr expansion))
2819 ""))))))
2820 ;; Possibly raise an error if named block doesn't exist.
2821 (if (or org-babel-noweb-error-all-langs
2822 (member lang org-babel-noweb-error-langs))
2823 (error "%s could not be resolved (see \
2824 `org-babel-noweb-error-langs')"
2825 (org-babel-noweb-wrap source-name))
2826 "")))
2827 "[\n\r]")
2828 (concat "\n" prefix))))))
2829 (funcall nb-add (buffer-substring index (point-max))))
2830 new-body))
2832 (defun org-babel--script-escape-inner (str)
2833 (let (in-single in-double backslash out)
2834 (mapc
2835 (lambda (ch)
2836 (setq
2838 (if backslash
2839 (progn
2840 (setq backslash nil)
2841 (cond
2842 ((and in-single (eq ch ?'))
2843 ;; Escaped single quote inside single quoted string:
2844 ;; emit just a single quote, since we've changed the
2845 ;; outer quotes to double.
2846 (cons ch out))
2847 ((eq ch ?\")
2848 ;; Escaped double quote
2849 (if in-single
2850 ;; This should be interpreted as backslash+quote,
2851 ;; not an escape. Emit a three backslashes
2852 ;; followed by a quote (because one layer of
2853 ;; quoting will be stripped by `org-babel-read').
2854 (append (list ch ?\\ ?\\ ?\\) out)
2855 ;; Otherwise we are in a double-quoted string. Emit
2856 ;; a single escaped quote
2857 (append (list ch ?\\) out)))
2858 ((eq ch ?\\)
2859 ;; Escaped backslash: emit a single escaped backslash
2860 (append (list ?\\ ?\\) out))
2861 ;; Other: emit a quoted backslash followed by whatever
2862 ;; the character was (because one layer of quoting will
2863 ;; be stripped by `org-babel-read').
2864 (t (append (list ch ?\\ ?\\) out))))
2865 (cl-case ch
2866 (?\[ (if (or in-double in-single)
2867 (cons ?\[ out)
2868 (cons ?\( out)))
2869 (?\] (if (or in-double in-single)
2870 (cons ?\] out)
2871 (cons ?\) out)))
2872 (?\{ (if (or in-double in-single)
2873 (cons ?\{ out)
2874 (cons ?\( out)))
2875 (?\} (if (or in-double in-single)
2876 (cons ?\} out)
2877 (cons ?\) out)))
2878 (?, (if (or in-double in-single)
2879 (cons ?, out) (cons ?\s out)))
2880 (?\' (if in-double
2881 (cons ?\' out)
2882 (setq in-single (not in-single)) (cons ?\" out)))
2883 (?\" (if in-single
2884 (append (list ?\" ?\\) out)
2885 (setq in-double (not in-double)) (cons ?\" out)))
2886 (?\\ (unless (or in-single in-double)
2887 (error "Can't handle backslash outside string in `org-babel-script-escape'"))
2888 (setq backslash t)
2889 out)
2890 (t (cons ch out))))))
2891 (string-to-list str))
2892 (when (or in-single in-double)
2893 (error "Unterminated string in `org-babel-script-escape'"))
2894 (apply #'string (reverse out))))
2896 (defun org-babel-script-escape (str &optional force)
2897 "Safely convert tables into elisp lists."
2898 (unless (stringp str)
2899 (error "`org-babel-script-escape' expects a string"))
2900 (let ((escaped
2901 (cond
2902 ((and (> (length str) 2)
2903 (or (and (string-equal "[" (substring str 0 1))
2904 (string-equal "]" (substring str -1)))
2905 (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)))))
2910 (concat "'" (org-babel--script-escape-inner str)))
2911 ((or force
2912 (and (> (length str) 2)
2913 (or (and (string-equal "'" (substring str 0 1))
2914 (string-equal "'" (substring str -1)))
2915 ;; We need to pass double-quoted strings
2916 ;; through the backslash-twiddling bits, even
2917 ;; though we don't need to change their
2918 ;; delimiters.
2919 (and (string-equal "\"" (substring str 0 1))
2920 (string-equal "\"" (substring str -1))))))
2921 (org-babel--script-escape-inner str))
2922 (t str))))
2923 (condition-case nil (org-babel-read escaped) (error escaped))))
2925 (defun org-babel-read (cell &optional inhibit-lisp-eval)
2926 "Convert the string value of CELL to a number if appropriate.
2927 Otherwise if CELL looks like lisp (meaning it starts with a
2928 \"(\", \"\\='\", \"\\=`\" or a \"[\") then read and evaluate it as
2929 lisp, otherwise return it unmodified as a string. Optional
2930 argument INHIBIT-LISP-EVAL inhibits lisp evaluation for
2931 situations in which is it not appropriate."
2932 (cond ((not (org-string-nw-p cell)) cell)
2933 ((org-babel--string-to-number cell))
2934 ((and (not inhibit-lisp-eval)
2935 (or (memq (string-to-char cell) '(?\( ?' ?` ?\[))
2936 (string= cell "*this*")))
2937 (eval (read cell) t))
2938 ((eq (string-to-char cell) ?\") (read cell))
2939 (t (org-no-properties cell))))
2941 (defun org-babel--string-to-number (string)
2942 "If STRING represents a number return its value.
2943 Otherwise return nil."
2944 (and (string-match-p "\\`-?[0-9]*\\.?[0-9]*\\'" string)
2945 (string-to-number string)))
2947 (defun org-babel-import-elisp-from-file (file-name &optional separator)
2948 "Read the results located at FILE-NAME into an elisp table.
2949 If the table is trivial, then return it as a scalar."
2950 (let (result)
2951 (save-window-excursion
2952 (with-temp-buffer
2953 (condition-case err
2954 (progn
2955 (org-table-import file-name separator)
2956 (delete-file file-name)
2957 (setq result (mapcar (lambda (row)
2958 (mapcar #'org-babel-string-read row))
2959 (org-table-to-lisp))))
2960 (error (message "Error reading results: %s" err) nil)))
2961 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
2962 (if (consp (car result))
2963 (if (null (cdr (car result)))
2964 (caar result)
2965 result)
2966 (car result))
2967 result))))
2969 (defun org-babel-string-read (cell)
2970 "Strip nested \"s from around strings."
2971 (org-babel-read (or (and (stringp cell)
2972 (string-match "\\\"\\(.+\\)\\\"" cell)
2973 (match-string 1 cell))
2974 cell) t))
2976 (defun org-babel-chomp (string &optional regexp)
2977 "Strip a trailing space or carriage return from STRING.
2978 The default regexp used is \"[ \\f\\t\\n\\r\\v]\" but another one
2979 can be specified as the REGEXP argument."
2980 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
2981 (while (and (> (length string) 0)
2982 (string-match regexp (substring string -1)))
2983 (setq string (substring string 0 -1)))
2984 string))
2986 (defun org-babel-process-file-name (name &optional no-quote-p)
2987 "Prepare NAME to be used in an external process.
2988 If NAME specifies a remote location, the remote portion of the
2989 name is removed, since in that case the process will be executing
2990 remotely. The file name is then processed by `expand-file-name'.
2991 Unless second argument NO-QUOTE-P is non-nil, the file name is
2992 additionally processed by `shell-quote-argument'"
2993 (let ((f (org-babel-local-file-name (expand-file-name name))))
2994 (if no-quote-p f (shell-quote-argument f))))
2996 (defvar org-babel-temporary-directory)
2997 (unless (or noninteractive (boundp 'org-babel-temporary-directory))
2998 (defvar org-babel-temporary-directory
2999 (or (and (boundp 'org-babel-temporary-directory)
3000 (file-exists-p org-babel-temporary-directory)
3001 org-babel-temporary-directory)
3002 (make-temp-file "babel-" t))
3003 "Directory to hold temporary files created to execute code blocks.
3004 Used by `org-babel-temp-file'. This directory will be removed on
3005 Emacs shutdown."))
3007 (defcustom org-babel-remote-temporary-directory "/tmp/"
3008 "Directory to hold temporary files on remote hosts."
3009 :group 'org-babel
3010 :type 'string)
3012 (defmacro org-babel-result-cond (result-params scalar-form &rest table-forms)
3013 "Call the code to parse raw string results according to RESULT-PARAMS."
3014 (declare (indent 1)
3015 (debug (form form &rest form)))
3016 (org-with-gensyms (params)
3017 `(let ((,params ,result-params))
3018 (unless (member "none" ,params)
3019 (if (or (member "scalar" ,params)
3020 (member "verbatim" ,params)
3021 (member "html" ,params)
3022 (member "code" ,params)
3023 (member "pp" ,params)
3024 (member "file" ,params)
3025 (and (or (member "output" ,params)
3026 (member "raw" ,params)
3027 (member "org" ,params)
3028 (member "drawer" ,params))
3029 (not (member "table" ,params))))
3030 ,scalar-form
3031 ,@table-forms)))))
3032 (def-edebug-spec org-babel-result-cond (form form body))
3034 (defun org-babel-temp-file (prefix &optional suffix)
3035 "Create a temporary file in the `org-babel-temporary-directory'.
3036 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
3037 value of `temporary-file-directory' temporarily set to the value
3038 of `org-babel-temporary-directory'."
3039 (if (file-remote-p default-directory)
3040 (let ((prefix
3041 (concat (file-remote-p default-directory)
3042 (expand-file-name
3043 prefix org-babel-remote-temporary-directory))))
3044 (make-temp-file prefix nil suffix))
3045 (let ((temporary-file-directory
3046 (or (and (boundp 'org-babel-temporary-directory)
3047 (file-exists-p org-babel-temporary-directory)
3048 org-babel-temporary-directory)
3049 temporary-file-directory)))
3050 (make-temp-file prefix nil suffix))))
3052 (defun org-babel-remove-temporary-directory ()
3053 "Remove `org-babel-temporary-directory' on Emacs shutdown."
3054 (when (and (boundp 'org-babel-temporary-directory)
3055 (file-exists-p org-babel-temporary-directory))
3056 ;; taken from `delete-directory' in files.el
3057 (condition-case nil
3058 (progn
3059 (mapc (lambda (file)
3060 ;; This test is equivalent to
3061 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
3062 ;; but more efficient
3063 (if (eq t (car (file-attributes file)))
3064 (delete-directory file)
3065 (delete-file file)))
3066 ;; We do not want to delete "." and "..".
3067 (directory-files org-babel-temporary-directory 'full
3068 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
3069 (delete-directory org-babel-temporary-directory))
3070 (error
3071 (message "Failed to remove temporary Org-babel directory %s"
3072 (if (boundp 'org-babel-temporary-directory)
3073 org-babel-temporary-directory
3074 "[directory not defined]"))))))
3076 (add-hook 'kill-emacs-hook 'org-babel-remove-temporary-directory)
3078 (defun org-babel-one-header-arg-safe-p (pair safe-list)
3079 "Determine if the PAIR is a safe babel header arg according to SAFE-LIST.
3081 For the format of SAFE-LIST, see `org-babel-safe-header-args'."
3082 (and (consp pair)
3083 (keywordp (car pair))
3084 (stringp (cdr pair))
3086 (memq (car pair) safe-list)
3087 (let ((entry (assq (car pair) safe-list)))
3088 (and entry
3089 (consp entry)
3090 (cond ((functionp (cdr entry))
3091 (funcall (cdr entry) (cdr pair)))
3092 ((listp (cdr entry))
3093 (member (cdr pair) (cdr entry)))
3094 (t nil)))))))
3096 (defun org-babel-generate-file-param (src-name params)
3097 "Calculate the filename for source block results.
3099 The directory is calculated from the :output-dir property of the
3100 source block; if not specified, use the current directory.
3102 If the source block has a #+NAME and the :file parameter does not
3103 contain any period characters, then the :file parameter is
3104 treated as an extension, and the output file name is the
3105 concatenation of the directory (as calculated above), the block
3106 name, a period, and the parameter value as a file extension.
3107 Otherwise, the :file parameter is treated as a full file name,
3108 and the output file name is the directory (as calculated above)
3109 plus the parameter value."
3110 (let* ((file-cons (assq :file params))
3111 (file-ext-cons (assq :file-ext params))
3112 (file-ext (cdr-safe file-ext-cons))
3113 (dir (cdr-safe (assq :output-dir params)))
3114 fname)
3115 ;; create the output-dir if it does not exist
3116 (when dir
3117 (make-directory dir t))
3118 (if file-cons
3119 ;; :file given; add :output-dir if given
3120 (when dir
3121 (setcdr file-cons (concat (file-name-as-directory dir) (cdr file-cons))))
3122 ;; :file not given; compute from name and :file-ext if possible
3123 (when (and src-name file-ext)
3124 (if dir
3125 (setq fname (concat (file-name-as-directory (or dir ""))
3126 src-name "." file-ext))
3127 (setq fname (concat src-name "." file-ext)))
3128 (setq params (cons (cons :file fname) params))))
3129 params))
3131 (defun org-babel-graphical-output-file (params)
3132 "File where a babel block should send graphical output, per PARAMS.
3133 Return nil if no graphical output is expected. Raise an error if
3134 the output file is ill-defined."
3135 (let ((file (cdr (assq :file params))))
3136 (cond (file (and (member "graphics" (cdr (assq :result-params params)))
3137 file))
3138 ((assq :file-ext params)
3139 (user-error ":file-ext given but no :file generated; did you forget \
3140 to name a block?"))
3141 (t (user-error "No :file header argument given; cannot create \
3142 graphical result")))))
3144 (defun org-babel-make-language-alias (new old)
3145 "Make source blocks of type NEW aliases for those of type OLD.
3147 NEW and OLD should be strings. This function should be called
3148 after the babel API for OLD-type source blocks is fully defined.
3150 Callers of this function will probably want to add an entry to
3151 `org-src-lang-modes' as well."
3152 (dolist (fn '("execute" "expand-body" "prep-session"
3153 "variable-assignments" "load-session"))
3154 (let ((sym (intern-soft (concat "org-babel-" fn ":" old))))
3155 (when (and sym (fboundp sym))
3156 (defalias (intern (concat "org-babel-" fn ":" new)) sym))))
3157 ;; Technically we don't need a `dolist' for just one variable, but
3158 ;; we keep it for symmetry/ease of future expansion.
3159 (dolist (var '("default-header-args"))
3160 (let ((sym (intern-soft (concat "org-babel-" var ":" old))))
3161 (when (and sym (boundp sym))
3162 (defvaralias (intern (concat "org-babel-" var ":" new)) sym)))))
3164 (defun org-babel-strip-quotes (string)
3165 "Strip \\\"s from around a string, if applicable."
3166 (org-unbracket-string "\"" "\"" string))
3168 (provide 'ob-core)
3170 ;; Local variables:
3171 ;; generated-autoload-file: "org-loaddefs.el"
3172 ;; End:
3174 ;;; ob-core.el ends here