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