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