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