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