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