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