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