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