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