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