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