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