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
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/>.
27 ;; See the online documentation for more information
29 ;; http://orgmode.org/worg/org-contrib/babel/
36 (defvar org-babel-call-process-region-original
)
37 (declare-function show-all
"outline" ())
38 (declare-function tramp-compat-make-temp-file
"tramp-compat"
39 (filename &optional dir-flag
))
40 (declare-function tramp-dissect-file-name
"tramp" (name &optional nodefault
))
41 (declare-function tramp-file-name-user
"tramp" (vec))
42 (declare-function tramp-file-name-host
"tramp" (vec))
43 (declare-function with-parsed-tramp-file-name
"tramp" (filename var
&rest body
))
44 (declare-function org-icompleting-read
"org" (&rest args
))
45 (declare-function org-edit-src-code
"org-src"
46 (&optional context code edit-buffer-name quietp
))
47 (declare-function org-edit-src-exit
"org-src" (&optional context
))
48 (declare-function org-open-at-point
"org" (&optional in-emacs reference-buffer
))
49 (declare-function org-save-outline-visibility
"org" (use-markers &rest body
))
50 (declare-function org-outline-overlay-data
"org" (&optional use-markers
))
51 (declare-function org-set-outline-overlay-data
"org" (data))
52 (declare-function org-narrow-to-subtree
"org" ())
53 (declare-function org-entry-get
"org"
54 (pom property
&optional inherit literal-nil
))
55 (declare-function org-make-options-regexp
"org" (kwds &optional extra
))
56 (declare-function org-do-remove-indentation
"org" (&optional n
))
57 (declare-function org-show-context
"org" (&optional key
))
58 (declare-function org-at-table-p
"org" (&optional table-type
))
59 (declare-function org-cycle
"org" (&optional arg
))
60 (declare-function org-uniquify
"org" (list))
61 (declare-function org-current-level
"org" ())
62 (declare-function org-table-import
"org-table" (file arg
))
63 (declare-function org-add-hook
"org-compat"
64 (hook function
&optional append local
))
65 (declare-function org-table-align
"org-table" ())
66 (declare-function org-table-end
"org-table" (&optional table-type
))
67 (declare-function orgtbl-to-generic
"org-table" (table params
))
68 (declare-function orgtbl-to-orgtbl
"org-table" (table params
))
69 (declare-function org-babel-lob-get-info
"ob-lob" nil
)
70 (declare-function org-babel-ref-split-args
"ob-ref" (arg-string))
71 (declare-function org-babel-ref-parse
"ob-ref" (assignment &optional params
))
72 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
73 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
75 (defgroup org-babel nil
76 "Code block evaluation and management in `org-mode' documents."
80 (defcustom org-confirm-babel-evaluate t
81 "Confirm before evaluation.
82 Require confirmation before interactively evaluating code
83 blocks in Org-mode buffers. The default value of this variable
84 is t, meaning confirmation is required for any code block
85 evaluation. This variable can be set to nil to inhibit any
86 future confirmation requests. This variable can also be set to a
87 function which takes two arguments the language of the code block
88 and the body of the code block. Such a function should then
89 return a non-nil value if the user should be prompted for
90 execution or nil if no prompt is required.
92 Warning: Disabling confirmation may result in accidental
93 evaluation of potentially harmful code. It may be advisable
94 remove code block execution from C-c C-c as further protection
95 against accidental code block evaluation. The
96 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
97 remove code block execution from the C-c C-c keybinding."
99 :type
'(choice boolean function
))
100 ;; don't allow this variable to be changed through file settings
101 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
103 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
104 "Remove code block evaluation from the C-c C-c key binding."
108 (defvar org-babel-src-name-regexp
109 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
110 "Regular expression used to match a source name line.")
112 (defvar org-babel-src-name-w-name-regexp
113 (concat org-babel-src-name-regexp
114 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
115 "Regular expression matching source name lines with a name.")
117 (defvar org-babel-src-block-regexp
119 ;; (1) indentation (2) lang
120 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
122 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
123 ;; (4) header arguments
126 "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
127 "Regexp used to identify code blocks.")
129 (defvar org-babel-inline-src-block-regexp
131 ;; (1) replacement target (2) lang
132 "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
133 ;; (3,4) (unused, headers)
134 "\\(\\|\\[\\(.*?\\)\\]\\)"
136 "{\\([^\f\n\r\v]+?\\)}\\)")
137 "Regexp used to identify inline src-blocks.")
139 (defun org-babel-get-header (params key
&optional others
)
140 "Select only header argument of type KEY from a list.
141 Optional argument OTHERS indicates that only the header that do
142 not match KEY should be returned."
145 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
148 (defun org-babel-get-src-block-info (&optional light
)
149 "Get information on the current source block.
151 Optional argument LIGHT does not resolve remote variable
152 references; a process which could likely result in the execution
153 of other code blocks.
156 (language body header-arguments-alist switches name indent)."
157 (let ((case-fold-search t
) head info name indent
)
159 (if (setq head
(org-babel-where-is-src-block-head))
162 (setq info
(org-babel-parse-src-block-match))
163 (setq indent
(car (last info
)))
164 (setq info
(butlast info
))
166 (when (looking-at org-babel-src-name-w-name-regexp
)
167 (setq name
(org-babel-clean-text-properties (match-string 2)))
168 (when (match-string 4)
169 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
170 (org-babel-merge-params
171 (mapcar (lambda (ref) (cons :var ref
))
172 (org-babel-ref-split-args (match-string 4)))
174 ;; inline source block
175 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t
)
176 (looking-at org-babel-inline-src-block-regexp
))
177 (setq info
(org-babel-parse-inline-src-block-match))))
178 ;; resolve variable references
179 (when (and info
(not light
))
181 (let ((params (nth 2 info
)))
182 (append (mapcar (lambda (el) (cons :var
(org-babel-ref-parse (cdr el
))))
183 (org-babel-get-header params
:var
))
184 (org-babel-get-header params
:var
'other
)))))
185 (append info
(list name indent
))))
187 (defun org-babel-confirm-evaluate (info)
188 "Confirm evaluation of the code block INFO.
189 This behavior can be suppressed by setting the value of
190 `org-confirm-babel-evaluate' to nil, in which case all future
191 interactive code block evaluations will proceed without any
192 confirmation from the user.
194 Note disabling confirmation may result in accidental evaluation
195 of potentially harmful code."
196 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
197 (when (assoc :noeval
(nth 2 info
)) "no")))
198 (query (or (equal eval
"query")
199 (if (functionp org-confirm-babel-evaluate
)
200 (funcall org-confirm-babel-evaluate
201 (nth 0 info
) (nth 1 info
))
202 org-confirm-babel-evaluate
))))
203 (if (or (equal eval
"never") (equal eval
"no")
206 (format "Evaluate this%scode on your system? "
207 (if info
(format " %s " (nth 0 info
)) " "))))))
208 (prog1 nil
(message "evaluation aborted"))
212 (defun org-babel-execute-safely-maybe ()
213 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
214 (org-babel-execute-maybe)))
216 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
219 (defun org-babel-execute-maybe ()
221 (or (org-babel-execute-src-block-maybe)
222 (org-babel-lob-execute-maybe)))
224 (defun org-babel-execute-src-block-maybe ()
225 "Conditionally execute a source block.
226 Detect if this is context for a Babel src-block and if so
227 then run `org-babel-execute-src-block'."
229 (let ((info (org-babel-get-src-block-info)))
231 (progn (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
234 (defun org-babel-expand-src-block-maybe ()
235 "Conditionally expand a source block.
236 Detect if this is context for a org-babel src-block and if so
237 then run `org-babel-expand-src-block'."
239 (let ((info (org-babel-get-src-block-info)))
241 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
245 (defun org-babel-load-in-session-maybe ()
246 "Conditionally load a source block in a session.
247 Detect if this is context for a org-babel src-block and if so
248 then run `org-babel-load-in-session'."
250 (let ((info (org-babel-get-src-block-info)))
252 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
255 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
258 (defun org-babel-pop-to-session-maybe ()
259 "Conditionally pop to a session.
260 Detect if this is context for a org-babel src-block and if so
261 then run `org-babel-pop-to-session'."
263 (let ((info (org-babel-get-src-block-info)))
264 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
266 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
268 (defconst org-babel-header-arg-names
269 '(cache cmdline colnames dir exports file noweb results
270 session tangle var eval noeval comments
)
271 "Common header arguments used by org-babel.
272 Note that individual languages may define their own language
273 specific header arguments as well.")
275 (defvar org-babel-default-header-args
276 '((:session .
"none") (:results .
"replace") (:exports .
"code")
277 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
278 "Default arguments to use when evaluating a source block.")
280 (defvar org-babel-default-inline-header-args
281 '((:session .
"none") (:results .
"silent") (:exports .
"results"))
282 "Default arguments to use when evaluating an inline source block.")
284 (defvar org-babel-current-buffer-properties nil
285 "Local cache for buffer properties.")
286 (make-variable-buffer-local 'org-babel-current-buffer-properties
)
288 (defvar org-babel-result-regexp
289 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
290 "Regular expression used to match result lines.
291 If the results are associated with a hash key then the hash will
292 be saved in the second match data.")
294 (defvar org-babel-result-w-name-regexp
295 (concat org-babel-result-regexp
296 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
298 (defvar org-babel-min-lines-for-block-output
10
299 "The minimum number of lines for block output.
300 If number of lines of output is equal to or exceeds this
301 value, the output is placed in a #+begin_example...#+end_example
302 block. Otherwise the output is marked as literal by inserting
303 colons at the starts of the lines. This variable only takes
304 effect if the :results output option is in effect.")
306 (defvar org-babel-noweb-error-langs nil
307 "Languages for which Babel will raise literate programming errors.
308 List of languages for which errors should be raised when the
309 source code block satisfying a noweb reference in this language
310 can not be resolved.")
312 (defvar org-babel-hash-show
4
313 "Number of initial characters to show of a hidden results hash.")
315 (defvar org-babel-after-execute-hook nil
316 "Hook for functions to be called after `org-babel-execute-src-block'")
317 (defun org-babel-named-src-block-regexp-for-name (name)
318 "This generates a regexp used to match a src block named NAME."
319 (concat org-babel-src-name-regexp
(regexp-quote name
) "[ \t\n]*"
320 (substring org-babel-src-block-regexp
1)))
323 (defvar call-process-region
)
326 (defun org-babel-execute-src-block (&optional arg info params
)
327 "Execute the current source code block.
328 Insert the results of execution into the buffer. Source code
329 execution and the collection and formatting of results can be
330 controlled through a variety of header arguments.
332 With prefix argument ARG, force re-execution even if a an
333 existing result cached in the buffer would otherwise have been
336 Optionally supply a value for INFO in the form returned by
337 `org-babel-get-src-block-info'.
339 Optionally supply a value for PARAMS which will be merged with
340 the header arguments specified at the front of the source code
343 (let ((info (or info
(org-babel-get-src-block-info))))
344 (when (org-babel-confirm-evaluate info
)
345 (let* ((lang (nth 0 info
))
348 (sort (org-babel-merge-params (nth 2 info
) params
)
349 (lambda (el1 el2
) (string< (symbol-name (car el1
))
350 (symbol-name (car el2
)))))))
352 (if (and (cdr (assoc :cache params
))
353 (string= "yes" (cdr (assoc :cache params
))))
354 (org-babel-sha1-hash info
)))
355 (old-hash (org-babel-result-hash info
))
356 (body (setf (nth 1 info
)
357 (if (and (cdr (assoc :noweb params
))
358 (string= "yes" (cdr (assoc :noweb params
))))
359 (org-babel-expand-noweb-references info
)
361 (result-params (split-string (or (cdr (assoc :results params
)) "")))
362 (result-type (cond ((member "output" result-params
) 'output
)
363 ((member "value" result-params
) 'value
)
365 (cmd (intern (concat "org-babel-execute:" lang
)))
366 (dir (cdr (assoc :dir params
)))
368 (or (and dir
(file-name-as-directory dir
)) default-directory
))
369 (org-babel-call-process-region-original
370 (if (boundp 'org-babel-call-process-region-original
)
371 org-babel-call-process-region-original
372 (symbol-function 'call-process-region
)))
373 (indent (car (last info
)))
376 (flet ((call-process-region (&rest args
)
377 (apply 'org-babel-tramp-handle-call-process-region args
)))
378 (unless (fboundp cmd
)
379 (error "No org-babel-execute function for %s!" lang
))
380 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
381 (save-excursion ;; return cached result
382 (goto-char (org-babel-where-is-src-block-result nil info
))
383 (end-of-line 1) (forward-char 1)
384 (setq result
(org-babel-read-result))
385 (message (replace-regexp-in-string
386 "%" "%%" (format "%S" result
))) result
)
387 (message "executing %s code block%s..."
389 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
390 (setq result
(funcall cmd body params
))
391 (if (eq result-type
'value
)
392 (setq result
(if (and (or (member "vector" result-params
)
393 (member "table" result-params
))
394 (not (listp result
)))
397 (org-babel-insert-result
398 result result-params info new-hash indent lang
)
399 (run-hooks 'org-babel-after-execute-hook
)
401 (setq call-process-region
'org-babel-call-process-region-original
))))))
403 (defun org-babel-expand-body:generic
(body params
&optional processed-params
)
404 "Expand BODY with PARAMS.
405 Expand a block of code with org-babel according to it's header
406 arguments. This generic implementation of body expansion is
407 called for languages which have not defined their own specific
408 org-babel-expand-body:lang function." body
)
411 (defun org-babel-expand-src-block (&optional arg info params
)
412 "Expand the current source code block.
413 Expand according to the source code block's header
414 arguments and pop open the results in a preview buffer."
416 (let* ((info (or info
(org-babel-get-src-block-info)))
418 (params (setf (nth 2 info
)
419 (sort (org-babel-merge-params (nth 2 info
) params
)
420 (lambda (el1 el2
) (string< (symbol-name (car el1
))
421 (symbol-name (car el2
)))))))
422 (body (setf (nth 1 info
)
423 (if (and (cdr (assoc :noweb params
))
424 (string= "yes" (cdr (assoc :noweb params
))))
425 (org-babel-expand-noweb-references info
) (nth 1 info
))))
426 (cmd (intern (concat "org-babel-expand-body:" lang
)))
427 (expanded (funcall (if (fboundp cmd
) cmd
'org-babel-expand-body
:generic
)
430 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
433 (defun org-babel-load-in-session (&optional arg info
)
434 "Load the body of the current source-code block.
435 Evaluate the header arguments for the source block before
436 entering the session. After loading the body this pops open the
439 (let* ((info (or info
(org-babel-get-src-block-info)))
441 (params (nth 2 info
))
442 (body (setf (nth 1 info
)
443 (if (and (cdr (assoc :noweb params
))
444 (string= "yes" (cdr (assoc :noweb params
))))
445 (org-babel-expand-noweb-references info
)
447 (session (cdr (assoc :session params
)))
448 (dir (cdr (assoc :dir params
)))
450 (or (and dir
(file-name-as-directory dir
)) default-directory
))
451 (cmd (intern (concat "org-babel-load-session:" lang
))))
452 (unless (fboundp cmd
)
453 (error "No org-babel-load-session function for %s!" lang
))
454 (pop-to-buffer (funcall cmd session body params
))
458 (defun org-babel-initiate-session (&optional arg info
)
459 "Initiate session for current code block.
460 If called with a prefix argument then evaluate the header arguments
461 for the code block before entering the session. Copy the body
462 of the code block to the kill ring."
464 (let* ((info (or info
(org-babel-get-src-block-info)))
467 (params (nth 2 info
))
468 (session (cdr (assoc :session params
)))
469 (dir (cdr (assoc :dir params
)))
471 (or (and dir
(file-name-as-directory dir
)) default-directory
))
472 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
473 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
474 (if (and (stringp session
) (string= session
"none"))
475 (error "This block is not using a session!"))
476 (unless (fboundp init-cmd
)
477 (error "No org-babel-initiate-session function for %s!" lang
))
478 (with-temp-buffer (insert (org-babel-trim body
))
479 (copy-region-as-kill (point-min) (point-max)))
481 (unless (fboundp prep-cmd
)
482 (error "No org-babel-prep-session function for %s!" lang
))
483 (funcall prep-cmd session params
))
484 (funcall init-cmd session params
)))
487 (defun org-babel-switch-to-session (&optional arg info
)
488 "Switch to the session of the current code block.
489 Uses `org-babel-initiate-session' to start the session. If called
490 with a prefix argument then this is passed on to
491 `org-babel-initiate-session'."
493 (pop-to-buffer (org-babel-initiate-session arg info
))
496 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
499 (defun org-babel-switch-to-session-with-code (&optional arg info
)
500 "Switch to code buffer and display session."
504 (let ((other-window-buffer (window-buffer (next-window))))
505 (set-window-buffer (next-window) (current-buffer))
506 (set-window-buffer (selected-window) other-window-buffer
))
508 (let ((info (org-babel-get-src-block-info))
509 (org-src-window-setup 'reorganize-frame
))
511 (org-babel-switch-to-session arg info
))
515 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
516 "Evaluate BODY in edit buffer if there is a code block at point.
517 Return t if a code block was found at point, nil otherwise."
518 `(let ((org-src-window-setup 'switch-invisibly
))
519 (when (and (org-babel-where-is-src-block-head)
520 (org-edit-src-code nil nil nil
'quietly
))
521 (unwind-protect (progn ,@body
)
522 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
523 (org-edit-src-exit)))
526 (defun org-babel-do-key-sequence-in-edit-buffer (key)
527 "Read key sequence and execute the command in edit buffer.
528 Enter a key sequence to be executed in the language major-mode
529 edit buffer. For example, TAB will alter the contents of the
530 Org-mode code block according to the effect of TAB in the
531 language major-mode buffer. For languages that support
532 interactive sessions, this can be used to send code from the Org
533 buffer to the session for evaluation using the native major-mode
534 evaluation mechanisms."
535 (interactive "kEnter key-sequence to execute in edit buffer: ")
536 (org-babel-do-in-edit-buffer
538 (key-binding (or key
(read-key-sequence nil
))))))
540 (defvar org-bracket-link-regexp
)
542 (defun org-babel-open-src-block-result (&optional re-run
)
543 "If `point' is on a src block then open the results of the
544 source code block, otherwise return nil. With optional prefix
545 argument RE-RUN the source-code block is evaluated even if
546 results already exist."
548 (when (org-babel-get-src-block-info)
550 ;; go to the results, if there aren't any then run the block
551 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
552 (progn (org-babel-execute-src-block)
553 (org-babel-where-is-src-block-result))))
555 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
557 (if (looking-at org-bracket-link-regexp
)
560 (let ((results (org-babel-read-result)))
561 (flet ((echo-res (result)
562 (if (stringp result
) result
(format "%S" result
))))
563 (pop-to-buffer (get-buffer-create "org-babel-results"))
564 (delete-region (point-min) (point-max))
567 (insert (orgtbl-to-generic results
'(:sep
"\t" :fmt echo-res
)))
569 (insert (echo-res results
))))))
573 (defun org-babel-execute-buffer (&optional arg
)
574 "Execute source code blocks in a buffer.
575 Call `org-babel-execute-src-block' on every source block in
578 (org-save-outline-visibility t
579 (org-babel-map-src-blocks nil
580 (org-babel-execute-src-block arg
))))
583 (defun org-babel-execute-subtree (&optional arg
)
584 "Execute source code blocks in a subtree.
585 Call `org-babel-execute-src-block' on every source block in
586 the current subtree."
590 (org-narrow-to-subtree)
591 (org-babel-execute-buffer arg
)
595 (defun org-babel-sha1-hash (&optional info
)
596 "Generate an sha1 hash based on the value of info."
598 (let* ((info (or info
(org-babel-get-src-block-info)))
603 (if (stringp (cdr arg
))
606 (sort (split-string (cdr arg
)) #'string
<) " ")
610 (when (interactive-p) (message hash
))
613 (defun org-babel-result-hash (&optional info
)
614 "Return the in-buffer hash associated with INFO."
615 (org-babel-where-is-src-block-result nil info
)
616 (org-babel-clean-text-properties (match-string 3)))
618 (defun org-babel-hide-hash ()
619 "Hide the hash in the current results line.
620 Only the initial `org-babel-hash-show' characters of the hash
621 will remain visible."
622 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
624 (when (and (re-search-forward org-babel-result-regexp nil t
)
626 (let* ((start (match-beginning 3))
627 (hide-start (+ org-babel-hash-show start
))
629 (hash (match-string 3))
631 (setq ov1
(make-overlay start hide-start
))
632 (setq ov2
(make-overlay hide-start end
))
633 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
634 (overlay-put ov1
'babel-hash hash
)))))
636 (defun org-babel-hide-all-hashes ()
637 "Hide the hash in the current buffer.
638 Only the initial `org-babel-hash-show' characters of each hash
639 will remain visible. This function should be called as part of
640 the `org-mode-hook'."
642 (while (re-search-forward org-babel-result-regexp nil t
)
643 (goto-char (match-beginning 0))
644 (org-babel-hide-hash)
645 (goto-char (match-end 0)))))
646 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
648 (defun org-babel-hash-at-point (&optional point
)
649 "Return the value of the hash at POINT.
650 The hash is also added as the last element of the kill ring.
651 This can be called with C-c C-c."
653 (let ((hash (car (delq nil
(mapcar
654 (lambda (ol) (overlay-get ol
'babel-hash
))
655 (overlays-at (or point
(point))))))))
656 (when hash
(kill-new hash
) (message hash
))))
657 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
659 (defun org-babel-result-hide-spec ()
660 "Hide portions of results lines.
661 Add `org-babel-hide-result' as an invisibility spec for hiding
662 portions of results lines."
663 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
664 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
666 (defvar org-babel-hide-result-overlays nil
667 "Overlays hiding results.")
669 (defun org-babel-result-hide-all ()
670 "Fold all results in the current buffer."
672 (org-babel-show-result-all)
674 (while (re-search-forward org-babel-result-regexp nil t
)
675 (save-excursion (goto-char (match-beginning 0))
676 (org-babel-hide-result-toggle-maybe)))))
678 (defun org-babel-show-result-all ()
679 "Unfold all results in the current buffer."
680 (mapc 'delete-overlay org-babel-hide-result-overlays
)
681 (setq org-babel-hide-result-overlays nil
))
684 (defun org-babel-hide-result-toggle-maybe ()
685 "Toggle visibility of result at point."
687 (let ((case-fold-search t
))
689 (beginning-of-line 1)
690 (looking-at org-babel-result-regexp
))
691 (progn (org-babel-hide-result-toggle)
692 t
) ;; to signal that we took action
693 nil
))) ;; to signal that we did not
695 (defun org-babel-hide-result-toggle (&optional force
)
696 "Toggle the visibility of the current result."
700 (if (re-search-forward org-babel-result-regexp nil t
)
701 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
702 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
704 (if (memq t
(mapcar (lambda (overlay)
705 (eq (overlay-get overlay
'invisible
)
706 'org-babel-hide-result
))
707 (overlays-at start
)))
708 (if (or (not force
) (eq force
'off
))
710 (when (member ov org-babel-hide-result-overlays
)
711 (setq org-babel-hide-result-overlays
712 (delq ov org-babel-hide-result-overlays
)))
713 (when (eq (overlay-get ov
'invisible
)
714 'org-babel-hide-result
)
715 (delete-overlay ov
)))
716 (overlays-at start
)))
717 (setq ov
(make-overlay start end
))
718 (overlay-put ov
'invisible
'org-babel-hide-result
)
719 ;; make the block accessible to isearch
721 ov
'isearch-open-invisible
723 (when (member ov org-babel-hide-result-overlays
)
724 (setq org-babel-hide-result-overlays
725 (delq ov org-babel-hide-result-overlays
)))
726 (when (eq (overlay-get ov
'invisible
)
727 'org-babel-hide-result
)
728 (delete-overlay ov
))))
729 (push ov org-babel-hide-result-overlays
)))
730 (error "Not looking at a result line"))))
732 ;; org-tab-after-check-for-cycling-hook
733 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
734 ;; Remove overlays when changing major mode
735 (add-hook 'org-mode-hook
736 (lambda () (org-add-hook 'change-major-mode-hook
737 'org-babel-show-result-all
'append
'local
)))
739 (defmacro org-babel-map-src-blocks
(file &rest body
)
740 "Evaluate BODY forms on each source-block in FILE.
741 If FILE is nil evaluate BODY forms on source blocks in current
742 buffer. During evaluation of BODY the following local variables
743 are set relative to the currently matched code block.
745 full-block ------- string holding the entirety of the code block
746 beg-block -------- point at the beginning of the code block
747 end-block -------- point at the end of the matched code block
748 lang ------------- string holding the language of the code block
749 beg-lang --------- point at the beginning of the lang
750 end-lang --------- point at the end of the lang
751 switches --------- string holding the switches
752 beg-switches ----- point at the beginning of the switches
753 end-switches ----- point at the end of the switches
754 header-args ------ string holding the header-args
755 beg-header-args -- point at the beginning of the header-args
756 end-header-args -- point at the end of the header-args
757 body ------------- string holding the body of the code block
758 beg-body --------- point at the beginning of the body
759 end-body --------- point at the end of the body"
761 `(let ((visited-p (or (null ,file
)
762 (get-file-buffer (expand-file-name ,file
))))
763 (point (point)) to-be-removed
)
764 (save-window-excursion
765 (when ,file
(find-file ,file
))
766 (setq to-be-removed
(current-buffer))
767 (goto-char (point-min))
768 (while (re-search-forward org-babel-src-block-regexp nil t
)
769 (goto-char (match-beginning 0))
770 (let ((full-block (match-string 0))
771 (beg-block (match-beginning 0))
772 (end-block (match-end 0))
773 (lang (match-string 2))
774 (beg-lang (match-beginning 2))
775 (end-lang (match-end 2))
776 (switches (match-string 3))
777 (beg-switches (match-beginning 3))
778 (end-switches (match-end 3))
779 (header-args (match-string 4))
780 (beg-header-args (match-beginning 4))
781 (end-header-args (match-end 4))
782 (body (match-string 5))
783 (beg-body (match-beginning 5))
784 (end-body (match-end 5)))
785 (save-match-data ,@body
))
786 (goto-char (match-end 0))))
788 (kill-buffer to-be-removed
))
791 (defvar org-file-properties
)
792 (defun org-babel-params-from-properties (&optional lang
)
793 "Retrieve parameters specified as properties.
794 Return an association list of any source block params which
795 may be specified in the properties of the current outline entry."
802 (or (condition-case nil
803 (org-entry-get (point) header-arg t
)
805 (cdr (assoc header-arg org-file-properties
))))
806 (cons (intern (concat ":" header-arg
))
807 (org-babel-read val
))))
811 org-babel-header-arg-names
813 (setq sym
(intern (concat "org-babel-header-arg-names:" lang
)))
814 (and (boundp sym
) (eval sym
))))))))))
816 (defun org-babel-params-from-buffer ()
817 "Retrieve per-buffer parameters.
818 Return an association list of any source block params which
819 may be specified at the top of the current buffer."
820 (or org-babel-current-buffer-properties
821 (setq org-babel-current-buffer-properties
826 (goto-char (point-min))
827 (when (re-search-forward
828 (org-make-options-regexp (list "BABEL")) nil t
)
829 (org-babel-parse-header-arguments
830 (org-match-string-no-properties 2)))))))))
832 (defvar org-src-preserve-indentation
)
833 (defun org-babel-parse-src-block-match ()
834 "Parse the results from a match of the `org-babel-src-block-regexp'."
835 (let* ((block-indentation (length (match-string 1)))
836 (lang (org-babel-clean-text-properties (match-string 2)))
837 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
838 (switches (match-string 3))
839 (body (org-babel-clean-text-properties (match-string 5)))
840 (preserve-indentation (or org-src-preserve-indentation
841 (string-match "-i\\>" switches
))))
843 ;; get block body less properties, protective commas, and indentation
846 (insert (org-babel-strip-protective-commas body
))
847 (unless preserve-indentation
(org-do-remove-indentation))
849 (org-babel-merge-params
850 org-babel-default-header-args
851 (org-babel-params-from-buffer)
852 (org-babel-params-from-properties lang
)
853 (if (boundp lang-headers
) (eval lang-headers
) nil
)
854 (org-babel-parse-header-arguments
855 (org-babel-clean-text-properties (or (match-string 4) ""))))
859 (defun org-babel-parse-inline-src-block-match ()
860 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
861 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
862 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
864 (org-babel-strip-protective-commas
865 (org-babel-clean-text-properties (match-string 5)))
866 (org-babel-merge-params
867 org-babel-default-inline-header-args
868 (org-babel-params-from-buffer)
869 (org-babel-params-from-properties lang
)
870 (if (boundp lang-headers
) (eval lang-headers
) nil
)
871 (org-babel-parse-header-arguments
872 (org-babel-clean-text-properties (or (match-string 4) "")))))))
874 (defun org-babel-parse-header-arguments (arg-string)
875 "Parse a string of header arguments returning an alist."
876 (if (> (length arg-string
) 0)
881 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
883 (cons (intern (concat ":" (match-string 1 arg
)))
884 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
885 (cons (intern (concat ":" arg
)) nil
)))
886 (split-string (concat " " arg-string
) "[ \f\t\n\r\v]+:" t
)))))
888 (defun org-babel-process-params (params)
889 "Parse params and resolve references.
891 Return a list (session vars result-params result-type colnames rownames)."
892 (let* ((session (cdr (assoc :session params
)))
893 (vars-and-names (org-babel-disassemble-tables
894 (mapcar #'cdr
(org-babel-get-header params
:var
))
895 (cdr (assoc :hlines params
))
896 (cdr (assoc :colnames params
))
897 (cdr (assoc :rownames params
))))
898 (vars (car vars-and-names
))
899 (colnames (cadr vars-and-names
))
900 (rownames (caddr vars-and-names
))
901 (result-params (split-string (or (cdr (assoc :results params
)) "")))
902 (result-type (cond ((member "output" result-params
) 'output
)
903 ((member "value" result-params
) 'value
)
905 (list session vars result-params result-type colnames rownames
)))
907 ;; row and column names
908 (defun org-babel-del-hlines (table)
909 "Remove all 'hlines from TABLE."
910 (remove 'hline table
))
912 (defun org-babel-get-colnames (table)
913 "Return the column names of TABLE.
914 Return a cons cell, the `car' of which contains the TABLE less
915 colnames, and the `cdr' of which contains a list of the column
917 (if (equal 'hline
(nth 1 table
))
918 (cons (cddr table
) (car table
))
919 (cons (cdr table
) (car table
))))
921 (defun org-babel-get-rownames (table)
922 "Return the row names of TABLE.
923 Return a cons cell, the `car' of which contains the TABLE less
924 colnames, and the `cdr' of which contains a list of the column
925 names. Note: this function removes any hlines in TABLE."
926 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
927 (let* ((width (apply 'max
928 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
929 (table (trans (mapcar (lambda (row)
930 (if (not (equal row
'hline
))
934 (setq row
(cons 'hline row
)))
937 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
939 (remove 'hline
(car table
))))))
941 (defun org-babel-put-colnames (table colnames
)
942 "Add COLNAMES to TABLE if they exist."
943 (if colnames
(apply 'list colnames
'hline table
) table
))
945 (defun org-babel-put-rownames (table rownames
)
946 "Add ROWNAMES to TABLE if they exist."
948 (mapcar (lambda (row)
950 (cons (or (pop rownames
) "") row
)
954 (defun org-babel-pick-name (names selector
)
955 "Select one out of an alist of row or column names.
956 SELECTOR can be either a list of names in which case those names
957 will be returned directly, or an index into the list NAMES in
958 which case the indexed names will be return."
962 (if (and selector
(symbolp selector
) (not (equal t selector
)))
963 (cdr (assoc selector names
))
964 (if (integerp selector
)
965 (nth (- selector
1) names
)
966 (cdr (car (last names
))))))))
968 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
969 "Parse tables for further processing.
970 Process the variables in VARS according to the HLINES,
971 ROWNAMES and COLNAMES header arguments. Return a list consisting
972 of the vars, cnames and rnames."
977 (when (listp (cdr var
))
978 (when (and (not (equal colnames
"no"))
979 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
980 (not (member 'hline
(cddr (cdr var
)))))))
981 (let ((both (org-babel-get-colnames (cdr var
))))
982 (setq cnames
(cons (cons (car var
) (cdr both
))
984 (setq var
(cons (car var
) (car both
)))))
985 (when (and rownames
(not (equal rownames
"no")))
986 (let ((both (org-babel-get-rownames (cdr var
))))
987 (setq rnames
(cons (cons (car var
) (cdr both
))
989 (setq var
(cons (car var
) (car both
)))))
990 (when (and hlines
(not (equal hlines
"yes")))
991 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
996 (defun org-babel-reassemble-table (table colnames rownames
)
997 "Add column and row names to a table.
998 Given a TABLE and set of COLNAMES and ROWNAMES add the names
999 to the table for reinsertion to org-mode."
1002 (if (and colnames
(listp (car table
)) (= (length (car table
))
1004 (org-babel-put-colnames table colnames
) table
))
1005 (if (and rownames
(= (length table
) (length rownames
)))
1006 (org-babel-put-rownames table rownames
) table
))
1009 (defun org-babel-where-is-src-block-head ()
1010 "Find where the current source block begins.
1011 Return the point at the beginning of the current source
1012 block. Specifically at the beginning of the #+BEGIN_SRC line.
1013 If the point is not on a source block then return nil."
1014 (let ((initial (point)) top bottom
)
1016 (save-excursion ;; on a source name line
1017 (beginning-of-line 1)
1018 (and (looking-at org-babel-src-name-regexp
) (forward-line 1)
1019 (looking-at org-babel-src-block-regexp
)
1021 (save-excursion ;; on a #+begin_src line
1022 (beginning-of-line 1)
1023 (and (looking-at org-babel-src-block-regexp
)
1025 (save-excursion ;; inside a src block
1027 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1028 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1029 (< top initial
) (< initial bottom
)
1030 (progn (goto-char top
) (beginning-of-line 1)
1031 (looking-at org-babel-src-block-regexp
))
1035 (defun org-babel-goto-src-block-head ()
1036 "Go to the beginning of the current code block."
1039 (if head
(goto-char head
) (error "not currently in a code block")))
1040 (org-babel-where-is-src-block-head)))
1043 (defun org-babel-goto-named-src-block (name)
1044 "Go to a named source-code block."
1046 (let ((completion-ignore-case t
))
1047 (list (org-icompleting-read "source-block name: "
1048 (org-babel-src-block-names) nil t
))))
1049 (let ((point (org-babel-find-named-block name
)))
1051 ;; taken from `org-open-at-point'
1052 (progn (goto-char point
) (org-show-context))
1053 (message "source-code block '%s' not found in this buffer" name
))))
1055 (defun org-babel-find-named-block (name)
1056 "Find a named source-code block.
1057 Return the location of the source block identified by source
1058 NAME, or nil if no such block exists. Set match data according to
1059 org-babel-named-src-block-regexp."
1061 (let ((case-fold-search t
)
1062 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1063 (goto-char (point-min))
1064 (when (or (re-search-forward regexp nil t
)
1065 (re-search-backward regexp nil t
))
1066 (match-beginning 0)))))
1068 (defun org-babel-src-block-names (&optional file
)
1069 "Returns the names of source blocks in FILE or the current buffer."
1071 (when file
(find-file file
)) (goto-char (point-min))
1073 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1074 (setq names
(cons (org-babel-clean-text-properties (match-string 2))
1079 (defun org-babel-goto-named-result (name)
1080 "Go to a named result."
1082 (let ((completion-ignore-case t
))
1083 (list (org-icompleting-read "source-block name: "
1084 (org-babel-result-names) nil t
))))
1085 (let ((point (org-babel-find-named-result name
)))
1087 ;; taken from `org-open-at-point'
1088 (progn (goto-char point
) (org-show-context))
1089 (message "result '%s' not found in this buffer" name
))))
1091 (defun org-babel-find-named-result (name)
1092 "Find a named result.
1093 Return the location of the result named NAME in the current
1094 buffer or nil if no such result exists."
1096 (goto-char (point-min))
1097 (when (re-search-forward
1098 (concat org-babel-result-regexp
1099 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1100 (beginning-of-line 0) (point))))
1102 (defun org-babel-result-names (&optional file
)
1103 "Returns the names of results in FILE or the current buffer."
1105 (when file
(find-file file
)) (goto-char (point-min))
1107 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1108 (setq names
(cons (org-babel-clean-text-properties (match-string 4))
1113 (defun org-babel-next-src-block (&optional arg
)
1114 "Jump to the next source block.
1115 With optional prefix argument ARG, jump forward ARG many source blocks."
1117 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1119 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1120 (error (error "No further code blocks")))
1121 (goto-char (match-beginning 0)) (org-show-context))
1124 (defun org-babel-previous-src-block (&optional arg
)
1125 "Jump to the previous source block.
1126 With optional prefix argument ARG, jump backward ARG many source blocks."
1129 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1130 (error (error "No previous code blocks")))
1131 (goto-char (match-beginning 0)) (org-show-context))
1133 (defvar org-babel-load-languages
)
1136 (defun org-babel-mark-block ()
1137 "Mark current src block"
1143 (looking-at org-babel-src-block-regexp
))
1144 (push-mark (match-end 5) nil t
)
1145 (goto-char (match-beginning 5))))
1146 (org-babel-where-is-src-block-head)))
1148 (defun org-babel-demarcate-block (&optional arg
)
1149 "Wrap or split the code in the region or on the point.
1150 When called from inside of a code block the current block is
1151 split. When called from outside of a code block a new code block
1152 is created. In both cases if the region is demarcated and if the
1153 region is not active then the point is demarcated."
1155 (let ((info (org-babel-get-src-block-info))
1156 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1162 (let ((lang (nth 0 info
))
1163 (indent (make-string (nth 6 info
) ?
)))
1164 (when (string-match "^[[:space:]]*$"
1165 (buffer-substring (point-at-bol)
1167 (delete-region (point-at-bol) (point-at-eol)))
1168 (insert (concat (if (looking-at "^") "" "\n")
1169 indent
"#+end_src\n"
1170 (if arg stars indent
) "\n"
1171 indent
"#+begin_src " lang
1172 (if (looking-at "[\n\r]") "" "\n")))))
1173 (move-end-of-line 2))
1174 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1175 (let ((start (point))
1176 (lang (org-icompleting-read "Lang: "
1177 (mapcar (lambda (el) (symbol-name (car el
)))
1178 org-babel-load-languages
)))
1179 (body (delete-and-extract-region
1180 (if (region-active-p) (mark) (point)) (point))))
1181 (insert (concat (if (looking-at "^") "" "\n")
1182 (if arg
(concat stars
"\n") "")
1183 "#+begin_src " lang
"\n"
1185 (if (or (= (length body
) 0)
1186 (string-match "[\r\n]$" body
)) "" "\n")
1188 (goto-char start
) (move-end-of-line 1)))))
1190 (defvar org-babel-lob-one-liner-regexp
)
1191 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1192 "Find where the current source block results begin.
1193 Return the point at the beginning of the result of the current
1194 source block. Specifically at the beginning of the results line.
1195 If no result exists for this block then create a results line
1196 following the source block."
1198 (let* ((on-lob-line (progn (beginning-of-line 1)
1199 (looking-at org-babel-lob-one-liner-regexp
)))
1200 (name (if on-lob-line
1201 (nth 0 (org-babel-lob-get-info))
1202 (nth 4 (or info
(org-babel-get-src-block-info)))))
1203 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1205 (when head
(goto-char head
))
1207 found
;; was there a result (before we potentially insert one)
1211 ;; - return t if it is found, else return nil
1212 ;; - if it does not need to be rebuilt, then don't set end
1213 ;; - if it does need to be rebuilt then do set end
1214 name
(setq beg
(org-babel-find-named-result name
))
1216 (when (and hash
(not (string= hash
(match-string 3))))
1217 (goto-char beg
) (setq end beg
) ;; beginning of result
1219 (delete-region end
(org-babel-result-end)) nil
)))
1222 ;; - return t if it is found, else return nil
1223 ;; - if it is found, and the hash doesn't match, delete and set end
1224 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1225 (progn (end-of-line 1)
1226 (if (eobp) (insert "\n") (forward-char 1))
1229 (progn ;; unnamed results line already exists
1230 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1231 (beginning-of-line 1)
1233 (concat org-babel-result-regexp
"\n")))
1235 ;; must remove and rebuild if hash!=old-hash
1236 (if (and hash
(not (string= hash
(match-string 3))))
1240 end
(org-babel-result-end)))
1241 (setq end nil
)))))))))
1242 (if (and insert end
)
1246 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1251 (org-number-sequence 1 indent
) "")
1254 (when hash
(concat "["hash
"]"))
1256 (when name
(concat " " name
)) "\n"))
1257 (unless beg
(insert "\n") (backward-char))
1258 (beginning-of-line 0)
1259 (if hash
(org-babel-hide-hash))
1263 (defvar org-block-regexp
)
1264 (defun org-babel-read-result ()
1265 "Read the result at `point' into emacs-lisp."
1266 (let ((case-fold-search t
) result-string
)
1268 ((org-at-table-p) (org-babel-read-table))
1269 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1270 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1271 ((looking-at "^[ \t]*: ")
1274 (mapconcat (lambda (line)
1275 (if (and (> (length line
) 1)
1276 (string-match "^[ \t]*: \\(.+\\)" line
))
1277 (match-string 1 line
)
1281 (point) (org-babel-result-end)) "[\r\n]+")
1283 (or (org-babel-number-p result-string
) result-string
))
1284 ((looking-at org-babel-result-regexp
)
1285 (save-excursion (forward-line 1) (org-babel-read-result))))))
1287 (defun org-babel-read-table ()
1288 "Read the table at `point' into emacs-lisp."
1289 (mapcar (lambda (row)
1290 (if (and (symbolp row
) (equal row
'hline
)) row
1291 (mapcar #'org-babel-read row
)))
1292 (org-table-to-lisp)))
1294 (defvar org-link-types-re
)
1295 (defun org-babel-read-link ()
1296 "Read the link at `point' into emacs-lisp.
1297 If the path of the link is a file path it is expanded using
1298 `expand-file-name'."
1299 (let* ((case-fold-search t
)
1300 (raw (and (looking-at org-bracket-link-regexp
)
1301 (org-babel-clean-text-properties (match-string 1))))
1302 (type (and (string-match org-link-types-re raw
)
1303 (match-string 1 raw
))))
1305 ((not type
) (expand-file-name raw
))
1306 ((string= type
"file")
1307 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1308 (expand-file-name (match-string 2 raw
))))
1311 (defun org-babel-insert-result
1312 (result &optional result-params info hash indent lang
)
1313 "Insert RESULT into the current buffer.
1314 By default RESULT is inserted after the end of the
1315 current source block. With optional argument RESULT-PARAMS
1316 controls insertion of results in the org-mode file.
1317 RESULT-PARAMS can take the following values...
1319 replace - (default option) insert results after the source block
1320 replacing any previously inserted results
1322 silent -- no results are inserted
1324 file ---- the results are interpreted as a file path, and are
1325 inserted into the buffer using the Org-mode file syntax
1327 raw ----- results are added directly to the org-mode file. This
1328 is a good option if you code block will output org-mode
1331 org ----- similar in effect to raw, only the results are wrapped
1332 in an org code block. Similar to the raw option, on
1333 export the results will be interpreted as org-formatted
1334 text, however by wrapping the results in an org code
1335 block they can be replaced upon re-execution of the
1338 html ---- results are added inside of a #+BEGIN_HTML block. This
1339 is a good option if you code block will output html
1342 latex --- results are added inside of a #+BEGIN_LATEX block.
1343 This is a good option if you code block will output
1344 latex formatted text.
1346 code ---- the results are extracted in the syntax of the source
1347 code of the language being evaluated and are added
1348 inside of a #+BEGIN_SRC block with the source-code
1349 language set appropriately. Note this relies on the
1350 optional LANG argument."
1351 (if (stringp result
)
1353 (setq result
(org-babel-clean-text-properties result
))
1354 (when (member "file" result-params
)
1355 (setq result
(org-babel-result-to-file result
))))
1356 (unless (listp result
) (setq result
(format "%S" result
))))
1357 (if (and result-params
(member "silent" result-params
))
1359 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1361 (when (and (stringp result
) ;; ensure results end in a newline
1362 (> (length result
) 0)
1363 (not (or (string-equal (substring result -
1) "\n")
1364 (string-equal (substring result -
1) "\r"))))
1365 (setq result
(concat result
"\n")))
1367 (let ((existing-result (org-babel-where-is-src-block-result
1368 t info hash indent
))
1370 (cdr (assoc :results_switches
(nth 2 info
))))
1372 (if (not existing-result
)
1374 (goto-char existing-result
)
1376 (re-search-forward "#" nil t
)
1377 (setq indent
(- (current-column) 1)))
1381 ((member "replace" result-params
)
1382 (delete-region (point) (org-babel-result-end)))
1383 ((member "append" result-params
)
1384 (goto-char (org-babel-result-end)) (setq beg
(point)))
1385 ((member "prepend" result-params
) ;; already there
1387 (setq results-switches
1388 (if results-switches
(concat " " results-switches
) ""))
1390 ;; do nothing for an empty result
1391 ((= (length result
) 0))
1392 ;; assume the result is a table if it's not a string
1393 ((not (stringp result
))
1394 (insert (concat (orgtbl-to-orgtbl
1395 (if (or (eq 'hline
(car result
))
1396 (and (listp (car result
))
1397 (listp (cdr (car result
)))))
1398 result
(list result
))
1399 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1400 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1401 ((member "file" result-params
)
1403 ((member "html" result-params
)
1404 (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
1405 results-switches result
)))
1406 ((member "latex" result-params
)
1407 (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
1408 results-switches result
)))
1409 ((member "code" result-params
)
1410 (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
1411 (or lang
"none") results-switches result
)))
1412 ((member "org" result-params
)
1413 (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result
)))
1414 ((member "raw" result-params
)
1415 (save-excursion (insert result
)) (if (org-at-table-p) (org-cycle)))
1417 (org-babel-examplize-region
1418 (point) (progn (insert result
) (point)) results-switches
)))
1419 ;; possibly indent the results to match the #+results line
1420 (setq end
(if (listp result
) (org-table-end) (point)))
1421 (when (and indent
(> indent
0)
1422 ;; in this case `table-align' does the work for us
1423 (not (and (listp result
)
1424 (member "append" result-params
))))
1425 (indent-rigidly beg end indent
))))
1426 (if (= (length result
) 0)
1427 (if (member "value" result-params
)
1428 (message "No result returned by source block")
1429 (message "Source block produced no output"))
1430 (message "finished"))))
1432 (defun org-babel-remove-result (&optional info
)
1433 "Remove the result of the current source block."
1435 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1438 (goto-char location
) (setq start
(point)) (forward-line 1)
1439 (delete-region start
(org-babel-result-end))))))
1441 (defun org-babel-result-end ()
1442 "Return the point at the end of the current set of results"
1444 (if (org-at-table-p)
1445 (progn (goto-char (org-table-end)) (point))
1446 (let ((case-fold-search t
))
1448 ((looking-at "[ \t]*#\\+begin_latex")
1449 (re-search-forward "[ \t]*#\\+end_latex" nil t
)
1451 ((looking-at "[ \t]*#\\+begin_html")
1452 (re-search-forward "[ \t]*#\\+end_html" nil t
)
1454 ((looking-at "[ \t]*#\\+begin_example")
1455 (re-search-forward "[ \t]*#\\+end_example" nil t
)
1457 ((looking-at "[ \t]*#\\+begin_src")
1458 (re-search-forward "[ \t]*#\\+end_src" nil t
)
1460 (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1461 (forward-line 1))))))
1464 (defun org-babel-result-to-file (result)
1465 "Convert RESULT into an `org-mode' link.
1466 If the `default-directory' is different from the containing
1467 file's directory then expand relative links."
1470 (if (and default-directory
1472 (not (string= (expand-file-name default-directory
)
1474 (file-name-directory buffer-file-name
)))))
1475 (expand-file-name result default-directory
)
1478 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1479 "Comment out region using the ': ' org example quote."
1481 (let ((size (count-lines beg end
)))
1484 (error (concat "This should not be impossible:"
1485 "a newline was appended to result if missing")))
1486 ((< size org-babel-min-lines-for-block-output
)
1489 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1492 (insert (if results-switches
1493 (format "#+begin_example%s\n" results-switches
)
1494 "#+begin_example\n"))
1495 (forward-char (- end beg
))
1496 (insert "#+end_example\n"))))))
1498 (defun org-babel-merge-params (&rest plists
)
1499 "Combine all parameter association lists in PLISTS.
1500 Later elements of PLISTS override the values of previous element.
1501 This takes into account some special considerations for certain
1502 parameters when merging lists."
1503 (let ((results-exclusive-groups
1504 '(("file" "vector" "table" "scalar" "raw" "org"
1505 "html" "latex" "code" "pp")
1506 ("replace" "silent" "append" "prepend")
1507 ("output" "value")))
1508 (exports-exclusive-groups
1509 '(("code" "results" "both" "none")))
1510 params results exports tangle noweb cache vars shebang comments
)
1511 (flet ((e-merge (exclusive-groups &rest result-params
)
1512 ;; maintain exclusivity of mutually exclusive parameters
1514 (mapc (lambda (new-params)
1515 (mapc (lambda (new-param)
1516 (mapc (lambda (exclusive-group)
1517 (when (member new-param exclusive-group
)
1518 (mapcar (lambda (excluded-param)
1525 (setq output
(org-uniquify
1526 (cons new-param output
))))
1530 (mapc (lambda (plist)
1531 (mapc (lambda (pair)
1534 (let ((name (if (listp (cdr pair
))
1537 ".+=[ \t]*\\([^\f\n\r\v]+\\)$"
1539 (intern (match-string 1)))))
1540 (unless (member name
(mapcar #'car vars
))
1541 (setq vars
(cons (cons name
(cdr pair
)) vars
)))))
1544 (e-merge results-exclusive-groups
1545 results
(split-string (cdr pair
)))))
1548 (setq results
(e-merge results-exclusive-groups
1550 (unless (or (member "both" exports
)
1551 (member "none" exports
)
1552 (member "code" exports
))
1553 (setq exports
(e-merge exports-exclusive-groups
1554 exports
'("results"))))
1557 (assq-delete-all (car pair
) params
)))))
1560 (e-merge exports-exclusive-groups
1561 exports
(split-string (cdr pair
)))))
1562 (:tangle
;; take the latest -- always overwrite
1563 (setq tangle
(or (list (cdr pair
)) tangle
)))
1566 (e-merge '(("yes" "no")) noweb
1567 (split-string (or (cdr pair
) "")))))
1570 (e-merge '(("yes" "no")) cache
1571 (split-string (or (cdr pair
) "")))))
1572 (:shebang
;; take the latest -- always overwrite
1573 (setq shebang
(or (list (cdr pair
)) shebang
)))
1576 (e-merge '(("yes" "no")) comments
1577 (split-string (or (cdr pair
) "")))))
1578 (t ;; replace: this covers e.g. :session
1581 (assq-delete-all (car pair
) params
))))))
1584 (while vars
(setq params
(cons (cons :var
(cdr (pop vars
))) params
)))
1585 (cons (cons :comments
(mapconcat 'identity comments
" "))
1586 (cons (cons :shebang
(mapconcat 'identity shebang
" "))
1587 (cons (cons :cache
(mapconcat 'identity cache
" "))
1588 (cons (cons :noweb
(mapconcat 'identity noweb
" "))
1589 (cons (cons :tangle
(mapconcat 'identity tangle
" "))
1590 (cons (cons :exports
1591 (mapconcat 'identity exports
" "))
1594 (mapconcat 'identity results
" "))
1597 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1598 "Expand Noweb references in the body of the current source code block.
1600 For example the following reference would be replaced with the
1601 body of the source-code block named 'example-block'.
1605 Note that any text preceding the <<foo>> construct on a line will
1606 be interposed between the lines of the replacement text. So for
1607 example if <<foo>> is placed behind a comment, then the entire
1608 replacement text will also be commented.
1610 This function must be called from inside of the buffer containing
1611 the source-code block which holds BODY.
1613 In addition the following syntax can be used to insert the
1614 results of evaluating the source-code block named 'example-block'.
1618 Any optional arguments can be passed to example-block by placing
1619 the arguments inside the parenthesis following the convention
1620 defined by `org-babel-lob'. For example
1622 <<example-block(a=9)>>
1624 would set the value of argument \"a\" equal to \"9\". Note that
1625 these arguments are not evaluated in the current source-code
1626 block but are passed literally to the \"example-block\"."
1627 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
1628 (info (or info
(org-babel-get-src-block-info)))
1631 (new-body "") index source-name evaluate prefix
)
1632 (flet ((nb-add (text)
1633 (setq new-body
(concat new-body text
))))
1635 (insert body
) (goto-char (point-min))
1636 (setq index
(point))
1637 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
1638 (save-match-data (setf source-name
(match-string 1)))
1639 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
1642 (buffer-substring (match-beginning 0)
1644 (beginning-of-line 1) (point)))))
1645 ;; add interval to new-body (removing noweb reference)
1646 (goto-char (match-beginning 0))
1647 (nb-add (buffer-substring index
(point)))
1648 (goto-char (match-end 0))
1649 (setq index
(point))
1650 (nb-add (with-current-buffer parent-buffer
1651 (mapconcat ;; interpose PREFIX between every line
1655 (let ((raw (org-babel-ref-resolve-reference
1657 (if (stringp raw
) raw
(format "%S" raw
)))
1660 (let ((point (org-babel-find-named-block
1666 (org-babel-expand-noweb-references
1667 (org-babel-get-src-block-info))))
1668 ;; optionally raise an error if named
1669 ;; source-block doesn't exist
1670 (if (member lang org-babel-noweb-error-langs
)
1673 "<<" source-name
">> "
1674 "could not be resolved (see "
1675 "`org-babel-noweb-error-langs')"))
1677 "[\n\r]") (concat "\n" prefix
)))))
1678 (nb-add (buffer-substring index
(point-max)))))
1681 (defun org-babel-clean-text-properties (text)
1682 "Strip all properties from text return."
1684 (set-text-properties 0 (length text
) nil text
) text
))
1686 (defun org-babel-strip-protective-commas (body)
1687 "Strip protective commas from bodies of source blocks."
1688 (replace-regexp-in-string "^,#" "#" body
))
1690 (defun org-babel-read (cell)
1691 "Convert the string value of CELL to a number if appropriate.
1692 Otherwise if cell looks like lisp (meaning it starts with a
1693 \"(\" or a \"'\") then read it as lisp, otherwise return it
1694 unmodified as a string.
1696 This is taken almost directly from `org-read-prop'."
1697 (if (and (stringp cell
) (not (equal cell
"")))
1698 (or (org-babel-number-p cell
)
1699 (if (or (equal "(" (substring cell
0 1))
1700 (equal "'" (substring cell
0 1))
1701 (equal "`" (substring cell
0 1)))
1703 (progn (set-text-properties 0 (length cell
) nil cell
) cell
)))
1706 (defun org-babel-number-p (string)
1707 "If STRING represents a number return it's value."
1708 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
1709 (= (length (substring string
(match-beginning 0)
1712 (string-to-number string
)))
1714 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
1715 "Read the results located at FILE-NAME into an elisp table.
1716 If the table is trivial, then return it as a scalar."
1718 (save-window-excursion
1722 (org-table-import file-name separator
)
1723 (delete-file file-name
)
1724 (setq result
(mapcar (lambda (row)
1725 (mapcar #'org-babel-string-read row
))
1726 (org-table-to-lisp))))
1728 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
1729 (if (consp (car result
))
1730 (if (null (cdr (car result
)))
1736 (defun org-babel-string-read (cell)
1737 "Strip nested \"s from around strings."
1738 (org-babel-read (or (and (stringp cell
)
1739 (string-match "\\\"\\(.+\\)\\\"" cell
)
1740 (match-string 1 cell
))
1743 (defun org-babel-reverse-string (string)
1744 "Return the reverse of STRING."
1745 (apply 'string
(reverse (string-to-list string
))))
1747 (defun org-babel-chomp (string &optional regexp
)
1748 "Strip trailing spaces and carriage returns from STRING.
1749 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1750 overwritten by specifying a regexp as a second argument."
1751 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
1752 (while (and (> (length string
) 0)
1753 (string-match regexp
(substring string -
1)))
1754 (setq string
(substring string
0 -
1)))
1757 (defun org-babel-trim (string &optional regexp
)
1758 "Strip leading and trailing spaces and carriage returns from STRING.
1759 Like `org-babel-chomp' only it runs on both the front and back
1761 (org-babel-chomp (org-babel-reverse-string
1762 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
1765 (defvar org-babel-org-babel-call-process-region-original nil
)
1766 (defun org-babel-tramp-handle-call-process-region
1767 (start end program
&optional delete buffer display
&rest args
)
1768 "Use tramp to handle call-process-region.
1769 Fixes a bug in `tramp-handle-call-process-region'."
1770 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
1771 (let ((tmpfile (tramp-compat-make-temp-file "")))
1772 (write-region start end tmpfile
)
1773 (when delete
(delete-region start end
))
1775 ;; (apply 'call-process program tmpfile buffer display args)
1777 (apply 'process-file program tmpfile buffer display args
)
1778 (delete-file tmpfile
)))
1779 ;; org-babel-call-process-region-original is the original emacs
1780 ;; definition. It is in scope from the let binding in
1781 ;; org-babel-execute-src-block
1782 (apply org-babel-call-process-region-original
1783 start end program delete buffer display args
)))
1785 (defun org-babel-local-file-name (file)
1786 "Return the local name component of FILE."
1787 (if (file-remote-p file
)
1789 (with-parsed-tramp-file-name file nil
1793 (defun org-babel-process-file-name (name &optional no-quote-p
)
1794 "Prepare NAME to be used in an external process.
1795 If NAME specifies a remote location, the remote portion of the
1796 name is removed, since in that case the process will be executing
1797 remotely. The file name is then processed by
1798 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
1799 the file name is additionally processed by
1800 `shell-quote-argument'"
1801 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
1802 (expand-file-name (org-babel-local-file-name name
))))
1804 (defvar org-babel-temporary-directory
)
1805 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
1806 (defvar org-babel-temporary-directory
1807 (or (and (boundp 'org-babel-temporary-directory
)
1808 (file-exists-p org-babel-temporary-directory
)
1809 org-babel-temporary-directory
)
1810 (make-temp-file "babel-" t
))
1811 "Directory to hold temporary files created to execute code blocks.
1812 Used by `org-babel-temp-file'. This directory will be removed on
1815 (defun org-babel-temp-file (prefix &optional suffix
)
1816 "Create a temporary file in the `org-babel-temporary-directory'.
1817 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
1818 value of `temporary-file-directory' temporarily set to the value
1819 of `org-babel-temporary-directory'."
1820 (if (file-remote-p default-directory
)
1822 (concat (file-remote-p default-directory
)
1824 prefix temporary-file-directory
)
1826 (let ((temporary-file-directory
1827 (or (and (file-exists-p org-babel-temporary-directory
)
1828 org-babel-temporary-directory
)
1829 temporary-file-directory
)))
1830 (make-temp-file prefix nil suffix
))))
1832 (defun org-babel-remove-temporary-directory ()
1833 "Remove `org-babel-temporary-directory' on Emacs shutdown."
1834 (when (and (boundp 'org-babel-temporary-directory
)
1835 (file-exists-p org-babel-temporary-directory
))
1836 ;; taken from `delete-directory' in files.el
1837 (mapc (lambda (file)
1838 ;; This test is equivalent to
1839 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
1840 ;; but more efficient
1841 (if (eq t
(car (file-attributes file
)))
1842 (delete-directory file
)
1843 (delete-file file
)))
1844 ;; We do not want to delete "." and "..".
1845 (directory-files org-babel-temporary-directory
'full
1846 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
1847 (delete-directory org-babel-temporary-directory
)))
1849 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
1853 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1