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