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