adding defgroup for org-babel
[org-mode.git] / lisp / ob.el
blob160cdf9b7d8aa280616d818905a33835fe7dc3c3
1 ;;; ob.el --- working with code blocks in org-mode
3 ;; Copyright (C) 2009, 2010 Free Software Foundation, Inc.
5 ;; Author: Eric Schulte, Dan Davison
6 ;; Keywords: literate programming, reproducible research
7 ;; Homepage: http://orgmode.org
8 ;; Version: 0.01
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 ;;; Commentary:
27 ;; See the online documentation for more information
28 ;;
29 ;; http://orgmode.org/worg/org-contrib/babel/
31 ;;; Code:
32 (eval-when-compile (require 'cl))
33 (require 'org-macs)
35 (defvar org-babel-call-process-region-original)
36 (declare-function show-all "outline" ())
37 (declare-function tramp-compat-make-temp-file "tramp" (filename &optional dir-flag))
38 (declare-function tramp-dissect-file-name "tramp" (name &optional nodefault))
39 (declare-function tramp-file-name-user "tramp" (vec))
40 (declare-function tramp-file-name-host "tramp" (vec))
41 (declare-function org-edit-src-code "org" (context code edit-buffer-name))
42 (declare-function org-open-at-point "org" (&optional in-emacs reference-buffer))
43 (declare-function org-save-outline-visibility "org" (use-markers &rest body))
44 (declare-function org-narrow-to-subtree "org" ())
45 (declare-function org-entry-get "org" (pom property &optional inherit))
46 (declare-function org-make-options-regexp "org" (kwds &optional extra))
47 (declare-function org-match-string-no-properties "org" (num &optional string))
48 (declare-function org-do-remove-indentation "org" (&optional n))
49 (declare-function org-show-context "org" (&optional key))
50 (declare-function org-at-table-p "org" (&optional table-type))
51 (declare-function org-cycle "org" (&optional arg))
52 (declare-function org-uniquify "org" (list))
53 (declare-function org-table-import "org" (file arg))
54 (declare-function org-add-hook "org-compat" (hook function &optional append local))
55 (declare-function org-table-align "org-table" ())
56 (declare-function org-table-end "org-table" (&optional table-type))
57 (declare-function orgtbl-to-generic "org-table" (table params))
58 (declare-function orgtbl-to-orgtbl "org-table" (table params))
59 (declare-function org-babel-lob-get-info "ob-lob" nil)
60 (declare-function org-babel-ref-split-args "ob-ref" (arg-string))
61 (declare-function org-babel-ref-variables "ob-ref" (params))
62 (declare-function org-babel-ref-resolve-reference "ob-ref" (ref &optional params))
64 (defgroup org-babel nil
65 "Code block evaluation and management in `org-mode' documents."
66 :tag "Babel"
67 :group 'org)
69 (defcustom org-confirm-babel-evaluate t
70 "Require confirmation before interactively evaluating code
71 blocks in Org-mode buffers. The default value of this variable
72 is t, meaning confirmation is required for any code block
73 evaluation. This variable can be set to nil to inhibit any
74 future confirmation requests. This variable can also be set to a
75 function which takes two arguments the language of the code block
76 and the body of the code block. Such a function should then
77 return a non-nil value if the user should be prompted for
78 execution or nil if no prompt is required.
80 Warning: Disabling confirmation may result in accidental
81 evaluation of potentially harmful code. It may be advisable
82 remove code block execution from C-c C-c as further protection
83 against accidental code block evaluation. The
84 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
85 remove code block execution from the C-c C-c keybinding."
86 :group 'org-babel
87 :type '(choice boolean function))
88 ;; don't allow this variable to be changed through file settings
89 (put 'org-confirm-babel-evaluate 'safe-local-variable (lambda (x) (eq x t)))
91 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
92 "This variable can be set to remove code block evaluation from
93 the C-c C-c key binding."
94 :group 'org-babel
95 :type 'boolean)
97 (defvar org-babel-source-name-regexp
98 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
99 "Regular expression used to match a source name line.")
101 (defvar org-babel-src-block-regexp
102 (concat
103 ;; (1) indentation (2) lang
104 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
105 ;; (3) switches
106 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
107 ;; (4) header arguments
108 "\\([^\n]*\\)\n"
109 ;; (5) body
110 "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
111 "Regexp used to identify code blocks.")
113 (defvar org-babel-inline-src-block-regexp
114 (concat
115 ;; (1) replacement target (2) lang
116 "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
117 ;; (3,4) (unused, headers)
118 "\\(\\|\\[\\(.*?\\)\\]\\)"
119 ;; (5) body
120 "{\\([^\f\n\r\v]+?\\)}\\)")
121 "Regexp used to identify inline src-blocks.")
123 (defun org-babel-get-src-block-info (&optional header-vars-only)
124 "Get information of the current source block.
126 Returns a list
127 (language body header-arguments-alist switches name function-args indent).
128 Unless HEADER-VARS-ONLY is non-nil, any variable
129 references provided in 'function call style' (i.e. in a
130 parenthesised argument list following the src block name) are
131 added to the header-arguments-alist."
132 (let ((case-fold-search t) head info args indent)
133 (if (setq head (org-babel-where-is-src-block-head))
134 (save-excursion
135 (goto-char head)
136 (setq info (org-babel-parse-src-block-match))
137 (setq indent (car (last info)))
138 (setq info (butlast info))
139 (forward-line -1)
140 (if (looking-at
141 (concat org-babel-source-name-regexp
142 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
143 (progn
144 (setq info (append info (list (org-babel-clean-text-properties
145 (match-string 2)))))
146 ;; Note that e.g. "name()" and "name( )" result in
147 ;; ((:var . "")). We maintain that behaviour, and the
148 ;; resulting non-nil sixth element is relied upon in
149 ;; org-babel-exp-code to detect a functional-style
150 ;; block in those cases. However, "name" without any
151 ;; parentheses would result in the same thing, so we
152 ;; explicitly avoid that.
153 (if (setq args (match-string 4))
154 (setq info
155 (append info (list
156 (mapcar
157 (lambda (ref) (cons :var ref))
158 (org-babel-ref-split-args args))))))
159 (unless header-vars-only
160 (setf (nth 2 info)
161 (org-babel-merge-params (nth 5 info) (nth 2 info)))))
162 (setq info (append info (list nil nil))))
163 (append info (list indent)))
164 (if (save-excursion ;; inline source block
165 (re-search-backward "[ \f\t\n\r\v]" nil t)
166 (looking-at org-babel-inline-src-block-regexp))
167 (org-babel-parse-inline-src-block-match)
168 nil))))
170 (defun org-babel-confirm-evaluate (info)
171 "Confirm that the user wishes to evaluate the code block
172 defined by INFO. This behavior can be suppressed by setting the
173 value of `org-confirm-babel-evaluate' to nil, in which case all
174 future interactive code block evaluations will proceed without
175 any confirmation from the user.
177 Note disabling confirmation may result in accidental evaluation
178 of potentially harmful code."
179 (let* ((eval (cdr (assoc :eval (nth 2 info))))
180 (query (or (equal eval "query")
181 (and (functionp org-confirm-babel-evaluate)
182 (funcall org-confirm-babel-evaluate
183 (nth 0 info) (nth 1 info)))
184 org-confirm-babel-evaluate)))
185 (when (or (equal eval "never")
186 (and query
187 (not (yes-or-no-p
188 (format "Evaluate this%scode on your system? "
189 (if info (format " %s " (nth 0 info)) " "))))))
190 (error "evaluation aborted"))))
192 ;;;###autoload
193 (defun org-babel-execute-src-block-maybe ()
194 "Detect if this is context for a org-babel src-block and if so
195 then run `org-babel-execute-src-block'."
196 (interactive)
197 (if (not org-babel-no-eval-on-ctrl-c-ctrl-c)
198 (let ((info (org-babel-get-src-block-info)))
199 (if info
200 (progn (org-babel-execute-src-block current-prefix-arg info) t) nil))
201 nil))
202 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-execute-src-block-maybe)
204 ;;;###autoload
205 (defun org-babel-expand-src-block-maybe ()
206 "Detect if this is context for a org-babel src-block and if so
207 then run `org-babel-expand-src-block'."
208 (interactive)
209 (let ((info (org-babel-get-src-block-info)))
210 (if info
211 (progn (org-babel-expand-src-block current-prefix-arg info) t)
212 nil)))
214 ;;;###autoload
215 (defun org-babel-load-in-session-maybe ()
216 "Detect if this is context for a org-babel src-block and if so
217 then run `org-babel-load-in-session'."
218 (interactive)
219 (let ((info (org-babel-get-src-block-info)))
220 (if info
221 (progn (org-babel-load-in-session current-prefix-arg info) t)
222 nil)))
224 (add-hook 'org-metaup-hook 'org-babel-load-in-session-maybe)
226 ;;;###autoload
227 (defun org-babel-pop-to-session-maybe ()
228 "Detect if this is context for a org-babel src-block and if so
229 then run `org-babel-pop-to-session'."
230 (interactive)
231 (let ((info (org-babel-get-src-block-info)))
232 (if info (progn (org-babel-pop-to-session current-prefix-arg info) t) nil)))
234 (add-hook 'org-metadown-hook 'org-babel-pop-to-session-maybe)
236 (defconst org-babel-header-arg-names
237 '(cache cmdline colnames dir exports file noweb results
238 session tangle var noeval)
239 "Common header arguments used by org-babel. Note that
240 individual languages may define their own language specific
241 header arguments as well.")
243 (defvar org-babel-default-header-args
244 '((:session . "none") (:results . "replace") (:exports . "code")
245 (:cache . "no") (:noweb . "no") (:hlines . "no") (:tangle . "no"))
246 "Default arguments to use when evaluating a source block.")
248 (defvar org-babel-default-inline-header-args
249 '((:session . "none") (:results . "silent") (:exports . "results"))
250 "Default arguments to use when evaluating an inline source block.")
252 (defvar org-babel-current-buffer-properties)
253 (make-variable-buffer-local 'org-babel-current-buffer-properties)
255 (defvar org-babel-result-regexp
256 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:"
257 "Regular expression used to match result lines. If the
258 results are associated with a hash key then the hash will be
259 saved in the second match data.")
261 (defvar org-babel-min-lines-for-block-output 10
262 "If number of lines of output is equal to or exceeds this
263 value, the output is placed in a #+begin_example...#+end_example
264 block. Otherwise the output is marked as literal by inserting
265 colons at the starts of the lines. This variable only takes
266 effect if the :results output option is in effect.")
268 (defvar org-babel-noweb-error-langs nil
269 "List of language for which errors should be raised when the
270 source code block satisfying a noweb reference in this language
271 can not be resolved.")
273 (defvar org-babel-hash-show 4
274 "Number of initial characters to show of a hidden results hash.")
276 (defvar org-babel-after-execute-hook nil
277 "Hook for functions to be called after `org-babel-execute-src-block'")
278 (defun org-babel-named-src-block-regexp-for-name (name)
279 "This generates a regexp used to match a src block named NAME."
280 (concat org-babel-source-name-regexp (regexp-quote name) "[ \t\n]*"
281 (substring org-babel-src-block-regexp 1)))
283 ;;; functions
284 (defvar call-process-region)
285 ;;;###autoload
286 (defun org-babel-execute-src-block (&optional arg info params)
287 "Execute the current source code block, and insert the results
288 into the buffer. Source code execution and the collection and
289 formatting of results can be controlled through a variety of
290 header arguments.
292 Optionally supply a value for INFO in the form returned by
293 `org-babel-get-src-block-info'.
295 Optionally supply a value for PARAMS which will be merged with
296 the header arguments specified at the front of the source code
297 block."
298 (interactive)
299 (let* ((info (or info (org-babel-get-src-block-info)))
300 ;; note the `evaluation-confirmed' variable is currently not
301 ;; used, but could be used later to avoid the need for
302 ;; chaining confirmations
303 (evaluation-confirmed (org-babel-confirm-evaluate info))
304 (lang (nth 0 info))
305 (params (setf (nth 2 info)
306 (sort (org-babel-merge-params (nth 2 info) params)
307 (lambda (el1 el2) (string< (symbol-name (car el1))
308 (symbol-name (car el2)))))))
309 (new-hash
310 (if (and (cdr (assoc :cache params))
311 (string= "yes" (cdr (assoc :cache params))))
312 (org-babel-sha1-hash info)))
313 (old-hash (org-babel-result-hash info))
314 (body (setf (nth 1 info)
315 (if (and (cdr (assoc :noweb params))
316 (string= "yes" (cdr (assoc :noweb params))))
317 (org-babel-expand-noweb-references info)
318 (nth 1 info))))
319 (result-params (split-string (or (cdr (assoc :results params)) "")))
320 (result-type (cond ((member "output" result-params) 'output)
321 ((member "value" result-params) 'value)
322 (t 'value)))
323 (cmd (intern (concat "org-babel-execute:" lang)))
324 (dir (cdr (assoc :dir params)))
325 (default-directory
326 (or (and dir (file-name-as-directory dir)) default-directory))
327 (org-babel-call-process-region-original
328 (if (boundp 'org-babel-call-process-region-original) org-babel-call-process-region-original
329 (symbol-function 'call-process-region)))
330 (indent (car (last info)))
331 result)
332 (unwind-protect
333 (flet ((call-process-region (&rest args)
334 (apply 'org-babel-tramp-handle-call-process-region args)))
335 (unless (fboundp cmd)
336 (error "No org-babel-execute function for %s!" lang))
337 (if (and (not arg) new-hash (equal new-hash old-hash))
338 (save-excursion ;; return cached result
339 (goto-char (org-babel-where-is-src-block-result nil info))
340 (end-of-line 1) (forward-char 1)
341 (setq result (org-babel-read-result))
342 (message (replace-regexp-in-string "%" "%%"
343 (format "%S" result))) result)
344 (setq result (funcall cmd body params))
345 (if (eq result-type 'value)
346 (setq result (if (and (or (member "vector" result-params)
347 (member "table" result-params))
348 (not (listp result)))
349 (list (list result))
350 result)))
351 (org-babel-insert-result
352 result result-params info new-hash indent lang)
353 (run-hooks 'org-babel-after-execute-hook)
354 result))
355 (setq call-process-region 'org-babel-call-process-region-original))))
357 (defun org-babel-expand-body:generic (body params &optional processed-params)
358 "Expand a block of code with org-babel according to it's header
359 arguments. This generic implementation of body expansion is
360 called for languages which have not defined their own specific
361 org-babel-expand-body:lang function." body)
363 ;;;###autoload
364 (defun org-babel-expand-src-block (&optional arg info params)
365 "Expand the current source code block according to it's header
366 arguments, and pop open the results in a preview buffer."
367 (interactive)
368 (let* ((info (or info (org-babel-get-src-block-info)))
369 (lang (nth 0 info))
370 (params (setf (nth 2 info)
371 (sort (org-babel-merge-params (nth 2 info) params)
372 (lambda (el1 el2) (string< (symbol-name (car el1))
373 (symbol-name (car el2)))))))
374 (body (setf (nth 1 info)
375 (if (and (cdr (assoc :noweb params))
376 (string= "yes" (cdr (assoc :noweb params))))
377 (org-babel-expand-noweb-references info) (nth 1 info))))
378 (cmd (intern (concat "org-babel-expand-body:" lang)))
379 (expanded (funcall (if (fboundp cmd) cmd 'org-babel-expand-body:generic)
380 body params)))
381 (org-edit-src-code
382 nil expanded (concat "*Org-Babel Preview " (buffer-name) "[ " lang " ]*"))))
384 ;;;###autoload
385 (defun org-babel-load-in-session (&optional arg info)
386 "Load the body of the current source-code block. Evaluate the
387 header arguments for the source block before entering the
388 session. After loading the body this pops open the session."
389 (interactive)
390 (let* ((info (or info (org-babel-get-src-block-info)))
391 (lang (nth 0 info))
392 (body (nth 1 info))
393 (params (nth 2 info))
394 (session (cdr (assoc :session params)))
395 (cmd (intern (concat "org-babel-load-session:" lang))))
396 (unless (fboundp cmd)
397 (error "No org-babel-load-session function for %s!" lang))
398 (pop-to-buffer (funcall cmd session body params))
399 (end-of-line 1)))
401 ;;;###autoload
402 (defun org-babel-switch-to-session (&optional arg info)
403 "Switch to the session of the current source-code block.
404 If called with a prefix argument then evaluate the header arguments
405 for the source block before entering the session. Copy the body
406 of the source block to the kill ring."
407 (interactive)
408 (let* ((info (or info (org-babel-get-src-block-info)))
409 (lang (nth 0 info))
410 (body (nth 1 info))
411 (params (nth 2 info))
412 (session (cdr (assoc :session params)))
413 (dir (cdr (assoc :dir params)))
414 (default-directory
415 (or (and dir (file-name-as-directory dir)) default-directory))
416 (cmd (intern (format "org-babel-%s-initiate-session" lang)))
417 (cmd2 (intern (concat "org-babel-prep-session:" lang))))
418 (unless (fboundp cmd)
419 (error "No org-babel-initiate-session function for %s!" lang))
420 ;; copy body to the kill ring
421 (with-temp-buffer (insert (org-babel-trim body))
422 (copy-region-as-kill (point-min) (point-max)))
423 ;; if called with a prefix argument, then process header arguments
424 (unless (fboundp cmd2)
425 (error "No org-babel-prep-session function for %s!" lang))
426 (when arg (funcall cmd2 session params))
427 ;; just to the session using pop-to-buffer
428 (pop-to-buffer (funcall cmd session params))
429 (end-of-line 1)))
431 (defalias 'org-babel-pop-to-session 'org-babel-switch-to-session)
433 (defvar org-bracket-link-regexp)
434 ;;;###autoload
435 (defun org-babel-open-src-block-result (&optional re-run)
436 "If `point' is on a src block then open the results of the
437 source code block, otherwise return nil. With optional prefix
438 argument RE-RUN the source-code block is evaluated even if
439 results already exist."
440 (interactive "P")
441 (when (org-babel-get-src-block-info)
442 (save-excursion
443 ;; go to the results, if there aren't any then run the block
444 (goto-char (or (and (not re-run) (org-babel-where-is-src-block-result))
445 (progn (org-babel-execute-src-block)
446 (org-babel-where-is-src-block-result))))
447 (end-of-line 1)
448 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
449 ;; open the results
450 (if (looking-at org-bracket-link-regexp)
451 ;; file results
452 (org-open-at-point)
453 (let ((results (org-babel-read-result)))
454 (flet ((echo-res (result)
455 (if (stringp result) result (format "%S" result))))
456 (pop-to-buffer (get-buffer-create "org-babel-results"))
457 (delete-region (point-min) (point-max))
458 (if (listp results)
459 ;; table result
460 (insert (orgtbl-to-generic results '(:sep "\t" :fmt echo-res)))
461 ;; scalar result
462 (insert (echo-res results))))))
463 t)))
465 ;;;###autoload
466 (defun org-babel-execute-buffer (&optional arg)
467 "Call `org-babel-execute-src-block' on every source block in
468 the current buffer."
469 (interactive "P")
470 (save-excursion
471 (org-save-outline-visibility t
472 (goto-char (point-min))
473 (show-all)
474 (while (re-search-forward org-babel-src-block-regexp nil t)
475 (let ((pos-end (match-end 0)))
476 (goto-char (match-beginning 0))
477 (org-babel-execute-src-block arg)
478 (goto-char pos-end))))))
480 ;;;###autoload
481 (defun org-babel-execute-subtree (&optional arg)
482 "Call `org-babel-execute-src-block' on every source block in
483 the current subtree."
484 (interactive "P")
485 (save-restriction
486 (save-excursion
487 (org-narrow-to-subtree)
488 (org-babel-execute-buffer)
489 (widen))))
491 ;;;###autoload
492 (defun org-babel-sha1-hash (&optional info)
493 "Generate an sha1 hash based on the value of info."
494 (interactive)
495 (let* ((info (or info (org-babel-get-src-block-info)))
496 (hash (sha1 (format "%s-%s" (mapconcat (lambda (arg) (format "%S" arg))
497 (nth 2 info) ":")
498 (nth 1 info)))))
499 (when (interactive-p) (message hash))
500 hash))
502 (defun org-babel-result-hash (&optional info)
503 "Return the in-buffer hash associated with the results
504 specified in INFO."
505 (org-babel-where-is-src-block-result nil info)
506 (org-babel-clean-text-properties (match-string 3)))
508 (defun org-babel-hide-hash ()
509 "Hide the hash in the current results line. Only the initial
510 `org-babel-hash-show' characters of the hash will remain
511 visible."
512 (add-to-invisibility-spec '(org-babel-hide-hash . t))
513 (save-excursion
514 (when (and (re-search-forward org-babel-result-regexp nil t)
515 (match-string 3))
516 (let* ((start (match-beginning 3))
517 (hide-start (+ org-babel-hash-show start))
518 (end (match-end 3))
519 (hash (match-string 3))
520 ov1 ov2)
521 (setq ov1 (make-overlay start hide-start))
522 (setq ov2 (make-overlay hide-start end))
523 (overlay-put ov2 'invisible 'org-babel-hide-hash)
524 (overlay-put ov1 'babel-hash hash)))))
526 (defun org-babel-hide-all-hashes ()
527 "Hide the hash in the current buffer. Only the initial
528 `org-babel-hash-show' characters of each hash will remain
529 visible. This function should be called as part of the
530 `org-mode-hook'."
531 (save-excursion
532 (while (re-search-forward org-babel-result-regexp nil t)
533 (goto-char (match-beginning 0))
534 (org-babel-hide-hash)
535 (goto-char (match-end 0)))))
536 (add-hook 'org-mode-hook 'org-babel-hide-all-hashes)
538 (defun org-babel-hash-at-point (&optional point)
539 "Return the value of the hash at `point'. The hash is also
540 added as the last element of the kill ring. This can be called
541 with C-c C-c."
542 (interactive)
543 (let ((hash (car (delq nil (mapcar
544 (lambda (ol) (overlay-get ol 'babel-hash))
545 (overlays-at (or point (point))))))))
546 (when hash (kill-new hash) (message hash))))
547 (add-hook 'org-ctrl-c-ctrl-c-hook 'org-babel-hash-at-point)
549 (defun org-babel-result-hide-spec ()
550 "Add `org-babel-hide-result' as an invisibility spec for hiding
551 portions of results lines."
552 (add-to-invisibility-spec '(org-babel-hide-result . t)))
553 (add-hook 'org-mode-hook 'org-babel-result-hide-spec)
555 (defvar org-babel-hide-result-overlays nil
556 "Overlays hiding results.")
558 (defun org-babel-result-hide-all ()
559 "Fold all results in the current buffer."
560 (interactive)
561 (org-babel-show-result-all)
562 (save-excursion
563 (while (re-search-forward org-babel-result-regexp nil t)
564 (save-excursion (goto-char (match-beginning 0))
565 (org-babel-hide-result-toggle-maybe)))))
567 (defun org-babel-show-result-all ()
568 "Unfold all results in the current buffer."
569 (mapc 'delete-overlay org-babel-hide-result-overlays)
570 (setq org-babel-hide-result-overlays nil))
572 ;;;###autoload
573 (defun org-babel-hide-result-toggle-maybe ()
574 "Toggle visibility of result at point."
575 (interactive)
576 (let ((case-fold-search t))
577 (if (save-excursion
578 (beginning-of-line 1)
579 (looking-at org-babel-result-regexp))
580 (progn (org-babel-hide-result-toggle)
581 t) ;; to signal that we took action
582 nil))) ;; to signal that we did not
584 (defun org-babel-hide-result-toggle (&optional force)
585 "Toggle the visibility of the current result."
586 (interactive)
587 (save-excursion
588 (beginning-of-line)
589 (if (re-search-forward org-babel-result-regexp nil t)
590 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
591 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
593 (if (memq t (mapcar (lambda (overlay)
594 (eq (overlay-get overlay 'invisible)
595 'org-babel-hide-result))
596 (overlays-at start)))
597 (if (or (not force) (eq force 'off))
598 (mapc (lambda (ov)
599 (when (member ov org-babel-hide-result-overlays)
600 (setq org-babel-hide-result-overlays
601 (delq ov org-babel-hide-result-overlays)))
602 (when (eq (overlay-get ov 'invisible)
603 'org-babel-hide-result)
604 (delete-overlay ov)))
605 (overlays-at start)))
606 (setq ov (make-overlay start end))
607 (overlay-put ov 'invisible 'org-babel-hide-result)
608 ;; make the block accessible to isearch
609 (overlay-put
610 ov 'isearch-open-invisible
611 (lambda (ov)
612 (when (member ov org-babel-hide-result-overlays)
613 (setq org-babel-hide-result-overlays
614 (delq ov org-babel-hide-result-overlays)))
615 (when (eq (overlay-get ov 'invisible)
616 'org-babel-hide-result)
617 (delete-overlay ov))))
618 (push ov org-babel-hide-result-overlays)))
619 (error "Not looking at a result line"))))
621 ;; org-tab-after-check-for-cycling-hook
622 (add-hook 'org-tab-first-hook 'org-babel-hide-result-toggle-maybe)
623 ;; Remove overlays when changing major mode
624 (add-hook 'org-mode-hook
625 (lambda () (org-add-hook 'change-major-mode-hook
626 'org-babel-show-result-all 'append 'local)))
628 (defmacro org-babel-map-source-blocks (file &rest body)
629 "Evaluate BODY forms on each source-block in FILE."
630 (declare (indent 1))
631 `(let ((visited-p (get-file-buffer (expand-file-name ,file)))
632 to-be-removed)
633 (save-window-excursion
634 (find-file ,file)
635 (setq to-be-removed (current-buffer))
636 (goto-char (point-min))
637 (while (re-search-forward org-babel-src-block-regexp nil t)
638 (goto-char (match-beginning 0))
639 (save-match-data ,@body)
640 (goto-char (match-end 0))))
641 (unless visited-p
642 (kill-buffer to-be-removed))))
644 (defvar org-file-properties)
645 (defun org-babel-params-from-properties (&optional lang)
646 "Return an association list of any source block params which
647 may be specified in the properties of the current outline entry."
648 (save-match-data
649 (let (val sym)
650 (delq nil
651 (mapcar
652 (lambda (header-arg)
653 (and (setq val
654 (or (condition-case nil
655 (org-entry-get (point) header-arg t)
656 (error nil))
657 (cdr (assoc header-arg org-file-properties))))
658 (cons (intern (concat ":" header-arg)) val)))
659 (mapcar
660 'symbol-name
661 (append
662 org-babel-header-arg-names
663 (progn
664 (setq sym (intern (concat "org-babel-header-arg-names:" lang)))
665 (and (boundp sym) (eval sym))))))))))
667 (defun org-babel-params-from-buffer ()
668 "Return an association list of any source block params which
669 may be specified at the top of the current buffer."
670 (or org-babel-current-buffer-properties
671 (setq org-babel-current-buffer-properties
672 (save-match-data
673 (save-excursion
674 (save-restriction
675 (widen)
676 (goto-char (point-min))
677 (when (re-search-forward
678 (org-make-options-regexp (list "BABEL")) nil t)
679 (org-babel-parse-header-arguments
680 (org-match-string-no-properties 2)))))))))
682 (defvar org-src-preserve-indentation)
683 (defun org-babel-parse-src-block-match ()
684 "Parse the match data resulting from a match of the
685 `org-babel-src-block-regexp'."
686 (let* ((block-indentation (length (match-string 1)))
687 (lang (org-babel-clean-text-properties (match-string 2)))
688 (lang-headers (intern (concat "org-babel-default-header-args:" lang)))
689 (switches (match-string 3))
690 (body (org-babel-clean-text-properties (match-string 5)))
691 (preserve-indentation (or org-src-preserve-indentation
692 (string-match "-i\\>" switches))))
693 (list lang
694 ;; get block body less properties, protective commas, and indentation
695 (with-temp-buffer
696 (save-match-data
697 (insert (org-babel-strip-protective-commas body))
698 (unless preserve-indentation (org-do-remove-indentation))
699 (buffer-string)))
700 (org-babel-merge-params
701 org-babel-default-header-args
702 (org-babel-params-from-buffer)
703 (org-babel-params-from-properties lang)
704 (if (boundp lang-headers) (eval lang-headers) nil)
705 (org-babel-parse-header-arguments
706 (org-babel-clean-text-properties (or (match-string 4) ""))))
707 switches
708 block-indentation)))
710 (defun org-babel-parse-inline-src-block-match ()
711 "Parse the match data resulting from a match of the
712 `org-babel-inline-src-block-regexp'."
713 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
714 (lang-headers (intern (concat "org-babel-default-header-args:" lang))))
715 (list lang
716 (org-babel-strip-protective-commas
717 (org-babel-clean-text-properties (match-string 5)))
718 (org-babel-merge-params
719 org-babel-default-inline-header-args
720 (org-babel-params-from-buffer)
721 (org-babel-params-from-properties lang)
722 (if (boundp lang-headers) (eval lang-headers) nil)
723 (org-babel-parse-header-arguments
724 (org-babel-clean-text-properties (or (match-string 4) "")))))))
726 (defun org-babel-parse-header-arguments (arg-string)
727 "Parse a string of header arguments returning an alist."
728 (if (> (length arg-string) 0)
729 (delq nil
730 (mapcar
731 (lambda (arg)
732 (if (string-match
733 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
734 arg)
735 (cons (intern (concat ":" (match-string 1 arg)))
736 (let ((raw (org-babel-chomp (match-string 2 arg))))
737 (if (org-babel-number-p raw)
738 raw (org-babel-read raw))))
739 (cons (intern (concat ":" arg)) nil)))
740 (split-string (concat " " arg-string) "[ \f\t\n\r\v]+:" t)))))
742 (defun org-babel-process-params (params)
743 "Parse params and resolve references.
745 Return a list (session vars result-params result-type colnames rownames)."
746 (let* ((session (cdr (assoc :session params)))
747 (vars-and-names (org-babel-disassemble-tables
748 (org-babel-ref-variables params)
749 (cdr (assoc :hlines params))
750 (cdr (assoc :colnames params))
751 (cdr (assoc :rownames params))))
752 (vars (car vars-and-names))
753 (colnames (cadr vars-and-names))
754 (rownames (caddr vars-and-names))
755 (result-params (split-string (or (cdr (assoc :results params)) "")))
756 (result-type (cond ((member "output" result-params) 'output)
757 ((member "value" result-params) 'value)
758 (t 'value))))
759 (list session vars result-params result-type colnames rownames)))
761 ;; row and column names
762 (defun org-babel-del-hlines (table)
763 "Remove all 'hlines from TABLE."
764 (remove 'hline table))
766 (defun org-babel-get-colnames (table)
767 "Return a cons cell, the `car' of which contains the TABLE less
768 colnames, and the `cdr' of which contains a list of the column
769 names."
770 (if (equal 'hline (nth 1 table))
771 (cons (cddr table) (car table))
772 (cons (cdr table) (car table))))
774 (defun org-babel-get-rownames (table)
775 "Return a cons cell, the `car' of which contains the TABLE less
776 colnames, and the `cdr' of which contains a list of the column
777 names. Note: this function removes any hlines in TABLE."
778 (flet ((trans (table) (apply #'mapcar* #'list table)))
779 (let* ((width (apply 'max (mapcar (lambda (el) (if (listp el) (length el) 0)) table)))
780 (table (trans (mapcar (lambda (row)
781 (if (not (equal row 'hline))
783 (setq row '())
784 (dotimes (n width) (setq row (cons 'hline row)))
785 row))
786 table))))
787 (cons (mapcar (lambda (row) (if (equal (car row) 'hline) 'hline row))
788 (trans (cdr table)))
789 (remove 'hline (car table))))))
791 (defun org-babel-put-colnames (table colnames)
792 "Add COLNAMES to TABLE if they exist."
793 (if colnames (apply 'list colnames 'hline table) table))
795 (defun org-babel-put-rownames (table rownames)
796 "Add ROWNAMES to TABLE if they exist."
797 (if rownames
798 (mapcar (lambda (row)
799 (if (listp row)
800 (cons (or (pop rownames) "") row)
801 row)) table)
802 table))
804 (defun org-babel-pick-name (names selector)
805 "Select one out of an alist of row or column names."
806 (when names
807 (if (and selector (symbolp selector) (not (equal t selector)))
808 (cdr (assoc selector names))
809 (if (integerp selector)
810 (nth (- selector 1) names)
811 (cdr (car (last names)))))))
813 (defun org-babel-disassemble-tables (vars hlines colnames rownames)
814 "Process the variables in VARS according to the HLINES,
815 ROWNAMES and COLNAMES header arguments. Return a list consisting
816 of the vars, cnames and rnames."
817 (let (cnames rnames)
818 (list
819 (mapcar
820 (lambda (var)
821 (when (listp (cdr var))
822 (when (and (not (equal colnames "no"))
823 (or colnames (and (equal (nth 1 (cdr var)) 'hline)
824 (not (member 'hline (cddr (cdr var)))))))
825 (let ((both (org-babel-get-colnames (cdr var))))
826 (setq cnames (cons (cons (car var) (cdr both))
827 cnames))
828 (setq var (cons (car var) (car both)))))
829 (when (and rownames (not (equal rownames "no")))
830 (let ((both (org-babel-get-rownames (cdr var))))
831 (setq rnames (cons (cons (car var) (cdr both))
832 rnames))
833 (setq var (cons (car var) (car both)))))
834 (when (and hlines (not (equal hlines "yes")))
835 (setq var (cons (car var) (org-babel-del-hlines (cdr var))))))
836 var)
837 vars)
838 cnames rnames)))
840 (defun org-babel-reassemble-table (table colnames rownames)
841 "Given a TABLE and set of COLNAMES and ROWNAMES add the names
842 to the table for reinsertion to org-mode."
843 (if (listp table)
844 ((lambda (table)
845 (if (and colnames (listp (car table)) (= (length (car table))
846 (length colnames)))
847 (org-babel-put-colnames table colnames) table))
848 (if (and rownames (= (length table) (length rownames)))
849 (org-babel-put-rownames table rownames) table))
850 table))
852 (defun org-babel-where-is-src-block-head ()
853 "Return the point at the beginning of the current source
854 block. Specifically at the beginning of the #+BEGIN_SRC line.
855 If the point is not on a source block then return nil."
856 (let ((initial (point)) top bottom)
858 (save-excursion ;; on a source name line
859 (beginning-of-line 1)
860 (and (looking-at org-babel-source-name-regexp) (forward-line 1)
861 (looking-at org-babel-src-block-regexp)
862 (point)))
863 (save-excursion ;; on a #+begin_src line
864 (beginning-of-line 1)
865 (and (looking-at org-babel-src-block-regexp)
866 (point)))
867 (save-excursion ;; inside a src block
868 (and
869 (re-search-backward "^[ \t]*#\\+begin_src" nil t) (setq top (point))
870 (re-search-forward "^[ \t]*#\\+end_src" nil t) (setq bottom (point))
871 (< top initial) (< initial bottom)
872 (progn (goto-char top) (beginning-of-line 1)
873 (looking-at org-babel-src-block-regexp))
874 (point))))))
876 ;;;###autoload
877 (defun org-babel-goto-named-source-block (&optional name)
878 "Go to a named source-code block."
879 (interactive "ssource-block name: ")
880 (let ((point (org-babel-find-named-block name)))
881 (if point
882 ;; taken from `org-open-at-point'
883 (progn (goto-char point) (org-show-context))
884 (message "source-code block '%s' not found in this buffer" name))))
886 (defun org-babel-find-named-block (name)
887 "Find a named source-code block.
888 Return the location of the source block identified by source
889 NAME, or nil if no such block exists. Set match data according to
890 org-babel-named-src-block-regexp."
891 (save-excursion
892 (let ((case-fold-search t)
893 (regexp (org-babel-named-src-block-regexp-for-name name)) msg)
894 (goto-char (point-min))
895 (when (or (re-search-forward regexp nil t)
896 (re-search-backward regexp nil t))
897 (match-beginning 0)))))
899 (defun org-babel-find-named-result (name)
900 "Return the location of the result named NAME in the current
901 buffer or nil if no such result exists."
902 (save-excursion
903 (goto-char (point-min))
904 (when (re-search-forward
905 (concat org-babel-result-regexp
906 "[ \t]" (regexp-quote name) "[ \t\n\f\v\r]") nil t)
907 (beginning-of-line 0) (point))))
909 (defvar org-babel-lob-one-liner-regexp)
910 (defun org-babel-where-is-src-block-result (&optional insert info hash indent)
911 "Return the point at the beginning of the result of the current
912 source block. Specifically at the beginning of the results line.
913 If no result exists for this block then create a results line
914 following the source block."
915 (save-excursion
916 (let* ((on-lob-line (progn (beginning-of-line 1)
917 (looking-at org-babel-lob-one-liner-regexp)))
918 (name (if on-lob-line
919 (nth 0 (org-babel-lob-get-info))
920 (nth 4 (or info (org-babel-get-src-block-info)))))
921 (head (unless on-lob-line (org-babel-where-is-src-block-head))) end)
922 (when head (goto-char head))
923 (or (and name (org-babel-find-named-result name))
924 (and (or on-lob-line (re-search-forward "^[ \t]*#\\+end_src" nil t))
925 (progn (end-of-line 1)
926 (if (eobp) (insert "\n") (forward-char 1))
927 (setq end (point))
928 (or (and (not name)
929 (progn ;; unnamed results line already exists
930 (re-search-forward "[^ \f\t\n\r\v]" nil t)
931 (beginning-of-line 1)
932 (looking-at
933 (concat org-babel-result-regexp "\n"))))
934 ;; or (with optional insert) back up and
935 ;; make one ourselves
936 (when insert
937 (goto-char end)
938 (if (looking-at "[\n\r]")
939 (forward-char 1) (insert "\n"))
940 (insert (concat
941 (if indent
942 (mapconcat
943 (lambda (el) " ")
944 (number-sequence 1 indent) "")
946 "#+results"
947 (when hash (concat "["hash"]"))
949 (when name (concat " " name)) "\n\n"))
950 (backward-char)
951 (beginning-of-line 0)
952 (if hash (org-babel-hide-hash)) t)))
953 (point))))))
955 (defvar org-block-regexp)
956 (defun org-babel-read-result ()
957 "Read the result at `point' into emacs-lisp."
958 (let ((case-fold-search t) result-string)
959 (cond
960 ((org-at-table-p) (org-babel-read-table))
961 ((looking-at org-bracket-link-regexp) (org-babel-read-link))
962 ((looking-at org-block-regexp) (org-babel-trim (match-string 4)))
963 ((looking-at "^[ \t]*: ")
964 (setq result-string
965 (org-babel-trim
966 (mapconcat (lambda (line)
967 (if (and (> (length line) 1)
968 (string-match "^[ \t]*: \\(.+\\)" line))
969 (match-string 1 line)
970 line))
971 (split-string
972 (buffer-substring
973 (point) (org-babel-result-end)) "[\r\n]+")
974 "\n")))
975 (or (org-babel-number-p result-string) result-string))
976 ((looking-at org-babel-result-regexp)
977 (save-excursion (forward-line 1) (org-babel-read-result))))))
979 (defun org-babel-read-table ()
980 "Read the table at `point' into emacs-lisp."
981 (mapcar (lambda (row)
982 (if (and (symbolp row) (equal row 'hline)) row
983 (mapcar #'org-babel-read row)))
984 (org-table-to-lisp)))
986 (defvar org-link-types-re)
987 (defun org-babel-read-link ()
988 "Read the link at `point' into emacs-lisp. If the path of the
989 link is a file path it is expanded using `expand-file-name'."
990 (let* ((case-fold-search t)
991 (raw (and (looking-at org-bracket-link-regexp)
992 (org-babel-clean-text-properties (match-string 1))))
993 (type (and (string-match org-link-types-re raw)
994 (match-string 1 raw))))
995 (cond
996 ((not type) (expand-file-name raw))
997 ((string= type "file")
998 (and (string-match "file\\(.*\\):\\(.+\\)" raw)
999 (expand-file-name (match-string 2 raw))))
1000 (t raw))))
1002 (defun org-babel-insert-result
1003 (result &optional result-params info hash indent lang)
1004 "Insert RESULT into the current buffer after the end of the
1005 current source block. With optional argument RESULT-PARAMS
1006 controls insertion of results in the org-mode file.
1007 RESULT-PARAMS can take the following values...
1009 replace - (default option) insert results after the source block
1010 replacing any previously inserted results
1012 silent -- no results are inserted
1014 file ---- the results are interpreted as a file path, and are
1015 inserted into the buffer using the Org-mode file syntax
1017 raw ----- results are added directly to the org-mode file. This
1018 is a good option if you code block will output org-mode
1019 formatted text.
1021 org ----- this is the same as the 'raw' option
1023 html ---- results are added inside of a #+BEGIN_HTML block. This
1024 is a good option if you code block will output html
1025 formatted text.
1027 latex --- results are added inside of a #+BEGIN_LATEX block.
1028 This is a good option if you code block will output
1029 latex formatted text.
1031 code ---- the results are extracted in the syntax of the source
1032 code of the language being evaluated and are added
1033 inside of a #+BEGIN_SRC block with the source-code
1034 language set appropriately. Note this relies on the
1035 optional LANG argument."
1036 (if (stringp result)
1037 (progn
1038 (setq result (org-babel-clean-text-properties result))
1039 (when (member "file" result-params)
1040 (setq result (org-babel-result-to-file result))))
1041 (unless (listp result) (setq result (format "%S" result))))
1042 (if (= (length result) 0)
1043 (if (member "value" result-params)
1044 (message "No result returned by source block")
1045 (message "Source block produced no output"))
1046 (if (and result-params (member "silent" result-params))
1047 (progn
1048 (message (replace-regexp-in-string "%" "%%" (format "%S" result)))
1049 result)
1050 (when (and (stringp result) ;; ensure results end in a newline
1051 (not (or (string-equal (substring result -1) "\n")
1052 (string-equal (substring result -1) "\r"))))
1053 (setq result (concat result "\n")))
1054 (save-excursion
1055 (let ((existing-result (org-babel-where-is-src-block-result
1056 t info hash indent))
1057 (results-switches
1058 (cdr (assoc :results_switches (nth 2 info))))
1059 beg end)
1060 (when existing-result
1061 (goto-char existing-result)
1062 (save-excursion
1063 (re-search-forward "#" nil t)
1064 (setq indent (- (current-column) 1)))
1065 (forward-line 1)
1066 (setq beg (point))
1067 (cond
1068 ((member "replace" result-params)
1069 (delete-region (point) (org-babel-result-end)))
1070 ((member "append" result-params)
1071 (goto-char (org-babel-result-end)) (setq beg (point)))
1072 ((member "prepend" result-params) ;; already there
1074 (setq results-switches
1075 (if results-switches (concat " " results-switches) ""))
1076 (cond
1077 ;; assume the result is a table if it's not a string
1078 ((not (stringp result))
1079 (insert (concat (orgtbl-to-orgtbl
1080 (if (or (eq 'hline (car result))
1081 (and (listp (car result))
1082 (listp (cdr (car result)))))
1083 result (list result))
1084 '(:fmt (lambda (cell) (format "%s" cell)))) "\n"))
1085 (goto-char beg) (when (org-at-table-p) (org-table-align)))
1086 ((member "file" result-params)
1087 (insert result))
1088 ((member "html" result-params)
1089 (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
1090 results-switches result)))
1091 ((member "latex" result-params)
1092 (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
1093 results-switches result)))
1094 ((member "code" result-params)
1095 (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
1096 (or lang "none") results-switches result)))
1097 ((or (member "raw" result-params) (member "org" result-params))
1098 (save-excursion (insert result)) (if (org-at-table-p) (org-cycle)))
1100 (org-babel-examplize-region
1101 (point) (progn (insert result) (point)) results-switches)))
1102 ;; possibly indent the results to match the #+results line
1103 (setq end (if (listp result) (org-table-end) (point)))
1104 (when (and indent (> indent 0)
1105 ;; in this case `table-align' does the work for us
1106 (not (and (listp result)
1107 (member "append" result-params))))
1108 (indent-rigidly beg end indent))))
1109 (message "finished"))))
1111 (defun org-babel-remove-result (&optional info)
1112 "Remove the result of the current source block."
1113 (interactive)
1114 (let ((location (org-babel-where-is-src-block-result nil info)) start)
1115 (when location
1116 (save-excursion
1117 (goto-char location) (setq start (point)) (forward-line 1)
1118 (delete-region start (org-babel-result-end))))))
1120 (defun org-babel-result-end ()
1121 "Return the point at the end of the current set of results"
1122 (save-excursion
1123 (if (org-at-table-p)
1124 (progn (goto-char (org-table-end)) (point))
1125 (let ((case-fold-search t))
1126 (cond
1127 ((looking-at "[ \t]*#\\+begin_latex")
1128 (re-search-forward "[ \t]*#\\+end_latex" nil t)
1129 (forward-line 1))
1130 ((looking-at "[ \t]*#\\+begin_html")
1131 (re-search-forward "[ \t]*#\\+end_html" nil t)
1132 (forward-line 1))
1133 ((looking-at "[ \t]*#\\+begin_example")
1134 (re-search-forward "[ \t]*#\\+end_example" nil t)
1135 (forward-line 1))
1136 ((looking-at "[ \t]*#\\+begin_src")
1137 (re-search-forward "[ \t]*#\\+end_src" nil t)
1138 (forward-line 1))
1139 (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1140 (forward-line 1))))))
1141 (point))))
1143 (defun org-babel-result-to-file (result)
1144 "Convert RESULT into an `org-mode' link. If the
1145 `default-directory' is different from the containing file's
1146 directory then expand relative links."
1147 (format
1148 "[[file:%s]]"
1149 (if (and default-directory
1150 buffer-file-name
1151 (not (string= (expand-file-name default-directory)
1152 (expand-file-name
1153 (file-name-directory buffer-file-name)))))
1154 (expand-file-name result default-directory)
1155 result)))
1157 (defun org-babel-examplize-region (beg end &optional results-switches)
1158 "Comment out region using the ': ' org example quote."
1159 (interactive "*r")
1160 (let ((size (count-lines beg end)))
1161 (save-excursion
1162 (cond ((= size 0)
1163 (error (concat "This should be impossible:"
1164 "a newline was appended to result if missing")))
1165 ((< size org-babel-min-lines-for-block-output)
1166 (goto-char beg)
1167 (dotimes (n size)
1168 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1170 (goto-char beg)
1171 (insert (if results-switches
1172 (format "#+begin_example%s\n" results-switches)
1173 "#+begin_example\n"))
1174 (forward-char (- end beg))
1175 (insert "#+end_example\n"))))))
1177 (defun org-babel-merge-params (&rest plists)
1178 "Combine all parameter association lists in PLISTS. Later
1179 elements of PLISTS override the values of previous element. This
1180 takes into account some special considerations for certain
1181 parameters when merging lists."
1182 (let ((results-exclusive-groups
1183 '(("file" "vector" "table" "scalar" "raw" "org"
1184 "html" "latex" "code" "pp")
1185 ("replace" "silent" "append" "prepend")
1186 ("output" "value")))
1187 (exports-exclusive-groups
1188 '(("code" "results" "both" "none")))
1189 params results exports tangle noweb cache vars var ref shebang comments)
1190 (flet ((e-merge (exclusive-groups &rest result-params)
1191 ;; maintain exclusivity of mutually exclusive parameters
1192 (let (output)
1193 (mapc (lambda (new-params)
1194 (mapc (lambda (new-param)
1195 (mapc (lambda (exclusive-group)
1196 (when (member new-param exclusive-group)
1197 (mapcar (lambda (excluded-param)
1198 (setq output
1199 (delete
1200 excluded-param
1201 output)))
1202 exclusive-group)))
1203 exclusive-groups)
1204 (setq output (org-uniquify
1205 (cons new-param output))))
1206 new-params))
1207 result-params)
1208 output)))
1209 (mapc (lambda (plist)
1210 (mapc (lambda (pair)
1211 (case (car pair)
1212 (:var
1213 ;; we want only one specification per variable
1214 (when (string-match
1215 (concat "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1216 "[ \t]*\\([^\f\n\r\v]+\\)$") (cdr pair))
1217 ;; TODO: When is this not true?
1218 (setq var (intern (match-string 1 (cdr pair)))
1219 ref (match-string 2 (cdr pair))
1220 vars (cons (cons var ref)
1221 (assq-delete-all var vars)))))
1222 (:results
1223 (setq results
1224 (e-merge results-exclusive-groups
1225 results (split-string (cdr pair)))))
1226 (:file
1227 (when (cdr pair)
1228 (setq results (e-merge results-exclusive-groups
1229 results '("file")))
1230 (unless (or (member "both" exports)
1231 (member "none" exports)
1232 (member "code" exports))
1233 (setq exports (e-merge exports-exclusive-groups
1234 exports '("results"))))
1235 (setq params
1236 (cons pair
1237 (assq-delete-all (car pair) params)))))
1238 (:exports
1239 (setq exports
1240 (e-merge exports-exclusive-groups
1241 exports (split-string (cdr pair)))))
1242 (:tangle ;; take the latest -- always overwrite
1243 (setq tangle (or (list (cdr pair)) tangle)))
1244 (:noweb
1245 (setq noweb
1246 (e-merge '(("yes" "no")) noweb
1247 (split-string (or (cdr pair) "")))))
1248 (:cache
1249 (setq cache
1250 (e-merge '(("yes" "no")) cache
1251 (split-string (or (cdr pair) "")))))
1252 (:shebang ;; take the latest -- always overwrite
1253 (setq shebang (or (list (cdr pair)) shebang)))
1254 (:comments
1255 (setq comments
1256 (e-merge '(("yes" "no")) comments
1257 (split-string (or (cdr pair) "")))))
1258 (t ;; replace: this covers e.g. :session
1259 (setq params
1260 (cons pair
1261 (assq-delete-all (car pair) params))))))
1262 plist))
1263 plists))
1264 (setq vars (mapcar (lambda (pair) (format "%s=%s" (car pair) (cdr pair))) vars))
1265 (while vars (setq params (cons (cons :var (pop vars)) params)))
1266 (cons (cons :comments (mapconcat 'identity comments " "))
1267 (cons (cons :shebang (mapconcat 'identity shebang " "))
1268 (cons (cons :cache (mapconcat 'identity cache " "))
1269 (cons (cons :noweb (mapconcat 'identity noweb " "))
1270 (cons (cons :tangle (mapconcat 'identity tangle " "))
1271 (cons (cons :exports
1272 (mapconcat 'identity exports " "))
1273 (cons
1274 (cons :results
1275 (mapconcat 'identity results " "))
1276 params)))))))))
1278 (defun org-babel-expand-noweb-references (&optional info parent-buffer)
1279 "This function expands Noweb style references in the body of
1280 the current source-code block. For example the following
1281 reference would be replaced with the body of the source-code
1282 block named 'example-block'.
1284 <<example-block>>
1286 Note that any text preceding the <<foo>> construct on a line will
1287 be interposed between the lines of the replacement text. So for
1288 example if <<foo>> is placed behind a comment, then the entire
1289 replacement text will also be commented.
1291 This function must be called from inside of the buffer containing
1292 the source-code block which holds BODY.
1294 In addition the following syntax can be used to insert the
1295 results of evaluating the source-code block named 'example-block'.
1297 <<example-block()>>
1299 Any optional arguments can be passed to example-block by placing
1300 the arguments inside the parenthesis following the convention
1301 defined by `org-babel-lob'. For example
1303 <<example-block(a=9)>>
1305 would set the value of argument \"a\" equal to \"9\". Note that
1306 these arguments are not evaluated in the current source-code
1307 block but are passed literally to the \"example-block\"."
1308 (let* ((parent-buffer (or parent-buffer (current-buffer)))
1309 (info (or info (org-babel-get-src-block-info)))
1310 (lang (nth 0 info))
1311 (body (nth 1 info))
1312 (new-body "") index source-name evaluate prefix)
1313 (flet ((nb-add (text)
1314 (setq new-body (concat new-body text))))
1315 (with-temp-buffer
1316 (insert body) (goto-char (point-min))
1317 (setq index (point))
1318 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t))
1319 (save-match-data (setf source-name (match-string 1)))
1320 (save-match-data (setq evaluate (string-match "\(.*\)" source-name)))
1321 (save-match-data
1322 (setq prefix
1323 (buffer-substring (match-beginning 0)
1324 (save-excursion
1325 (beginning-of-line 1) (point)))))
1326 ;; add interval to new-body (removing noweb reference)
1327 (goto-char (match-beginning 0))
1328 (nb-add (buffer-substring index (point)))
1329 (goto-char (match-end 0))
1330 (setq index (point))
1331 (nb-add (with-current-buffer parent-buffer
1332 (mapconcat ;; interpose PREFIX between every line
1333 #'identity
1334 (split-string
1335 (if evaluate
1336 (let ((raw (org-babel-ref-resolve-reference
1337 source-name nil)))
1338 (if (stringp raw) raw (format "%S" raw)))
1339 (save-restriction
1340 (widen)
1341 (let ((point (org-babel-find-named-block
1342 source-name)))
1343 (if point
1344 (save-excursion
1345 (goto-char point)
1346 (org-babel-trim
1347 (org-babel-expand-noweb-references
1348 (org-babel-get-src-block-info))))
1349 ;; optionally raise an error if named
1350 ;; source-block doesn't exist
1351 (if (member lang org-babel-noweb-error-langs)
1352 (error "%s"
1353 (concat
1354 "<<" source-name ">> "
1355 "could not be resolved (see "
1356 "`org-babel-noweb-error-langs')"))
1357 "")))))
1358 "[\n\r]") (concat "\n" prefix)))))
1359 (nb-add (buffer-substring index (point-max)))))
1360 new-body))
1362 (defun org-babel-clean-text-properties (text)
1363 "Strip all properties from text return."
1364 (when text
1365 (set-text-properties 0 (length text) nil text) text))
1367 (defun org-babel-strip-protective-commas (body)
1368 "Strip protective commas from bodies of source blocks."
1369 (replace-regexp-in-string "^,#" "#" body))
1371 (defun org-babel-read (cell)
1372 "Convert the string value of CELL to a number if appropriate.
1373 Otherwise if cell looks like lisp (meaning it starts with a
1374 \"(\" or a \"'\") then read it as lisp, otherwise return it
1375 unmodified as a string.
1377 This is taken almost directly from `org-read-prop'."
1378 (if (and (stringp cell) (not (equal cell "")))
1379 (or (org-babel-number-p cell)
1380 (if (or (equal "(" (substring cell 0 1))
1381 (equal "'" (substring cell 0 1))
1382 (equal "`" (substring cell 0 1)))
1383 (eval (read cell))
1384 (progn (set-text-properties 0 (length cell) nil cell) cell)))
1385 cell))
1387 (defun org-babel-number-p (string)
1388 "Return t if STRING represents a number."
1389 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string)
1390 (= (length (substring string (match-beginning 0)
1391 (match-end 0)))
1392 (length string)))
1393 (string-to-number string)))
1395 (defun org-babel-import-elisp-from-file (file-name)
1396 "Read the results located at FILE-NAME into an elisp table. If
1397 the table is trivial, then return it as a scalar."
1398 (let (result)
1399 (save-window-excursion
1400 (with-temp-buffer
1401 (condition-case nil
1402 (progn
1403 (org-table-import file-name nil)
1404 (delete-file file-name)
1405 (setq result (mapcar (lambda (row)
1406 (mapcar #'org-babel-string-read row))
1407 (org-table-to-lisp))))
1408 (error nil)))
1409 (if (null (cdr result)) ;; if result is trivial vector, then scalarize it
1410 (if (consp (car result))
1411 (if (null (cdr (car result)))
1412 (caar result)
1413 result)
1414 (car result))
1415 result))))
1417 (defun org-babel-string-read (cell)
1418 "Strip nested \"s from around strings."
1419 (org-babel-read (or (and (stringp cell)
1420 (string-match "\\\"\\(.+\\)\\\"" cell)
1421 (match-string 1 cell))
1422 cell)))
1424 (defun org-babel-reverse-string (string)
1425 "Return the reverse of STRING."
1426 (apply 'string (reverse (string-to-list string))))
1428 (defun org-babel-chomp (string &optional regexp)
1429 "Remove any trailing space or carriage returns characters from
1430 STRING. Default regexp used is \"[ \f\t\n\r\v]\" but can be
1431 overwritten by specifying a regexp as a second argument."
1432 (let ((regexp (or regexp "[ \f\t\n\r\v]")))
1433 (while (and (> (length string) 0)
1434 (string-match regexp (substring string -1)))
1435 (setq string (substring string 0 -1)))
1436 string))
1438 (defun org-babel-trim (string &optional regexp)
1439 "Like `org-babel-chomp' only it runs on both the front and back
1440 of the string."
1441 (org-babel-chomp (org-babel-reverse-string
1442 (org-babel-chomp (org-babel-reverse-string string) regexp))
1443 regexp))
1445 (defvar org-babel-org-babel-call-process-region-original nil)
1446 (defun org-babel-tramp-handle-call-process-region
1447 (start end program &optional delete buffer display &rest args)
1448 "Use tramp to handle call-process-region. Fixes a bug in
1449 `tramp-handle-call-process-region'."
1450 (if (and (featurep 'tramp) (file-remote-p default-directory))
1451 (let ((tmpfile (tramp-compat-make-temp-file "")))
1452 (write-region start end tmpfile)
1453 (when delete (delete-region start end))
1454 (unwind-protect
1455 ;; (apply 'call-process program tmpfile buffer display args)
1456 ;; bug in tramp
1457 (apply 'process-file program tmpfile buffer display args)
1458 (delete-file tmpfile)))
1459 ;; org-babel-call-process-region-original is the original emacs definition. It
1460 ;; is in scope from the let binding in org-babel-execute-src-block
1461 (apply org-babel-call-process-region-original
1462 start end program delete buffer display args)))
1464 (defun org-babel-maybe-remote-file (file)
1465 "If FILE specifies a remove file, then parse the information on
1466 the remote connection."
1467 (if (file-remote-p default-directory)
1468 (let* ((vec (tramp-dissect-file-name default-directory))
1469 (user (tramp-file-name-user vec))
1470 (host (tramp-file-name-host vec)))
1471 (concat "/" user (when user "@") host ":" file))
1472 file))
1474 (provide 'ob)
1476 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1
1478 ;;; ob.el ends here