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