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))
72 (declare-function org-babel-ref-resolve
"ob-ref" (ref))
73 (declare-function org-babel-lob-execute-maybe
"ob-lob" ())
74 (declare-function org-number-sequence
"org-compat" (from &optional to inc
))
76 (defgroup org-babel nil
77 "Code block evaluation and management in `org-mode' documents."
81 (defcustom org-confirm-babel-evaluate t
82 "Confirm before evaluation.
83 Require confirmation before interactively evaluating code
84 blocks in Org-mode buffers. The default value of this variable
85 is t, meaning confirmation is required for any code block
86 evaluation. This variable can be set to nil to inhibit any
87 future confirmation requests. This variable can also be set to a
88 function which takes two arguments the language of the code block
89 and the body of the code block. Such a function should then
90 return a non-nil value if the user should be prompted for
91 execution or nil if no prompt is required.
93 Warning: Disabling confirmation may result in accidental
94 evaluation of potentially harmful code. It may be advisable
95 remove code block execution from C-c C-c as further protection
96 against accidental code block evaluation. The
97 `org-babel-no-eval-on-ctrl-c-ctrl-c' variable can be used to
98 remove code block execution from the C-c C-c keybinding."
100 :type
'(choice boolean function
))
101 ;; don't allow this variable to be changed through file settings
102 (put 'org-confirm-babel-evaluate
'safe-local-variable
(lambda (x) (eq x t
)))
104 (defcustom org-babel-no-eval-on-ctrl-c-ctrl-c nil
105 "Remove code block evaluation from the C-c C-c key binding."
109 (defvar org-babel-src-name-regexp
110 "^[ \t]*#\\+\\(srcname\\|source\\|function\\):[ \t]*"
111 "Regular expression used to match a source name line.")
113 (defvar org-babel-multi-line-header-regexp
114 "^[ \t]*#\\+headers?:[ \t]*\\([^\n]*\\)$"
115 "Regular expression used to match multi-line header arguments.")
117 (defvar org-babel-src-name-w-name-regexp
118 (concat org-babel-src-name-regexp
120 org-babel-multi-line-header-regexp
122 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)")
123 "Regular expression matching source name lines with a name.")
125 (defvar org-babel-src-block-regexp
127 ;; (1) indentation (2) lang
128 "^\\([ \t]*\\)#\\+begin_src[ \t]+\\([^ \f\t\n\r\v]+\\)[ \t]*"
130 "\\([^\":\n]*\"[^\"\n*]*\"[^\":\n]*\\|[^\":\n]*\\)"
131 ;; (4) header arguments
134 "\\([^\000]+?\n\\)[ \t]*#\\+end_src")
135 "Regexp used to identify code blocks.")
137 (defvar org-babel-inline-src-block-regexp
139 ;; (1) replacement target (2) lang
140 "[ \f\t\n\r\v]\\(src_\\([^ \f\t\n\r\v]+\\)"
141 ;; (3,4) (unused, headers)
142 "\\(\\|\\[\\(.*?\\)\\]\\)"
144 "{\\([^\f\n\r\v]+?\\)}\\)")
145 "Regexp used to identify inline src-blocks.")
147 (defun org-babel-get-header (params key
&optional others
)
148 "Select only header argument of type KEY from a list.
149 Optional argument OTHERS indicates that only the header that do
150 not match KEY should be returned."
153 (lambda (p) (when (funcall (if others
#'not
#'identity
) (eq (car p
) key
)) p
))
156 (defun org-babel-get-src-block-info (&optional light
)
157 "Get information on the current source block.
159 Optional argument LIGHT does not resolve remote variable
160 references; a process which could likely result in the execution
161 of other code blocks.
164 (language body header-arguments-alist switches name indent)."
165 (let ((case-fold-search t
) head info name indent
)
167 (if (setq head
(org-babel-where-is-src-block-head))
170 (setq info
(org-babel-parse-src-block-match))
171 (setq indent
(car (last info
)))
172 (setq info
(butlast info
))
173 (while (and (forward-line -
1)
174 (looking-at org-babel-multi-line-header-regexp
))
176 (org-babel-merge-params
177 (org-babel-parse-header-arguments (match-string 1))
179 (when (looking-at org-babel-src-name-w-name-regexp
)
180 (setq name
(org-babel-clean-text-properties (match-string 4)))
181 (when (match-string 6)
182 (setf (nth 2 info
) ;; merge functional-syntax vars and header-args
183 (org-babel-merge-params
184 (mapcar (lambda (ref) (cons :var ref
))
185 (org-babel-ref-split-args (match-string 6)))
187 ;; inline source block
188 (when (save-excursion (re-search-backward "[ \f\t\n\r\v]" nil t
)
189 (looking-at org-babel-inline-src-block-regexp
))
190 (setq info
(org-babel-parse-inline-src-block-match))))
191 ;; resolve variable references and add summary parameters
192 (when (and info
(not light
))
193 (setf (nth 2 info
) (org-babel-process-params (nth 2 info
))))
194 (when info
(append info
(list name indent
)))))
196 (defun org-babel-confirm-evaluate (info)
197 "Confirm evaluation of the code block INFO.
198 This behavior can be suppressed by setting the value of
199 `org-confirm-babel-evaluate' to nil, in which case all future
200 interactive code block evaluations will proceed without any
201 confirmation from the user.
203 Note disabling confirmation may result in accidental evaluation
204 of potentially harmful code."
205 (let* ((eval (or (cdr (assoc :eval
(nth 2 info
)))
206 (when (assoc :noeval
(nth 2 info
)) "no")))
207 (query (or (equal eval
"query")
208 (if (functionp org-confirm-babel-evaluate
)
209 (funcall org-confirm-babel-evaluate
210 (nth 0 info
) (nth 1 info
))
211 org-confirm-babel-evaluate
))))
212 (if (or (equal eval
"never") (equal eval
"no")
215 (format "Evaluate this%scode on your system? "
216 (if info
(format " %s " (nth 0 info
)) " "))))))
217 (prog1 nil
(message "evaluation aborted"))
221 (defun org-babel-execute-safely-maybe ()
222 (unless org-babel-no-eval-on-ctrl-c-ctrl-c
223 (org-babel-execute-maybe)))
225 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-execute-safely-maybe
)
228 (defun org-babel-execute-maybe ()
230 (or (org-babel-execute-src-block-maybe)
231 (org-babel-lob-execute-maybe)))
233 (defun org-babel-execute-src-block-maybe ()
234 "Conditionally execute a source block.
235 Detect if this is context for a Babel src-block and if so
236 then run `org-babel-execute-src-block'."
238 (let ((info (org-babel-get-src-block-info)))
240 (progn (org-babel-execute-src-block current-prefix-arg info
) t
) nil
)))
243 (defun org-babel-expand-src-block-maybe ()
244 "Conditionally expand a source block.
245 Detect if this is context for a org-babel src-block and if so
246 then run `org-babel-expand-src-block'."
248 (let ((info (org-babel-get-src-block-info)))
250 (progn (org-babel-expand-src-block current-prefix-arg info
) t
)
254 (defun org-babel-load-in-session-maybe ()
255 "Conditionally load a source block in a session.
256 Detect if this is context for a org-babel src-block and if so
257 then run `org-babel-load-in-session'."
259 (let ((info (org-babel-get-src-block-info)))
261 (progn (org-babel-load-in-session current-prefix-arg info
) t
)
264 (add-hook 'org-metaup-hook
'org-babel-load-in-session-maybe
)
267 (defun org-babel-pop-to-session-maybe ()
268 "Conditionally pop to a session.
269 Detect if this is context for a org-babel src-block and if so
270 then run `org-babel-pop-to-session'."
272 (let ((info (org-babel-get-src-block-info)))
273 (if info
(progn (org-babel-pop-to-session current-prefix-arg info
) t
) nil
)))
275 (add-hook 'org-metadown-hook
'org-babel-pop-to-session-maybe
)
277 (defconst org-babel-header-arg-names
278 '(cache cmdline colnames dir exports file noweb results
279 session tangle var eval noeval comments
)
280 "Common header arguments used by org-babel.
281 Note that individual languages may define their own language
282 specific header arguments as well.")
284 (defvar org-babel-default-header-args
285 '((:session .
"none") (:results .
"replace") (:exports .
"code")
286 (:cache .
"no") (:noweb .
"no") (:hlines .
"no") (:tangle .
"no"))
287 "Default arguments to use when evaluating a source block.")
289 (defvar org-babel-default-inline-header-args
290 '((:session .
"none") (:results .
"silent") (:exports .
"results"))
291 "Default arguments to use when evaluating an inline source block.")
293 (defvar org-babel-current-buffer-properties nil
294 "Local cache for buffer properties.")
295 (make-variable-buffer-local 'org-babel-current-buffer-properties
)
297 (defvar org-babel-result-regexp
298 "^[ \t]*#\\+res\\(ults\\|name\\)\\(\\[\\([[:alnum:]]+\\)\\]\\)?\\:[ \t]*"
299 "Regular expression used to match result lines.
300 If the results are associated with a hash key then the hash will
301 be saved in the second match data.")
303 (defvar org-babel-result-w-name-regexp
304 (concat org-babel-result-regexp
305 "\\([^ ()\f\t\n\r\v]+\\)\\(\(\\(.*\\)\)\\|\\)"))
307 (defvar org-babel-min-lines-for-block-output
10
308 "The minimum number of lines for block output.
309 If number of lines of output is equal to or exceeds this
310 value, the output is placed in a #+begin_example...#+end_example
311 block. Otherwise the output is marked as literal by inserting
312 colons at the starts of the lines. This variable only takes
313 effect if the :results output option is in effect.")
315 (defvar org-babel-noweb-error-langs nil
316 "Languages for which Babel will raise literate programming errors.
317 List of languages for which errors should be raised when the
318 source code block satisfying a noweb reference in this language
319 can not be resolved.")
321 (defvar org-babel-hash-show
4
322 "Number of initial characters to show of a hidden results hash.")
324 (defvar org-babel-after-execute-hook nil
325 "Hook for functions to be called after `org-babel-execute-src-block'")
326 (defun org-babel-named-src-block-regexp-for-name (name)
327 "This generates a regexp used to match a src block named NAME."
328 (concat org-babel-src-name-regexp
(regexp-quote name
) "[ \t\n]*"
329 (substring org-babel-src-block-regexp
1)))
332 (defvar call-process-region
)
335 (defun org-babel-execute-src-block (&optional arg info params
)
336 "Execute the current source code block.
337 Insert the results of execution into the buffer. Source code
338 execution and the collection and formatting of results can be
339 controlled through a variety of header arguments.
341 With prefix argument ARG, force re-execution even if a an
342 existing result cached in the buffer would otherwise have been
345 Optionally supply a value for INFO in the form returned by
346 `org-babel-get-src-block-info'.
348 Optionally supply a value for PARAMS which will be merged with
349 the header arguments specified at the front of the source code
352 (let ((info (or info
(org-babel-get-src-block-info))))
353 (when (org-babel-confirm-evaluate info
)
354 (let* ((lang (nth 0 info
))
356 (org-babel-process-params
357 (org-babel-merge-params (nth 2 info
) params
))
359 (cache?
(and (not arg
) (cdr (assoc :cache params
))
360 (string= "yes" (cdr (assoc :cache params
)))))
361 (result-params (cdr (assoc :result-params params
)))
362 (new-hash (when cache?
(org-babel-sha1-hash info
)))
363 (old-hash (when cache?
(org-babel-result-hash info
)))
364 (body (setf (nth 1 info
)
365 (if (and (cdr (assoc :noweb params
))
366 (string= "yes" (cdr (assoc :noweb params
))))
367 (org-babel-expand-noweb-references info
)
369 (cmd (intern (concat "org-babel-execute:" lang
)))
370 (dir (cdr (assoc :dir params
)))
372 (or (and dir
(file-name-as-directory dir
)) default-directory
))
373 (org-babel-call-process-region-original
374 (if (boundp 'org-babel-call-process-region-original
)
375 org-babel-call-process-region-original
376 (symbol-function 'call-process-region
)))
377 (indent (car (last info
)))
380 (flet ((call-process-region (&rest args
)
381 (apply 'org-babel-tramp-handle-call-process-region args
)))
382 (unless (fboundp cmd
)
383 (error "No org-babel-execute function for %s!" lang
))
384 (if (and (not arg
) new-hash
(equal new-hash old-hash
))
385 (save-excursion ;; return cached result
386 (goto-char (org-babel-where-is-src-block-result nil info
))
387 (end-of-line 1) (forward-char 1)
388 (setq result
(org-babel-read-result))
389 (message (replace-regexp-in-string
390 "%" "%%" (format "%S" result
))) result
)
391 (message "executing %s code block%s..."
393 (if (nth 4 info
) (format " (%s)" (nth 4 info
)) ""))
394 (setq result
(funcall cmd body params
))
395 (if (eq (cdr (assoc :result-type params
)) 'value
)
396 (setq result
(if (and (or (member "vector" result-params
)
397 (member "table" result-params
))
398 (not (listp result
)))
401 (org-babel-insert-result
402 result result-params info new-hash indent lang
)
403 (run-hooks 'org-babel-after-execute-hook
)
405 (setq call-process-region
'org-babel-call-process-region-original
))))))
407 (defun org-babel-expand-body:generic
(body params
&optional var-lines
)
408 "Expand BODY with PARAMS.
409 Expand a block of code with org-babel according to it's header
410 arguments. This generic implementation of body expansion is
411 called for languages which have not defined their own specific
412 org-babel-expand-body:lang function."
413 (mapconcat #'identity
(append var-lines
(list body
)) "\n"))
416 (defun org-babel-expand-src-block (&optional arg info params
)
417 "Expand the current source code block.
418 Expand according to the source code block's header
419 arguments and pop open the results in a preview buffer."
421 (let* ((info (or info
(org-babel-get-src-block-info)))
423 (params (setf (nth 2 info
)
424 (sort (org-babel-merge-params (nth 2 info
) params
)
425 (lambda (el1 el2
) (string< (symbol-name (car el1
))
426 (symbol-name (car el2
)))))))
427 (body (setf (nth 1 info
)
428 (if (and (cdr (assoc :noweb params
))
429 (string= "yes" (cdr (assoc :noweb params
))))
430 (org-babel-expand-noweb-references info
) (nth 1 info
))))
431 (expand-cmd (intern (concat "org-babel-expand-body:" lang
)))
432 (assignments-cmd (intern (concat "org-babel-variable-assignments:" lang
)))
434 (if (fboundp expand-cmd
) (funcall expand-cmd body params
)
435 (org-babel-expand-body:generic
436 body params
(and (fboundp assignments-cmd
) (funcall assignments-cmd params
))))))
438 nil expanded
(concat "*Org-Babel Preview " (buffer-name) "[ " lang
" ]*"))))
441 (defun org-babel-load-in-session (&optional arg info
)
442 "Load the body of the current source-code block.
443 Evaluate the header arguments for the source block before
444 entering the session. After loading the body this pops open the
447 (let* ((info (or info
(org-babel-get-src-block-info)))
449 (params (nth 2 info
))
450 (body (setf (nth 1 info
)
451 (if (and (cdr (assoc :noweb params
))
452 (string= "yes" (cdr (assoc :noweb params
))))
453 (org-babel-expand-noweb-references info
)
455 (session (cdr (assoc :session params
)))
456 (dir (cdr (assoc :dir params
)))
458 (or (and dir
(file-name-as-directory dir
)) default-directory
))
459 (cmd (intern (concat "org-babel-load-session:" lang
))))
460 (unless (fboundp cmd
)
461 (error "No org-babel-load-session function for %s!" lang
))
462 (pop-to-buffer (funcall cmd session body params
))
466 (defun org-babel-initiate-session (&optional arg info
)
467 "Initiate session for current code block.
468 If called with a prefix argument then evaluate the header arguments
469 for the code block before entering the session. Copy the body
470 of the code block to the kill ring."
472 (let* ((info (or info
(org-babel-get-src-block-info)))
475 (params (nth 2 info
))
476 (session (cdr (assoc :session params
)))
477 (dir (cdr (assoc :dir params
)))
479 (or (and dir
(file-name-as-directory dir
)) default-directory
))
480 (init-cmd (intern (format "org-babel-%s-initiate-session" lang
)))
481 (prep-cmd (intern (concat "org-babel-prep-session:" lang
))))
482 (if (and (stringp session
) (string= session
"none"))
483 (error "This block is not using a session!"))
484 (unless (fboundp init-cmd
)
485 (error "No org-babel-initiate-session function for %s!" lang
))
486 (with-temp-buffer (insert (org-babel-trim body
))
487 (copy-region-as-kill (point-min) (point-max)))
489 (unless (fboundp prep-cmd
)
490 (error "No org-babel-prep-session function for %s!" lang
))
491 (funcall prep-cmd session params
))
492 (funcall init-cmd session params
)))
495 (defun org-babel-switch-to-session (&optional arg info
)
496 "Switch to the session of the current code block.
497 Uses `org-babel-initiate-session' to start the session. If called
498 with a prefix argument then this is passed on to
499 `org-babel-initiate-session'."
501 (pop-to-buffer (org-babel-initiate-session arg info
))
504 (defalias 'org-babel-pop-to-session
'org-babel-switch-to-session
)
507 (defun org-babel-switch-to-session-with-code (&optional arg info
)
508 "Switch to code buffer and display session."
512 (let ((other-window-buffer (window-buffer (next-window))))
513 (set-window-buffer (next-window) (current-buffer))
514 (set-window-buffer (selected-window) other-window-buffer
))
516 (let ((info (org-babel-get-src-block-info))
517 (org-src-window-setup 'reorganize-frame
))
519 (org-babel-switch-to-session arg info
))
523 (defmacro org-babel-do-in-edit-buffer
(&rest body
)
524 "Evaluate BODY in edit buffer if there is a code block at point.
525 Return t if a code block was found at point, nil otherwise."
526 `(let ((org-src-window-setup 'switch-invisibly
))
527 (when (and (org-babel-where-is-src-block-head)
528 (org-edit-src-code nil nil nil
'quietly
))
529 (unwind-protect (progn ,@body
)
530 (if (org-bound-and-true-p org-edit-src-from-org-mode
)
531 (org-edit-src-exit)))
534 (defun org-babel-do-key-sequence-in-edit-buffer (key)
535 "Read key sequence and execute the command in edit buffer.
536 Enter a key sequence to be executed in the language major-mode
537 edit buffer. For example, TAB will alter the contents of the
538 Org-mode code block according to the effect of TAB in the
539 language major-mode buffer. For languages that support
540 interactive sessions, this can be used to send code from the Org
541 buffer to the session for evaluation using the native major-mode
542 evaluation mechanisms."
543 (interactive "kEnter key-sequence to execute in edit buffer: ")
544 (org-babel-do-in-edit-buffer
546 (key-binding (or key
(read-key-sequence nil
))))))
548 (defvar org-bracket-link-regexp
)
550 (defun org-babel-open-src-block-result (&optional re-run
)
551 "If `point' is on a src block then open the results of the
552 source code block, otherwise return nil. With optional prefix
553 argument RE-RUN the source-code block is evaluated even if
554 results already exist."
556 (when (org-babel-get-src-block-info)
558 ;; go to the results, if there aren't any then run the block
559 (goto-char (or (and (not re-run
) (org-babel-where-is-src-block-result))
560 (progn (org-babel-execute-src-block)
561 (org-babel-where-is-src-block-result))))
563 (while (looking-at "[\n\r\t\f ]") (forward-char 1))
565 (if (looking-at org-bracket-link-regexp
)
568 (let ((results (org-babel-read-result)))
569 (flet ((echo-res (result)
570 (if (stringp result
) result
(format "%S" result
))))
571 (pop-to-buffer (get-buffer-create "org-babel-results"))
572 (delete-region (point-min) (point-max))
575 (insert (orgtbl-to-generic results
'(:sep
"\t" :fmt echo-res
)))
577 (insert (echo-res results
))))))
581 (defun org-babel-execute-buffer (&optional arg
)
582 "Execute source code blocks in a buffer.
583 Call `org-babel-execute-src-block' on every source block in
586 (org-save-outline-visibility t
587 (org-babel-map-src-blocks nil
588 (org-babel-execute-src-block arg
))))
591 (defun org-babel-execute-subtree (&optional arg
)
592 "Execute source code blocks in a subtree.
593 Call `org-babel-execute-src-block' on every source block in
594 the current subtree."
598 (org-narrow-to-subtree)
599 (org-babel-execute-buffer arg
)
603 (defun org-babel-sha1-hash (&optional info
)
604 "Generate an sha1 hash based on the value of info."
606 (let ((print-level nil
)
607 (info (or info
(org-babel-get-src-block-info))))
610 (lambda (a b
) (string< (car a
) (car b
)))))
619 (when (and v
(not (and (sequencep v
)
625 (when (interactive-p) (message hash
))
628 (defun org-babel-result-hash (&optional info
)
629 "Return the in-buffer hash associated with INFO."
630 (org-babel-where-is-src-block-result nil info
)
631 (org-babel-clean-text-properties (match-string 3)))
633 (defun org-babel-hide-hash ()
634 "Hide the hash in the current results line.
635 Only the initial `org-babel-hash-show' characters of the hash
636 will remain visible."
637 (add-to-invisibility-spec '(org-babel-hide-hash . t
))
639 (when (and (re-search-forward org-babel-result-regexp nil t
)
641 (let* ((start (match-beginning 3))
642 (hide-start (+ org-babel-hash-show start
))
644 (hash (match-string 3))
646 (setq ov1
(make-overlay start hide-start
))
647 (setq ov2
(make-overlay hide-start end
))
648 (overlay-put ov2
'invisible
'org-babel-hide-hash
)
649 (overlay-put ov1
'babel-hash hash
)))))
651 (defun org-babel-hide-all-hashes ()
652 "Hide the hash in the current buffer.
653 Only the initial `org-babel-hash-show' characters of each hash
654 will remain visible. This function should be called as part of
655 the `org-mode-hook'."
657 (while (re-search-forward org-babel-result-regexp nil t
)
658 (goto-char (match-beginning 0))
659 (org-babel-hide-hash)
660 (goto-char (match-end 0)))))
661 (add-hook 'org-mode-hook
'org-babel-hide-all-hashes
)
663 (defun org-babel-hash-at-point (&optional point
)
664 "Return the value of the hash at POINT.
665 The hash is also added as the last element of the kill ring.
666 This can be called with C-c C-c."
668 (let ((hash (car (delq nil
(mapcar
669 (lambda (ol) (overlay-get ol
'babel-hash
))
670 (overlays-at (or point
(point))))))))
671 (when hash
(kill-new hash
) (message hash
))))
672 (add-hook 'org-ctrl-c-ctrl-c-hook
'org-babel-hash-at-point
)
674 (defun org-babel-result-hide-spec ()
675 "Hide portions of results lines.
676 Add `org-babel-hide-result' as an invisibility spec for hiding
677 portions of results lines."
678 (add-to-invisibility-spec '(org-babel-hide-result . t
)))
679 (add-hook 'org-mode-hook
'org-babel-result-hide-spec
)
681 (defvar org-babel-hide-result-overlays nil
682 "Overlays hiding results.")
684 (defun org-babel-result-hide-all ()
685 "Fold all results in the current buffer."
687 (org-babel-show-result-all)
689 (while (re-search-forward org-babel-result-regexp nil t
)
690 (save-excursion (goto-char (match-beginning 0))
691 (org-babel-hide-result-toggle-maybe)))))
693 (defun org-babel-show-result-all ()
694 "Unfold all results in the current buffer."
695 (mapc 'delete-overlay org-babel-hide-result-overlays
)
696 (setq org-babel-hide-result-overlays nil
))
699 (defun org-babel-hide-result-toggle-maybe ()
700 "Toggle visibility of result at point."
702 (let ((case-fold-search t
))
704 (beginning-of-line 1)
705 (looking-at org-babel-result-regexp
))
706 (progn (org-babel-hide-result-toggle)
707 t
) ;; to signal that we took action
708 nil
))) ;; to signal that we did not
710 (defun org-babel-hide-result-toggle (&optional force
)
711 "Toggle the visibility of the current result."
715 (if (re-search-forward org-babel-result-regexp nil t
)
716 (let ((start (progn (beginning-of-line 2) (- (point) 1)))
717 (end (progn (goto-char (- (org-babel-result-end) 1)) (point)))
719 (if (memq t
(mapcar (lambda (overlay)
720 (eq (overlay-get overlay
'invisible
)
721 'org-babel-hide-result
))
722 (overlays-at start
)))
723 (if (or (not force
) (eq force
'off
))
725 (when (member ov org-babel-hide-result-overlays
)
726 (setq org-babel-hide-result-overlays
727 (delq ov org-babel-hide-result-overlays
)))
728 (when (eq (overlay-get ov
'invisible
)
729 'org-babel-hide-result
)
730 (delete-overlay ov
)))
731 (overlays-at start
)))
732 (setq ov
(make-overlay start end
))
733 (overlay-put ov
'invisible
'org-babel-hide-result
)
734 ;; make the block accessible to isearch
736 ov
'isearch-open-invisible
738 (when (member ov org-babel-hide-result-overlays
)
739 (setq org-babel-hide-result-overlays
740 (delq ov org-babel-hide-result-overlays
)))
741 (when (eq (overlay-get ov
'invisible
)
742 'org-babel-hide-result
)
743 (delete-overlay ov
))))
744 (push ov org-babel-hide-result-overlays
)))
745 (error "Not looking at a result line"))))
747 ;; org-tab-after-check-for-cycling-hook
748 (add-hook 'org-tab-first-hook
'org-babel-hide-result-toggle-maybe
)
749 ;; Remove overlays when changing major mode
750 (add-hook 'org-mode-hook
751 (lambda () (org-add-hook 'change-major-mode-hook
752 'org-babel-show-result-all
'append
'local
)))
754 (defmacro org-babel-map-src-blocks
(file &rest body
)
755 "Evaluate BODY forms on each source-block in FILE.
756 If FILE is nil evaluate BODY forms on source blocks in current
757 buffer. During evaluation of BODY the following local variables
758 are set relative to the currently matched code block.
760 full-block ------- string holding the entirety of the code block
761 beg-block -------- point at the beginning of the code block
762 end-block -------- point at the end of the matched code block
763 lang ------------- string holding the language of the code block
764 beg-lang --------- point at the beginning of the lang
765 end-lang --------- point at the end of the lang
766 switches --------- string holding the switches
767 beg-switches ----- point at the beginning of the switches
768 end-switches ----- point at the end of the switches
769 header-args ------ string holding the header-args
770 beg-header-args -- point at the beginning of the header-args
771 end-header-args -- point at the end of the header-args
772 body ------------- string holding the body of the code block
773 beg-body --------- point at the beginning of the body
774 end-body --------- point at the end of the body"
776 `(let ((visited-p (or (null ,file
)
777 (get-file-buffer (expand-file-name ,file
))))
778 (point (point)) to-be-removed
)
779 (save-window-excursion
780 (when ,file
(find-file ,file
))
781 (setq to-be-removed
(current-buffer))
782 (goto-char (point-min))
783 (while (re-search-forward org-babel-src-block-regexp nil t
)
784 (goto-char (match-beginning 0))
785 (let ((full-block (match-string 0))
786 (beg-block (match-beginning 0))
787 (end-block (match-end 0))
788 (lang (match-string 2))
789 (beg-lang (match-beginning 2))
790 (end-lang (match-end 2))
791 (switches (match-string 3))
792 (beg-switches (match-beginning 3))
793 (end-switches (match-end 3))
794 (header-args (match-string 4))
795 (beg-header-args (match-beginning 4))
796 (end-header-args (match-end 4))
797 (body (match-string 5))
798 (beg-body (match-beginning 5))
799 (end-body (match-end 5)))
801 (goto-char end-block
))))
802 (unless visited-p
(kill-buffer to-be-removed
))
805 (defvar org-file-properties
)
806 (defun org-babel-params-from-properties (&optional lang
)
807 "Retrieve parameters specified as properties.
808 Return an association list of any source block params which
809 may be specified in the properties of the current outline entry."
816 (or (condition-case nil
817 (org-entry-get (point) header-arg t
)
819 (cdr (assoc header-arg org-file-properties
))))
820 (cons (intern (concat ":" header-arg
))
821 (org-babel-read val
))))
825 org-babel-header-arg-names
827 (setq sym
(intern (concat "org-babel-header-arg-names:" lang
)))
828 (and (boundp sym
) (eval sym
))))))))))
830 (defun org-babel-params-from-buffer ()
831 "Retrieve per-buffer parameters.
832 Return an association list of any source block params which
833 may be specified at the top of the current buffer."
834 (or org-babel-current-buffer-properties
835 (setq org-babel-current-buffer-properties
840 (goto-char (point-min))
841 (when (re-search-forward
842 (org-make-options-regexp (list "BABEL")) nil t
)
843 (org-babel-parse-header-arguments
844 (org-match-string-no-properties 2)))))))))
846 (defvar org-src-preserve-indentation
)
847 (defun org-babel-parse-src-block-match ()
848 "Parse the results from a match of the `org-babel-src-block-regexp'."
849 (let* ((block-indentation (length (match-string 1)))
850 (lang (org-babel-clean-text-properties (match-string 2)))
851 (lang-headers (intern (concat "org-babel-default-header-args:" lang
)))
852 (switches (match-string 3))
853 (body (org-babel-clean-text-properties (match-string 5)))
854 (preserve-indentation (or org-src-preserve-indentation
855 (string-match "-i\\>" switches
))))
857 ;; get block body less properties, protective commas, and indentation
860 (insert (org-babel-strip-protective-commas body
))
861 (unless preserve-indentation
(org-do-remove-indentation))
863 (org-babel-merge-params
864 org-babel-default-header-args
865 (org-babel-params-from-buffer)
866 (org-babel-params-from-properties lang
)
867 (if (boundp lang-headers
) (eval lang-headers
) nil
)
868 (org-babel-parse-header-arguments
869 (org-babel-clean-text-properties (or (match-string 4) ""))))
873 (defun org-babel-parse-inline-src-block-match ()
874 "Parse the results from a match of the `org-babel-inline-src-block-regexp'."
875 (let* ((lang (org-babel-clean-text-properties (match-string 2)))
876 (lang-headers (intern (concat "org-babel-default-header-args:" lang
))))
878 (org-babel-strip-protective-commas
879 (org-babel-clean-text-properties (match-string 5)))
880 (org-babel-merge-params
881 org-babel-default-inline-header-args
882 (org-babel-params-from-buffer)
883 (org-babel-params-from-properties lang
)
884 (if (boundp lang-headers
) (eval lang-headers
) nil
)
885 (org-babel-parse-header-arguments
886 (org-babel-clean-text-properties (or (match-string 4) "")))))))
888 (defun org-babel-parse-header-arguments (arg-string)
889 "Parse a string of header arguments returning an alist."
890 (if (> (length arg-string
) 0)
895 "\\([^ \f\t\n\r\v]+\\)[ \f\t\n\r\v]+\\([^ \f\t\n\r\v]+.*\\)"
897 (cons (intern (concat ":" (match-string 1 arg
)))
898 (org-babel-read (org-babel-chomp (match-string 2 arg
))))
899 (cons (intern (concat ":" arg
)) nil
)))
900 (split-string (concat " " arg-string
) "[ \f\t\n\r\v]+:" t
)))))
902 (defun org-babel-process-params (params)
903 "Expand variables in PARAMS and add summary parameters."
904 (let* ((vars-and-names (org-babel-disassemble-tables
907 (cdr el
) (org-babel-ref-parse (cdr el
))))
908 (org-babel-get-header params
:var
))
909 (cdr (assoc :hlines params
))
910 (cdr (assoc :colnames params
))
911 (cdr (assoc :rownames params
))))
912 (result-params (append
913 (split-string (or (cdr (assoc :results params
)) ""))
914 (cdr (assoc :result-params params
)))))
916 (mapcar (lambda (var) (cons :var var
)) (car vars-and-names
))
918 (cons :colname-names
(cadr vars-and-names
))
919 (cons :rowname-names
(caddr vars-and-names
))
920 (cons :result-params result-params
)
921 (cons :result-type
(cond ((member "output" result-params
) 'output
)
922 ((member "value" result-params
) 'value
)
924 (org-babel-get-header params
:var
'other
))))
926 ;; row and column names
927 (defun org-babel-del-hlines (table)
928 "Remove all 'hlines from TABLE."
929 (remove 'hline table
))
931 (defun org-babel-get-colnames (table)
932 "Return the column names of TABLE.
933 Return a cons cell, the `car' of which contains the TABLE less
934 colnames, and the `cdr' of which contains a list of the column
936 (if (equal 'hline
(nth 1 table
))
937 (cons (cddr table
) (car table
))
938 (cons (cdr table
) (car table
))))
940 (defun org-babel-get-rownames (table)
941 "Return the row names of TABLE.
942 Return a cons cell, the `car' of which contains the TABLE less
943 colnames, and the `cdr' of which contains a list of the column
944 names. Note: this function removes any hlines in TABLE."
945 (flet ((trans (table) (apply #'mapcar
* #'list table
)))
946 (let* ((width (apply 'max
947 (mapcar (lambda (el) (if (listp el
) (length el
) 0)) table
)))
948 (table (trans (mapcar (lambda (row)
949 (if (not (equal row
'hline
))
953 (setq row
(cons 'hline row
)))
956 (cons (mapcar (lambda (row) (if (equal (car row
) 'hline
) 'hline row
))
958 (remove 'hline
(car table
))))))
960 (defun org-babel-put-colnames (table colnames
)
961 "Add COLNAMES to TABLE if they exist."
962 (if colnames
(apply 'list colnames
'hline table
) table
))
964 (defun org-babel-put-rownames (table rownames
)
965 "Add ROWNAMES to TABLE if they exist."
967 (mapcar (lambda (row)
969 (cons (or (pop rownames
) "") row
)
973 (defun org-babel-pick-name (names selector
)
974 "Select one out of an alist of row or column names.
975 SELECTOR can be either a list of names in which case those names
976 will be returned directly, or an index into the list NAMES in
977 which case the indexed names will be return."
981 (if (and selector
(symbolp selector
) (not (equal t selector
)))
982 (cdr (assoc selector names
))
983 (if (integerp selector
)
984 (nth (- selector
1) names
)
985 (cdr (car (last names
))))))))
987 (defun org-babel-disassemble-tables (vars hlines colnames rownames
)
988 "Parse tables for further processing.
989 Process the variables in VARS according to the HLINES,
990 ROWNAMES and COLNAMES header arguments. Return a list consisting
991 of the vars, cnames and rnames."
996 (when (listp (cdr var
))
997 (when (and (not (equal colnames
"no"))
998 (or colnames
(and (equal (nth 1 (cdr var
)) 'hline
)
999 (not (member 'hline
(cddr (cdr var
)))))))
1000 (let ((both (org-babel-get-colnames (cdr var
))))
1001 (setq cnames
(cons (cons (car var
) (cdr both
))
1003 (setq var
(cons (car var
) (car both
)))))
1004 (when (and rownames
(not (equal rownames
"no")))
1005 (let ((both (org-babel-get-rownames (cdr var
))))
1006 (setq rnames
(cons (cons (car var
) (cdr both
))
1008 (setq var
(cons (car var
) (car both
)))))
1009 (when (and hlines
(not (equal hlines
"yes")))
1010 (setq var
(cons (car var
) (org-babel-del-hlines (cdr var
))))))
1015 (defun org-babel-reassemble-table (table colnames rownames
)
1016 "Add column and row names to a table.
1017 Given a TABLE and set of COLNAMES and ROWNAMES add the names
1018 to the table for reinsertion to org-mode."
1021 (if (and colnames
(listp (car table
)) (= (length (car table
))
1023 (org-babel-put-colnames table colnames
) table
))
1024 (if (and rownames
(= (length table
) (length rownames
)))
1025 (org-babel-put-rownames table rownames
) table
))
1028 (defun org-babel-where-is-src-block-head ()
1029 "Find where the current source block begins.
1030 Return the point at the beginning of the current source
1031 block. Specifically at the beginning of the #+BEGIN_SRC line.
1032 If the point is not on a source block then return nil."
1033 (let ((initial (point)) top bottom
)
1035 (save-excursion ;; on a source name line
1036 (beginning-of-line 1)
1037 (and (looking-at org-babel-src-name-regexp
) (forward-line 1)
1038 (looking-at org-babel-src-block-regexp
)
1040 (save-excursion ;; on a #+begin_src line
1041 (beginning-of-line 1)
1042 (and (looking-at org-babel-src-block-regexp
)
1044 (save-excursion ;; inside a src block
1046 (re-search-backward "^[ \t]*#\\+begin_src" nil t
) (setq top
(point))
1047 (re-search-forward "^[ \t]*#\\+end_src" nil t
) (setq bottom
(point))
1048 (< top initial
) (< initial bottom
)
1049 (progn (goto-char top
) (beginning-of-line 1)
1050 (looking-at org-babel-src-block-regexp
))
1054 (defun org-babel-goto-src-block-head ()
1055 "Go to the beginning of the current code block."
1058 (if head
(goto-char head
) (error "not currently in a code block")))
1059 (org-babel-where-is-src-block-head)))
1062 (defun org-babel-goto-named-src-block (name)
1063 "Go to a named source-code block."
1065 (let ((completion-ignore-case t
))
1066 (list (org-icompleting-read "source-block name: "
1067 (org-babel-src-block-names) nil t
))))
1068 (let ((point (org-babel-find-named-block name
)))
1070 ;; taken from `org-open-at-point'
1071 (progn (goto-char point
) (org-show-context))
1072 (message "source-code block '%s' not found in this buffer" name
))))
1074 (defun org-babel-find-named-block (name)
1075 "Find a named source-code block.
1076 Return the location of the source block identified by source
1077 NAME, or nil if no such block exists. Set match data according to
1078 org-babel-named-src-block-regexp."
1080 (let ((case-fold-search t
)
1081 (regexp (org-babel-named-src-block-regexp-for-name name
)) msg
)
1082 (goto-char (point-min))
1083 (when (or (re-search-forward regexp nil t
)
1084 (re-search-backward regexp nil t
))
1085 (match-beginning 0)))))
1087 (defun org-babel-src-block-names (&optional file
)
1088 "Returns the names of source blocks in FILE or the current buffer."
1090 (when file
(find-file file
)) (goto-char (point-min))
1092 (while (re-search-forward org-babel-src-name-w-name-regexp nil t
)
1093 (setq names
(cons (org-babel-clean-text-properties (match-string 3))
1098 (defun org-babel-goto-named-result (name)
1099 "Go to a named result."
1101 (let ((completion-ignore-case t
))
1102 (list (org-icompleting-read "source-block name: "
1103 (org-babel-result-names) nil t
))))
1104 (let ((point (org-babel-find-named-result name
)))
1106 ;; taken from `org-open-at-point'
1107 (progn (goto-char point
) (org-show-context))
1108 (message "result '%s' not found in this buffer" name
))))
1110 (defun org-babel-find-named-result (name)
1111 "Find a named result.
1112 Return the location of the result named NAME in the current
1113 buffer or nil if no such result exists."
1115 (goto-char (point-min))
1116 (when (re-search-forward
1117 (concat org-babel-result-regexp
1118 "[ \t]" (regexp-quote name
) "[ \t\n\f\v\r]") nil t
)
1119 (beginning-of-line 0) (point))))
1121 (defun org-babel-result-names (&optional file
)
1122 "Returns the names of results in FILE or the current buffer."
1124 (when file
(find-file file
)) (goto-char (point-min))
1126 (while (re-search-forward org-babel-result-w-name-regexp nil t
)
1127 (setq names
(cons (org-babel-clean-text-properties (match-string 4))
1132 (defun org-babel-next-src-block (&optional arg
)
1133 "Jump to the next source block.
1134 With optional prefix argument ARG, jump forward ARG many source blocks."
1136 (when (looking-at org-babel-src-block-regexp
) (forward-char 1))
1138 (re-search-forward org-babel-src-block-regexp nil nil
(or arg
1))
1139 (error (error "No further code blocks")))
1140 (goto-char (match-beginning 0)) (org-show-context))
1143 (defun org-babel-previous-src-block (&optional arg
)
1144 "Jump to the previous source block.
1145 With optional prefix argument ARG, jump backward ARG many source blocks."
1148 (re-search-backward org-babel-src-block-regexp nil nil
(or arg
1))
1149 (error (error "No previous code blocks")))
1150 (goto-char (match-beginning 0)) (org-show-context))
1152 (defvar org-babel-load-languages
)
1155 (defun org-babel-mark-block ()
1156 "Mark current src block"
1162 (looking-at org-babel-src-block-regexp
))
1163 (push-mark (match-end 5) nil t
)
1164 (goto-char (match-beginning 5))))
1165 (org-babel-where-is-src-block-head)))
1167 (defun org-babel-demarcate-block (&optional arg
)
1168 "Wrap or split the code in the region or on the point.
1169 When called from inside of a code block the current block is
1170 split. When called from outside of a code block a new code block
1171 is created. In both cases if the region is demarcated and if the
1172 region is not active then the point is demarcated."
1174 (let ((info (org-babel-get-src-block-info 'light
))
1175 (stars (concat (make-string (or (org-current-level) 1) ?
*) " ")))
1181 (let ((lang (nth 0 info
))
1182 (indent (make-string (nth 5 info
) ?
)))
1183 (when (string-match "^[[:space:]]*$"
1184 (buffer-substring (point-at-bol)
1186 (delete-region (point-at-bol) (point-at-eol)))
1187 (insert (concat (if (looking-at "^") "" "\n")
1188 indent
"#+end_src\n"
1189 (if arg stars indent
) "\n"
1190 indent
"#+begin_src " lang
1191 (if (looking-at "[\n\r]") "" "\n")))))
1192 (move-end-of-line 2))
1193 (sort (if (region-active-p) (list (mark) (point)) (list (point))) #'>))
1194 (let ((start (point))
1195 (lang (org-icompleting-read "Lang: "
1196 (mapcar (lambda (el) (symbol-name (car el
)))
1197 org-babel-load-languages
)))
1198 (body (delete-and-extract-region
1199 (if (region-active-p) (mark) (point)) (point))))
1200 (insert (concat (if (looking-at "^") "" "\n")
1201 (if arg
(concat stars
"\n") "")
1202 "#+begin_src " lang
"\n"
1204 (if (or (= (length body
) 0)
1205 (string-match "[\r\n]$" body
)) "" "\n")
1207 (goto-char start
) (move-end-of-line 1)))))
1209 (defvar org-babel-lob-one-liner-regexp
)
1210 (defun org-babel-where-is-src-block-result (&optional insert info hash indent
)
1211 "Find where the current source block results begin.
1212 Return the point at the beginning of the result of the current
1213 source block. Specifically at the beginning of the results line.
1214 If no result exists for this block then create a results line
1215 following the source block."
1217 (let* ((on-lob-line (progn (beginning-of-line 1)
1218 (looking-at org-babel-lob-one-liner-regexp
)))
1219 (name (if on-lob-line
1220 (nth 0 (org-babel-lob-get-info))
1221 (nth 4 (or info
(org-babel-get-src-block-info)))))
1222 (head (unless on-lob-line
(org-babel-where-is-src-block-head)))
1224 (when head
(goto-char head
))
1226 found
;; was there a result (before we potentially insert one)
1230 ;; - return t if it is found, else return nil
1231 ;; - if it does not need to be rebuilt, then don't set end
1232 ;; - if it does need to be rebuilt then do set end
1233 name
(setq beg
(org-babel-find-named-result name
))
1235 (when (and hash
(not (string= hash
(match-string 3))))
1236 (goto-char beg
) (setq end beg
) ;; beginning of result
1238 (delete-region end
(org-babel-result-end)) nil
)))
1241 ;; - return t if it is found, else return nil
1242 ;; - if it is found, and the hash doesn't match, delete and set end
1243 (or on-lob-line
(re-search-forward "^[ \t]*#\\+end_src" nil t
))
1244 (progn (end-of-line 1)
1245 (if (eobp) (insert "\n") (forward-char 1))
1248 (progn ;; unnamed results line already exists
1249 (re-search-forward "[^ \f\t\n\r\v]" nil t
)
1250 (beginning-of-line 1)
1252 (concat org-babel-result-regexp
"\n")))
1254 ;; must remove and rebuild if hash!=old-hash
1255 (if (and hash
(not (string= hash
(match-string 3))))
1259 end
(org-babel-result-end)))
1260 (setq end nil
)))))))))
1261 (if (and insert end
)
1265 (if (looking-at "[\n\r]") (forward-char 1) (insert "\n")))
1270 (org-number-sequence 1 indent
) "")
1273 (when hash
(concat "["hash
"]"))
1275 (when name
(concat " " name
)) "\n"))
1276 (unless beg
(insert "\n") (backward-char))
1277 (beginning-of-line 0)
1278 (if hash
(org-babel-hide-hash))
1282 (defvar org-block-regexp
)
1283 (defun org-babel-read-result ()
1284 "Read the result at `point' into emacs-lisp."
1285 (let ((case-fold-search t
) result-string
)
1287 ((org-at-table-p) (org-babel-read-table))
1288 ((looking-at org-bracket-link-regexp
) (org-babel-read-link))
1289 ((looking-at org-block-regexp
) (org-babel-trim (match-string 4)))
1290 ((looking-at "^[ \t]*: ")
1293 (mapconcat (lambda (line)
1294 (if (and (> (length line
) 1)
1295 (string-match "^[ \t]*: \\(.+\\)" line
))
1296 (match-string 1 line
)
1300 (point) (org-babel-result-end)) "[\r\n]+")
1302 (or (org-babel-number-p result-string
) result-string
))
1303 ((looking-at org-babel-result-regexp
)
1304 (save-excursion (forward-line 1) (org-babel-read-result))))))
1306 (defun org-babel-read-table ()
1307 "Read the table at `point' into emacs-lisp."
1308 (mapcar (lambda (row)
1309 (if (and (symbolp row
) (equal row
'hline
)) row
1310 (mapcar #'org-babel-read row
)))
1311 (org-table-to-lisp)))
1313 (defvar org-link-types-re
)
1314 (defun org-babel-read-link ()
1315 "Read the link at `point' into emacs-lisp.
1316 If the path of the link is a file path it is expanded using
1317 `expand-file-name'."
1318 (let* ((case-fold-search t
)
1319 (raw (and (looking-at org-bracket-link-regexp
)
1320 (org-babel-clean-text-properties (match-string 1))))
1321 (type (and (string-match org-link-types-re raw
)
1322 (match-string 1 raw
))))
1324 ((not type
) (expand-file-name raw
))
1325 ((string= type
"file")
1326 (and (string-match "file\\(.*\\):\\(.+\\)" raw
)
1327 (expand-file-name (match-string 2 raw
))))
1330 (defun org-babel-insert-result
1331 (result &optional result-params info hash indent lang
)
1332 "Insert RESULT into the current buffer.
1333 By default RESULT is inserted after the end of the
1334 current source block. With optional argument RESULT-PARAMS
1335 controls insertion of results in the org-mode file.
1336 RESULT-PARAMS can take the following values...
1338 replace - (default option) insert results after the source block
1339 replacing any previously inserted results
1341 silent -- no results are inserted
1343 file ---- the results are interpreted as a file path, and are
1344 inserted into the buffer using the Org-mode file syntax
1346 raw ----- results are added directly to the org-mode file. This
1347 is a good option if you code block will output org-mode
1350 org ----- similar in effect to raw, only the results are wrapped
1351 in an org code block. Similar to the raw option, on
1352 export the results will be interpreted as org-formatted
1353 text, however by wrapping the results in an org code
1354 block they can be replaced upon re-execution of the
1357 html ---- results are added inside of a #+BEGIN_HTML block. This
1358 is a good option if you code block will output html
1361 latex --- results are added inside of a #+BEGIN_LATEX block.
1362 This is a good option if you code block will output
1363 latex formatted text.
1365 code ---- the results are extracted in the syntax of the source
1366 code of the language being evaluated and are added
1367 inside of a #+BEGIN_SRC block with the source-code
1368 language set appropriately. Note this relies on the
1369 optional LANG argument."
1370 (if (stringp result
)
1372 (setq result
(org-babel-clean-text-properties result
))
1373 (when (member "file" result-params
)
1374 (setq result
(org-babel-result-to-file result
))))
1375 (unless (listp result
) (setq result
(format "%S" result
))))
1376 (if (and result-params
(member "silent" result-params
))
1378 (message (replace-regexp-in-string "%" "%%" (format "%S" result
)))
1380 (when (and (stringp result
) ;; ensure results end in a newline
1381 (> (length result
) 0)
1382 (not (or (string-equal (substring result -
1) "\n")
1383 (string-equal (substring result -
1) "\r"))))
1384 (setq result
(concat result
"\n")))
1386 (let ((existing-result (org-babel-where-is-src-block-result
1387 t info hash indent
))
1389 (cdr (assoc :results_switches
(nth 2 info
))))
1391 (if (not existing-result
)
1393 (goto-char existing-result
)
1395 (re-search-forward "#" nil t
)
1396 (setq indent
(- (current-column) 1)))
1400 ((member "replace" result-params
)
1401 (delete-region (point) (org-babel-result-end)))
1402 ((member "append" result-params
)
1403 (goto-char (org-babel-result-end)) (setq beg
(point)))
1404 ((member "prepend" result-params
) ;; already there
1406 (setq results-switches
1407 (if results-switches
(concat " " results-switches
) ""))
1409 ;; do nothing for an empty result
1410 ((= (length result
) 0))
1411 ;; assume the result is a table if it's not a string
1412 ((not (stringp result
))
1413 (insert (concat (orgtbl-to-orgtbl
1414 (if (or (eq 'hline
(car result
))
1415 (and (listp (car result
))
1416 (listp (cdr (car result
)))))
1417 result
(list result
))
1418 '(:fmt
(lambda (cell) (format "%s" cell
)))) "\n"))
1419 (goto-char beg
) (when (org-at-table-p) (org-table-align)))
1420 ((member "file" result-params
)
1422 ((member "html" result-params
)
1423 (insert (format "#+BEGIN_HTML%s\n%s#+END_HTML\n"
1424 results-switches result
)))
1425 ((member "latex" result-params
)
1426 (insert (format "#+BEGIN_LaTeX%s\n%s#+END_LaTeX\n"
1427 results-switches result
)))
1428 ((member "code" result-params
)
1429 (insert (format "#+BEGIN_SRC %s%s\n%s#+END_SRC\n"
1430 (or lang
"none") results-switches result
)))
1431 ((member "org" result-params
)
1432 (insert (format "#+BEGIN_SRC org\n%s#+END_SRC\n" result
)))
1433 ((member "raw" result-params
)
1434 (save-excursion (insert result
)) (if (org-at-table-p) (org-cycle)))
1436 (org-babel-examplize-region
1437 (point) (progn (insert result
) (point)) results-switches
)))
1438 ;; possibly indent the results to match the #+results line
1439 (setq end
(if (listp result
) (org-table-end) (point)))
1440 (when (and indent
(> indent
0)
1441 ;; in this case `table-align' does the work for us
1442 (not (and (listp result
)
1443 (member "append" result-params
))))
1444 (indent-rigidly beg end indent
))))
1445 (if (= (length result
) 0)
1446 (if (member "value" result-params
)
1447 (message "No result returned by source block")
1448 (message "Source block produced no output"))
1449 (message "finished"))))
1451 (defun org-babel-remove-result (&optional info
)
1452 "Remove the result of the current source block."
1454 (let ((location (org-babel-where-is-src-block-result nil info
)) start
)
1457 (goto-char location
) (setq start
(point)) (forward-line 1)
1458 (delete-region start
(org-babel-result-end))))))
1460 (defun org-babel-result-end ()
1461 "Return the point at the end of the current set of results"
1463 (if (org-at-table-p)
1464 (progn (goto-char (org-table-end)) (point))
1465 (let ((case-fold-search t
))
1467 ((looking-at "[ \t]*#\\+begin_latex")
1468 (re-search-forward "[ \t]*#\\+end_latex" nil t
)
1470 ((looking-at "[ \t]*#\\+begin_html")
1471 (re-search-forward "[ \t]*#\\+end_html" nil t
)
1473 ((looking-at "[ \t]*#\\+begin_example")
1474 (re-search-forward "[ \t]*#\\+end_example" nil t
)
1476 ((looking-at "[ \t]*#\\+begin_src")
1477 (re-search-forward "[ \t]*#\\+end_src" nil t
)
1479 (t (progn (while (looking-at "[ \t]*\\(: \\|\\[\\[\\)")
1480 (forward-line 1))))))
1483 (defun org-babel-result-to-file (result)
1484 "Convert RESULT into an `org-mode' link.
1485 If the `default-directory' is different from the containing
1486 file's directory then expand relative links."
1489 (if (and default-directory
1491 (not (string= (expand-file-name default-directory
)
1493 (file-name-directory buffer-file-name
)))))
1494 (expand-file-name result default-directory
)
1497 (defun org-babel-examplize-region (beg end
&optional results-switches
)
1498 "Comment out region using the ': ' org example quote."
1500 (let ((size (count-lines beg end
)))
1503 (error (concat "This should not be impossible:"
1504 "a newline was appended to result if missing")))
1505 ((< size org-babel-min-lines-for-block-output
)
1508 (beginning-of-line 1) (insert ": ") (forward-line 1)))
1511 (insert (if results-switches
1512 (format "#+begin_example%s\n" results-switches
)
1513 "#+begin_example\n"))
1514 (forward-char (- end beg
))
1515 (insert "#+end_example\n"))))))
1517 (defun org-babel-merge-params (&rest plists
)
1518 "Combine all parameter association lists in PLISTS.
1519 Later elements of PLISTS override the values of previous element.
1520 This takes into account some special considerations for certain
1521 parameters when merging lists."
1522 (let ((results-exclusive-groups
1523 '(("file" "vector" "table" "scalar" "raw" "org"
1524 "html" "latex" "code" "pp")
1525 ("replace" "silent" "append" "prepend")
1526 ("output" "value")))
1527 (exports-exclusive-groups
1528 '(("code" "results" "both" "none")))
1529 params results exports tangle noweb cache vars shebang comments
)
1530 (flet ((e-merge (exclusive-groups &rest result-params
)
1531 ;; maintain exclusivity of mutually exclusive parameters
1533 (mapc (lambda (new-params)
1534 (mapc (lambda (new-param)
1535 (mapc (lambda (exclusive-group)
1536 (when (member new-param exclusive-group
)
1537 (mapcar (lambda (excluded-param)
1544 (setq output
(org-uniquify
1545 (cons new-param output
))))
1555 (let ((name (if (listp (cdr pair
))
1557 (and (string-match "^\\([^= \f\t\n\r\v]+\\)[ \t]*="
1559 (intern (match-string 1 (cdr pair
)))))))
1562 (cons (cons name pair
)
1563 (if (member name
(mapcar #'car vars
))
1566 (lambda (p) (unless (equal (car p
) name
) p
))
1570 (setq results
(e-merge results-exclusive-groups
1571 results
(split-string (cdr pair
)))))
1574 (setq results
(e-merge results-exclusive-groups
1576 (unless (or (member "both" exports
)
1577 (member "none" exports
)
1578 (member "code" exports
))
1579 (setq exports
(e-merge exports-exclusive-groups
1580 exports
'("results"))))
1581 (setq params
(cons pair
(assq-delete-all (car pair
) params
)))))
1583 (setq exports
(e-merge exports-exclusive-groups
1584 exports
(split-string (cdr pair
)))))
1585 (:tangle
;; take the latest -- always overwrite
1586 (setq tangle
(or (list (cdr pair
)) tangle
)))
1588 (setq noweb
(e-merge '(("yes" "no")) noweb
1589 (split-string (or (cdr pair
) "")))))
1591 (setq cache
(e-merge '(("yes" "no")) cache
1592 (split-string (or (cdr pair
) "")))))
1593 (:shebang
;; take the latest -- always overwrite
1594 (setq shebang
(or (list (cdr pair
)) shebang
)))
1596 (setq comments
(e-merge '(("yes" "no")) comments
1597 (split-string (or (cdr pair
) "")))))
1598 (t ;; replace: this covers e.g. :session
1599 (setq params
(cons pair
(assq-delete-all (car pair
) params
))))))
1602 (while vars
(setq params
(cons (cons :var
(cddr (pop vars
))) params
)))
1603 (cons (cons :comments
(mapconcat 'identity comments
" "))
1604 (cons (cons :shebang
(mapconcat 'identity shebang
" "))
1605 (cons (cons :cache
(mapconcat 'identity cache
" "))
1606 (cons (cons :noweb
(mapconcat 'identity noweb
" "))
1607 (cons (cons :tangle
(mapconcat 'identity tangle
" "))
1608 (cons (cons :exports
1609 (mapconcat 'identity exports
" "))
1612 (mapconcat 'identity results
" "))
1615 (defun org-babel-expand-noweb-references (&optional info parent-buffer
)
1616 "Expand Noweb references in the body of the current source code block.
1618 For example the following reference would be replaced with the
1619 body of the source-code block named 'example-block'.
1623 Note that any text preceding the <<foo>> construct on a line will
1624 be interposed between the lines of the replacement text. So for
1625 example if <<foo>> is placed behind a comment, then the entire
1626 replacement text will also be commented.
1628 This function must be called from inside of the buffer containing
1629 the source-code block which holds BODY.
1631 In addition the following syntax can be used to insert the
1632 results of evaluating the source-code block named 'example-block'.
1636 Any optional arguments can be passed to example-block by placing
1637 the arguments inside the parenthesis following the convention
1638 defined by `org-babel-lob'. For example
1640 <<example-block(a=9)>>
1642 would set the value of argument \"a\" equal to \"9\". Note that
1643 these arguments are not evaluated in the current source-code
1644 block but are passed literally to the \"example-block\"."
1645 (let* ((parent-buffer (or parent-buffer
(current-buffer)))
1646 (info (or info
(org-babel-get-src-block-info)))
1649 (new-body "") index source-name evaluate prefix
)
1650 (flet ((nb-add (text)
1651 (setq new-body
(concat new-body text
))))
1653 (insert body
) (goto-char (point-min))
1654 (setq index
(point))
1655 (while (and (re-search-forward "<<\\(.+?\\)>>" nil t
))
1656 (save-match-data (setf source-name
(match-string 1)))
1657 (save-match-data (setq evaluate
(string-match "\(.*\)" source-name
)))
1660 (buffer-substring (match-beginning 0)
1662 (beginning-of-line 1) (point)))))
1663 ;; add interval to new-body (removing noweb reference)
1664 (goto-char (match-beginning 0))
1665 (nb-add (buffer-substring index
(point)))
1666 (goto-char (match-end 0))
1667 (setq index
(point))
1668 (nb-add (with-current-buffer parent-buffer
1669 (mapconcat ;; interpose PREFIX between every line
1673 (let ((raw (org-babel-ref-resolve source-name
)))
1674 (if (stringp raw
) raw
(format "%S" raw
)))
1677 (let ((point (org-babel-find-named-block
1683 (org-babel-expand-noweb-references
1684 (org-babel-get-src-block-info))))
1685 ;; optionally raise an error if named
1686 ;; source-block doesn't exist
1687 (if (member lang org-babel-noweb-error-langs
)
1690 "<<" source-name
">> "
1691 "could not be resolved (see "
1692 "`org-babel-noweb-error-langs')"))
1694 "[\n\r]") (concat "\n" prefix
)))))
1695 (nb-add (buffer-substring index
(point-max)))))
1698 (defun org-babel-clean-text-properties (text)
1699 "Strip all properties from text return."
1701 (set-text-properties 0 (length text
) nil text
) text
))
1703 (defun org-babel-strip-protective-commas (body)
1704 "Strip protective commas from bodies of source blocks."
1705 (replace-regexp-in-string "^,#" "#" body
))
1707 (defun org-babel-read (cell)
1708 "Convert the string value of CELL to a number if appropriate.
1709 Otherwise if cell looks like lisp (meaning it starts with a
1710 \"(\" or a \"'\") then read it as lisp, otherwise return it
1711 unmodified as a string.
1713 This is taken almost directly from `org-read-prop'."
1714 (if (and (stringp cell
) (not (equal cell
"")))
1715 (or (org-babel-number-p cell
)
1716 (if (or (equal "(" (substring cell
0 1))
1717 (equal "'" (substring cell
0 1))
1718 (equal "`" (substring cell
0 1)))
1720 (progn (set-text-properties 0 (length cell
) nil cell
) cell
)))
1723 (defun org-babel-number-p (string)
1724 "If STRING represents a number return it's value."
1725 (if (and (string-match "^-?[0-9]*\\.?[0-9]*$" string
)
1726 (= (length (substring string
(match-beginning 0)
1729 (string-to-number string
)))
1731 (defun org-babel-import-elisp-from-file (file-name &optional separator
)
1732 "Read the results located at FILE-NAME into an elisp table.
1733 If the table is trivial, then return it as a scalar."
1735 (save-window-excursion
1739 (org-table-import file-name separator
)
1740 (delete-file file-name
)
1741 (setq result
(mapcar (lambda (row)
1742 (mapcar #'org-babel-string-read row
))
1743 (org-table-to-lisp))))
1745 (if (null (cdr result
)) ;; if result is trivial vector, then scalarize it
1746 (if (consp (car result
))
1747 (if (null (cdr (car result
)))
1753 (defun org-babel-string-read (cell)
1754 "Strip nested \"s from around strings."
1755 (org-babel-read (or (and (stringp cell
)
1756 (string-match "\\\"\\(.+\\)\\\"" cell
)
1757 (match-string 1 cell
))
1760 (defun org-babel-reverse-string (string)
1761 "Return the reverse of STRING."
1762 (apply 'string
(reverse (string-to-list string
))))
1764 (defun org-babel-chomp (string &optional regexp
)
1765 "Strip trailing spaces and carriage returns from STRING.
1766 Default regexp used is \"[ \f\t\n\r\v]\" but can be
1767 overwritten by specifying a regexp as a second argument."
1768 (let ((regexp (or regexp
"[ \f\t\n\r\v]")))
1769 (while (and (> (length string
) 0)
1770 (string-match regexp
(substring string -
1)))
1771 (setq string
(substring string
0 -
1)))
1774 (defun org-babel-trim (string &optional regexp
)
1775 "Strip leading and trailing spaces and carriage returns from STRING.
1776 Like `org-babel-chomp' only it runs on both the front and back
1778 (org-babel-chomp (org-babel-reverse-string
1779 (org-babel-chomp (org-babel-reverse-string string
) regexp
))
1782 (defvar org-babel-org-babel-call-process-region-original nil
)
1783 (defun org-babel-tramp-handle-call-process-region
1784 (start end program
&optional delete buffer display
&rest args
)
1785 "Use tramp to handle call-process-region.
1786 Fixes a bug in `tramp-handle-call-process-region'."
1787 (if (and (featurep 'tramp
) (file-remote-p default-directory
))
1788 (let ((tmpfile (tramp-compat-make-temp-file "")))
1789 (write-region start end tmpfile
)
1790 (when delete
(delete-region start end
))
1792 ;; (apply 'call-process program tmpfile buffer display args)
1794 (apply 'process-file program tmpfile buffer display args
)
1795 (delete-file tmpfile
)))
1796 ;; org-babel-call-process-region-original is the original emacs
1797 ;; definition. It is in scope from the let binding in
1798 ;; org-babel-execute-src-block
1799 (apply org-babel-call-process-region-original
1800 start end program delete buffer display args
)))
1802 (defun org-babel-local-file-name (file)
1803 "Return the local name component of FILE."
1804 (if (file-remote-p file
)
1806 (with-parsed-tramp-file-name file nil
1810 (defun org-babel-process-file-name (name &optional no-quote-p
)
1811 "Prepare NAME to be used in an external process.
1812 If NAME specifies a remote location, the remote portion of the
1813 name is removed, since in that case the process will be executing
1814 remotely. The file name is then processed by
1815 `expand-file-name'. Unless second argument NO-QUOTE-P is non-nil,
1816 the file name is additionally processed by
1817 `shell-quote-argument'"
1818 ((lambda (f) (if no-quote-p f
(shell-quote-argument f
)))
1819 (expand-file-name (org-babel-local-file-name name
))))
1821 (defvar org-babel-temporary-directory
)
1822 (unless (or noninteractive
(boundp 'org-babel-temporary-directory
))
1823 (defvar org-babel-temporary-directory
1824 (or (and (boundp 'org-babel-temporary-directory
)
1825 (file-exists-p org-babel-temporary-directory
)
1826 org-babel-temporary-directory
)
1827 (make-temp-file "babel-" t
))
1828 "Directory to hold temporary files created to execute code blocks.
1829 Used by `org-babel-temp-file'. This directory will be removed on
1832 (defun org-babel-temp-file (prefix &optional suffix
)
1833 "Create a temporary file in the `org-babel-temporary-directory'.
1834 Passes PREFIX and SUFFIX directly to `make-temp-file' with the
1835 value of `temporary-file-directory' temporarily set to the value
1836 of `org-babel-temporary-directory'."
1837 (if (file-remote-p default-directory
)
1839 (concat (file-remote-p default-directory
)
1841 prefix temporary-file-directory
)
1843 (let ((temporary-file-directory
1844 (or (and (file-exists-p org-babel-temporary-directory
)
1845 org-babel-temporary-directory
)
1846 temporary-file-directory
)))
1847 (make-temp-file prefix nil suffix
))))
1849 (defun org-babel-remove-temporary-directory ()
1850 "Remove `org-babel-temporary-directory' on Emacs shutdown."
1851 (when (and (boundp 'org-babel-temporary-directory
)
1852 (file-exists-p org-babel-temporary-directory
))
1853 ;; taken from `delete-directory' in files.el
1854 (mapc (lambda (file)
1855 ;; This test is equivalent to
1856 ;; (and (file-directory-p fn) (not (file-symlink-p fn)))
1857 ;; but more efficient
1858 (if (eq t
(car (file-attributes file
)))
1859 (delete-directory file
)
1860 (delete-file file
)))
1861 ;; We do not want to delete "." and "..".
1862 (directory-files org-babel-temporary-directory
'full
1863 "^\\([^.]\\|\\.\\([^.]\\|\\..\\)\\).*"))
1864 (delete-directory org-babel-temporary-directory
)))
1866 (add-hook 'kill-emacs-hook
'org-babel-remove-temporary-directory
)
1870 ;; arch-tag: 01a7ebee-06c5-4ee4-a709-e660d28c0af1