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